Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have vim highlight code in R markup?

Tags:

vim

r

Say I have an .Rmd file like this:

The total number of steps per day can also be calculated
using `tapply`.
```{r}
tapply(d$steps, INDEX=d$date, FUN=sum)[1:5]
```
What seems to be different is that, per default, `xtabs`
returns 0 for `NA` values and `tapply` returns `NA`.

In my terminal window, this looks like this:

enter image description here

It would be great if somehow I could inform vim that the R chunk is actually R code which it could highlight just as it does when working in an actual .R file.

Is this possible?

like image 537
TMOTTM Avatar asked Dec 08 '22 06:12

TMOTTM


2 Answers

Yes you can. This code is taken from here.

Put this in the ~/.vim/r.vim file (if any of these files do not exist, create them)

function! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
  let ft=toupper(a:filetype)
  let group='textGroup'.ft
  if exists('b:current_syntax')
    let s:current_syntax=b:current_syntax
    " Remove current syntax definition, as some syntax files (e.g. cpp.vim)
    " do nothing if b:current_syntax is defined.
    unlet b:current_syntax
  endif
  execute 'syntax include @'.group.' syntax/'.a:filetype.'.vim'
  try
    execute 'syntax include @'.group.' after/syntax/'.a:filetype.'.vim'
  catch
  endtry
  if exists('s:current_syntax')
    let b:current_syntax=s:current_syntax
  else
    unlet b:current_syntax
  endif
  execute 'syntax region textSnip'.ft.'
  \ matchgroup='.a:textSnipHl.'
  \ start="'.a:start.'" end="'.a:end.'"
  \ contains=@'.group
endfunction

Now you can use

:call TextEnableCodeSnip(  'r',   '```{r}',   '```', 'SpecialComment')

As long as there is an r.vim syntax file.

You could also automatically call this method every time you open a .Rmd file:

autocmd BufNewFile,BufRead *.Rmd :call TextEnableCodeSnip(  'r',   '```{r}',   '```', 'SpecialComment')

If you wanted to highlight with r followed by any number of characters you can use regular expressions:

:call TextEnableCodeSnip(  'r',   '```{r.*}',   '```', 'SpecialComment')

Or in your .vimrc:

autocmd BufNewFile,BufRead *.Rmd :call TextEnableCodeSnip(  'r',   '```{r.*}',   '```', 'SpecialComment')

The .* regular expression means any repeating character. So r.* means r followed by any number of characters.

Therefore this will work with

```{r whatever you want to put here}`
    Some r code here
```
like image 133
Zach Avatar answered Dec 10 '22 19:12

Zach


You might also be interested in my SyntaxRange plugin, which is based on the Vim Tip in @Zach's answer. It simplifies the setup of such syntax regions.

The setup would be like this (e.g. in ~/.vim/ftplugin/markdown.vim):

call SyntaxRange#Include('^````{r}', '^````', 'r', 'SpecialComment')
like image 34
Ingo Karkat Avatar answered Dec 10 '22 20:12

Ingo Karkat