rstdoc.el (2904B)
1 ;;; rstdoc.el --- help generate documentation from docstrings -*- lexical-binding: t -*- 2 3 ;; Copyright (C) 2018 David Bremner 4 5 ;; Author: David Bremner <david@tethera.net> 6 ;; Created: 26 May 2018 7 ;; Keywords: emacs lisp, documentation 8 ;; Homepage: https://notmuchmail.org 9 10 ;; This file is not part of GNU Emacs. 11 12 ;; rstdoc.el is free software: you can redistribute it and/or modify it 13 ;; under the terms of the GNU General Public License as published by 14 ;; the Free Software Foundation, either version 3 of the License, or 15 ;; (at your option) any later version. 16 ;; 17 ;; rstdoc.el is distributed in the hope that it will be useful, but 18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of 19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 ;; General Public License for more details. 21 ;; 22 ;; You should have received a copy of the GNU General Public License 23 ;; along with rstdoc.el. If not, see <https://www.gnu.org/licenses/>. 24 ;; 25 26 ;;; Commentary: 27 28 ;; Rstdoc provides a facility to extract all of the docstrings defined in 29 ;; an elisp source file. Usage: 30 ;; 31 ;; emacs -Q --batch -L . -l rstdoc -f rstdoc-batch-extract foo.el foo.rsti 32 33 ;;; Code: 34 35 (defun rstdoc-batch-extract () 36 "Extract docstrings to and from the files on the command line." 37 (apply #'rstdoc-extract command-line-args-left)) 38 39 (defun rstdoc-extract (in-file out-file) 40 "Write docstrings from IN-FILE to OUT-FILE." 41 (load-file in-file) 42 (let* ((definitions (cdr (assoc (expand-file-name in-file) load-history))) 43 (text-quoting-style 'grave) 44 (doc-hash (make-hash-table :test 'eq))) 45 (mapc 46 (lambda (elt) 47 (let ((pair 48 (pcase elt 49 (`(defun . ,name) (cons name (documentation name))) 50 (`(,_ . ,_) nil) 51 (sym (cons sym (get sym 'variable-documentation)))))) 52 (when (and pair (cdr pair)) 53 (puthash (car pair) (cdr pair) doc-hash)))) 54 definitions) 55 (with-temp-buffer 56 (maphash 57 (lambda (key val) 58 (rstdoc--insert-docstring key val)) 59 doc-hash) 60 (write-region (point-min) (point-max) out-file)))) 61 62 (defun rstdoc--insert-docstring (symbol docstring) 63 (insert (format "\n.. |docstring::%s| replace::\n" symbol)) 64 (insert (replace-regexp-in-string "^" " " 65 (rstdoc--rst-quote-string docstring))) 66 (insert "\n")) 67 68 (defvar rst--escape-alist 69 '( ("\\\\='" . "\001") 70 ("`\\([^\n`']*\\)[`']" . "\002\\1\002") ;; good enough for now... 71 ("`" . "\\\\`") 72 ("\001" . "'") 73 ("\002" . "`") 74 ("[*]" . "\\\\*") 75 ("^[[:space:]]*$" . "|br|") 76 ("^[[:space:]]" . "|indent| ")) 77 "list of (regex . replacement) pairs") 78 79 (defun rstdoc--rst-quote-string (str) 80 (with-temp-buffer 81 (insert str) 82 (dolist (pair rst--escape-alist) 83 (goto-char (point-min)) 84 (while (re-search-forward (car pair) nil t) 85 (replace-match (cdr pair)))) 86 (buffer-substring (point-min) (point-max)))) 87 88 (provide 'rstdoc) 89 90 ;;; rstdoc.el ends here