Using Vim for YAML editing

Recently, I was taking an online course in preparation for the Kubernetes exam. In the labs I had an broken Kubernetes configuration which I needed to fix only by editing it using Vim. Every time the lab started the environment was created from scratch and I had limited time to fix the problem and close the lab.

From the editing tools I had only preinstalled Vim so I had to use this tool for yml editing. I am not new to Vim itself, but after several tries and failed labs I realized how inconvenient default Vim is for yml editing. To deal with this, I did some quick research on what settings I should change in order to make yml editing easier. I came up with clear requirements in my head about which settings and configurations I could use and which did not.

Easy to remember

The list of pre-set settings should be as small as possible. I will not be able to remember every possible macros and setting.

Use only default settings

Since I don't know which Vim version is installed on the machine I have to stick to the default and most common settings.

No plugins

Since we don't know which Vim version will be installed, installation of particular plugins can be impossible and finding an alternative can be time consuming.

List of settings

In my case only three settins are needed to be set up prior editing:

:set paste

By enable this setting pasted content formatting will stay untouched, which is critical for pasting a yml content

:set shiftwidth=2

When you move(<< or >>) block of text shiftwidth tells by how many spaces it will move it by. For yml it is used 2 spaces for indention.

:set autoindent

Save indentions of previous line. When you press enter it's better to stay on the same column as before.

If you want you Vim to remember those setting between Vim sessions, create a file in the home directory like this:

touch ~/.vimrc

and put all three lines in the file, so it looks like this:

set paste
set shiftwidth=2
set autoindent

Useful tips with editing

Moving block of text

Moving block of code is quite easy one. You will need to select block of code with Shift + V and j or k and then by pressing > or < it will move it (by shiftwidth number). Then if you want to repeat it hit . or revert it by u

Commenting block of code

  • ctrl+v
  • use navigation keys to select lines you want (includes current cursor row)
  • Shift+i
  • insert #
  • press Esc

Uncommenting block of code

  • ctrl+v
  • use navigation keys to select lines you need to uncomment
  • press x


Essentially, just having those three settings configured was enough for me to get through the quick and occasional yml editing.