Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Show Trailing Whitespace in Markdown Files with vim-better-whitespace

show-trailing-whitespace-in-markdown-files-with-vim-better-whitespace.jpg

Trailing whitespace is important in Markdown since having 2 spaces will add a single line break. You may not want to strip that.

Quick Jump:

I’ve been using https://github.com/ntpeters/vim-better-whitespac for a long time which is a very nice plugin to show and automatically strip trailing whitespace from any file on save. At least that’s how I configured it.

Out of the box it supports not applying to Markdown files and other files like diffs where stripping trailing whitespace isn’t ideal because it has meaning. For example in Markdown adding 2 spaces at the end of the line will add a <br>.

However, out of the box it also never showed whitespace in the files it didn’t apply to. That was problematic for me because I wanted to see that whitespace in Markdown files but not have it stripped on saved. That helps me know if I have accidental trailing whitespace.

Turns out this is easy to do!

First, you can disable stripping whitespace on Markdown files:

autocmd FileType markdown DisableStripWhitespaceOnSave

After that you can tweak better whitespace’s blacklist:

let g:better_whitespace_filetypes_blacklist=[]

This list defaults to ['diff', 'git', 'gitcommit', 'unite', 'qf', 'help', 'markdown', 'fugitive'] but I want whitespace to be shown for all of these file types. With the first setting their whitespace won’t be stripped. Feel free to adjust this to your preferences.

That’s it. Now you’ll see whitespace in Markdown files but it won’t be stripped on save. I commit this in my dotfiles recently.

After configuring this I ran grep -R ".*\s$" against my directory of 500+ blog posts written in Markdown and found quite a few cases where I had a hanging space after a sentence or a bunch of extra spaces within a code block.

The video below demonstrates how this works.

# Demo Video

Timestamps

  • 0:17 – Spaces being shown in Markdown but not other file types
  • 1:22 – Checking out the plugin’s settings
  • 2:06 – Configuring it to do what we want

Reference Links

Did you configure this? Let me know below!

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments