Vim Script Best Practices

gmarik 3 min
Table Of Contents ↓

Happy Holidays everyone!

This post has been sitting in my drafts for a while now, so today I finally managed to complete it.

Antipatterns

There are best-practices for all kinds of programming languages but I haven’t seen vim-script’s one.

This post doern’t try to cover actual best practices but rather just “issues” often found when scripting Vim.

1. Copy-pasting

There are number of WIKIs, blog posts, super-duper-vim-configs unintentionally propagating copy-pasting anti-pattern. There’s no particular person to blame for promoting bad practices, rather copy-pasting had been the only solution to a problem of sharing vim-scripts for a while. I’ve gone through lots of vim-configs(just to learn stuff) and find the most popular snippet being copy-pasted is:

" restore last file position
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endi

To me this looks like a quick hack and not something I’d like to see in my .vimrc You can even find that snippet in official help by running :h last-position-jump.

Copy-pasting is bad. I guess every programmer knows this. Imagine your other programming language used copy-pasting as a way to share code…

Anyways, what’s the good solution then?

Use Plugins.

TPope’s pathogen started “Vim plugins revolution”. Getting scripts is becoming easier. For example Vundle lets in your .vimrc have:

" Restore last file position
Bundle 'vim-scripts/last-pos'

instead keeping the script itself. You can even remove the comment above as intent is quite obvious.

2. Bloated .vimrc

If .vimrc has actual code(ie custom functions) along with configuration settings it’s probably a time to look into and extract the code into a plugin. This also applies to any other code sitting in your .vim/, colorscheme, syntax tweaks or custom functions can be easily extracted into a plugin so other people can benefit as well ;)

Create plugins

IMO publishing scripts has never been easier. Just push plugin to github that’s all it takes to let other ppl use it. Pushing to vim.org is still too complicated(and hopefully vim-scripts will fix that soon, you could help too )

For example ide-popup.vim, ingretu colorscheme, sudo-gui.vim are good examples in my case.

Contribute

And if it doesn’t fit into own plugin then maybe you could contribute to already existing one?

Bonuses

Learn by doing

By practicing above you’ll

  1. learn/improve your vim-script fu
  2. let others use your cool ninja stars^W ideas

Atleast that’s how I got started.

Make your vim plugin day

Should we?! )

References

  1. :h help
  2. :h eval
  3. Writing Vim Plugins by Steve Losh
  4. Learn Vim Script The Hard Way by Steve Losh
  5. VimL source codes on Github
Related Posts
Read More
Ruby and Mysql on OSX Snow Leopard
Map as a Presenter pattern and more
Comments
read or add one↓