• +43 660 1453541
  • contact@germaniumhq.com

Vim Auto-Formatting for Asciidoc and Markdown


Vim Auto-Formatting for Asciidoc and Markdown

When writing a Markdown file, or an Asciidoc, you might want to use the vim formatter, to do automatic text wraps. You type gq to call the formatter, and the text splits and wraps correctly. Oh, wait a minute, now all the lists are broken. Now what?

Now’s the time to introduce vim’s formatter options, so you don’t get from this:

Yay Document

1. multi
2. list
3. with a long lorem ipsum that should go on the next line because it's a very long string.

Some table:

| arst | rst tar st |
| rs t | rs trs tra |

This:

Yay Document

1. multi 2. list 3. with a long lorem ipsum that should go on the next line
because it's a very long string. rsa trsa r tars tars tras

Some table:

| arst | rst tar st | | rs t | rs trs tra |

The default format options for vim are tcqj, which mean:

  • t - auto-wrap using the text width (you can change it, i.e. :set tw=80)

  • c - auto-wrap comments

  • q - allow formatting comments

  • j - remove a comment leader - basically allows collapsing single-line multiple comments into a single comment.

You can see all the available format options by merely calling :help fo-table. From what I’ve noticed, the want settings work very well for this scenario:

  • w - Trailing white space indicates a paragraph continues in the next line. A line that ends in a non-white character ends a paragraph.

  • a - Automatic formatting of paragraphs. Every time text is inserted or deleted the paragraph will be reformatted. When the 'c' flag is present this only happens for recognized comments.

  • n - When formatting text, recognize numbered lists.

  • t - auto-wrap.

Here’s the text formatted with want:

Yay Document

1. multi
2. list
3. with a long lorem ipsum that should go on the next line because it's a very
   long string.

Some table:

| arst | rst tar st |
| rs t | rs trs tra |

Lists and tables are staying in place? w - Check. Now paragraphs are terminated by any non-whitespace character. So | that ends the table or any letter from the list also concludes the paragraph.

Text gets automatically wrapped when typed? a + t - Check.

The extra finesse - next line spaces - added in the list indenting? n - Check.

So :set fo=want and type away.