我想改变knitr
' 在创建figure
环境LaTeX
以调用与 不同的LaTeX
命令时的行为\label{}
,例如,\alabel{}
我定义\alabel
在其中运行\label{foo}
以及\hypertarget{foo}{}
使用hyperref
LaTeX
包的位置。我这样做是为了可以在 Web 浏览器中构造一个 URL,以访问使用..pdf
构建的文档中的特定位置pdflatex
,例如http://.../my.pdf#nameddest=foo
.
如何在图中覆盖\label{}
或发出附加信息\hypertarget{same label used by \label{}
?
这是在.Rnw
文件的上下文中。我希望锚出现在figure
环境for optimal positioning of the cursor when jumping into the
.pdf` 文档中。
更新
在重新考虑这一点时,我认为最好不要生成hypertarget
锚,而是编写一个R
函数来解析LaTeX
aux
文件以检索引用的页码(\newlabel
行)以生成pdf
文件所需的 URL。在.Rnw
or.Rmd
文件中,我可以在句子中调用此函数来插入计算的 URL。
更新
毕竟我决定采用@werner 的出色方法,该方法完美无缺。对于任何对R
不需要使用的基于 - 的方法感兴趣的人hypertarget
,这里是LaTeX
设置它所需的代码 - 这可以处理物理页码与逻辑页码不匹配的情况(例如,使用诸如章号 - 章内的页码。
% 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
## Create hyperlink to appropriate physical page in a pdf document
## created by pdflatex given the .aux and .pag file. Absolute and
## named page numbers are store in the .pag file created by hslide.sty
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, '}')
)
}