如何使用Emacs、ESS、pandoc模式和polymode从Rmd文件创建pdf



这是一个"经典"Rmd文件的改编版,我想使用Emacs(Emacs Speak Statistics)和polymode将其编织成pdf。我找不到正确的命令。关于polymode的文档很少。我正在使用Emacs社会科学入门套件

---
title: "Untitled"
author: "SB"
date: "Wednesday, February 04, 2015"
output: pdf_document
---
You can embed an R code chunk like this:
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```

正如文档所说,使用M-n wM-n w来设置/更改编织器。对于ESS,您可能应该使用knitr-ESS weaver,因为它使用当前的*R*进程。

您可以使用rmarkdown包中的rmarkdown::render()来编织一个.Rmd文件,以通过一个命令进行标记并呈现输出文件(PDF、Word、HTML等)!

我不确定ESS中是否已经包含了对rmarkdown工作流的支持(我正在尝试涉猎elisp),所以我编写了一个调用rmarkdown::render()的函数,并允许使用前缀arg(例如C-u)自定义rmarkdown::render()函数调用的输入。

;; spa/rmd-render
;; Global history list allows Emacs to "remember" the last
;; render commands and propose as suggestions in the minibuffer.
(defvar rmd-render-history nil "History list for spa/rmd-render.")
(defun spa/rmd-render (arg)
  "Render the current Rmd file to PDF output.
   With a prefix arg, edit the R command in the minibuffer"
  (interactive "P")
  ;; Build the default R render command
  (setq rcmd (concat "rmarkdown::render('" buffer-file-name "',"
                 "output_dir = '../reports',"
                 "output_format = 'pdf_document')"))
  ;; Check for prefix argument
  (if arg
      (progn
    ;; Use last command as the default (if non-nil)
    (setq prev-history (car rmd-render-history))
    (if prev-history
        (setq rcmd prev-history)
      nil)
    ;; Allow the user to modify rcmd
    (setq rcmd
          (read-from-minibuffer "Run: " rcmd nil nil 'rmd-render-history))
    )
    ;; With no prefix arg, add default rcmd to history
    (setq rmd-render-history (add-to-history 'rmd-render-history rcmd)))
  ;; Build and evaluate the shell command
  (setq command (concat "echo "" rcmd "" | R --vanilla"))
  (compile command))
(define-key polymode-mode-map (kbd "C-c r")  'spa/rmd-render)

请注意,我有一些特定的参数设置,如output_dir = '../reports',但可以很容易地自定义elisp以满足您的需求。

在init文件中,您只需要从.Rmd文件中输入C-c r(或C-u C-c r以呈现为不同的格式、位置等)。该命令将打开一个新窗口,其中包含一个名为*compilation*的缓冲区,任何错误都会出现在该窗口中。

这肯定可以改进,我很乐意听取建议。

最新更新