Rcjp's Weblog

September 20, 2007

Posting Code

Filed under: utils — rcjp @ 5:42 pm

After spending several frustrating sessions trying to find a solution to posting sourcecode on this blog I think I’ve got something workable.

Most of the methods I tried, including the one in the WordPress FAQ, fail on some operator characters found in lisp or C++ (like e.g.<<) and although I don’t use vim much these days, tending to prefer nvi, it does have a handy htmlize function :TOhtml. This, with some tweaking, generates html acceptable to WordPress from a buffer of code (or some lines marked in Visual Mode).

I used some vim scripting given below to strip out the <pre> section from the generated html, wrap <code> just inside it and copy it to the clipboard ready for pasting into the browser. I have it bound to the keystroke Alt-l. One further complication was that WordPress, trying to be helpful, swaps out some characters even though they are in a <code> block, so I do a search/replace for apostrophes.

func Convert2HTMLClip(line1, line2)
    if a:line2 >= a:line1
        let g:html_start_line = a:line1
        let g:html_end_line = a:line2
        let g:html_start_line = a:line2
        let g:html_end_line = a:line1
    runtime syntax/2html.vim
    unlet g:html_start_line
    unlet g:html_end_line
    normal! gg
    exe ":0,/<pre>/- d"
    normal! A<code>
    normal! G
    exe ":?</pre>?+,$ d"
    normal! I</code>
    exe ":%s/'/\\&#39;/eg"
    exe ":%s/&amp;#39;/\\&amp;\\&#35;39;/eg"
    exe ":%s/&amp;#35;/\\&amp;\\&#35;35;/eg"
    normal! ggVG"+y
    exe ":bd!"
command -range=% TohtmlClip :call Convert2HTMLClip(<line1>, <line2>)
map <M-l> :TohtmlClip<CR>

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: