Set pandoc
as your formatprg
to get Markdown formatting:
setlocal formatprg=pandoc -f markdown -t markdown
However, this will wrap long links, e.g.
[This is a really long cool link to a cool website](https://www.reallylongurl.com/foo/bar/baz)
becomes
[This is a really long cool link
to a cool website](https://www.reallylongurl.com/foo/bar/baz)
To prevent this, we can use Vim to do pre-processing after running formatprg
, using the formatexpr
option.
What we need this function to do is find wrapped links and then join them. We can do this in Vim using a combination of :g
and :j
.
We want to find lines that have an opening [
character but no closing ]
on the same line. The pattern for this is
\[[^]]*$
Similarly, we also need a pattern for a line that has the closing ]
but no opening [
. That pattern is
\%(\[.*\)\@<!]
See :h /\@<!
for the explanation of this pattern.
Now, we want to run :j[oin]
on the lines between these two patterns. First, we use :g
to find all lines
matching the first pattern (no closing bracket):
:g/\[[^]]*$/
Next, we want to run :join
from the matched line to the next line that matches the second pattern (no opening bracket):
.,/\%(\[.*\)\@<!]/join
The .
means "from this line" and the ,/.../
means "to the line matching the pattern ...
".
Putting this all together, the command is:
:g/\[[^]]*$/.,/\%(\[.*\)\@<!]/j
The two files above can be dropped into your Vim runtime to allow you to format Markdown documents using gq
without wrapping long link lines.