Vim + YAML

I’ve been cutting my teeth on a K8S stack. That means a lot of YAML.

After some time, there are two things I recommend if you’re working with Vim.

First off, add the following magic line to your .vimrc

autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab indentkeys-=0# indentkeys-=<:> foldmethod=indent nofoldenable

In english, this autocommand will enable Vim to apply a couple of rules to YAML files

  • Skip re-indenting lines after a comment #, after a colon : or at the beginning of a line.
  • ts (tabstop) a <Tab> key will count as two spaces
  • sw (shiftwidth) identation and auto-identation will use two spaces (eg. when using >> or gg=G)
  • sts (softtabstop) a <Tab> will count for two spaces when expanding tabs (inserting a tab, or using the Backspace key)
  • expandttab use spaces instead of tabs
  • foldmethod folding will be based on indentation levels
  • nofoldenable the file will be opened without any folds

You might want to take a look at the Folding page of the Vim wiki. In short, if your cursor is inside a fold-able section, use zc to close a fold, zo to open one, and za to toggle/alternate the current fold. Alternatively, use zM to close or zR to open all folds throughout the file.

Secondly, you could also use mrk21’s yaml-vim plugin. It will enable syntax highlighting, and set indentation settings on its own. Since Vim v8, there’s native support for packages, so you can even avoid using a package manager and just

git clone ~/.vim/pack/plugins/yaml-vim

Oh, and since last post, I’ve joined Beat as a Backend Engineer; I’m more pumped than I’ve been in a long time! : )
But I think this deserves another post of its own (soon).

Optional Reading

Ask HN: What’s in your .vimrc?
:help tabstop
:help softtabstop
:help shiftwidth
:help expandtab
ts/sw/sts explanation

Written on November 22, 2019