I am often writing documents in knitr using vim, which means that I have markdown code mixed with R code. I would like to have R syntax coloring on R chunks, but markdown or no coloring on all the other fragments. Is this doable? How?
1 Answer
As Peter Rincker notes, Vim's standard markdown formatting already includes support for highlighting r
code within a "fenced code block", and to enable it, you just have to set a global variable with code in your vimrc
:
let g:markdown_fenced_languages = ['r']
However, after doing so, you will find that your knitr code blocks are still not highlighted.
This is because knitr uses Pandoc's formatting of info strings in order to differentiate R code that is to be run from a regular code block, and Vim's regular Markdown highlighting doesn't support this1.
The easiest way to fix this is to manually add an extra syntax item to match this type of code block by adding the following line to ~/.vim/after/syntax/markdown.vim
syntax region markdownHighlightr matchgroup=markdownCodeDelimiter start=/^\s*```{r}.*$/ end=/^\s*```\ze\s*$/ keepend contains=@markdownHighlightr
You could also consider installing a Vim plugin for Pandoc highlighting, which would presumably support this out of the box.
1: This can't really be considered an issue in Vim's markdown syntax file. The original Markdown syntax doesn't include fenced code blocks at all, and the CommonMark spec doesn't define how info strings should be formatted.
s:syntax_include
ands:file_type_handler
: github.com/junegunn/dotfiles/blob/master/vimrcg:markdown_fenced_languages
in yourvimrc
e.g. let g:markdown_fenced_languages = ['r']`. I am assuming you are using the default markdown syntax provided by Tim Pope. More on fenced languages