I want to change the behavior knitr
when it creates an environment figure
in LaTeX
to invoke a different command LaTeX
than \label{}
, for example \alabel{}
, where I define \alabel
to run \label{foo}
, as well \hypertarget{foo}{}
as using a package hyperref
LaTeX
. I am doing this to create a URL in a web browser to get to a specific place in a document .pdf
built with pdflatex
for example. http://.../my.pdf#nameddest=foo
.
How can I either override \label{}
or fix the extra digit \hypertarget{same label used by \label{}
in the figures?
This is in the context of the file .Rnw
. I want the anchor to appear inside the figure
for optimal positioning of the cursor when jumping into the
.pdf` document figure
.
UPDATE
In rethinking this, I believe that it’s better not to generate the bindings hypertarget
, but to write a function R
that parses the file LaTeX
aux
to get the link page number ( \newlabel
), to generate the necessary URL to the file pdf
. In a file .Rnw
or .Rmd
I can call this function from a sentence to insert a calculated URL.
UPDATE
I finally decided to go with the excellent @werner method, which works flawlessly. For everyone who is interested in an approach R
that does not require use hypertarget
, here is the code LaTeX
needed to configure it - this handles the case when the physical page numbers do not match the logical page of the number (for example, using logical numbers such as the chapter number - the page in the chapter.
% Creates .pag file mapping absolute page numbers to logical page
% numbers; works with R function latexRef
\newwrite\pgfile
\immediate\openout\pgfile=\jobname .pag
\newcounter{abspage}
\setcounter{abspage}{0}
\useackage{everypage}
\AddEverypageHook{%
\addtocounter{abspage}{1}
\immediate\write\pgfile{\thepage, \theabspage}%
}
\AtEndDocument{\clearpage\immediate\closeout\pgfile}
R
, .aux, .pag
:
latexRef <- function(label, base, name, path='doc/',
blogpath='/home/harrelfe/R/blog/blogdown/static/doc/',
lang=c('markdown', 'latex')) {
lang <- match.arg(lang)
aux <- paste0(blogpath, base, '.aux')
if(! file.exists(aux))
stop(paste('no file named', aux))
path <- paste0(path, base, '.pdf')
pag <- paste0(blogpath, base, '.pag')
pagemap <- NULL
if(file.exists(pag)) {
p <- read.table(pag, sep=',')
pagemap <- trimws(p[[2]])
names(pagemap) <- trimws(p[[1]])
}
r <- readLines(aux)
w <- paste0('\\\\newlabel\\{', label, '\\}')
i <- grepl(w, r)
if(! any(i)) stop(paste('no label =', label))
r <- r[i][1]
r <- gsub('\\{', ',', r)
r <- gsub('\\}', ',', r)
x <- scan(text=r, sep=',', what=character(0), quiet=TRUE)
section <- x[5]
if(section != '') section <- paste0(' Section ', section)
page <- trimws(x[7])
if(length(pagemap)) page <- pagemap[page]
url <- paste0('http://fharrell.com/', path, '#page=', page)
switch(lang,
markdown = paste0('[', name, section, '](', url, ')'),
latex = paste0('\\href{', url, '}{', name, section, '}')
)
}