randomfox (randomfox) wrote,
randomfox
randomfox

Vim: Convert special characters to HTML entities

This Vim macro converts <, >, ", and & into &lt;, &gt;, &quot;, and &amp; respectively. You can use this macro in both normal and visual modes. Its main use so far has been to convert scripts and code for posting to this journal.


" ------------------------------------------------------------------
" Convert text to HTML by escaping <, >, ", and &.
function! HtmlizeText()
    let line = getline(".")
    let line = substitute(line, '&', '\&amp;', 'g')
    let line = substitute(line, '<', '\&lt;', 'g')
    let line = substitute(line, '>', '\&gt;', 'g')
    let line = substitute(line, '"', '\&quot;', 'g')
    call setline(".", line)
endfunction

nmap ,h :call HtmlizeText()<cr>
vmap ,h :call HtmlizeText()<cr>

Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments