2021-05-02 Org-mode to Markdown via the clipboard

Some time ago I have written about transforming stuff while copying it from Emacs to the system clipboard. Recently, I noticed that I sometimes write something in Org-mode only to subsequently copy it to some place which accepts Markdown formatting.

So, I decided to write a simple function transforming the region in Org-mode syntax to Markdown. While at that, I decided that I should put it into the system clipboard, bypassing the Emacs kill ring – after all, why would I want to yank it back into Emacs?

As it turned out, the most tricky part was to learn how to tell the Org-mode exporter not to output the table of contents. After several failed attempts, I asked on the Org-mode mailing list, and voilà!

So, here is my (very rudimentary) command to take the active region (in Org-mode) and copy its Markdown equivalent to the system clipboard.

(defun org-copy-region-as-markdown ()
  "Copy the region (in Org) to the system clipboard as Markdown."
  (interactive)
  (if (use-region-p)
      (let* ((region
	      (buffer-substring-no-properties
		      (region-beginning)
		      (region-end)))
	     (markdown
	      (org-export-string-as region 'md t '(:with-toc nil))))
	(gui-set-selection 'CLIPBOARD markdown))))

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryOrgMode