stevengharms.com

Sententiae viri ex temporibus duobus

Preview Markdown as Rendered HTML From Vim

Or, “Dont' make me use your ‘rich editor’”

At work we’re using a wiki engine whose power user syntax has been disabled. While it’s been disabled for good reasons, it still bothers me much.

What one is left with is the rich text box which works great for dumping in cut-from-Word documents or which people who don’t want to type quickly and don’t mind mousing to turn on bold etc. As a person who wants to type fast and format as he thinks it, not being able to write markup as I write in wiki data is sad, sad sad.

A guru on the topic suggested that I take some sort of editor, generate the HTML, and then paste that into the rich box because modern OS’s carry HTML formatting data into pastes.

Ugh.

But it’s better than the alternative. Ergo, I downloaded the Markdown extension for VIM. This was a step forward because it provided me the syntax highlighting that makes the process a bit faster. What I really needed was a way to generate the HTML and put it in a browser for ease of cut-and-pasting.

This forced me to dive into the world of vim scripting. Agg. I give it to Emacs every time on this, Vim’s scripting language sucks. I avoid it at all costs, when I can. Tonight I couldn’t. I wrote this pair of functions such that you:

  1. Write markdown in Vim (yay)
  2. See the syntax highlighting thanks to the plugin (yay)
  3. Hit :mm (yay)
  4. An HTML artifact is generated via the markdown perl script
  5. open() on MacOS is called to process that HTML artifact so that it launches your browser, in my case, Chrome

To make the :mm work you need this snippet of code added to your .vimrc.

<code>
" Written by steven for quick loadup of Markdown text into HTML
function Mkdp()
  write
  let file   = expand("%")
  let mkd_file = file . ".html"
  let result = system("markdown " . file . " > " . mkd_file)
  let result = system("open " . mkd_file)
endfunction
:map :mm :call Mkdp()<cr>

</code>

A few caveats.

  1. I think I must be doing it wrong, I suspect putting this code in the .vimrc is not the “blessed” way to do it.
  2. I use the vim system() call which is complete butchery in most programming languages. I’m pretty sure there’s a more blessed way to make requests to the OS, if anyone knows it, please leave a comment.

Comments