Sweave Syntax Highlighting in vim


Tags: R-Project, Open Source, Linux.

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:

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:

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:

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.



Last update date: 2006-11-27.
Creation date: 2005-01-16.

Send your comments


E-mail: Name: