As a user of LaTeX, R and Emacs, I naturally write up my research in .Rnw
files, using knitr to produce .tex
sources. With Emacs, this means I have access to both the awesome AUCTeX for writing LaTeX and the excellent ESS environment for the statistics at the same time. However, being the absent-minded academic that I am, I sometimes end up opening the woven .tex
file instead of the .Rnw
and make edits to that, which means it gets overwritten and lost the next time I run knitr
. This is suboptimal, but of course Emacs allows us to fix it.
This can be achieved by advising the relevant function — in this case switch-to-buffer
. The following bit of Elisp code will ask you when you’re trying to switch to a buffer with a .tex
file when there’s a corresponding .Rnw
file open at the some time. It’s not particularly robust (e.g. it doesn’t take cognizance of multiple buffers visiting files of the same name), but it gets the basic job done.
(defun tex-Rnw-check (name)
"When opening a .tex file, check to make sure there isn't a
corresponding .Rnw available, to make sure we don't try to edit
the wrong file."
(when (and (bufferp name)
(buffer-file-name name))
(let* ((rnw-file (format "%s.Rnw" (file-name-sans-extension (buffer-file-name name)))))
(when (and (equal (file-name-extension (buffer-file-name name)) "tex")
(member rnw-file (mapcar #'buffer-file-name (buffer-list))))
(if (yes-or-no-p "You are trying to open a .tex file, but the corresponding .Rnw file seems to be open. Are you sure?")
name
(find-buffer-visiting rnw-file))))))
(defadvice switch-to-buffer (around noweb-check activate)
(let ((buffer-or-name (or (tex-Rnw-check (ad-get-arg 0))
(ad-get-arg 0))))
ad-do-it))
(ad-update 'switch-to-buffer)
This uses the old defadvice
mechanism rather than the new add-function
, but seems to work well enough. (I’m stuck on Emacs 24.3, as later versions seems to have funky bugs with the display of some Unicode characters that I badly need.)
I’m Pavel Iosad, and I’m a Professor in the department of Linguistics and English Language at the University of Edinburgh. ¶ You can always go to the start page to learn more.