Sweave Syntax Highlighting in vim

November 27, 2006
By

(This article was first published on fernandohrosa.com.br - en » R, and kindly contributed to R-bloggers)

If you use Sweave and vim, you might have wondered if it’s possible to have it syntax highlight Rnw/Snw files properly : the latex bits with LaTeX syntax and the noweb R chunks with R syntax. It is! Take a look a the screenshot below:

Screenshoot of a syntax-highlighted Sweave file

In order to have this working, you only need to properly configure your vim. First, edit your ~/.vim/filetype.vim, adding the following lines to it:

1
2
3
4
5
augroup filetypedetect
  au! BufRead,BufNewFile *.r         setfiletype r
  au! BufRead,BufNewFile *.R         setfiletype r
  au! BufRead,BufNewFile *.Rnw       setf noweb
augroup END

Then, create a file named ~/.vim/after/syntax/noweb.vim, (create the directories with mkdir, if needed), with the following content:

1
2
3
4
5
6
7
8
9
runtime! syntax/tex.vim
unlet b:current_syntax
 
syntax include @nowebR syntax/r.vim
syntax region nowebChunk start="^<<.*>>=" end="^@" contains=@nowebR
syntax region Sexpr  start="\\Sexpr{"  end="}" keepend
hi Sexpr gui=bold guifg=chocolate2
 
let b:current_syntax="noweb"

For users of Windows (contributed by Gabor Grothendieck)

If you’re running vim under Windows, the directory structure might difer somewhat from the above. On Windows (assuming gvim 6.3), the %VIM%\gvim63 directory should contain:

1
2
3
4
vim.exe
gvim.exe
filetype.vim
syntax\noweb.vim

You should just do the alterations indicated above but you should save the files according to this structure.

That’s it, next time you open a file with extension .Rnw, vim will properly syntax highlight it.

flattr this!

To leave a comment for the author, please follow the link and comment on his blog: fernandohrosa.com.br - en » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.