Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple autocommands in vim

Tags:

vim

I've got some sections in my .vimrc that look like this:

autocmd Filetype ruby setlocal ts=2
autocmd Filetype ruby setlocal sts=2
autocmd Filetype ruby setlocal sw=2

now it seems I can convert them to this:

autocmd Filetype ruby setlocal ts=2 sts=2 sw=2

but here's my question: is there a vim way to have a structure like this?

<something mentioning Filetype ruby>
  setlocal ts=2
  setlocal sts=2
  ...
<end>

ie, can the autocmd Filetype bit somehow be made to address a group of actions? (this is a simple example, I'm really asking for more complicated situations.)

like image 376
Peter Avatar asked Sep 11 '09 21:09

Peter


3 Answers

You can call a function, if you like:

autocmd Filetype ruby call SetRubyOptions()
function SetRubyOptions()
    setlocal ts=2
    ...
endfunction
like image 60
Lucas Oman Avatar answered Nov 20 '22 20:11

Lucas Oman


You can chain most commands with |:

au Filetype ruby
            \ setlocal ts=2  |
            \ setlocal sts=2 |
            \ ...

Not sure if this syntax is better or worse than writing a function. Some commands can't be chained like this, but you can use execute to get around that; see :h :bar.

Also see :h line-continuation for an explanation of the weird syntax with the \ at the beginning of the lines.

like image 45
Brian Carper Avatar answered Nov 20 '22 20:11

Brian Carper


ftplugins are the neat answer to your question.

  1. Ensure your .vimrc has a line such as :filetype plugin on
  2. Define a file named {rtp}/ftplugin/{thefiletype}.vim or {rtp}/ftplugin/{thefiletype}/whatever.vim (see :h rtp for more details).
  3. Edit this new file and put your VIM commands in there. It is probably a good idea to use the :setlocal command to ensure filetype-specific settings are only for that file (e.g., don't turn all comments purple across all filetypes).

See examples in vim distribution if you plan to override default settings ; or among the many ftplugins I wrote otherwise), just write down your :setlocal, :*map <buffer>, etc. definitions.

It represents some more line to type, but at least, it does scale.

like image 24
5 revs, 3 users 76% Avatar answered Nov 20 '22 19:11

5 revs, 3 users 76%