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 fileBufWinEnter
- after buffer displayed in windowsInsertEnter
- 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
- runautocmd
on all files with.go
extensions.*
- runautocmd
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 calledgofmt
alongside its arguments-w
and-s
.match Warning /\s\+$/
- calling vim configurations to apply the settings namedWarning
.call clearmatches()
- calling an vim internal function calledclearmatches()
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.