Automatic Run Command Per Action

vimrc actually allows you to configure automatic command execution per your action. The line is:

autocmd [action] [path/to/file OR pattern] [command] [passable-variables]

Hence, some examples are:

autocmd BufWritePost *.go !gofmt -w -s %:p
autocmd BufWritePost *.go !clear && golangci-lint run --color never --enable-all %:p:h
autocmd BufWinEnter * match Warning /\s\+$/
autocmd InsertEnter * match Warning /\s\+\%#\@<!$/
autocmd InsertLeave * match Warning /\s\+$/
autocmd BufWinLeave * call clearmatches()

Action

You can get the list of action via the vim help autocmd. Here is the full link: http://vimdoc.sourceforge.net/htmldoc/autocmd.html. Based on the examples above, we have:

  • BufWritePost - write to file
  • BufWinEnter - after buffer displayed in windows
  • InsertEnter - start inserting mode (write)
  • InsertLeave - exit inserting mode (write)
  • BufWinLeave - before buffer leaves the windows

Pick the right action you want the autocmd to run.

Path/to/File OR Pattern

This is for filtering when to trigger the autocmd. You can either provide a path/to/file or a pattern. Based on the examples above:

  • *.go - run autocmd on all files with .go extensions.
  • * - run autocmd on all files.

Command

This is the command you want to execute automatically. It can be vim specific commands or calling an external shell commands using the exclamation mark (!). Based on the examples above:

  • !gofmt -w -s - calling external shell command called gofmt alongside its arguments -w and -s.
  • match Warning /\s\+$/ - calling vim configurations to apply the settings named Warning.
  • call clearmatches() - calling an vim internal function called clearmatches()

Passable Variables

These are known filename-modifiers, available at this link: http://vimdoc.sourceforge.net/htmldoc/cmdline.html#filename-modifiers or :help filename-modifiers in vim. Sometimes, some external commands might need you to feed some parameters into it (e.g. path to filename or its residing directory). A quick pattern would be:

%:p                     /home/mool/vim/src/version.c
%:p:.                                  src/version.c
%:p:~                            ~/vim/src/version.c
%:h                                    src
%:p:h                   /home/mool/vim/src
%:p:h:h                 /home/mool/vim
%:t                                        version.c
%:p:t                                      version.c
%:r                                    src/version
%:p:r                   /home/mool/vim/src/version
%:t:r                                      version
%:e                                             c
%:s?version?main?                      src/main.c
%:s?version?main?:p     /home/mool/vim/src/main.c
%:p:gs?/?\\?            \home\mool\vim\src\version.c

Based on the example above, we got:

  • %:p - path to currently opened file
  • %:p:h - path to directory having currently opened file

That's all about autocmd in vim.