Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rayortigas/7c5ed449fcfafcf6851d to your computer and use it in GitHub Desktop.
Save rayortigas/7c5ed449fcfafcf6851d to your computer and use it in GitHub Desktop.
Stuff for exporting formatted code snippets from Emacs using Pygments.
;; Stuff for exporting formatted code snippets using Pygments
;; <http://pygments.org/>. Install pygments (e.g. pip install
;; pygments) to use.
(setq pygmentize-lexers (make-hash-table))
(puthash 'emacs-lisp-mode "common-lisp" pygmentize-lexers)
(puthash 'scala-mode "scala" pygmentize-lexers)
(puthash 'java-mode "java" pygmentize-lexers)
(puthash 'ruby-mode "rb" pygmentize-lexers)
(puthash 'python-mode "py" pygmentize-lexers)
(puthash 'sh-mode "sh" pygmentize-lexers)
(puthash 'diff-mode "diff" pygmentize-lexers)
;; Code adapted from markdown-mode
;; <http://jblevins.org/projects/markdown-mode/>.
(defun pygmentize-html-command (beginning-line-number)
(let ((lexer (gethash major-mode pygmentize-lexers))
(linenostart (number-to-string beginning-line-number)))
(if (not lexer) (error (concat "error: no lexer for " (symbol-name major-mode))))
(concat "pygmentize -f html"
" -l " lexer
" -O style=autumn,linenos=inline,noclasses=true,linenostart=" linenostart)))
(defconst pygmentize-html-output-buffer-name
"*pygmentize-html-output*" "temporary buffer for pygmentize-html output")
(defun pygmentize-html (&optional output-buffer-name)
(interactive)
(save-window-excursion
(unless output-buffer-name
(setq output-buffer-name pygmentize-html-output-buffer-name))
(let* ((beginning-line-number (line-number-at-pos (region-beginning)))
(shell-command (pygmentize-html-command beginning-line-number)))
(shell-command-on-region (region-beginning)
(region-end)
shell-command
output-buffer-name))
(switch-to-buffer output-buffer-name)
(clipboard-kill-ring-save (point-min) (point-max))
output-buffer-name))
(defun pygmentize-html-preview (&optional output-buffer-name)
(interactive)
(unless output-buffer-name
(setq output-buffer-name pygmentize-html-output-buffer-name))
(browse-url-of-buffer (pygmentize-html output-buffer-name)))
(global-set-key (kbd "C-c h p") 'pygmentize-html-preview)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment