Skip to content

Instantly share code, notes, and snippets.

Last active November 12, 2021 02:09
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save camsaul/71d8d8c3e9c1cc4e0a3ee2d4b04d0fef to your computer and use it in GitHub Desktop.
Markdown live previews source
;;; -*- lexical-binding: t; coding: utf-8; -*-
(defun cam/-scroll-percentage ()
(/ (float (line-number-at-pos (window-start)))
(float (line-number-at-pos (point-max)))))
(defun cam/-set-window-start-to-percentage (scroll-percentage)
(goto-char (point-min))
(let ((target-line-number (truncate (* (line-number-at-pos (point-max)) scroll-percentage))))
(forward-line (1- target-line-number)))
(set-window-start nil (point)))
(defun cam/-render-markdown-preview-current-buffer ()
(message "Rendering Markdown preview of %s" buffer-file-name)
(let ((url (concat "file://" buffer-file-name)))
(shell-command-on-region (point-min) (point-max) "pandoc -f gfm" "*Preview Markdown Output*")
(switch-to-buffer-other-window "*Preview Markdown Output*")
(let ((document (libxml-parse-html-region (point) (point-max))))
(shr-insert-document `(base ((href . ,url)) ,document))
(setq buffer-read-only t))))
(defun cam/-preview-markdown-file (filename)
(find-file filename)
(let ((scroll-percentage (cam/-scroll-percentage)))
(cam/-set-window-start-to-percentage scroll-percentage))))
(defun cam/preview-markdown (&optional filename)
"Render a markdown preview of FILENAME (by default, the current file) and open it in an `eww' window."
(interactive "fFile: ")
(if filename
(cam/-preview-markdown-file filename)
(switch-to-buffer (current-buffer)))
(cam/-preview-markdown-file buffer-file-name)))
(add-hook 'markdown-mode-hook
(lambda ()
(add-hook 'after-save-hook #'cam/preview-markdown nil t)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment