Skip to content

Instantly share code, notes, and snippets.

@chipotle
Last active November 3, 2025 15:44
Show Gist options
  • Select an option

  • Save chipotle/b8e91447f4bb69eebad7629dc6078412 to your computer and use it in GitHub Desktop.

Select an option

Save chipotle/b8e91447f4bb69eebad7629dc6078412 to your computer and use it in GitHub Desktop.
Emacs copy as formatted text
;; This can be added to your init.el file or included as a require. It requires
;; Pandoc to be installed and available on your $PATH (and for Emacs to be able
;; to see your path!). This only works on MacOS, although it could be adapted
;; for Linux with replacements for pbcopy and textutil (if necessary).
;; get region or beginning of buffer
(defun wm/begin ()
(if (region-active-p)
(region-beginning)
(point-min)))
;; get region or end of buffer
(defun wm/end ()
(if (region-active-p)
(region-end)
(point-max)))
;; copy region as rich text
(defun copy-as-rich-text (&optional begin end)
"Copy selected region or buffer as rich text."
(interactive)
(let
((cur-mode (buffer-local-value 'major-mode (current-buffer)))
(xp1 (if begin begin (wm/begin)))
(xp2 (if end end (wm/end))))
(let ((from (pcase cur-mode
('org-mode "org")
(_ "markdown"))))
(save-restriction
(narrow-to-region xp1 xp2)
(shell-command-on-region xp1 xp2
(concat "pandoc -f " from "+smart -t html "
"| textutil -stdin -format html -inputencoding UTF-8 -convert rtf -stdout "
"| pbcopy"))))))
;; copy region as HTML
(defun copy-as-html (&optional begin end)
"Copy selected region or buffer as HTML."
(interactive)
(let
((cur-mode (buffer-local-value 'major-mode (current-buffer)))
(xp1 (if begin begin (wm/begin)))
(xp2 (if end end (wm/end))))
(let ((from (pcase cur-mode
('org-mode "org")
(_ "markdown"))))
(save-restriction
(narrow-to-region xp1 xp2)
(shell-command-on-region xp1 xp2
(concat "pandoc -f " from " -t html --wrap=none "
"| pbcopy"))))))
;; copy as Markdown
(defun copy-as-markdown (&optional begin end)
"Copy selected region or buffer as Markdown."
(interactive)
(let
((cur-mode (buffer-local-value 'major-mode (current-buffer)))
(xp1 (if begin begin (wm/begin)))
(xp2 (if end end (wm/end))))
(let ((from (pcase cur-mode
('org-mode "org")
('xml-mode "xml")
(_ "html"))))
(save-restriction
(narrow-to-region xp1 xp2)
(shell-command-on-region xp1 xp2
(concat "pandoc -f " from " -t markdown --wrap=none"
"| pbcopy"))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment