Last active
November 3, 2025 15:44
-
-
Save chipotle/b8e91447f4bb69eebad7629dc6078412 to your computer and use it in GitHub Desktop.
Emacs copy as formatted text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; 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