[ESS] Inserting Rmd chunk delimiters

Kevin Wright kw.stat at gmail.com
Fri Feb 20 23:42:33 CET 2015

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.


(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)))
              (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)))
          (goto-char end)
          (forward-line) ; region-end seems to be at start of previous line ???
          (insert "```\n")
          (goto-char beg)
          (insert "```{r}\n") ) ) ) )

Kevin Wright

More information about the ESS-help mailing list