[ESS] Inserting Rmd chunk delimiters
Laurent Gatto
|g390 @end|ng |rom c@m@@c@uk
Fri Feb 20 23:56:07 CET 2015
I have defined the following functions:
(defun insert-md-code-chunk ()
"Insert Rmd code chunk"
(interactive)
(insert "```\n\n```")
(backward-char 4))
(defun insert-rmd-code-chunk ()
"Insert Rmd code chunk"
(interactive)
(insert "```{r}\n\n```")
(backward-char 4))
(defun insert-rnw-code-chunk ()
"Insert Rnw code chunk"
(interactive)
(insert "<<>>=\n\n@")
(backward-char 2))
(defun insert-org-code-chunk ()
"Insert Rnw code chunk"
(interactive)
(insert "#+BEGIN_SRC R :session *R*\n\n#+END_SRC")
(backward-char 10))
(defun insert-code-chunk ()
"Insert appropriate code chunk based on buffer extension"
(interactive)
(pcase (file-name-extension (buffer-file-name))
(`"Rnw" (insert-rnw-code-chunk))
(`"org" (insert-org-code-chunk))
(`"Rmd" (insert-rmd-code-chunk))
(`"md" (insert-md-code-chunk))
(code (message "Unknown buffer extension"))))
and bound the last one to C-c, which then inserts the appropriate code
chunks delimiters in Rnw, org, Rmd and md file. Comments most welcome.
Best wishes,
Laurent
On 20 February 2015 22:42, Kevin Wright wrote:
> I think it would be nice for Rmd buffers to have an electric-backtick
> function that auto-inserts the chunk delimiters for R chunks, similar
> to the way that Rnw files can auto-insert the R chunk delimiters <<>>=
> @.
>
> In the meantime, I hard-coded ctrl-backtick to insert the delimiters,
> wrapping the delimiters around the current region if it is active.
>
> I don't really grok lisp, so this code is horrible, but it more or less works.
>
> Improvements would be welcome.
>
> Kevin
>
>
> (global-set-key (kbd "C-`") 'ess-insert-rmd-chunk)
>
> ; Some code derived from wrap-region
> ; https://github.com/rejeep/wrap-region.el/blob/master/wrap-region.el
> (defun ess-insert-rmd-chunk (arg)
> "Insert R chunk delimiters"
> (interactive "*P")
> ;; no region, and blank line
> (if (and (not (region-active-p))
> (looking-at "[ \t]*$"))
> (let ((pos (point)))
> (save-excursion
> (insert "```{r}\n\n```")
> (goto-char (+ pos 3) ) ) ) ) ; does NOT move forward. Why?
> ;; region active
> (if (region-active-p)
>
> (let ((beg (region-beginning))
> (end (region-end))
> (pos (point)))
> (save-excursion
> (goto-char end)
> (forward-line) ; region-end seems to be at start of previous line ???
> (insert "```\n")
> (goto-char beg)
> (insert "```{r}\n") ) ) ) )
More information about the ESS-help
mailing list