Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: wrap text ("gq") without modifying underlined headings

Is there a way of formatting text in Vim that respects underlined headings?

In Markdown, there are two ways of representing headings:

#Level 1 heading
##Level 2 heading
###Level 3 heading

and for level 1 & 2 only:

Level 1 heading
===============

Level 2 heading
---------------

I am fond of the underlining style, as I think it reads better.

When I compose markdown in Vim with, say, :set textwidth=72, I would like to be able to reformat the entire document with gggqG, but it treats these underlined headings as paragraphs, and squeezes them together onto one line. So if I started with the following:

Lorem ipsum
===========

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 

After running gq on the entire passage, I would end up with something like this:

Lorem ipsum ===========

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. 

Is there any way that I can prevent Vim from formatting the underlined headings?

I suppose there must be a solution using either formatexpr or formatprg. I have studied the documentation for par, and despite being very powerful it looks as though this is not one of its features. So I'm wondering if there is another external program which could be used with formatprg that understands markdown, or if this can be achieved instead using vimscript with the formatexpr setting.

like image 275
nelstrom Avatar asked Apr 21 '10 11:04

nelstrom


1 Answers

One option that sorta works is to add the underline strings to the comments variable.

If your underline strings are a fixed size, you could add just those:

:set comments+=:---------------,:===============

If they're variable size (more than one):

:set comments+=n:--,n:==

Using more-than-one allows a paragraph to start with a single - or = and keeps subsequent lines from being prepended with the comment string.

Remove the + above to set comments just to those strings instead of adding them on.

There are some cases where the formatting will act unexpectedly (e.g. underlines on consecutive lines). I'm sure there's a more appropriate way to do this but hopefully this will get you started.

:h comments
:h format-comments
:h formatoptions
:h fo-table
like image 64
Curt Nelson Avatar answered Sep 19 '22 17:09

Curt Nelson