Enclose paragraphs with <p> tags in vim

4

I tried to create a mapping in order to enclose the visually selected paragraphs in

tags:

vnoremap <silent> _p <Esc>`>a</p><Esc>`<i<p><Esc>:'<,'>s/\n\{2,}/<\/p>\r\r<p>/g<CR>

Unfortunately, this mapping always adds an unwanted </p>\r\r<p> at the end of the selection (i.e. behind the </p> added behind the last character in step 1).

The selection does not end with a double linebreak, so the pattern should not match. What am I doing wrong?

From Answer

Thanks, Romain – I have the surround plugin installed, but it's not helpful when the selected block contains multiple paragraphs. The above mapping is used for this case, not to enclose a single paragraph.

My mapping first adds </p> to the end, then <p> to the beginning of the selection, afterwards it should replace each occurrence of two or more linebreaks with the appropriate combination of closing and opening tag.

I still do not understand why the replacement pattern is applied to the end of the selection, which never consists of a double linebreak.

janeden

Posted 2011-09-21T20:22:15.933

Reputation: 277

Please review the FAQ. This is not a forum. Please use comments to reply to answers or alternatively update your question with further information. – BinaryMisfit – 2011-09-23T11:40:34.447

Answers

0

After reading the documentation on \%V more closely, I can answer the question myself:

To make sure the whole pattern is inside the Visual area put \%V at the start and end of the pattern

So my mapping needed to be changed to

vnoremap <silent> _p <Esc>`>a</p><Esc>`<i<p><Esc>:'<,'>s/\%V\n\{2,}\%V/<\/p>\r\r<p>/ge<CR>:nohl<CR>

I apologize for improper research prior to posting my question.

janeden

Posted 2011-09-21T20:22:15.933

Reputation: 277

0

It's not really unfortunate since that's what you ask explicitely with the:'<,'>s/\n\{2,}/<\/p>\r\r<p>/g<CR> part.

The visually selected block is perfectly enclosed in <p></p> right before the :.

Do you know about the surround plugin? It solves this ans other problems beautifully. This plugin is a must when editing HTML.

romainl

Posted 2011-09-21T20:22:15.933

Reputation: 19 227