Skip to content

Instantly share code, notes, and snippets.

@ncdulo
Forked from camsaul/preview-markdown.el
Last active November 12, 2021 02:00
Show Gist options
  • Save ncdulo/05c42c0f57ae231350376ed9a3b2f5f0 to your computer and use it in GitHub Desktop.
Save ncdulo/05c42c0f57ae231350376ed9a3b2f5f0 to your computer and use it in GitHub Desktop.
rst-mode live previews
;;; preview-rst.el --- description -*- lexical-binding: t; -*-
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Based on the "Intro To Emacs Lisp: Adding Live Preview when Editing Markdown"
;; guide at the link below. This has been followed along, but re-written to use
;; docutils and rst-mode as I do not have pandoc, nor do I feel I want to deal
;; with installing it and it's many Haskell dependencies.
;;
;; This gist was forked from the original gist shared by camsaul, then updated to
;; work for rst-mode.
;;
;; Original Code from:
;; https://camsaul.com/emacs-lisp/2020/06/09/emacs-lisp-intro-markdown-live-previews-part-1.html
;;
;;; Code:
(defun ncdulo/-scroll-percentage ()
"Return a float representing how far down the current window is scrolled."
(/ (float (line-number-at-pos (window-start)))
(float (line-number-at-pos (point-max)))))
(defun ncdulo/-set-window-start-to-percentage (scroll-percentage)
"Scroll the current window down by 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 ncdulo/-render-rst-preview-current-buffer ()
(message "Rendering rST preview of %s" buffer-file-name)
(let ((url (concat "file://" buffer-file-name)))
(shell-command-on-region (point-min) (point-max)
"/usr/bin/rst2html.py" "*Preview rST Output*")
(switch-to-buffer-other-window "*Preview rST Output*")
(let ((document (libxml-parse-html-region (point) (point-max))))
(erase-buffer)
(shr-insert-document `(base ((href . ,url)) ,document))
(setq buffer-read-only t))))
(defun ncdulo/-preview-rst-file (filename)
(save-selected-window
(find-file filename)
(let ((scroll-percentage (ncdulo/-scroll-percentage)))
(ncdulo/-render-rst-preview-current-buffer)
(ncdulo/-set-window-start-to-percentage scroll-percentage))))
(defun ncdulo/preview-rst (&optional filename)
"Render a rST preview of FILENAME (by default, the current file) \
to HTML and display it with `shr-insert-document'."
(interactive "fFile: ")
(if filename
(progn
(ncdulo/-preview-rst-file filename)
(switch-to-buffer (current-buffer)))
(ncdulo/-preview-rst-file buffer-file-name)))
(add-hook 'rst-mode-hook
(lambda ()
(add-hook 'after-save-hook #'ncdulo/preview-rst nil t)))
(provide 'preview-rst)
;;; preview-rst.el ends here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment