This is the in-depth vimscript guide. If you’re just a casual user looking to write a plugin, the abbreviated style guide is for you.
This rather rotund guide dives into justifications and clarifications. It provides an idealized set of rules that are rather too draconian to push on casual scripters.
It’s for users who want to know why certain decisions were made in the abbreviated guide and who want to learn a thing or two about using vimscript safely.
Fair warning: Vimscript is a maddening abyss. When you gaze into it, it gazes also into you. Proceed with caution.
Vim is highly configurable. Users can change many of the default settings, including the case sensitivity, the regular expression rules, the substitution rules, and more. In order for your vimscript to work for all users, follow these guidelines:
Always prefix regular expressions with one of \m, \v, \M, or \V
(prefer tersity)
., *,
and {.magic setting you must prefix it with one of the magic
control atoms. This future-proofs your regular expression against other
devs modifying it and forgetting to add the control atom.substitute())
since it makes the pattern self-contained and future-proofs against the
same pattern being used in other contexts.Avoid using :s[ubstitute] in scripts.
:substitute moves the cursor.:substitute outputs an error message when the match does not exist.g flag depends upon the gdefault setting. If you
do use :substitute you must save gdefault, set it to 0 or 1,
perform the substitution, and then restore it.maktaba#buffer#Replace.Always use case-explicit operators for strings (=~# and =~?, never
=~).
!~ == != > >= < <= is and isnot.== and >= are fine for numbers, but
==# and >=# must be used for comparing values that may be strings.=~ and friends is dependant upon the ignorecase
setting.ignorecase setting. Be prepared to justify your reasoning.When using regular expressions as arguments to functions, prepend them with
\c or \C.
=~#, etc.).ignorecase setting.ignorecase setting. Be prepared to justify your reasoning.Always use normal! instead of normal.
! the command will use the user’s key mappings and
you have literally no idea what your macro will do.Always use the noremap family of commands.
map command respects the users existing mappings and could do
anything.When using catch, match the error code rather than the error text.
:help error-messages.In general, guard all commands and functions against user settings.
Line continuations: Yes
Exceptions: Yes, with caution
maktaba#error codes found in maktaba.:help error-messages.maktaba#error#Message.Public user commands and functions should catch and echo known errors
(via echomsg or maktaba#error#Shout) before they reach the user.
try
call somelibrary#FuncThatCanFail()
catch /ERROR(NotFound):/
call maktaba#error#Shout('Failed to do thing: %s', v:exception)
endtry
@throws directive.Global Variables: As configuration only
Messaging: As little as possible.
Type checking: Use strict and explicit checks where possible.
0 == 'foo' evaluates to true.is# operator. Otherwise, prefer
maktaba#value#IsEqual or check type() explicitly.maktaba#ensure, or check maktaba#value or type() and throw your
own errors.:unlet for variables that may change types, particularly those
assigned inside loops.FuncRefs: No in most cases.
maktaba#function instead to create and manipulate
handles to functions.Python: Sparingly
Ruby: No
Lua: No
Dict Functions: Encouraged
self parameter which access the dict state.All other language features are fair game.
Provided functionality should be packed into modular plugins.
maktaba.plugin-names-like-this
Each plugin must consist of one directory (or code repository), sharing a name with the plugin (with a “vim-“ prefix or “.vim” suffix if desired).
Plugin metadata should be declared in the addon-info.json format (see the VAM documentation for details).
Functions should go in the autoload/ subdirectory of your plugin.
Each file in the plugin/ or instant/ directory should begin with the
boilerplate
let [s:plugin, s:enter] = maktaba#plugin#Enter(expand('<sfile>:p'))
if !s:enter
finish
endif
(This prevents re-entry and allows users to selectively disable functionality.)
User configuration should be via plugin flags defined in
instant/flags.vim.
call s:plugin.Flag('FLAGNAME', DEFAULT_VALUE).:Glaive command (see
glaive).Commands, autocommands, mappings, and settings changes should occur either
in the plugin/ or the ftplugin/ subdirectories.
plugin/commands.vim or ftplugin/
files.plugin/autocmds.vim, inside an
augroup.plugin/mappings.vim and will be disabled
unless explicitly enabled by users.plugin/settings.vim or instant/settings.vim.Avoid using the after/ subdirectory.
after/ should be reserved for the user.after/.Separate library-providing plugins from command-providing plugins.
Many plugins provide either user functionality (commands, autocommands, etc) or an API (of autoloaded functions) but not both. This separation is encouraged, as it allows other plugins to pull in a library without also pulling in commands, setting changes, and other plugin functionality that affects the end user.
Don’t clobber user settings. Provide as much configurability as possible: that’s what Vim’s all about.
Use maktaba flags for plugin configuration. Users can configure them using
the :Glaive command.
Check if configuration variables exist before setting them.
if !exists('g:myplugin_option')
let g:myplugin_option = 1
endif
Follow google-wide style conventions. Mimic google python style when in doubt.
Use vimdoc.
Provide help files generated by vimdoc. Write documentation in .vim files in conformance with the vimdoc standards and include fields like “description” and “author” in the addon-info.json file (see the VAM documentation).
Follow google-wide conventions.
Use spaces around operators except for arguments to commands.
Using spaces around operators for commands is often invalid syntax. This is inconsistently enforced by vimscript. To be safe, always omit whitespace around arguments to commands.
let s:variable = "concatenated " . "strings"
command -range=% MyCommand
let s:variable="concatenated "."strings"
command -range = % MyCommand
Do not introduce trailing whitespace.
Restrict lines to 80 columns wide.
Indent continued lines by four spaces.
let l:something = SomeReallyLongFunctionName(
\ 'arg1', 0, ['XXXXX'], {'somekey': 9999999999})
Do not waste whitespace aligning common segments of similar commands. It is both difficult and expensive to maintain.
command -bang MyCommand call myplugin#foo()
command MyCommand2 call myplugin#bar()
command -bang MyCommand call myplugin#foo()
command MyCommand2 call myplugin#bar()
Prefer line continuations on semantic boundaries.
command SomeLongCommand
\ call some#function()
command SomeLongCommand call
\ some#function()
Use your best judgement.
Place one space after the backslash denoting a line continuation.
When continuing a multi-line command a pipe can be substituted for this space as necessary, as follows:
autocommand BufEnter <buffer>
\ if !empty(s:var)
\| call some#function()
\|else
\| call some#function(s:var)
\|endif
Do not continue multi-line commands when you can avoid it. Prefer function calls.
Place a space after the " before the comment text.
" I am a line comment.
call call(s:my_function)
Do not use inline comments.
When leaving blank lines in comments, include the quote in the blank line.
" I am one continuous
"
" comment block
plugin-names-like-this, FunctionNamesLikeThis, CommandNamesLikeThis,
augroup_names_like_this, variable_names_like_this. Prefix all variables with
their scope.
variable_names_like_this
Prefix global variables with g:
autoload directories.Prefix script-local variables with s:
Prefix function arguments with a:
Prefix function-local variables with l:
l: disambiguates between function-local and vim-predefined variables.
For example, count refers to v:count, not l:count.Prefix pre-defined vim variables with v:
Prefix buffer-local or window-local variables with b: or w:
Prefer single quotes.
Prefer single quoted strings. Specifically, in order of precedence:
Always use single quotes for regular expressions.
'\s*' is not the same as "\s*"'example ('')' represents the string example (')If your string requires escape characters (\n, \t, etc.) use double
quotes.
'\n' in a regex does not represent a newline, but rather
“\n”. You only need to use double quotes when you want to embed the
represented character itself (e.g. a newline) in the string.If your string contains no escapes nor single quotes, use single quoted strings.
If your non-regex string contains single quotes but no double quotes, use double quotes.
If your string contains both single and double quotes, use whichever quoting style requires less escaping.
Prefer long names. Set settings locally.
tabstop over ts).Set local settings unless you explicitly want to set global settings.
setlocal and &l: instead of set and &.Vim plugins should provide any or all of the following: Commands, Autocommands, Functions, Statusline Flags, and Mappings.
plugin/commands.vim.[!]Extract logic into functions.
CommandNamesLikeThis
Commands should be defined in one block with no whitespace between them.
Name commands semantically at the expense of a common prefix.
command WhitespaceFixTrailing
command WhitespaceFixIndentation
command FixTrailingWhitespace
command FixIndentation
Use command without a bang.
Do not put logic in commands.
<bang>, <register>, etc.)
before argument parameters (<f-args>, etc.).Do not autoload commands.
instant/commands.vim file in plugins using maktaba, or explicitly
installed via an autoload function in non-maktaba plugins.Pass <bang> to functions with '<bang>' == '!'.
plugin/autocmds.vim.augroup_names_like_this.Extract logic into functions.
All autocommands should be defined in the plugin/autocmds.vim file.
Glaive myplugin
!plugin[autocmds].Declare all autocommands in an augroup block.
This allows your autocommands to be cleared with autocmd!.
If your plugin only has one augroup, the augroup name should be the
same as your plugin name, with underscores in place of any hyphens.
Otherwise augroup names should start with your plugin name followed by
an underscore.
Do not put logic in autocommands.
When creating a new augroup, clear it with autocmd!
s:[!].Use [abort].
FunctionNamesLikeThis
s:Do not provide global functions. Use autoloaded functions instead.
Place two blank lines between top-level functions.
Declare all functions with abort.
try..endtry block somewhere on the stack.abort keyword forces the function to act consistently.Use function! with a bang.
autoload directory.Use ... for optional arguments, not for lists of arguments.
... for a list of arguments.Throw exceptions rather than printing errors.
plugin/mappings.vim.<Plug> mappings can be defined in plugin/plugs.vim (unlike mappings.vim,
plugs.vim is opt-out).
Define key mappings in plugin/mappings.vim, using
maktaba#plugin#MapPrefix to get a prefix.
plugin/mappings.vim file will be
disabled by default (by the standard maktaba#plugin#Enter()
boilerplate).Glaive myplugin plugin[mappings].Make all mappings with <unique>.
You may provide pseudo-mappings using <Plug> and your plugin’s name in
plugin/plugs.vim (separate from standard key mappings).
<Plug> is a sequence which can not be typed.noremap <Plug>namespace#MappingName
some_key_sequence and then users can do `noremap plugin/mappings.vim or they will
be disabled by default.<Plug> followed by your plugin
name, a pound sign, and a unique mapping name (CamelCased like a
function).Always use the noremap family of commands. Never use the map family.
map depends upon the user’s existing mappings, and could do anything.Only use noremap for commands that both make a motion and take a range.
noremap makes mappings in normal, visual, and operator-pending modes.nnoremap onoremap or vnoremap
explicitly.Always use <SID> in place of s: when accessing script locals in
mappings.
s: will often fail as the mapping attempts to type a literal s
and colon.Declare dependencies in addon-info.json and use maktaba.
Declaring dependencies in addon-info.json allows conformant plugin managers (like VAM) to ensure dependencies are installed. See the VAM documentation for details.
Calling maktaba#library#Require from dependent code at runtime ensures that
dependencies have been installed and that they don’t include unsafe non-library
files.
Use <plugin-name>#status#Status() or its finer-grained variants to provide
statusline flags.
Following is a convention for exposing statusline flags to the user. A plugin should never modify the user’s statusline except for when that is the only purpose of the plugin (powerline, etc.).
Info, Alert, Warning, and Error functions under the
<plugin-name>#status namespace.Infoshould provide information about the state of the buffer.
Alert should provide a quiet reminder that the buffer is non-standard.
Warningshould provide a warning about the current state of the buffer.
Error should bring to attention a loud issue with the buffer.
[Google]. For
example:
[$] if the file contains
trailing whitespace[write] if vim is in writing mode.<plugin-name>#status#Status function.
Error, Warning, Alert, or
Info.These are commands which can only be used by a limited number of plugins, and should not in general be used by yours.
:match :2match or :3match
matchadd() to create a matchlevel unique to your plugin.echoerr.
echoerr does not print the red error message that you might think it
does.echoerr prints an error message as well as context about the code
where echoerr was called.echoerr is best suited for debugging.echohl in tandem with echomsg if you want the red error bar.echomsg instead of echo.
echomsg messages can be reviewed with the :messages command.echo messages disappear permanently on redraw, which can be very
annoying to users who failed to read the message in time.Lay out plugin/ files in the following sections, if applicable, separated by
two blank lines:
commands.vim file, autocommands in
autocmds.vim file, etc.)Lay out autoload/ files in the following sections, if applicable, separated by
two blank lines:
maktaba#library#Require callsThis is recommended convention and is not enforced.
Use the following shortcuts:
catch over catch /.*/return over return 0 when the return value has no semantic purpose.This section plumbs some of the darker corners of vimscript, explaining the language pathologies that you wish you didn’t have to know.
If you don’t support vi-compatibility mode, fail gracefully.
When compatible is set, many vim features are not available. The vim feature
which most commonly affects vimscript authors is line continuations.
If you want your plugin to work in vim with vi compatibility on, you will need
to save the compatibility options at the beginning of each plugin file, clear
them, and restore them at the end of each plugin file. See :help use-cpo-save
for details.
Plugins that depend on maktaba generally don’t need to worry about compatible mode since maktaba currently just disables it, printing a warning.