Fix R syntax highlighting in vim

One little annoyance of editing R scripts with vi is the syntax highlighting for newly created ‘.R’ files is all wrong.  The reason is by default vi opens new files with a ‘.R’ extension as a ‘rexx’ filetype instead of an ‘r’ filetype.  Presumably vi’s default behavior was conceived back when R was not the enormously popular statistical programming language it is today.

If you save a ‘.R’ file with some code and some comments and then re-open it vim is usually smart enough to detect the correct filetype, but a more elegant fix is to specify the filetype for new files with a ‘.R’ extension.  The incorrect syntax highlighting can be corrected by putting this snippet into ~/.vim/filetype.vim to specify the filetype for new ‘.R’ files:

if exists("did_load_filetypes")                                                 
  finish                                                                        
endif                                                                           
augroup filetypedetect                                                          
  au BufNewFile,BufRead *.r,*.R setf r                                          
augroup END  

Leave a Reply