Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an HTML escape paste mode for vim?

Tags:

vim

I'm using vim to maintain a weblog of what I do through the day (what commands I used to generate output, etc..), and sometimes I need to copy-paste strings that have special html characters in them. Is there a way to make an "html-paste" mode that will (for instance) convert < to &lt;?

like image 973
PerilousApricot Avatar asked Apr 20 '11 16:04

PerilousApricot


2 Answers

There are a few small functions here if someone feels like modifying them to accept a range, then provide a mapping which passes the [ and ] marks to act on the last pasted text.


Actually, after looking a bit, you don't need to modify the functions from the vim tip at all. If a function doesn't explicitly pass the range option, the function is called once for each line of the given range. This means that all you need to do is call the function with a range.

A couple useful examples are below. The first calls HtmlEscape() for each line in the last pasted text, the second does the same but for each line in a visually selected block. Add this to your .vimrc:

nnoremap <Leader>h :'[,']call HtmlEscape()<CR>
vnoremap <Leader>h :call HtmlEscape()<CR>

function HtmlEscape()
  silent s/&/\&amp;/eg
  silent s/</\&lt;/eg
  silent s/>/\&gt;/eg
endfunction

Obviously if you want more things replaced you'd have to add them; there are many on the linked wiki page.

like image 172
Randy Morris Avatar answered Oct 05 '22 23:10

Randy Morris


For simple XML encoding I use Tim Pope's unimpaired.vim.

  • [x followed by a motion
  • visually select the text then [x
  • [xx to encode the current line

To encode the just pasted text:

`[[x`]

Explanation:

  • `[ and `] are marks set by the boundaries of a change or a yank. `[ at the beginning and `] at the end.
  • First move to the start of the just pasted text with `[
  • Next execute [x to encode the following motion
  • By using `] the motion will be all the text between the current cursor location to the end of the pasted text.

Optionally you can wrap this up into a mapping

nmap <leader>x `[[x`]

More information:

:h mark-motion
:h `[
like image 23
Peter Rincker Avatar answered Oct 05 '22 22:10

Peter Rincker