Sunday, July 5, 2009

markdown blogging in emacs

Blogging in Markdown from Emacs is nice. Most people, me included, start out by writing a file, running a processor on it (such as Pandoc) to get the HTML, then copying the HTML to the web form to publish.

There is a way to do it faster with a little .emacs hacking (I got here with some help from #emacs IRC, and probably there are better ways to do this, but still) :

(defun pandoc () 
"Runs the contents of the current buffer through Pandoc and
copies the produced HTML to clipboard."
(interactive)
(let ((fn (make-temp-file "pandoc"))
(pbuf (get-buffer-create "*pandoc-output*")))
;; copy the contents of the current buffer to the temp file
(write-region (buffer-end -1) (buffer-end 1) fn)
;; switch to *pandoc-output*, then return to the curr. buffer;
;; clean it, call pandoc on the temp file, copy to clipboard.
(save-current-buffer
(progn
(set-buffer pbuf)
(erase-buffer)
(call-process "pandoc" fn pbuf nil "--no-wrap")
(clipboard-kill-region (buffer-end -1) (buffer-end 1))))
(kill-buffer pbuf) ; cleanup the buffer
(delete-file fn))) ; .. and the temp file
(global-set-key "\C-cp" 'pandoc)

Now you can just type the post in a buffer, hit C-c p, switch to Firefox and paste the Pandoc output.

2 comments:

  1. Hi, Anton. Nice to see you!

    1) Consider using `(point-min)', `(point-max)' instead of `(buffer-end -1)', `(buffer-end 1)' respectively. They are shorter and easier to read.

    2) I use a similar approach to copy wiki page (generated from - ahem -
    m4 source) to X buffer.

    I make(1) the following: ..

    [page.in] --> m4 --> [page.html] --> xclip.sh

    .. and then just paste to Opera.

    PS: xclip.sh uses Emacs (gnuclient) to copy file to X buffer:

    -----BEGIN SCRIPT-----
    #!/bin/sh
    set -e
    [ $# -eq 1 ] || { echo "usage: ${0##*/} FILE" >&2; exit 1; }

    ## `xclip' utility (http://xclip.sf.net/) mangles Cyrillic alphabet.
    # which xclip >/dev/null && { xclip -in "$1"; exit 0; }

    gnuclient -q -batch -eval "
    (let ((default-directory \"`pwd`\"))
    (view-file \"$1\")
    (kill-new (filter-buffer-substring (point-min) (point-max)))
    (View-quit))"
    -----END SCRIPT-----

    ReplyDelete
  2. NICE! Thanks a ton. Reading the ELISP manual about Points :)

    Indeed, haven't tried with the Cyrillics yet, could be a problem.

    Also I feel M4 is one of those mysteries I'd better left unsolved :)

    ReplyDelete