tl;dr In this post I’ll explain the basics of writing a vim plugin, talking about structure and some useful commands.
Getting started
The firs thing to know is that to write a plugin you only need a project with a folder called plugin
and some files with the .vim
extension inside it (on the startup, vim will load those files).
Another, important, thing to know is that a vim plugin is just a bunch of vim commands (this may sound obvious but, ‘cause of ~reasons~, I allways thought that a plugin was some kind of magic spells). For example, if you want to write a plugin that strip trailing whitespaces, you need the following structure
and, inside awesome.vim
and just run :call StripWhiteSpaces()
(or map to something else) and you’re done! (ps: this simple function has some problems, such as: 1) after you execute it will move your cursor to the last line that was modified; 2) if there is no trailing whitespace it will throw an error, because we’are trying to replace a pattern that does not exist. But it is enought to get the idea).
You also can add a folde called doc
(in the same level as plugin
) and add a awesome.txt
there, so people can read the help from vim.
Reading a more complete example
Now lets look at another function that do more stuffs (this example is part of the sort-quire.vim’s plugin):
The s:
and l:
refers to the scope of the function and variables, I wont talk about them here (I
put them there just to tell about their existence), but you can read about scope here.
You need to define the function with a bang in the end (function!
) to replace if it alreaday exists. This may sound strange but, otherwise, everythime (but the first) that this file gets sourced you will get an error, because vim will try to create the function (so it’s a good idea to avoid creating plugin with a name that already exists).
This is a simple example because it deals only with the current file content, to write something that handle external content (eg: write/read from/to another files) you probably won’t want to do that in VimL, you will be better using something else (python, rust, go etc) and interacting with vim through their client api (just google that:), maybe in the future I write a walkthrough about that.
Comments