Can I use vim highlighting code in R markup?

Say I have a file .Rmd:

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, it looks like this:

enter image description here

It would be great if I could tell vim that a piece Ris actually code Rthat it can allocate in the same way as when working in the actual file .R.

Is it possible?

+4
source share
2 answers

Yes, you can. This code is taken from here .

Put this in a file ~/.vim/r.vim(if any of these files does 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 the r.vim syntax file exists.

You can also call this method automatically every time you open the .Rmd file:

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

r, , :

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

.vimrc:

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

.* . , r.* r, .

```{r whatever you want to put here}`
    Some r code here
```
+10

SyntaxRange, Vim @Zach. .

(, ~/.vim/ftplugin/markdown.vim):

call SyntaxRange#Include('^````{r}', '^````', 'r', 'SpecialComment')
+4

All Articles