I am trying to write a yasnippet to insert code chunks into an R Markdown file. I use polymode to have multiple major modes (markdown, ESS[S]) in a single file. This is my snippet:

# -*- mode: snippet -*-
# name: chunk
# key: chunk
# --
\`\`\`{r $1}

When I try to insert the snippet into a .Rmd file in markdown mode, I get this error:

Error in post-command-hook (yas--post-command-handler): (error "Marker points into wrong buffer" #<marker at 7 in test.Rmd>)

The snippet does appear and my cursor is in the correct spot (right before the second curly brace):

```{r }


When I hit tab I get the following:

yas-next-field: Wrong type argument: overlayp, nil

I am guessing that I'm running into an interaction with polymode: I'm in markdown mode when I insert the snippet, but then polymode converts the contents of the code chunk to ESS[S] mode. It looks like there will eventually be a command to insert a new chunk in polymode, but in the meantime is there any way to get this snippet working?

1 Answer 1


I ran into a similar issue, and wrote a stand-alone function to get around the weird interactions between yasnippet and polymode.

The following function mimics the behaviour of the snippet you tried, prompting first for the header info, which gets inserted at your $1, and then dropping you in the chunck body (your $0):

(defun tws-insert-r-chunk (header) 
  "Insert an r-chunk in markdown mode. Necessary due to interactions between polymode and yas snippet" 
  (interactive "sHeader: ") 
  (insert (concat "```{r " header "}\n\n```")) 
  (forward-line -1))
  • Thanks for this. I'm an avid emacs user but familiar with lisp, Can you describe how you implement this function Rmd workflow??
    – chandler
    Jan 28, 2017 at 13:51
  • 4
    Put the code in your .emacs file, so it gets loaded every time you start Emacs. Then you can call it via M-x tws-insert-r-chunk. Probably you will want to bind this command to a keyboard shortcut - there are lots of questions here about setting keybindings.
    – Tyler
    Jan 28, 2017 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.