Hidden characters in Vim

Here’s a feature that most code editors have: the ability to show “hidden” characters. This usually means spaces, tabs and return characters. With Vim, this is really easy. In fact, you can show spaces, non-breaking spaces, tabs, return characters, trailing spaces and more. And you can choose which character you want to use for each one of these things.

This is useful when you import or use someone else’s file or copy and paste some code. Maybe you use spaces and you want to check to make sure this new code you added isn’t using tabs. Another use case: the eslint setup I use at work does not allow you to add trailing spaces to the end of a line, so it’s nice to be able to quickly check for them visually - and have them look different than other spaces, so they really stand out.

To turn on the visibility of these normally hidden characters, type the following:

1
:set list

To turn them off, type:

1
:set nolist

Or to toggle them off and on, type:

1
:set list!

That last one makes a useful shortcut. I have it set up something like this in my Vim config:

1
nnoremap <Leader>l :set list!<CR>

Now, by default, this might not show anything at all. You’ll probably have to specify what characters you want to use for each hidden character you would like to see. This is done with the listchars setting. Here’s what I have:

1
set listchars=tab:→\ ,eol:↲,nbsp:␣,trail:✗,space:·

It’s a simple comma-delimited list with the name of the hidden character, a colon, and the character you want to show in its place.

I have characters for tab, end of line (return character), trailing spaces and regular spaces. Note that tab uses two characters. The first character is shown where the actual tab character is. The second character is repeated as many times as necessary to fill up the space that the tab takes up. I have →\ - the arrow, plus an escaped space - so it only shows the arrow, like this:

1
2
····Great!·This·line·starts·with·spaces!↲
→ Oh·no!·This·line·starts·with·a·tab!↲

You might want to use something like →-, which would fill the rest of the space with hyphens:

1
2
····Great!·This·line·starts·with·spaces!↲
→---Oh·no!·This·line·starts·with·a·tab!↲

To me, the empty space after the tab stands out better, but to each their own.

Also note that I have a nice for trailing spaces so it really stands out:

1
This·line·has·trailing·spaces!✗✗✗↲

You can use a wide range of characters, including lots of common unicode symbols. Type :digraphs to get some inspiration. Note, however, that you should only use single width characters and should not use : or , as those are used in the definition itself. Sadly, this means you probably can’t use 💩 for your tab characters.

See :help listchars for more information on other hidden characters you can display. Some of them might be useful for your workflow.