4

我想改变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。在.Rnwor.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, '}')
         )
  }
4

1 回答 1

2

您可以通过以下方式将以下内容添加到您的 LaTeX 序言中,以使用-and-\label的组合进行全局替换:\label\hypertarget

---
title: 'A title'
author: 'An author'
date: 'A date'
output: 
  pdf_document:
    keep_tex: true
header-includes:
  - \AtBeginDocument{
      \let\oldlabel\label
      \renewcommand{\label}[1]{\oldlabel{#1}\hypertarget{#1}{}}
    }
---

See Figure \ref{fig:figure}.

\begin{figure}
  \caption{A figure caption}
  \label{fig:figure}
\end{figure}
于 2018-01-19T16:37:27.733 回答