Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Configuration and Plugins

Autocommands and Vim Script

Make Vim react to events with autocommands and augroup, and learn the Vim script basics (variables, lists, functions, user commands) needed to read and write a vimrc.

Two features turn a static vimrc into something that reacts: autocommands (run this when that happens) and Vim script (a small language for variables, conditions, functions and commands). This lesson covers enough of both to read other people's configs and write your own helpers.

Autocommands

An autocommand runs a command when an event occurs.

VIM
autocmd BufWritePre *.py :%s/\s\+$//e

The parts are: the event (BufWritePre, just before a buffer is written), a pattern that must match the file name (*.py), and the command. This one removes trailing whitespace from Python files on every save. (The e flag avoids an error when there is nothing to remove.)

Common events:

Event When
BufReadPost After reading a file into a buffer
BufWritePre / BufWritePost Before / after writing
BufEnter / BufLeave Entering / leaving a buffer
FileType The file type was detected or set
VimEnter Startup is done
InsertEnter / InsertLeave Entering / leaving insert mode
TextYankPost After a yank (highlight what was copied)
CursorHold Cursor idle for updatetime
FocusGained The terminal window got focus

:help autocmd-events lists them all.

The most important rule: use an augroup

Each time you :source your vimrc, plain autocmd lines add duplicates. After ten reloads the command runs ten times. The cure is a named group that you clear first:

VIM
augroup my_config
  autocmd!
  autocmd BufWritePre *.py :%s/\s\+$//e
  autocmd FileType yaml setlocal shiftwidth=2
  autocmd TextYankPost * silent! lua vim.highlight.on_yank()
augroup END

autocmd! inside the group deletes everything the group had, so sourcing again leaves exactly one copy. (The lua line works only in Neovim; remove it in Vim.) Name groups after what they do: my_config, trim_whitespace, restore_cursor.

JS Stand-in: an autocommand dispatcher

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Vim script basics

Vim has had its own language since the beginning. A newer dialect, Vim9 script, is faster and stricter and is used in newer Vim plugins. Your vimrc normally uses the classic syntax shown here. Neovim favors Lua instead (the Lua lesson covers it).

Variables and scopes

VIM
let name = "Ada"
let count = 3
let g:my_option = 1      " global
let b:local = "buffer"   " buffer-local
let &tabstop = 4         " set an option as a variable
let @a = "text"          " set register a
echo name . " has " . count   " . joins strings

Prefixes: g: global, b: buffer, w: window, t: tab, s: script, l: function-local, a: function argument, v: Vim predefined. Inside a function, a variable with no prefix is local.

Lists, dictionaries, control flow

VIM
let fruits = ['apple', 'pear']
call add(fruits, 'plum')
let ages = {'ann': 31, 'bob': 28}

for f in fruits
  echo f
endfor

if has('nvim')
  echo 'Neovim'
elseif has('win32')
  echo 'Windows Vim'
else
  echo 'Vim'
endif

Lists are indexed from 0. len(), join(), split(), map(), filter(), sort() and get() are the functions you use most. has('feature') and exists('*name') check what the editor supports.

Functions and commands

VIM
function! s:TrimTrailing() abort
  let l:view = winsaveview()
  keeppatterns %s/\s\+$//e
  call winrestview(l:view)
endfunction

command! Trim call s:TrimTrailing()
nnoremap <silent> <leader>t :Trim<CR>

function! (with the bang) replaces an existing function so reloading works. The s: prefix keeps it private to the file; user functions without a prefix must start with a capital letter. abort stops at the first error. winsaveview() and winrestview() keep the cursor from jumping. command! defines your own Ex command, which must also start with a capital.

:execute and :normal

:execute "normal! gg=G" builds a command from a string. :normal! keys plays keys as normal-mode commands (the bang avoids user mappings). :%normal Atext appends "text" to every line, :g/pattern/normal dd deletes matching lines with a command.

JS Stand-in: what TrimTrailing does

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debugging

  • :messages shows recent messages and errors; :echo and :echom print values (the second saves to the message history).
  • :verbose plus a command shows where something was set.
  • vim -V9vimlog logs everything that startup does into a file.
  • :breakadd and :debug exist for step debugging, but echom is usually enough.
  • Read errors from the bottom up: the last line names the file and line number of the failure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why wrap autocmd lines in an augroup that starts with autocmd!?

    autocmd! clears the group's old entries, so reloading leaves exactly one copy of each autocommand.
  2. 2. Which variable scope prefix means buffer-local?

    b: is buffer-local; g: global, s: script-local, a: a function argument.
  3. 3. What does command! Trim call s:TrimTrailing() create?

    User commands must start with an uppercase letter and are called as :Trim.
  4. 4. Which event fires just before a buffer is saved?

    BufWritePre is the right place for formatting or trimming whitespace.

Summary

  • autocmd Event Pattern Command reacts to events; always put it in an augroup with autocmd!.
  • Vim script has scoped variables (g:, b:, s:), lists, dictionaries, if, for, functions and command!.
  • :normal, :execute and :g let you reuse editing keys inside scripts.
  • Debug with :messages, :verbose and echom.

Next: Plugins and Packages