18

Let's say I have this Markdown file:

[Lorem ipsum dolor sit ](http://vi.stackexchange.com/many-links-are-often-very)

Lookin' good. But the link isn't finished it, so I type -long, and now Vim breaks the line:

[Lorem ipsum dolor sit
](http://vi.stackexchange.com/many-links-are-often-very-long)

Because of my textwidth=80 setting... While breaking a link mid-tag is technically valid markdown, it looks very unsightly IMHO; having nice looking source files is sort of the point of markdown.

With gq the problem is often even worse:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
[Lorem ipsum dolor sit](http://vi.stackexchange.com/many-links-are-often-very-very-long)

Becomes this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec [Lorem
ipsum dolor
sit](http://vi.stackexchange.com/many-links-are-often-very-very-long)

Is there any way I can tell Vim or the markdown syntax to not break links in this way?

  • Maybe by treating the entire link (from [ to )) as a single word.
  • I have the same problem with [this][type] of markdown link.

1 Answer 1

11

In the past I had similar problem with function signatures. Here is solution adapted to your problem. Add to .vimrc:

au CursorMovedI *.md call ModifyTextWidth() " Use only within *.md files

function! ModifyTextWidth()
    if getline(".")=~'^.*\[.*\](.*)$' " If the line ends with Markdown link - set big value for textwidth
        setlocal textwidth=500
    else
        setlocal textwidth=80 " Otherwise use normal textwidth
    endif
endfunction

Note, you may want to change '^.*\[.*\](.*)$' regex. Currently if there is any text after the link, line may be broken as in your example. However, if the regex would match lines with links anywhere inside, another problem can appear:

Some info [here](https://www.google.com). Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris

In this example line break is not inserted after amet, and should be added manually.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.