Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

491 line
18 KiB

4 年之前
  1. ;;; ess-swv.el --- Some simple functions for ESS and Sweave
  2. ;; Copyright (C) 2005 David Whiting, A.J. Rossini, Richard M. Heiberger, Martin
  3. ;; Maechler, Kurt Hornik, Rodney Sparapani, and Stephen Eglen.
  4. ;; Copyright (C) 2006-2008 A.J. Rossini, Richard M. Heiberger, Martin Maechler,
  5. ;; Kurt Hornik, Rodney Sparapani, and Stephen Eglen.
  6. ;; Author: David Whiting <david.whiting@ncl.ac.uk>
  7. ;; Created: 15 April 2005
  8. ;; Maintainer: ESS-core <ESS-core@r-project.org>
  9. ;; Keywords: statistics, tools
  10. ;; This file is part of ESS.
  11. ;; This file is free software; you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 2, or (at your option)
  14. ;; any later version.
  15. ;; This file is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; A copy of the GNU General Public License is available at
  20. ;; https://www.r-project.org/Licenses/
  21. ;;; Commentary:
  22. ;;
  23. ;; Some simple functions for ESS and Sweave
  24. ;; david.whiting at ncl.ac.uk
  25. ;; Wed Sep 1 14:55:52 CEST 2004
  26. ;; I have written some very simple elisp functions that I have found
  27. ;; useful and thought others might like to see. I dabble with elisp
  28. ;; occasionally at best so there are probably better ways to do what I
  29. ;; have done, but so far this seems to work for me. There are several
  30. ;; things that are hard-coded, I use Linux and I think that this would
  31. ;; probably not work in Windows (not as it is now anyway).
  32. ;; With these functions and key bindings all I need to do is open a .Rnw
  33. ;; file and, assuming R is running, I press:
  34. ;; M-n s to Sweave the file, then
  35. ;; M-n l to run latex on the results of Sweave, then
  36. ;; M-n p to make and display a postscript file , or
  37. ;; M-n P to make and display a PDF version.
  38. ;; David Whiting to Anthony Rossini, Mar 30
  39. ;; On Wed, Mar 30, 2005 at 11:51:26AM +0200, A.J. Rossini wrote:
  40. ;; > I'm going to go ahead and add this stuff to the distribution tonight
  41. ;; > if you don't mind. I'd forgotten about it!
  42. ;; It would make me very happy indeed.
  43. ;; > (however, need permission to do so).
  44. ;; Permission granted!
  45. ;; Dave
  46. ;; --
  47. ;; David Whiting
  48. ;; School of Clinical Medical Sciences, The Medical School
  49. ;; University of Newcastle upon Tyne, NE2 4HH, UK.
  50. ;;; TODO:
  51. ;;;
  52. ;;; 1. I want to be able to send ess-swv-latex a parameter to tell it
  53. ;;; the number of times to run LaTeX (to get references updated
  54. ;;; correctly).
  55. ;;;
  56. ;;; 2. Also need to add ess-swv-Bibtex.
  57. ;;;
  58. ;;; 3. Might be good to have a way to chain commands.
  59. ;;;
  60. ;;; 4. ADD to the ../doc/ess.texi !!
  61. ;;; Code:
  62. ;;; Autoloads and Requires
  63. (eval-when-compile
  64. (require 'ess-custom))
  65. (require 'ess-utils)
  66. (require 'ess-noweb-mode)
  67. (require 'ess-r-mode); for Rnw-mode
  68. (require 'easymenu)
  69. (defvar TeX-command-list)
  70. (defvar TeX-command-default)
  71. (defvar TeX-file-extensions)
  72. (declare-function TeX-normal-mode "tex")
  73. (defgroup ess-sweave nil
  74. "Mode for editing Sweave (*.[SR]nw) files."
  75. :group 'ess-S
  76. :prefix "ess-")
  77. (defcustom ess-pdf-viewer-pref nil
  78. "External pdf viewer you like to use from ESS.
  79. Can be a string giving a name of the program or a list with car
  80. giving heprogram and the tail giving the arguments. For example
  81. '(\"okular\" \"--unique\")."
  82. :type '(choice (const nil) (repeat :tag "Command with arguments" string) (string :tag "Command")))
  83. (defcustom ess-ps-viewer-pref nil
  84. "External PostScript viewer you like to use from ESS.
  85. If nil, ESS will try finding one from a list."
  86. :type '(choice (const nil) string))
  87. (defcustom ess-swv-pdflatex-commands '("texi2pdf" "pdflatex" "make")
  88. "Commands to run a version of pdflatex in \\[ess-swv-PDF];
  89. the first entry is the default command."
  90. :group 'ess-sweave
  91. :type '(repeat string))
  92. (defcustom ess-swv-plug-into-AUCTeX-p nil
  93. "Non-nil means add commands to AUCTeX's \\[TeX-command-list]
  94. to sweave the current noweb file and latex the result."
  95. :group 'ess-sweave
  96. :type '(choice (const :tag "Off" nil)
  97. (const :tag "On" t)))
  98. (defcustom ess-swv-processing-command ".ess_weave(%s, %s)"
  99. "Command used by `ess-swv-run-in-R'.
  100. First %s is literally replaced by the processing command (for
  101. example: Sweave) second %s is replaced with a string containing a
  102. processed file and possibly additional argument encoding (example:
  103. \"path/to/foo.Rnw\", encoding='utf-8')
  104. .ess_weave changes the working directory to that of the supplied
  105. file.
  106. If you want to simply call knitr or Sweave in global environment
  107. set this command to \"%s(%s)\"."
  108. :group 'ess-R
  109. :type 'string)
  110. ;; currently use exactly for "Sweave", "Stangle", "knit", and "purl"
  111. (defun ess-swv-run-in-R (cmd &optional choose-process block)
  112. "Run \\[cmd] on the current .Rnw file. Utility function not called by user."
  113. (let* ((rnw-buf (current-buffer)))
  114. (if choose-process ;; previous behavior
  115. (ess-force-buffer-current "R process to load into: ")
  116. ;; else
  117. (update-ess-process-name-list)
  118. (cond ((= 0 (length ess-process-name-list))
  119. (message "no ESS processes running; starting R")
  120. (sit-for 1); so the user notices before the next msgs/prompt
  121. (run-ess-r)
  122. (set-buffer rnw-buf)
  123. )
  124. ((not (string= "R" (ess-make-buffer-current))); e.g. Splus, need R
  125. (ess-force-buffer-current "R process to load into: "))
  126. ))
  127. (save-excursion
  128. ;; (ess-execute (format "require(tools)")) ;; Make sure tools is loaded.
  129. (basic-save-buffer); do not Sweave/Stangle old version of file !
  130. (let* ((sprocess (ess-get-process ess-current-process-name))
  131. (sbuffer (process-buffer sprocess))
  132. (rnw-file (buffer-file-name))
  133. (Rnw-dir (file-name-directory rnw-file))
  134. (buf-coding (symbol-name buffer-file-coding-system))
  135. ;; could consider other encodings, but utf-8 is "R standard" for non-ASCII:
  136. (cmd-args (concat "\"" rnw-file "\""
  137. (if (string-match "^utf-8" buf-coding)
  138. ", encoding = \"utf-8\"")))
  139. (Sw-cmd
  140. (format ess-swv-processing-command cmd cmd-args)))
  141. (message "%s()ing %S" cmd rnw-file)
  142. ;; need to block when we are running ess-swv-weave-PDF so we
  143. ;; know when to start compiling the generated .tex file
  144. (if block
  145. (progn
  146. (ess-eval-linewise (concat Sw-cmd "\n") nil nil nil t)
  147. (message "Finished %s()ing %S" cmd rnw-file))
  148. (ess-execute Sw-cmd 'buffer nil nil)
  149. (pop-to-buffer-same-window rnw-buf)
  150. (display-buffer (buffer-name sbuffer)))))))
  151. (defcustom ess-swv-processor 'sweave
  152. "Processor to use for weaving and tangling.
  153. Currently 'sweave or 'knitr"
  154. :group 'ess-R
  155. :type '(choice (const sweave) (const knitr)))
  156. (defun ess-swv-tangle ()
  157. "Run Stangle/purl on the current .Rnw file.
  158. Depending on the `ess-swv-processor' used."
  159. (interactive)
  160. (ess-swv-run-in-R (cond ((eq ess-swv-processor 'sweave) "Stangle")
  161. ((eq ess-swv-processor 'knitr) "purl")
  162. (t (error "Not a valid processor %s" ess-swv-processor)))))
  163. (defun ess-swv-weave (&optional choose)
  164. "Run Sweave/knit on the current .Rnw file.
  165. Depending on the `ess-swv-processor' used.
  166. If CHOOSE is non-nil, offer a menu of available weavers.
  167. "
  168. (interactive "P")
  169. (let ((processor (if choose
  170. (ess-completing-read "Weaver" '("sweave" "knitr") nil t)
  171. (symbol-name ess-swv-processor))))
  172. (ess-swv-run-in-R (cond ((string= processor "sweave") "Sweave")
  173. ((string= processor "knitr") "knit")
  174. (t (error "Not a valid processor %s" processor))))))
  175. (defun ess-swv-sweave ()
  176. "Run Sweave on the current .Rnw file."
  177. (interactive)
  178. (ess-swv-run-in-R "Sweave"))
  179. (defun ess-swv-stangle ()
  180. "Run Stangle on the current .Rnw file."
  181. (interactive)
  182. (ess-swv-run-in-R "Stangle"))
  183. (defun ess-swv-knit ()
  184. "Run knit on the current .Rnw file."
  185. (interactive)
  186. (ess-swv-run-in-R "knit"))
  187. (defun ess-swv-purl ()
  188. "Run purl on the current .Rnw file."
  189. (interactive)
  190. (ess-swv-run-in-R "purl"))
  191. ;; trying different viewers; thanks to an original patch for
  192. ;; ess-swv.el from Leo <sdl@web.de> :
  193. (defun ess-get-ps-viewer ()
  194. "Get external PostScript viewer to be used from ESS.
  195. Use `ess-ps-viewer-pref' when that is executably found by \\[executable-find].
  196. Otherwise try a list of fixed known viewers."
  197. (file-name-nondirectory
  198. (or (and ess-ps-viewer-pref ; -> ./ess-custom.el
  199. (executable-find ess-ps-viewer-pref))
  200. (executable-find "gv")
  201. (executable-find "evince")
  202. (executable-find "kghostview"))))
  203. (defun ess-get-pdf-viewer ()
  204. "Get external PDF viewer to be used from ESS.
  205. Use `ess-pdf-viewer-pref' when that is executably found by \\[executable-find].
  206. Otherwise try a list of fixed known viewers."
  207. (let ((viewer (or ess-pdf-viewer-pref
  208. ;; (and (stringp ess-pdf-viewer-pref) ; -> ./ess-custom.el
  209. ;; (executable-find ess-pdf-viewer-pref))
  210. (executable-find "evince")
  211. (executable-find "kpdf")
  212. (executable-find "okular")
  213. (executable-find "xpdf")
  214. (executable-find "acroread")
  215. (executable-find "xdg-open")
  216. ;; this one is wrong, (ok for time being as it is used only in swv)
  217. (when (fboundp 'ess-get-words-from-vector)
  218. (car (ess-get-words-from-vector
  219. "getOption(\"pdfviewer\")\n"))))))
  220. (when (stringp viewer)
  221. (setq viewer (file-name-nondirectory viewer)))
  222. viewer))
  223. (defun ess-swv-weave-PDF (&optional choose)
  224. "Sweave/knit, compile TeX, and display PDF.
  225. Run Sweave or knit depending on `ess-swv-processor' used.
  226. If CHOOSE is non-nil, offer a menu of available weavers.
  227. "
  228. (interactive "P")
  229. (let ((processor (if choose
  230. (ess-completing-read "Weaver" '("sweave" "knitr") nil t)
  231. (symbol-name ess-swv-processor))))
  232. (ess-swv-run-in-R (cond ((string= processor "sweave") "Sweave")
  233. ((string= processor "knitr") "knit")
  234. (t (error "Not a valid processor %s" processor)))
  235. nil t)
  236. (ess-swv-PDF nil t)))
  237. (defun ess-swv-latex ()
  238. "Run LaTeX on the product of Sweave()ing the current file."
  239. (interactive)
  240. (save-excursion
  241. (let* ((namestem (file-name-sans-extension (buffer-file-name)))
  242. (latex-filename (concat namestem ".tex"))
  243. (tex-buf (get-buffer-create " *ESS-tex-output*")))
  244. (message "Running LaTeX on '%s' ..." latex-filename)
  245. (switch-to-buffer tex-buf)
  246. (call-process "latex" nil tex-buf 1 latex-filename)
  247. (switch-to-buffer (buffer-name))
  248. (display-buffer tex-buf)
  249. (message "Finished running LaTeX" ))))
  250. (defun ess-swv-PS ()
  251. "Create a postscript file from a dvi file (name based on the current
  252. Sweave file buffer name) and display it."
  253. (interactive)
  254. (let* ((buf (buffer-name))
  255. (namestem (file-name-sans-extension (buffer-file-name)))
  256. (dvi-filename (concat namestem ".dvi"))
  257. (psviewer (ess-get-ps-viewer)))
  258. (shell-command (concat "dvips -o temp.ps " dvi-filename))
  259. (shell-command (concat psviewer " temp.ps & "))
  260. (switch-to-buffer buf)
  261. ))
  262. (defun ess-swv-PDF (&optional pdflatex-cmd hide-compile-buffer)
  263. "From LaTeX file, create a PDF (via 'texi2pdf' or 'pdflatex', ...), by
  264. default using the first entry of `ess-swv-pdflatex-commands' and display it."
  265. (interactive)
  266. (setq pdflatex-cmd
  267. (or pdflatex-cmd
  268. (and (eq (length ess-swv-pdflatex-commands) 1)
  269. (car ess-swv-pdflatex-commands))
  270. (ess-completing-read "pdf latex command"
  271. ess-swv-pdflatex-commands ; <- collection to choose from
  272. nil 'confirm ; or 'confirm-after-completion
  273. nil nil (car ess-swv-pdflatex-commands))))
  274. (let* ((buf (buffer-name))
  275. (namestem (file-name-sans-extension (buffer-file-name)))
  276. (latex-filename (concat namestem ".tex"))
  277. (tex-buf (get-buffer-create "*ESS-tex-output*"))
  278. (pdfviewer (ess-get-pdf-viewer))
  279. (pdf-status)
  280. (cmdstr-win (format "start \"%s\" \"%s.pdf\"" pdfviewer namestem))
  281. (pdffile (format "%s.pdf" namestem))
  282. (cmd (if (stringp pdfviewer)
  283. (list pdfviewer pdffile)
  284. (append pdfviewer (list pdffile)))))
  285. ;;(shell-command (concat "pdflatex " latex-filename))
  286. (message "Running '%s' on '%s' ..." pdflatex-cmd latex-filename)
  287. (with-current-buffer tex-buf (erase-buffer))
  288. (setq pdf-status
  289. (call-process pdflatex-cmd nil tex-buf t
  290. (if (string= "texi2" (substring pdflatex-cmd 0 5))
  291. ;; workaround (bug?): texi2pdf or texi2dvi *fail* to work with full path:
  292. (file-name-nondirectory latex-filename)
  293. latex-filename)))
  294. (if (not (= 0 pdf-status))
  295. (progn (message "** OOPS: error in '%s' (%d)!" pdflatex-cmd pdf-status)
  296. (display-buffer tex-buf))
  297. ;; else: pdflatex probably ok
  298. ;; (set-process-sentinel proc 'shell-command-sentinel)
  299. (if (and (and ess-microsoft-p
  300. ;; Silence byte compiler warns about w32-fns
  301. (fboundp 'w32-shell-dos-semantics))
  302. (w32-shell-dos-semantics))
  303. (shell-command cmdstr-win)
  304. (message "%s" (mapconcat 'identity cmd " "))
  305. (apply 'start-process (car cmd) nil cmd))
  306. (unless hide-compile-buffer (display-buffer tex-buf))
  307. (message "%s finished with status %d" pdflatex-cmd pdf-status))))
  308. (defun ess-insert-Sexpr ()
  309. "Insert Sexpr{} into the buffer at point."
  310. (interactive)
  311. (insert "\\Sexpr{}")
  312. (backward-char))
  313. ;;; back-compatible wrappers:
  314. (defun ess-makeSweave () "old *DEPRECATED* version of \\[ess-swv-weave]."
  315. (interactive) (ding)
  316. (message
  317. "** warning: ess-makeSweave is deprecated. Do use (ess-swv-weave) instead!")
  318. (ess-swv-weave))
  319. (defun ess-makeLatex () "old *DEPRECATED* version of \\[ess-swv-latex]."
  320. (interactive) (ding)
  321. (message
  322. "** warning: ess-makeLatex is deprecated. Do use (ess-swv-latex) instead!")
  323. (ess-swv-latex))
  324. (defun ess-makePS () "old *DEPRECATED* version of \\[ess-swv-PS]."
  325. (interactive) (ding)
  326. (message
  327. "** warning: ess-makePS is deprecated. Do use (ess-swv-PS) instead!")
  328. (ess-swv-PS))
  329. (defun ess-makePDF () "old *DEPRECATED* version of \\[ess-swv-PDF]."
  330. (interactive) (ding)
  331. (message
  332. "** warning: ess-makePDF is deprecated. Do use (ess-swv-PDF) instead!")
  333. (ess-swv-PDF))
  334. ;; AUCTeX integration. This is independent of this library, but it fits
  335. ;; here nonetheless since it's an alternative way of Sweave'ing without
  336. ;; starting iESS.
  337. (defun ess-swv-add-TeX-commands ()
  338. "Add commands to AUCTeX's \\[TeX-command-list]."
  339. (unless (and (featurep 'tex-site) (featurep 'tex))
  340. (error "AUCTeX does not seem to be loaded"))
  341. (add-to-list 'TeX-command-list
  342. '("Sweave" "R CMD Sweave %t"
  343. TeX-run-command nil (latex-mode) :help
  344. "Run Sweave") t)
  345. (add-to-list 'TeX-command-list
  346. '("LaTeXSweave" "%l %(mode) %s"
  347. TeX-run-TeX nil (latex-mode) :help
  348. "Run LaTeX after Sweave") t)
  349. (setq TeX-command-default "Sweave")
  350. (mapc (lambda (suffix)
  351. (add-to-list 'TeX-file-extensions suffix))
  352. '("nw" "Snw" "Rnw")))
  353. (defun ess-swv-remove-TeX-commands (x)
  354. "Helper function: check if car of X is one of the Sweave strings"
  355. (let ((swv-cmds '("Sweave" "LaTeXSweave")))
  356. (unless (member (car x) swv-cmds) x)))
  357. (defun ess-swv-plug-into-AUCTeX ()
  358. "Add commands to AUCTeX's \\[TeX-command-list] to sweave the current noweb
  359. file and latex the result."
  360. (if ess-swv-plug-into-AUCTeX-p
  361. (add-hook 'Rnw-mode-hook 'ess-swv-add-TeX-commands)
  362. (remove-hook 'Rnw-mode-hook 'ess-swv-add-TeX-commands)
  363. (setq TeX-command-list (mapcar 'ess-swv-remove-TeX-commands TeX-command-list)
  364. ;; this will remove the items, leaving nils, so remove them.
  365. TeX-command-list (delq nil TeX-command-list))))
  366. ;; as ess-swv-plug-into-AUCTeX-p is customizable ... :
  367. (if ess-swv-plug-into-AUCTeX-p
  368. (eval-after-load "tex" '(ess-swv-plug-into-AUCTeX)))
  369. (defun ess-swv-toggle-plug-into-AUCTeX ()
  370. "Toggle inclusion of commands to sweave noweb files and latex the results in
  371. \\[TeX-command-list] on and off. Commands are added via \\[Rnw-mode-hook]."
  372. (interactive)
  373. (unless (and (featurep 'tex-site) (featurep 'tex))
  374. (error "AUCTeX are not available"))
  375. (setq ess-swv-plug-into-AUCTeX-p (not ess-swv-plug-into-AUCTeX-p))
  376. (ess-swv-plug-into-AUCTeX)
  377. (TeX-normal-mode t)
  378. (if ess-swv-plug-into-AUCTeX-p
  379. (message "Sweave and LaTeXSweave are activated in AUCTeX.")
  380. (message "Sweave and LaTeXSweave are de-activated in AUCTeX.")))
  381. ;;; Now bind some keys.
  382. (define-key ess-noweb-minor-mode-map "\M-ns" 'ess-swv-sweave)
  383. (define-key ess-noweb-minor-mode-map "\M-nT" 'ess-swv-tangle)
  384. (define-key ess-noweb-minor-mode-map "\M-nl" 'ess-swv-latex)
  385. (define-key ess-noweb-minor-mode-map "\M-np" 'ess-swv-PS)
  386. (define-key ess-noweb-minor-mode-map "\M-nP" 'ess-swv-PDF)
  387. (define-key ess-noweb-minor-mode-map "\M-nr" 'ess-swv-knit)
  388. (define-key ess-noweb-minor-mode-map "\M-nu" 'ess-swv-purl)
  389. (define-key ess-noweb-minor-mode-map "\M-nv" 'ess-swv-weave-PDF)
  390. (define-key ess-noweb-minor-mode-map "\M-nw" 'ess-swv-weave); depends on proc.
  391. (define-key ess-noweb-minor-mode-map "\M-nx" 'ess-insert-Sexpr)
  392. ;; AND add these to the noweb menu we have anyway ! :
  393. (easy-menu-define ess-swv-menu
  394. ess-noweb-minor-mode-menu
  395. "Submenu for use in `Rnw-mode'."
  396. '("Sweaving, Tangling, ..."
  397. ["Sweave" ess-swv-sweave t]
  398. ["Tangle" ess-swv-tangle t]
  399. ["LaTeX" ess-swv-latex t]
  400. ["PDF(LaTeX)" ess-swv-PDF t]
  401. ["PS (dvips)" ess-swv-PS t]
  402. ["Knit" ess-swv-knit t]
  403. ["Purl" ess-swv-purl t]
  404. ["View PDF" ess-swv-weave-PDF t]
  405. ["Weave (Sweave/Knit)" ess-swv-weave t]
  406. ["Insert Sexpr" ess-insert-Sexpr t]
  407. ["AUCTeX Interface" ess-swv-toggle-plug-into-AUCTeX
  408. :style toggle :selected ess-swv-plug-into-AUCTeX-p]
  409. ))
  410. (easy-menu-add-item ess-noweb-minor-mode-menu
  411. nil ;; <= path
  412. ess-swv-menu)
  413. ; provides
  414. (provide 'ess-swv)
  415. ;;; ess-swv.el ends here