1

I'm using vim and markdown for note taking.

Sometimes I find some useful information online, so I'll copy and paste into vim like below:

useful information line1
useful information line2
useful information line3
useful information line4

The annoying thing is, when I preview my markdown notes in html, these lines of texts are on the same line, because in markdown, to break a line, you must add two empty space at the end of the line.

How can I make vim automatically do this for me?

  • It would be one thing if you were writing the content yourself, but modifying copy-pasted content on the fly... No, I'd suggest you use code-formatting. – muru Jul 20 '15 at 7:13
  • 2
    The fact that newlines are ignored is also considered a feature, since it allows you to wrap your source document to 78 characters, and still format it differently. Learn to love it :-) – Martin Tournoij Jul 20 '15 at 10:04
2

Assuming you put the text with "*p you can remap this command to first do a substitution on the * register, such that every newline not preceded by two spaces is replaced by a newline preceded by two spaces.

nnoremap "*p :let @* = substitute(@*, '\(\S\S\)\(\n\)', '\1  \2', 'g')<CR>"*p

If you use a different command to put (i.e., <C-v>) or a different register (i.e., "+) you can adapt it accordingly. Perhaps something like

noremap <C-v> :let @+ = substitute(@+, '\(\S\S\)\(\n\)', '\1  \2', 'g')<CR><C-v>

You should also probably either make the mapping buffer specific (nnoremap <buffer> "*p etc.) or map it to a different left hand expression (e.g., <leader>mdp for "markdown-put") and place the snippet in a file that you source when you need it–either manually or perhaps in an "after script" for the markdown filetype (~/.vim/after/ftplugin/markdown.vim), or alternatively load it with an autocmd.

1

Assuming you know about regular expressions, you can probably use substitution to match every line, and replace that line with itself plus the desired terminated space character at the end.

You can match a line against the '\n' escape sequence. Then you can replace that with '\n '. This hasn't been tested, so no guarantees.

  • 1
    Hmm, I think you meant ` \n` and not \n . In Markdown, contiguous lines form a paragraph and get wrapped, unless a) they are in a code block, list or other such special environment or b) a line ends with two spaces foo__$. Though it doesn't have to be as complicated as you make it out: :s/$/ / should be enough. The problem is doing it to pasted content automatically. – muru Jul 20 '15 at 7:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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