1;;; rst.el --- Mode for viewing and editing reStructuredText-documents -*- lexical-binding: t -*- 2 3;; Copyright (C) 2003-2021 Free Software Foundation, Inc. 4 5;; Maintainer: Stefan Merten <stefan at merten-home dot de> 6;; Author: Stefan Merten <stefan at merten-home dot de>, 7;; Martin Blais <blais@furius.ca>, 8;; David Goodger <goodger@python.org>, 9;; Wei-Wei Guo <wwguocn@gmail.com> 10 11;; This file is part of GNU Emacs. 12 13;; GNU Emacs is free software: you can redistribute it and/or modify 14;; it under the terms of the GNU General Public License as published by 15;; the Free Software Foundation, either version 3 of the License, or 16;; (at your option) any later version. 17 18;; GNU Emacs is distributed in the hope that it will be useful, 19;; but WITHOUT ANY WARRANTY; without even the implied warranty of 20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21;; GNU General Public License for more details. 22 23;; You should have received a copy of the GNU General Public License 24;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. 25 26;;; Commentary: 27 28;; This package provides major mode rst-mode, which supports documents marked 29;; up using the reStructuredText format. Support includes font locking as well 30;; as a lot of convenience functions for editing. It does this by defining a 31;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode. 32;; This package also contains: 33;; 34;; - Functions to automatically adjust and cycle the section underline 35;; adornments; 36;; - A mode that displays the table of contents and allows you to jump anywhere 37;; from it; 38;; - Functions to insert and automatically update a TOC in your source 39;; document; 40;; - Function to insert list, processing item bullets and enumerations 41;; automatically; 42;; - Font-lock highlighting of most reStructuredText structures; 43;; - Indentation and filling according to reStructuredText syntax; 44;; - Cursor movement according to reStructuredText syntax; 45;; - Some other convenience functions. 46;; 47;; See the accompanying document in the docutils documentation about 48;; the contents of this package and how to use it. 49;; 50;; For more information about reStructuredText, see 51;; http://docutils.sourceforge.net/rst.html 52;; 53;; For full details on how to use the contents of this file, see 54;; http://docutils.sourceforge.net/docs/user/emacs.html 55;; 56;; There are a number of convenient key bindings provided by rst-mode. For the 57;; bindings, try C-c C-h when in rst-mode. There are also many variables that 58;; can be customized, look for defcustom in this file or look for the "rst" 59;; customization group contained in the "wp" group. 60;; 61;; If you use the table-of-contents feature, you may want to add a hook to 62;; update the TOC automatically every time you adjust a section title:: 63;; 64;; (add-hook 'rst-adjust-hook 'rst-toc-update) 65;; 66;; Syntax highlighting: font-lock is enabled by default. If you want to turn 67;; off syntax highlighting to rst-mode, you can use the following:: 68;; 69;; (setq font-lock-global-modes '(not rst-mode ...)) 70;; 71 72;;; DOWNLOAD 73 74;; The latest release of this file lies in the docutils source code repository: 75;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el 76 77;;; INSTALLATION 78 79;; Add the following lines to your init file: 80;; 81;; (require 'rst) 82;; 83;; If you are using `.txt' as a standard extension for reST files as 84;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file 85;; suggests you may use one of the `Local Variables in Files' mechanism Emacs 86;; provides to set the major mode automatically. For instance you may use:: 87;; 88;; .. -*- mode: rst -*- 89;; 90;; in the very first line of your file. The following code is useful if you 91;; want automatically enter rst-mode from any file with compatible extensions: 92;; 93;; (setq auto-mode-alist 94;; (append '(("\\.txt\\'" . rst-mode) 95;; ("\\.rst\\'" . rst-mode) 96;; ("\\.rest\\'" . rst-mode)) auto-mode-alist)) 97;; 98 99;;; Code: 100 101;; FIXME: Check through major mode conventions again. 102 103;; FIXME: Embed complicated `defconst's in `eval-when-compile'. 104 105;; Common Lisp stuff 106(require 'cl-lib) 107 108;; Correct wrong declaration. 109(def-edebug-spec push 110 (&or [form symbolp] [form gv-place])) 111 112;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 113;; Support for `testcover' 114 115(defun rst-testcover-add-compose (fun) 116 "Add FUN to `testcover-compose-functions'." 117 (when (boundp 'testcover-compose-functions) 118 (add-to-list 'testcover-compose-functions fun))) 119 120(defun rst-testcover-add-1value (fun) 121 "Add FUN to `testcover-1value-functions'." 122 (when (boundp 'testcover-1value-functions) 123 (add-to-list 'testcover-1value-functions fun))) 124 125 126;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 127;; Helpers. 128 129(cl-defmacro rst-destructuring-dolist 130 ((arglist list &optional result) &rest body) 131 "`cl-dolist' with destructuring of the list elements. 132ARGLIST is a Common List argument list which may include 133destructuring. LIST, RESULT and BODY are as for `cl-dolist'. 134Note that definitions in ARGLIST are visible only in the BODY and 135neither in RESULT nor in LIST." 136 ;; FIXME: It would be very useful if the definitions in ARGLIST would be 137 ;; visible in RESULT. But may be this is rather a 138 ;; `rst-destructuring-do' then. 139 (declare (debug 140 (&define ([&or symbolp cl-macro-list] def-form &optional def-form) 141 cl-declarations def-body)) 142 (indent 1)) 143 (let ((var (make-symbol "--rst-destructuring-dolist-var--"))) 144 `(cl-dolist (,var ,list ,result) 145 (cl-destructuring-bind ,arglist ,var 146 ,@body)))) 147 148(defun rst-forward-line-strict (n &optional limit) 149 ;; testcover: ok. 150 "Try to move point to beginning of line I + N where I is the current line. 151Return t if movement is successful. Otherwise don't move point 152and return nil. If a position is given by LIMIT, movement 153happened but the following line is missing and thus its beginning 154can not be reached but the movement reached at least LIMIT 155consider this a successful movement. LIMIT is ignored in other 156cases." 157 (let ((start (point))) 158 (if (and (zerop (forward-line n)) 159 (or (bolp) 160 (and limit 161 (>= (point) limit)))) 162 t 163 (goto-char start) 164 nil))) 165 166(defun rst-forward-line-looking-at (n rst-re-args &optional fun) 167 ;; testcover: ok. 168 "Move forward N lines and if successful check whether RST-RE-ARGS is matched. 169Moving forward is done by `rst-forward-line-strict'. RST-RE-ARGS 170is a single or a list of arguments for `rst-re'. FUN is a 171function defaulting to `identity' which is called after the call 172to `looking-at' receiving its return value as the first argument. 173When FUN is called match data is just set by `looking-at' and 174point is at the beginning of the line. Return nil if moving 175forward failed or otherwise the return value of FUN. Preserve 176global match data, point, mark and current buffer." 177 (unless (listp rst-re-args) 178 (setq rst-re-args (list rst-re-args))) 179 (unless fun 180 (setq fun #'identity)) 181 (save-match-data 182 (save-excursion 183 (when (rst-forward-line-strict n) 184 (funcall fun (looking-at (apply #'rst-re rst-re-args))))))) 185 186(rst-testcover-add-1value 'rst-delete-entire-line) 187(defun rst-delete-entire-line (n) 188 "Move N lines and delete the entire line." 189 (delete-region (line-beginning-position (+ n 1)) 190 (line-beginning-position (+ n 2)))) 191 192 193;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 194;; Versions 195 196(defun rst-extract-version (delim-re head-re re tail-re var &optional default) 197 ;; testcover: ok. 198 "Extract the version from a variable according to the given regexes. 199Return the version after regex DELIM-RE and HEAD-RE matching RE 200and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match." 201 (if (string-match 202 (concat delim-re head-re "\\(" re "\\)" tail-re delim-re) 203 var) 204 (match-string 1 var) 205 default)) 206 207;; Use CVSHeader to really get information from CVS and not other version 208;; control systems. 209(defconst rst-cvs-header 210 "$CVSHeader: sm/rst_el/rst.el,v 1.1058.2.9 2017/01/08 09:54:50 stefan Exp $") 211(defconst rst-cvs-rev 212 (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+" 213 " .*" rst-cvs-header "0.0") 214 "The CVS revision of this file. CVS revision is the development revision.") 215(defconst rst-cvs-timestamp 216 (rst-extract-version "\\$" "CVSHeader: \\S + \\S + " 217 "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*" 218 rst-cvs-header "1970-01-01 00:00:00") 219 "The CVS time stamp of this file.") 220 221;; Use LastChanged... to really get information from SVN. 222(defconst rst-svn-rev 223 (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " " 224 "$LastChangedRevision: 8015 $") 225 "The SVN revision of this file. 226SVN revision is the upstream (docutils) revision.") 227(defconst rst-svn-timestamp 228 (rst-extract-version "\\$" "LastChangedDate: " ".+" " " 229 "$LastChangedDate: 2017-01-08 10:54:35 +0100 (Sun, 08 Jan 2017) $") 230 "The SVN time stamp of this file.") 231 232;; Maintained by the release process. 233(defconst rst-official-version 234 (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " " 235 "%OfficialVersion: 1.5.2 %") 236 "Official version of the package.") 237(defconst rst-official-cvs-rev 238 (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " " 239 "$Revision: 1.1058.2.9 $") 240 "CVS revision of this file in the official version.") 241 242(defconst rst-version 243 (if (equal rst-official-cvs-rev rst-cvs-rev) 244 rst-official-version 245 (format "%s (development %s [%s])" rst-official-version 246 rst-cvs-rev rst-cvs-timestamp)) 247 "The version string. 248Starts with the current official version. For developer versions 249in parentheses follows the development revision and the time stamp.") 250 251(defconst rst-package-emacs-version-alist 252 '(("1.0.0" . "24.3") 253 ("1.1.0" . "24.3") 254 ("1.2.0" . "24.3") 255 ("1.2.1" . "24.3") 256 ("1.3.0" . "24.3") 257 ("1.3.1" . "24.3") 258 ("1.4.0" . "24.3") 259 ("1.4.1" . "25.1") 260 ("1.4.2" . "25.1") 261 ("1.5.0" . "26.1") 262 ("1.5.1" . "26.1") 263 ("1.5.2" . "26.1") 264 ;; Whatever the Emacs version is this rst.el version ends up in. 265 )) 266 267(unless (assoc rst-official-version rst-package-emacs-version-alist) 268 (error "Version %s not listed in `rst-package-emacs-version-alist'" 269 rst-version)) 270 271(add-to-list 'customize-package-emacs-version-alist 272 (cons 'ReST rst-package-emacs-version-alist)) 273 274 275;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 276;; Initialize customization 277 278(defgroup rst nil "Support for reStructuredText documents." 279 :group 'text 280 :version "23.1" 281 :link '(url-link "http://docutils.sourceforge.net/rst.html")) 282 283 284;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 285;; Facilities for regular expressions used everywhere 286 287;; The trailing numbers in the names give the number of referenceable regex 288;; groups contained in the regex. 289 290;; Used to be customizable but really is not customizable but fixed by the reST 291;; syntax. 292(defconst rst-bullets 293 ;; Sorted so they can form a character class when concatenated. 294 '(?- ?* ?+ ?• ?‣ ?⁃) 295 "List of all possible bullet characters for bulleted lists.") 296 297(defconst rst-uri-schemes 298 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap" 299 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp" 300 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais") 301 "Supported URI schemes.") 302 303(defconst rst-adornment-chars 304 ;; Sorted so they can form a character class when concatenated. 305 '(?\] 306 ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\ 307 ?^ ?_ ?` ?{ ?| ?} ?~ 308 ?-) 309 "Characters which may be used in adornments for sections and transitions.") 310 311(defconst rst-max-inline-length 312 1000 313 "Maximum length of inline markup to recognize.") 314 315(defconst rst-re-alist-def 316 ;; `*-beg' matches * at the beginning of a line. 317 ;; `*-end' matches * at the end of a line. 318 ;; `*-prt' matches a part of *. 319 ;; `*-tag' matches *. 320 ;; `*-sta' matches the start of * which may be followed by respective content. 321 ;; `*-pfx' matches the delimiter left of *. 322 ;; `*-sfx' matches the delimiter right of *. 323 ;; `*-hlp' helper for *. 324 ;; 325 ;; A trailing number says how many referenceable groups are contained. 326 `( 327 328 ;; Horizontal white space (`hws') 329 (hws-prt "[\t ]") 330 (hws-tag hws-prt "*") ; Optional sequence of horizontal white space. 331 (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space. 332 333 ;; Lines (`lin') 334 (lin-beg "^" hws-tag) ; Beginning of a possibly indented line. 335 (lin-end hws-tag "$") ; End of a line with optional trailing white space. 336 (linemp-tag "^" hws-tag "$") ; Empty line with optional white space. 337 338 ;; Various tags and parts 339 (ell-tag "\\.\\.\\.") ; Ellipsis 340 (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet. 341 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag. 342 (num-prt "[0-9]") ; A number enumerator part. 343 (num-tag num-prt "+") ; A number enumerator tag. 344 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part. 345 (rom-tag rom-prt "+") ; A roman enumerator tag. 346 (aut-tag "#") ; An automatic enumerator tag. 347 (dcl-tag "::") ; Double colon. 348 349 ;; Block lead in (`bli') 350 (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional* 351 ; immediate content. 352 353 ;; Various starts 354 (bul-sta bul-tag bli-sfx) ; Start of a bulleted item. 355 (bul-beg lin-beg bul-sta) ; A bullet item at the beginning of a line. 356 357 ;; Explicit markup tag (`exm') 358 (exm-tag "\\.\\.") 359 (exm-sta exm-tag hws-sta) 360 (exm-beg lin-beg exm-sta) 361 362 ;; Counters in enumerations (`cnt') 363 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter. 364 (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter. 365 366 ;; Enumerator (`enm') 367 (enmany-tag (:alt 368 (:seq cntany-tag "\\.") 369 (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator. 370 (enmexp-tag (:alt 371 (:seq cntexp-tag "\\.") 372 (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit 373 ; enumerator. 374 (enmaut-tag (:alt 375 (:seq aut-tag "\\.") 376 (:seq "(?" aut-tag ")"))) ; An automatic enumerator. 377 (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start. 378 (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start. 379 (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start 380 ; at the beginning of a line. 381 382 ;; Items may be enumerated or bulleted (`itm') 383 (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag. 384 (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group 385 ; is the item tag. 386 (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the 387 ; beginning of a line, group is the 388 ; item tag. 389 390 ;; Inline markup (`ilm') 391 (ilm-pfx (:alt "^" hws-prt "['\"([{<‘“«’/:-]")) 392 (ilm-sfx (:alt "$" hws-prt "[]'\")}>’”»/:.,;!?\\-]")) 393 394 ;; Inline markup content (`ilc') 395 (ilcsgl-tag "\\S ") ; A single non-white character. 396 (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content. 397 (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content. 398 (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote 399 ; definition. 400 (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content. 401 (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar 402 ; definition. 403 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content. 404 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content. 405 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content. 406 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count. 407 (ilcast-tag (:alt ilcsgl-tag 408 (:seq ilcsgl-tag 409 ilcast-prt ilcrep-hlp 410 ilcast-sfx))) ; Non-asterisk content. 411 (ilcbkq-tag (:alt ilcsgl-tag 412 (:seq ilcsgl-tag 413 ilcbkq-prt ilcrep-hlp 414 ilcbkq-sfx))) ; Non-backquote content. 415 (ilcbkqdef-tag (:alt ilcsgl-tag 416 (:seq ilcsgl-tag 417 ilcbkqdef-prt ilcrep-hlp 418 ilcbkq-sfx))) ; Non-backquote definition. 419 (ilcbar-tag (:alt ilcsgl-tag 420 (:seq ilcsgl-tag 421 ilcbar-prt ilcrep-hlp 422 ilcbar-sfx))) ; Non-vertical-bar content. 423 (ilcbardef-tag (:alt ilcsgl-tag 424 (:seq ilcsgl-tag 425 ilcbardef-prt ilcrep-hlp 426 ilcbar-sfx))) ; Non-vertical-bar definition. 427 428 ;; Fields (`fld') 429 (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name. 430 (fldnam-tag fldnam-prt "+") ; A field name. 431 (fld-tag ":" fldnam-tag ":") ; A field marker. 432 433 ;; Options (`opt') 434 (optsta-tag (:alt "[+/-]" "--")) ; Start of an option. 435 (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option. 436 (optarg-tag (:shy "[ =]\\S +")) ; Option argument. 437 (optsep-tag (:shy "," hws-prt)) ; Separator between options. 438 (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option. 439 440 ;; Footnotes and citations (`fnc') 441 (fncnam-prt "[^]\n]") ; Part of a footnote or citation name. 442 (fncnam-tag fncnam-prt "+") ; A footnote or citation name. 443 (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag. 444 (fncdef-tag-2 (:grp exm-sta) 445 (:grp fnc-tag)) ; A complete footnote or citation definition 446 ; tag. First group is the explicit markup 447 ; start, second group is the footnote / 448 ; citation tag. 449 (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation 450 ; definition. First group is the explicit 451 ; markup start, second group is the 452 ; footnote / citation tag. 453 454 ;; Substitutions (`sub') 455 (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag. 456 (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition 457 ; tag. 458 459 ;; Symbol (`sym') 460 (sym-prt "[+.:_-]") ; Non-word part of a symbol. 461 (sym-tag (:shy "\\sw+" (:shy sym-prt "\\sw+") "*")) 462 463 ;; URIs (`uri') 464 (uri-tag (:alt ,@rst-uri-schemes)) 465 466 ;; Adornment (`ado') 467 (ado-prt "[" ,(concat rst-adornment-chars) "]") 468 (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because 469 ; otherwise explicit markup start would be 470 ; recognized. 471 (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three 472 ; characters is matched differently. 473 (ado-tag-1-1 (:grp ado-prt) 474 "\\1" adorep2-hlp) ; A complete adornment, group is the first 475 ; adornment character and MUST be the FIRST 476 ; group in the whole expression. 477 (ado-tag-1-2 (:grp ado-prt) 478 "\\2" adorep2-hlp) ; A complete adornment, group is the first 479 ; adornment character and MUST be the 480 ; SECOND group in the whole expression. 481 (ado-beg-2-1 "^" (:grp ado-tag-1-2) 482 lin-end) ; A complete adornment line; first group is the whole 483 ; adornment and MUST be the FIRST group in the whole 484 ; expression; second group is the first adornment 485 ; character. 486 487 ;; Titles (`ttl') 488 (ttl-tag "\\S *\\w.*\\S ") ; A title text. 489 (ttl-beg-1 lin-beg (:grp ttl-tag)) ; A title text at the beginning of a 490 ; line. First group is the complete, 491 ; trimmed title text. 492 493 ;; Directives and substitution definitions (`dir') 494 (dir-tag-3 (:grp exm-sta) 495 (:grp (:shy subdef-tag hws-sta) "?") 496 (:grp sym-tag dcl-tag)) ; A directive or substitution definition 497 ; tag. First group is explicit markup 498 ; start, second group is a possibly 499 ; empty substitution tag, third group is 500 ; the directive tag including the double 501 ; colon. 502 (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution 503 ; definition. Groups are as in dir-tag-3. 504 505 ;; Literal block (`lit') 506 (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?" 507 (:grp dcl-tag) "$") ; Start of a literal block. First group is 508 ; any text before the double colon tag which 509 ; may not exist, second group is the double 510 ; colon tag. 511 512 ;; Comments (`cmt') 513 (cmt-sta-1 (:grp exm-sta) "[^[|_\n]" 514 (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$"))) 515 "*$") ; Start of a comment block; first group is explicit markup 516 ; start. 517 518 ;; Paragraphs (`par') 519 (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag) 520 ) ; Tag at the beginning of a paragraph; there may be groups in 521 ; certain cases. 522 ) 523 "Definition alist of relevant regexes. 524Each entry consists of the symbol naming the regex and an 525argument list for `rst-re'.") 526 527(defvar rst-re-alist) ; Forward declare to use it in `rst-re'. 528 529;; FIXME: Use `sregex' or `rx' instead of re-inventing the wheel. 530(rst-testcover-add-compose 'rst-re) 531(defun rst-re (&rest args) 532 ;; testcover: ok. 533 "Interpret ARGS as regular expressions and return a regex string. 534Each element of ARGS may be one of the following: 535 536A string which is inserted unchanged. 537 538A character which is resolved to a quoted regex. 539 540A symbol which is resolved to a string using `rst-re-alist-def'. 541 542A list with a keyword in the car. Each element of the cdr of such 543a list is recursively interpreted as ARGS. The results of this 544interpretation are concatenated according to the keyword. 545 546For the keyword `:seq' the results are simply concatenated. 547 548For the keyword `:shy' the results are concatenated and 549surrounded by a shy-group (\"\\(?:...\\)\"). 550 551For the keyword `:alt' the results form an alternative (\"\\|\") 552which is shy-grouped (\"\\(?:...\\)\"). 553 554For the keyword `:grp' the results are concatenated and form a 555referenceable group (\"\\(...\\)\"). 556 557After interpretation of ARGS the results are concatenated as for 558`:seq'." 559 (apply #'concat 560 (mapcar 561 #'(lambda (re) 562 (cond 563 ((stringp re) 564 re) 565 ((symbolp re) 566 (cadr (assoc re rst-re-alist))) 567 ((characterp re) 568 (regexp-quote (char-to-string re))) 569 ((listp re) 570 (let ((nested 571 (mapcar (lambda (elt) 572 (rst-re elt)) 573 (cdr re)))) 574 (cond 575 ((eq (car re) :seq) 576 (mapconcat #'identity nested "")) 577 ((eq (car re) :shy) 578 (concat "\\(?:" (mapconcat #'identity nested "") "\\)")) 579 ((eq (car re) :grp) 580 (concat "\\(" (mapconcat #'identity nested "") "\\)")) 581 ((eq (car re) :alt) 582 (concat "\\(?:" (mapconcat #'identity nested "\\|") "\\)")) 583 (t 584 (error "Unknown list car: %s" (car re)))))) 585 (t 586 (error "Unknown object type for building regex: %s" re)))) 587 args))) 588 589;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'. 590(with-no-warnings ; Silence byte-compiler about this construction. 591 (defconst rst-re-alist 592 ;; Shadow global value we are just defining so we can construct it step by 593 ;; step. 594 (let (rst-re-alist) 595 (dolist (re rst-re-alist-def rst-re-alist) 596 (setq rst-re-alist 597 (nconc rst-re-alist 598 (list (list (car re) (apply #'rst-re (cdr re)))))))) 599 "Alist mapping symbols from `rst-re-alist-def' to regex strings.")) 600 601 602;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 603;; Concepts 604 605;; Each of the following classes represents an own concept. The suffix of the 606;; class name is used in the code to represent entities of the respective 607;; class. 608;; 609;; In addition a reStructuredText section header in the buffer is called 610;; "section". 611;; 612;; For lists a "s" is added to the name of the concepts. 613 614 615;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 616;; Class rst-Ado 617 618(cl-defstruct 619 (rst-Ado 620 (:constructor nil) ; Prevent creating unchecked values. 621 ;; Construct a transition. 622 (:constructor 623 rst-Ado-new-transition 624 (&aux 625 (char nil) 626 (-style 'transition))) 627 ;; Construct a simple section header. 628 (:constructor 629 rst-Ado-new-simple 630 (char-arg 631 &aux 632 (char (rst-Ado--validate-char char-arg)) 633 (-style 'simple))) 634 ;; Construct an over-and-under section header. 635 (:constructor 636 rst-Ado-new-over-and-under 637 (char-arg 638 &aux 639 (char (rst-Ado--validate-char char-arg)) 640 (-style 'over-and-under))) 641 ;; Construct from adornment with inverted style. 642 (:constructor 643 rst-Ado-new-invert 644 (ado-arg 645 &aux 646 (char (rst-Ado-char ado-arg)) 647 (-style (let ((sty (rst-Ado--style ado-arg))) 648 (cond 649 ((eq sty 'simple) 650 'over-and-under) 651 ((eq sty 'over-and-under) 652 'simple) 653 (sty))))))) 654 "Representation of a reStructuredText adornment. 655Adornments are either section markers where they markup the 656section header or transitions. 657 658This type is immutable." 659 ;; The character used for the adornment. 660 (char nil :read-only t) 661 ;; The style of the adornment. This is a private attribute. 662 (-style nil :read-only t)) 663 664;; Private class methods 665 666(defun rst-Ado--validate-char (char) 667 ;; testcover: ok. 668 "Validate CHAR to be a valid adornment character. 669Return CHAR if so or signal an error otherwise." 670 (cl-check-type char character) 671 (cl-check-type char (satisfies 672 (lambda (c) 673 (memq c rst-adornment-chars))) 674 "Character must be a valid adornment character") 675 char) 676 677;; Public methods 678 679(defun rst-Ado-is-transition (self) 680 ;; testcover: ok. 681 "Return non-nil if SELF is a transition adornment." 682 (cl-check-type self rst-Ado) 683 (eq (rst-Ado--style self) 'transition)) 684 685(defun rst-Ado-is-section (self) 686 ;; testcover: ok. 687 "Return non-nil if SELF is a section adornment." 688 (cl-check-type self rst-Ado) 689 (not (rst-Ado-is-transition self))) 690 691(defun rst-Ado-is-simple (self) 692 ;; testcover: ok. 693 "Return non-nil if SELF is a simple section adornment." 694 (cl-check-type self rst-Ado) 695 (eq (rst-Ado--style self) 'simple)) 696 697(defun rst-Ado-is-over-and-under (self) 698 ;; testcover: ok. 699 "Return non-nil if SELF is an over-and-under section adornment." 700 (cl-check-type self rst-Ado) 701 (eq (rst-Ado--style self) 'over-and-under)) 702 703(defun rst-Ado-equal (self other) 704 ;; testcover: ok. 705 "Return non-nil when SELF and OTHER are equal." 706 (cl-check-type self rst-Ado) 707 (cl-check-type other rst-Ado) 708 (cond 709 ((not (eq (rst-Ado--style self) (rst-Ado--style other))) 710 nil) 711 ((rst-Ado-is-transition self)) 712 ((equal (rst-Ado-char self) (rst-Ado-char other))))) 713 714(defun rst-Ado-position (self ados) 715 ;; testcover: ok. 716 "Return position of SELF in ADOS or nil." 717 (cl-check-type self rst-Ado) 718 (cl-position-if #'(lambda (e) 719 (rst-Ado-equal self e)) 720 ados)) 721 722 723;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 724;; Class rst-Hdr 725 726(cl-defstruct 727 (rst-Hdr 728 (:constructor nil) ; Prevent creating unchecked values. 729 ;; Construct while all parameters must be valid. 730 (:constructor 731 rst-Hdr-new 732 (ado-arg 733 indent-arg 734 &aux 735 (ado (rst-Hdr--validate-ado ado-arg)) 736 (indent (rst-Hdr--validate-indent indent-arg ado nil)))) 737 ;; Construct while all parameters but `indent' must be valid. 738 (:constructor 739 rst-Hdr-new-lax 740 (ado-arg 741 indent-arg 742 &aux 743 (ado (rst-Hdr--validate-ado ado-arg)) 744 (indent (rst-Hdr--validate-indent indent-arg ado t)))) 745 ;; Construct a header with same characteristics but opposite style as `ado'. 746 (:constructor 747 rst-Hdr-new-invert 748 (ado-arg 749 indent-arg 750 &aux 751 (ado (rst-Hdr--validate-ado (rst-Ado-new-invert ado-arg))) 752 (indent (rst-Hdr--validate-indent indent-arg ado t)))) 753 (:copier nil)) ; Not really needed for an immutable type. 754 "Representation of reStructuredText section header characteristics. 755 756This type is immutable." 757 ;; The adornment of the header. 758 (ado nil :read-only t) 759 ;; The indentation of a title text or nil if not given. 760 (indent nil :read-only t)) 761 762;; Private class methods 763 764(defun rst-Hdr--validate-indent (indent ado lax) 765 ;; testcover: ok. 766 "Validate INDENT to be a valid indentation for ADO. 767Return INDENT if so or signal an error otherwise. If LAX don't 768signal an error and return a valid indent." 769 (cl-check-type indent integer) 770 (cond 771 ((zerop indent) 772 indent) 773 ((rst-Ado-is-simple ado) 774 (if lax 775 0 776 (signal 'args-out-of-range 777 '("Indentation must be 0 for style simple")))) 778 ((< indent 0) 779 (if lax 780 0 781 (signal 'args-out-of-range 782 '("Indentation must not be negative")))) 783 ;; Implicitly over-and-under. 784 (indent))) 785 786(defun rst-Hdr--validate-ado (ado) 787 ;; testcover: ok. 788 "Validate ADO to be a valid adornment. 789Return ADO if so or signal an error otherwise." 790 (cl-check-type ado rst-Ado) 791 (cond 792 ((rst-Ado-is-transition ado) 793 (signal 'args-out-of-range 794 '("Adornment for header must not be transition."))) 795 (ado))) 796 797;; Public class methods 798 799(define-obsolete-variable-alias 800 'rst-preferred-decorations 'rst-preferred-adornments "rst 1.0.0") 801 802(defvar rst-preferred-adornments) ; Forward declaration. 803 804(defun rst-Hdr-preferred-adornments () 805 ;; testcover: ok. 806 "Return preferred adornments as list of `rst-Hdr'." 807 (mapcar (cl-function 808 (lambda ((character style indent)) 809 (rst-Hdr-new-lax 810 (if (eq style 'over-and-under) 811 (rst-Ado-new-over-and-under character) 812 (rst-Ado-new-simple character)) 813 indent))) 814 rst-preferred-adornments)) 815 816;; Public methods 817 818(defun rst-Hdr-member-ado (self hdrs) 819 ;; testcover: ok. 820 "Return sublist of HDRS whose car's adornment equals that of SELF or nil." 821 (cl-check-type self rst-Hdr) 822 (let ((ado (rst-Hdr-ado self))) 823 (cl-member-if #'(lambda (hdr) 824 (rst-Ado-equal ado (rst-Hdr-ado hdr))) 825 hdrs))) 826 827(defun rst-Hdr-ado-map (selves) 828 ;; testcover: ok. 829 "Return `rst-Ado' list extracted from elements of SELVES." 830 (mapcar #'rst-Hdr-ado selves)) 831 832(defun rst-Hdr-get-char (self) 833 ;; testcover: ok. 834 "Return character of the adornment of SELF." 835 (cl-check-type self rst-Hdr) 836 (rst-Ado-char (rst-Hdr-ado self))) 837 838(defun rst-Hdr-is-over-and-under (self) 839 ;; testcover: ok. 840 "Return non-nil if SELF is an over-and-under section header." 841 (cl-check-type self rst-Hdr) 842 (rst-Ado-is-over-and-under (rst-Hdr-ado self))) 843 844 845;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 846;; Class rst-Ttl 847 848(cl-defstruct 849 (rst-Ttl 850 (:constructor nil) ; Prevent creating unchecked values. 851 ;; Construct with valid parameters for all attributes. 852 (:constructor ; Private constructor 853 rst-Ttl--new 854 (ado-arg 855 match-arg 856 indent-arg 857 text-arg 858 &aux 859 (ado (rst-Ttl--validate-ado ado-arg)) 860 (match (rst-Ttl--validate-match match-arg ado)) 861 (indent (rst-Ttl--validate-indent indent-arg ado)) 862 (text (rst-Ttl--validate-text text-arg ado)) 863 (hdr (condition-case nil 864 (rst-Hdr-new ado indent) 865 (error nil))))) 866 (:copier nil)) ; Not really needed for an immutable type. 867 "Representation of a reStructuredText section header as found in a buffer. 868This type gathers information about an adorned part in the buffer. 869 870This type is immutable." 871 ;; The adornment characteristics or nil for a title candidate. 872 (ado nil :read-only t) 873 ;; The match-data for `ado' in a form similarly returned by `match-data' (but 874 ;; not necessarily with markers in buffers). Match group 0 matches the whole 875 ;; construct. Match group 1 matches the overline adornment if present. 876 ;; Match group 2 matches the section title text or the transition. Match 877 ;; group 3 matches the underline adornment. 878 (match nil :read-only t) 879 ;; An indentation found for the title line or nil for a transition. 880 (indent nil :read-only t) 881 ;; The text of the title or nil for a transition. 882 (text nil :read-only t) 883 ;; The header characteristics if it is a valid section header. 884 (hdr nil :read-only t) 885 ;; FIXME refactoring: Should have an attribute `buffer' for the buffer this 886 ;; title is found in. This breaks lots and lots of tests. 887 ;; However, with private constructor they may not be 888 ;; necessary any more. In case it is really a buffer then 889 ;; also `match' could be real data from `match-data' which 890 ;; contains markers instead of integers. 891 ) 892 893;; Private class methods 894 895(defun rst-Ttl--validate-ado (ado) 896 ;; testcover: ok. 897 "Return valid ADO or signal error." 898 (cl-check-type ado (or null rst-Ado)) 899 ado) 900 901(defun rst-Ttl--validate-match (match ado) 902 ;; testcover: ok. 903 "Return valid MATCH matching ADO or signal error." 904 (cl-check-type ado (or null rst-Ado)) 905 (cl-check-type match list) 906 (cl-check-type match (satisfies (lambda (m) 907 (equal (length m) 8))) 908 "Match data must consist of exactly 8 buffer positions.") 909 (dolist (pos match) 910 (cl-check-type pos (or null integer-or-marker))) 911 (cl-destructuring-bind (all-beg all-end 912 ovr-beg ovr-end 913 txt-beg txt-end 914 und-beg und-end) match 915 (unless (and (integer-or-marker-p all-beg) (integer-or-marker-p all-end)) 916 (signal 'args-out-of-range 917 '("First two elements of match data must be buffer positions."))) 918 (cond 919 ((null ado) 920 (unless (and (null ovr-beg) (null ovr-end) 921 (integer-or-marker-p txt-beg) (integer-or-marker-p txt-end) 922 (null und-beg) (null und-end)) 923 (signal 'args-out-of-range 924 '("For a title candidate exactly the third match pair must be set.")))) 925 ((rst-Ado-is-transition ado) 926 (unless (and (null ovr-beg) (null ovr-end) 927 (integer-or-marker-p txt-beg) (integer-or-marker-p txt-end) 928 (null und-beg) (null und-end)) 929 (signal 'args-out-of-range 930 '("For a transition exactly the third match pair must be set.")))) 931 ((rst-Ado-is-simple ado) 932 (unless (and (null ovr-beg) (null ovr-end) 933 (integer-or-marker-p txt-beg) (integer-or-marker-p txt-end) 934 (integer-or-marker-p und-beg) (integer-or-marker-p und-end)) 935 (signal 'args-out-of-range 936 '("For a simple section adornment exactly the third and fourth match pair must be set.")))) 937 (t ; over-and-under 938 (unless (and (integer-or-marker-p ovr-beg) (integer-or-marker-p ovr-end) 939 (integer-or-marker-p txt-beg) (integer-or-marker-p txt-end) 940 (or (null und-beg) (integer-or-marker-p und-beg)) 941 (or (null und-end) (integer-or-marker-p und-end))) 942 (signal 'args-out-of-range 943 '("For an over-and-under section adornment all match pairs must be set.")))))) 944 match) 945 946(defun rst-Ttl--validate-indent (indent ado) 947 ;; testcover: ok. 948 "Return valid INDENT for ADO or signal error." 949 (if (and ado (rst-Ado-is-transition ado)) 950 (cl-check-type indent null 951 "Indent for a transition must be nil.") 952 (cl-check-type indent (integer 0 *) 953 "Indent for a section header must be non-negative.")) 954 indent) 955 956(defun rst-Ttl--validate-text (text ado) 957 ;; testcover: ok. 958 "Return valid TEXT for ADO or signal error." 959 (if (and ado (rst-Ado-is-transition ado)) 960 (cl-check-type text null 961 "Transitions may not have title text.") 962 (cl-check-type text string)) 963 text) 964 965;; Public class methods 966 967(defun rst-Ttl-from-buffer (ado beg-ovr beg-txt beg-und txt) 968 ;; testcover: ok. 969 "Return a `rst-Ttl' constructed from information in the current buffer. 970ADO is the adornment or nil for a title candidate. BEG-OVR and 971BEG-UND are the starting points of the overline or underline, 972respectively. They may be nil if the respective thing is missing. 973BEG-TXT is the beginning of the title line or the transition and 974must be given. The end of the line is used as the end point. TXT 975is the title text or nil. If TXT is given the indentation of the 976line containing BEG-TXT is used as indentation. Match group 0 is 977derived from the remaining information." 978 (cl-check-type beg-txt integer-or-marker) 979 (save-excursion 980 (let ((end-ovr (when beg-ovr 981 (goto-char beg-ovr) 982 (line-end-position))) 983 (end-txt (progn 984 (goto-char beg-txt) 985 (line-end-position))) 986 (end-und (when beg-und 987 (goto-char beg-und) 988 (line-end-position))) 989 (ind (when txt 990 (goto-char beg-txt) 991 (current-indentation)))) 992 (rst-Ttl--new ado 993 (list 994 (or beg-ovr beg-txt) (or end-und end-txt) 995 beg-ovr end-ovr 996 beg-txt end-txt 997 beg-und end-und) 998 ind txt)))) 999 1000;; Public methods 1001 1002(defun rst-Ttl-get-title-beginning (self) 1003 ;; testcover: ok. 1004 "Return position of beginning of title text of SELF. 1005This position should always be at the start of a line." 1006 (cl-check-type self rst-Ttl) 1007 (nth 4 (rst-Ttl-match self))) 1008 1009(defun rst-Ttl-get-beginning (self) 1010 ;; testcover: ok. 1011 "Return position of beginning of whole SELF." 1012 (cl-check-type self rst-Ttl) 1013 (nth 0 (rst-Ttl-match self))) 1014 1015(defun rst-Ttl-get-end (self) 1016 ;; testcover: ok. 1017 "Return position of end of whole SELF." 1018 (cl-check-type self rst-Ttl) 1019 (nth 1 (rst-Ttl-match self))) 1020 1021(defun rst-Ttl-is-section (self) 1022 ;; testcover: ok. 1023 "Return non-nil if SELF is a section header or candidate." 1024 (cl-check-type self rst-Ttl) 1025 (rst-Ttl-text self)) 1026 1027(defun rst-Ttl-is-candidate (self) 1028 ;; testcover: ok. 1029 "Return non-nil if SELF is a candidate for a section header." 1030 (cl-check-type self rst-Ttl) 1031 (not (rst-Ttl-ado self))) 1032 1033(defun rst-Ttl-contains (self position) 1034 "Return whether SELF contain POSITION. 1035Return 0 if SELF contains POSITION, < 0 if SELF ends before 1036POSITION and > 0 if SELF starts after position." 1037 (cl-check-type self rst-Ttl) 1038 (cl-check-type position integer-or-marker) 1039 (cond 1040 ((< (nth 1 (rst-Ttl-match self)) position) 1041 -1) 1042 ((> (nth 0 (rst-Ttl-match self)) position) 1043 +1) 1044 (0))) 1045 1046 1047;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 1048;; Class rst-Stn 1049 1050(cl-defstruct 1051 (rst-Stn 1052 (:constructor nil) ; Prevent creating unchecked values. 1053 ;; Construct while all parameters must be valid. 1054 (:constructor 1055 rst-Stn-new 1056 (ttl-arg 1057 level-arg 1058 children-arg 1059 &aux 1060 (ttl (rst-Stn--validate-ttl ttl-arg)) 1061 (level (rst-Stn--validate-level level-arg ttl)) 1062 (children (rst-Stn--validate-children children-arg ttl))))) 1063 "Representation of a section tree node. 1064 1065This type is immutable." 1066 ;; The title of the node or nil for a missing node. 1067 (ttl nil :read-only t) 1068 ;; The level of the node in the tree. Negative for the (virtual) top level 1069 ;; node. 1070 (level nil :read-only t) 1071 ;; The list of children of the node. 1072 (children nil :read-only t)) 1073;; FIXME refactoring: Should have an attribute `buffer' for the buffer this 1074;; title is found in. Or use `rst-Ttl-buffer'. 1075 1076;; Private class methods 1077 1078(defun rst-Stn--validate-ttl (ttl) 1079 ;; testcover: ok. 1080 "Return valid TTL or signal error." 1081 (cl-check-type ttl (or null rst-Ttl)) 1082 ttl) 1083 1084(defun rst-Stn--validate-level (level ttl) 1085 ;; testcover: ok. 1086 "Return valid LEVEL for TTL or signal error." 1087 (cl-check-type level integer) 1088 (when (and ttl (< level 0)) 1089 ;; testcover: Never reached because a title may not have a negative level 1090 (signal 'args-out-of-range 1091 '("Top level node must not have a title."))) 1092 level) 1093 1094(defun rst-Stn--validate-children (children ttl) 1095 ;; testcover: ok. 1096 "Return valid CHILDREN for TTL or signal error." 1097 (cl-check-type children list) 1098 (dolist (child children) 1099 (cl-check-type child rst-Stn)) 1100 (unless (or ttl children) 1101 (signal 'args-out-of-range 1102 '("A missing node must have children."))) 1103 children) 1104 1105;; Public methods 1106 1107(defun rst-Stn-get-title-beginning (self) 1108 ;; testcover: ok. 1109 "Return the beginning of the title of SELF. 1110Handles missing node properly." 1111 (cl-check-type self rst-Stn) 1112 (let ((ttl (rst-Stn-ttl self))) 1113 (if ttl 1114 (rst-Ttl-get-title-beginning ttl) 1115 (rst-Stn-get-title-beginning (car (rst-Stn-children self)))))) 1116 1117(defun rst-Stn-get-text (self &optional default) 1118 ;; testcover: ok. 1119 "Return title text of SELF or DEFAULT if SELF is a missing node. 1120For a missing node and no DEFAULT given return a standard title text." 1121 (cl-check-type self rst-Stn) 1122 (let ((ttl (rst-Stn-ttl self))) 1123 (cond 1124 (ttl 1125 (rst-Ttl-text ttl)) 1126 (default) 1127 ("[missing node]")))) 1128 1129(defun rst-Stn-is-top (self) 1130 ;; testcover: ok. 1131 "Return non-nil if SELF is a top level node." 1132 (cl-check-type self rst-Stn) 1133 (< (rst-Stn-level self) 0)) 1134 1135 1136;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 1137;; Mode definition 1138 1139(defun rst-define-key (keymap key def &rest deprecated) 1140 ;; testcover: ok. 1141 "Bind like `define-key' but add deprecated key definitions. 1142KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key 1143definitions should be in vector notation. These are defined 1144as well but give an additional message." 1145 (define-key keymap key def) 1146 (when deprecated 1147 (let* ((command-name (symbol-name def)) 1148 (forwarder-function-name 1149 (if (string-match "^rst-\\(.*\\)$" command-name) 1150 (concat "rst-deprecated-" 1151 (match-string 1 command-name)) 1152 (error "Not an RST command: %s" command-name))) 1153 (forwarder-function (intern forwarder-function-name))) 1154 (unless (fboundp forwarder-function) 1155 (defalias forwarder-function 1156 (lambda () 1157 (interactive) 1158 (call-interactively def) 1159 (message "[Deprecated use of key %s; use key %s instead]" 1160 (key-description (this-command-keys)) 1161 (key-description key))) 1162 ;; FIXME: In Emacs-25 we could use (:documentation ...) instead. 1163 (format "Deprecated binding for %s, use \\[%s] instead." 1164 def def))) 1165 (dolist (dep-key deprecated) 1166 (define-key keymap dep-key forwarder-function))))) 1167 1168 ;; Key bindings. 1169(defvar rst-mode-map 1170 (let ((map (make-sparse-keymap))) 1171 1172 ;; \C-c is the general keymap. 1173 (rst-define-key map [?\C-c ?\C-h] #'describe-prefix-bindings) 1174 1175 ;; 1176 ;; Section Adornments 1177 ;; 1178 ;; The adjustment function that adorns or rotates a section title. 1179 (rst-define-key map [?\C-c ?\C-=] #'rst-adjust [?\C-c ?\C-a t]) 1180 (rst-define-key map [?\C-=] #'rst-adjust) ; Does not work on macOS and 1181 ; on consoles. 1182 1183 ;; \C-c \C-a is the keymap for adornments. 1184 (rst-define-key map [?\C-c ?\C-a ?\C-h] #'describe-prefix-bindings) 1185 ;; Another binding which works with all types of input. 1186 (rst-define-key map [?\C-c ?\C-a ?\C-a] #'rst-adjust) 1187 ;; Display the hierarchy of adornments implied by the current document 1188 ;; contents. 1189 (rst-define-key map [?\C-c ?\C-a ?\C-d] #'rst-display-hdr-hierarchy) 1190 ;; Homogenize the adornments in the document. 1191 (rst-define-key map [?\C-c ?\C-a ?\C-s] #'rst-straighten-sections 1192 [?\C-c ?\C-s]) 1193 1194 ;; 1195 ;; Section Movement and Selection 1196 ;; 1197 ;; Mark the subsection where the cursor is. 1198 (rst-define-key map [?\C-\M-h] #'rst-mark-section 1199 ;; Same as mark-defun sgml-mark-current-element. 1200 [?\C-c ?\C-m]) 1201 ;; Move backward/forward between section titles. 1202 ;; FIXME: Also bind similar to outline mode. 1203 (rst-define-key map [?\C-\M-a] #'rst-backward-section 1204 ;; Same as beginning-of-defun. 1205 [?\C-c ?\C-n]) 1206 (rst-define-key map [?\C-\M-e] #'rst-forward-section 1207 ;; Same as end-of-defun. 1208 [?\C-c ?\C-p]) 1209 1210 ;; 1211 ;; Operating on regions 1212 ;; 1213 ;; \C-c \C-r is the keymap for regions. 1214 (rst-define-key map [?\C-c ?\C-r ?\C-h] #'describe-prefix-bindings) 1215 ;; Makes region a line-block. 1216 (rst-define-key map [?\C-c ?\C-r ?\C-l] #'rst-line-block-region 1217 [?\C-c ?\C-d]) 1218 ;; Shift region left or right according to tabs. 1219 (rst-define-key map [?\C-c ?\C-r tab] #'rst-shift-region 1220 [?\C-c ?\C-r t] [?\C-c ?\C-l t]) 1221 1222 ;; 1223 ;; Operating on lists 1224 ;; 1225 ;; \C-c \C-l is the keymap for lists. 1226 (rst-define-key map [?\C-c ?\C-l ?\C-h] #'describe-prefix-bindings) 1227 ;; Makes paragraphs in region as a bullet list. 1228 (rst-define-key map [?\C-c ?\C-l ?\C-b] #'rst-bullet-list-region 1229 [?\C-c ?\C-b]) 1230 ;; Makes paragraphs in region an enumeration. 1231 (rst-define-key map [?\C-c ?\C-l ?\C-e] #'rst-enumerate-region 1232 [?\C-c ?\C-e]) 1233 ;; Converts bullets to an enumeration. 1234 (rst-define-key map [?\C-c ?\C-l ?\C-c] #'rst-convert-bullets-to-enumeration 1235 [?\C-c ?\C-v]) 1236 ;; Make sure that all the bullets in the region are consistent. 1237 (rst-define-key map [?\C-c ?\C-l ?\C-s] #'rst-straighten-bullets-region 1238 [?\C-c ?\C-w]) 1239 ;; Insert a list item. 1240 (rst-define-key map [?\C-c ?\C-l ?\C-i] #'rst-insert-list) 1241 1242 ;; 1243 ;; Table-of-Contents Features 1244 ;; 1245 ;; \C-c \C-t is the keymap for table of contents. 1246 (rst-define-key map [?\C-c ?\C-t ?\C-h] #'describe-prefix-bindings) 1247 ;; Enter a TOC buffer to view and move to a specific section. 1248 (rst-define-key map [?\C-c ?\C-t ?\C-t] #'rst-toc) 1249 ;; Insert a TOC here. 1250 (rst-define-key map [?\C-c ?\C-t ?\C-i] #'rst-toc-insert 1251 [?\C-c ?\C-i]) 1252 ;; Update the document's TOC (without changing the cursor position). 1253 (rst-define-key map [?\C-c ?\C-t ?\C-u] #'rst-toc-update 1254 [?\C-c ?\C-u]) 1255 ;; Go to the section under the cursor (cursor must be in internal TOC). 1256 (rst-define-key map [?\C-c ?\C-t ?\C-j] #'rst-toc-follow-link 1257 [?\C-c ?\C-f]) 1258 1259 ;; 1260 ;; Converting Documents from Emacs 1261 ;; 1262 ;; \C-c \C-c is the keymap for compilation. 1263 (rst-define-key map [?\C-c ?\C-c ?\C-h] #'describe-prefix-bindings) 1264 ;; Run one of two pre-configured toolset commands on the document. 1265 (rst-define-key map [?\C-c ?\C-c ?\C-c] #'rst-compile 1266 [?\C-c ?1]) 1267 (rst-define-key map [?\C-c ?\C-c ?\C-a] #'rst-compile-alt-toolset 1268 [?\C-c ?2]) 1269 ;; Convert the active region to pseudo-xml using the docutils tools. 1270 (rst-define-key map [?\C-c ?\C-c ?\C-x] #'rst-compile-pseudo-region 1271 [?\C-c ?3]) 1272 ;; Convert the current document to PDF and launch a viewer on the results. 1273 (rst-define-key map [?\C-c ?\C-c ?\C-p] #'rst-compile-pdf-preview 1274 [?\C-c ?4]) 1275 ;; Convert the current document to S5 slides and view in a web browser. 1276 (rst-define-key map [?\C-c ?\C-c ?\C-s] #'rst-compile-slides-preview 1277 [?\C-c ?5]) 1278 1279 map) 1280 "Keymap for reStructuredText mode commands. 1281This inherits from Text mode.") 1282 1283 1284;; Abbrevs. 1285(define-abbrev-table 'rst-mode-abbrev-table 1286 (mapcar #'(lambda (x) 1287 (append x '(nil 0 system))) 1288 '(("contents" ".. contents::\n..\n ") 1289 ("con" ".. contents::\n..\n ") 1290 ("cont" "[...]") 1291 ("skip" "\n\n[...]\n\n ") 1292 ("seq" "\n\n[...]\n\n ") 1293 ;; FIXME: Add footnotes, links, and more. 1294 )) 1295 "Abbrev table used while in `rst-mode'.") 1296 1297 1298;; Syntax table. 1299(defvar rst-mode-syntax-table 1300 (let ((st (copy-syntax-table text-mode-syntax-table))) 1301 (modify-syntax-entry ?$ "." st) 1302 (modify-syntax-entry ?% "." st) 1303 (modify-syntax-entry ?& "." st) 1304 (modify-syntax-entry ?' "." st) 1305 (modify-syntax-entry ?* "." st) 1306 (modify-syntax-entry ?+ "." st) 1307 (modify-syntax-entry ?- "." st) 1308 (modify-syntax-entry ?/ "." st) 1309 (modify-syntax-entry ?< "." st) 1310 (modify-syntax-entry ?= "." st) 1311 (modify-syntax-entry ?> "." st) 1312 (modify-syntax-entry ?\\ "\\" st) 1313 (modify-syntax-entry ?_ "." st) 1314 (modify-syntax-entry ?| "." st) 1315 (modify-syntax-entry ?« "." st) 1316 (modify-syntax-entry ?» "." st) 1317 (modify-syntax-entry ?‘ "." st) 1318 (modify-syntax-entry ?’ "." st) 1319 (modify-syntax-entry ?“ "." st) 1320 (modify-syntax-entry ?” "." st) 1321 st) 1322 "Syntax table used while in `rst-mode'.") 1323 1324(defcustom rst-mode-hook nil 1325 "Hook run when `rst-mode' is turned on. 1326The hook for `text-mode' is run before this one." 1327 :group 'rst 1328 :type '(hook)) 1329 1330;; Pull in variable definitions silencing byte-compiler. 1331(require 'newcomment) 1332 1333(defvar electric-pair-pairs) 1334(defvar electric-indent-inhibit) 1335 1336;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files 1337;; use *.txt, but this is too generic to be set as a default. 1338;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode))) 1339;;;###autoload 1340(define-derived-mode rst-mode text-mode "ReST" 1341 "Major mode for editing reStructuredText documents. 1342\\<rst-mode-map> 1343 1344Turning on `rst-mode' calls the normal hooks `text-mode-hook' 1345and `rst-mode-hook'. This mode also supports font-lock 1346highlighting. 1347 1348\\{rst-mode-map}" 1349 :abbrev-table rst-mode-abbrev-table 1350 :syntax-table rst-mode-syntax-table 1351 :group 'rst 1352 1353 ;; Paragraph recognition. 1354 (setq-local paragraph-separate 1355 (rst-re '(:alt 1356 "\f" 1357 lin-end))) 1358 (setq-local paragraph-start 1359 (rst-re '(:alt 1360 "\f" 1361 lin-end 1362 (:seq hws-tag par-tag- bli-sfx)))) 1363 1364 ;; Indenting and filling. 1365 (setq-local indent-line-function #'rst-indent-line) 1366 (setq-local adaptive-fill-mode t) 1367 (setq-local adaptive-fill-regexp (rst-re 'hws-tag 'par-tag- "?" 'hws-tag)) 1368 (setq-local adaptive-fill-function #'rst-adaptive-fill) 1369 (setq-local fill-paragraph-handle-comment nil) 1370 1371 ;; Comments. 1372 (setq-local comment-start ".. ") 1373 (setq-local comment-start-skip (rst-re 'lin-beg 'exm-tag 'bli-sfx)) 1374 (setq-local comment-continue " ") 1375 (setq-local comment-multi-line t) 1376 (setq-local comment-use-syntax nil) 1377 ;; reStructuredText has not really a comment ender but nil is not really a 1378 ;; permissible value. 1379 (setq-local comment-end "") 1380 (setq-local comment-end-skip nil) 1381 1382 ;; Commenting in reStructuredText is very special so use our own set of 1383 ;; functions. 1384 (setq-local comment-line-break-function #'rst-comment-line-break) 1385 (setq-local comment-indent-function #'rst-comment-indent) 1386 (setq-local comment-insert-comment-function #'rst-comment-insert-comment) 1387 (setq-local comment-region-function #'rst-comment-region) 1388 (setq-local uncomment-region-function #'rst-uncomment-region) 1389 1390 (setq-local electric-pair-pairs '((?\" . ?\") (?\* . ?\*) (?\` . ?\`))) 1391 1392 ;; Imenu and which function. 1393 ;; FIXME: Check documentation of `which-function' for alternative ways to 1394 ;; determine the current function name. 1395 (setq-local imenu-create-index-function #'rst-imenu-create-index) 1396 1397 ;; Font lock. 1398 (setq-local font-lock-defaults 1399 '(rst-font-lock-keywords 1400 t nil nil nil 1401 (font-lock-multiline . t) 1402 (font-lock-mark-block-function . mark-paragraph))) 1403 (add-hook 'font-lock-extend-region-functions #'rst-font-lock-extend-region t) 1404 1405 ;; Text after a changed line may need new fontification. 1406 (setq-local jit-lock-contextually t) 1407 1408 ;; Indentation is not deterministic. 1409 (setq-local electric-indent-inhibit t)) 1410 1411;;;###autoload 1412(define-minor-mode rst-minor-mode 1413 "Toggle ReST minor mode. 1414 1415When ReST minor mode is enabled, the ReST mode keybindings 1416are installed on top of the major mode bindings. Use this 1417for modes derived from Text mode, like Mail mode." 1418 ;; The initial value. 1419 nil 1420 ;; The indicator for the mode line. 1421 " ReST" 1422 ;; The minor mode bindings. 1423 rst-mode-map 1424 :group 'rst) 1425 1426;; FIXME: can I somehow install these too? 1427;; :abbrev-table rst-mode-abbrev-table 1428;; :syntax-table rst-mode-syntax-table 1429 1430 1431;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 1432;; Section adornment adjustment 1433 1434;; The following functions implement a smart automatic title sectioning feature. 1435;; The idea is that with the cursor sitting on a section title, we try to get as 1436;; much information from context and try to do the best thing automatically. 1437;; This function can be invoked many times and/or with prefix argument to rotate 1438;; between the various sectioning adornments. 1439;; 1440;; Some notes: 1441;; 1442;; - The underlining character that is used depends on context. The file is 1443;; scanned to find other sections and an appropriate character is selected. 1444;; If the function is invoked on a section that is complete, the character is 1445;; rotated among the existing section adornments. 1446;; 1447;; Note that when rotating the characters, if we come to the end of the 1448;; hierarchy of adornments, the variable `rst-preferred-adornments' is 1449;; consulted to propose a new underline adornment, and if continued, we cycle 1450;; the adornments all over again. Set this variable to nil if you want to 1451;; limit the underlining character propositions to the existing adornments in 1452;; the file. 1453;; 1454;; - An underline/overline that is not extended to the column at which it should 1455;; be hanging is dubbed INCOMPLETE. For example:: 1456;; 1457;; |Some Title 1458;; |------- 1459;; 1460;; Examples of default invocation: 1461;; 1462;; |Some Title ---> |Some Title 1463;; | |---------- 1464;; 1465;; |Some Title ---> |Some Title 1466;; |----- |---------- 1467;; 1468;; | |------------ 1469;; | Some Title ---> | Some Title 1470;; | |------------ 1471;; 1472;; In over-and-under style, when alternating the style, a variable is 1473;; available to select how much default indent to use (it can be zero). Note 1474;; that if the current section adornment already has an indent, we don't 1475;; adjust it to the default, we rather use the current indent that is already 1476;; there for adjustment (unless we cycle, in which case we use the indent 1477;; that has been found previously). 1478 1479(defgroup rst-adjust nil 1480 "Settings for adjustment and cycling of section title adornments." 1481 :group 'rst 1482 :version "21.1") 1483 1484;; FIXME: Default must match suggestion in 1485;; http://sphinx-doc.org/rest.html#sections for Python documentation. 1486(defcustom rst-preferred-adornments '((?= over-and-under 1) 1487 (?= simple 0) 1488 (?- simple 0) 1489 (?~ simple 0) 1490 (?+ simple 0) 1491 (?` simple 0) 1492 (?# simple 0) 1493 (?@ simple 0)) 1494 "Preferred hierarchy of section title adornments. 1495A list consisting of lists of the form (CHARACTER STYLE INDENT). 1496CHARACTER is the character used. STYLE is one of the symbols 1497`over-and-under' or `simple'. INDENT is an integer giving the 1498wanted indentation for STYLE `over-and-under'. 1499 1500This sequence is consulted to offer a new adornment suggestion 1501when we rotate the underlines at the end of the existing 1502hierarchy of characters, or when there is no existing section 1503title in the file. 1504 1505Set this to an empty list to use only the adornment found in the 1506file." 1507 :group 'rst-adjust 1508 :type `(repeat 1509 (group :tag "Adornment specification" 1510 (choice :tag "Adornment character" 1511 ,@(mapcar #'(lambda (char) 1512 (list 'const 1513 :tag (char-to-string char) char)) 1514 rst-adornment-chars)) 1515 (radio :tag "Adornment type" 1516 (const :tag "Overline and underline" over-and-under) 1517 (const :tag "Underline only" simple)) 1518 (integer :tag "Indentation for overline and underline type" 1519 :value 0)))) 1520 1521;; FIXME: Rename this to `rst-over-and-under-default-indent' and set default to 1522;; 0 because the effect of 1 is probably surprising in the few cases 1523;; where this is used. 1524;; FIXME: A matching adornment style can be looked for in 1525;; `rst-preferred-adornments' and its indentation used before using this 1526;; variable. 1527(defcustom rst-default-indent 1 1528 "Number of characters to indent the section title. 1529This is only used while toggling adornment styles when switching 1530from a simple adornment style to an over-and-under adornment 1531style. In addition this is used in cases where the adornments 1532found in the buffer are to be used but the indentation for 1533over-and-under adornments is inconsistent across the buffer." 1534 :group 'rst-adjust 1535 :type '(integer)) 1536 1537(defun rst-new-preferred-hdr (seen prev) 1538 ;; testcover: ok. 1539 "Return a new, preferred `rst-Hdr' different from all in SEEN. 1540PREV is the previous `rst-Hdr' in the buffer. If given the 1541search starts after this entry. Return nil if no new preferred 1542`rst-Hdr' can be found." 1543 ;; All preferred adornments are candidates. 1544 (let ((candidates 1545 (append 1546 (if prev 1547 ;; Start searching after the level of the previous adornment. 1548 (cdr (rst-Hdr-member-ado prev (rst-Hdr-preferred-adornments)))) 1549 (rst-Hdr-preferred-adornments)))) 1550 (cl-find-if #'(lambda (cand) 1551 (not (rst-Hdr-member-ado cand seen))) 1552 candidates))) 1553 1554(defun rst-update-section (hdr) 1555 ;; testcover: ok. 1556 "Unconditionally update the style of the section header at point to HDR. 1557If there are existing overline and/or underline from the 1558existing adornment, they are removed before adding the 1559requested adornment." 1560 (end-of-line) 1561 (let ((indent (or (rst-Hdr-indent hdr) 0)) 1562 (marker (point-marker)) 1563 new) 1564 1565 ;; Fixup whitespace at the beginning and end of the line. 1566 (1value 1567 (rst-forward-line-strict 0)) 1568 (delete-horizontal-space) 1569 (insert (make-string indent ? )) 1570 (end-of-line) 1571 (delete-horizontal-space) 1572 (setq new (make-string (+ (current-column) indent) (rst-Hdr-get-char hdr))) 1573 1574 ;; Remove previous line if it is an adornment. 1575 ;; FIXME refactoring: Check whether this deletes `hdr' which *has* all the 1576 ;; data necessary. 1577 (when (and (rst-forward-line-looking-at -1 'ado-beg-2-1) 1578 ;; Avoid removing the underline of a title right above us. 1579 (not (rst-forward-line-looking-at -2 'ttl-beg-1))) 1580 (rst-delete-entire-line -1)) 1581 1582 ;; Remove following line if it is an adornment. 1583 (when (rst-forward-line-looking-at +1 'ado-beg-2-1) 1584 (rst-delete-entire-line +1)) 1585 1586 ;; Insert underline. 1587 (unless (rst-forward-line-strict +1) 1588 ;; Normalize buffer by adding final newline. 1589 (newline 1)) 1590 (open-line 1) 1591 (insert new) 1592 1593 ;; Insert overline. 1594 (when (rst-Hdr-is-over-and-under hdr) 1595 (1value ; Underline inserted above. 1596 (rst-forward-line-strict -1)) 1597 (open-line 1) 1598 (insert new)) 1599 1600 (goto-char marker))) 1601 1602(defun rst-classify-adornment (adornment end &optional accept-over-only) 1603 ;; testcover: ok. 1604 "Classify adornment string for section titles and transitions. 1605ADORNMENT is the complete adornment string as found in the buffer 1606with optional trailing whitespace. END is the point after the 1607last character of ADORNMENT. Return a `rst-Ttl' or nil if no 1608syntactically valid adornment is found. If ACCEPT-OVER-ONLY an 1609overline with a missing underline is accepted as valid and 1610returned." 1611 (save-excursion 1612 (save-match-data 1613 (when (string-match (rst-re 'ado-beg-2-1) adornment) 1614 (goto-char end) 1615 (let* ((ado-ch (string-to-char (match-string 2 adornment))) 1616 (ado-re (rst-re ado-ch 'adorep3-hlp)) ; RE matching the 1617 ; adornment. 1618 (beg-pnt (progn 1619 (1value 1620 (rst-forward-line-strict 0)) 1621 (point))) 1622 (nxt-emp ; Next line nonexistent or empty 1623 (not (rst-forward-line-looking-at +1 'lin-end #'not))) 1624 (prv-emp ; Previous line nonexistent or empty 1625 (not (rst-forward-line-looking-at -1 'lin-end #'not))) 1626 txt-blw 1627 (ttl-blw ; Title found below starting here. 1628 (rst-forward-line-looking-at 1629 +1 'ttl-beg-1 1630 #'(lambda (mtcd) 1631 (when mtcd 1632 (setq txt-blw (match-string-no-properties 1)) 1633 (point))))) 1634 txt-abv 1635 (ttl-abv ; Title found above starting here. 1636 (rst-forward-line-looking-at 1637 -1 'ttl-beg-1 1638 #'(lambda (mtcd) 1639 (when mtcd 1640 (setq txt-abv (match-string-no-properties 1)) 1641 (point))))) 1642 (und-fnd ; Matching underline found starting here. 1643 (and ttl-blw 1644 (rst-forward-line-looking-at 1645 +2 (list ado-re 'lin-end) 1646 #'(lambda (mtcd) 1647 (when mtcd 1648 (point)))))) 1649 (ovr-fnd ; Matching overline found starting here. 1650 (and ttl-abv 1651 (rst-forward-line-looking-at 1652 -2 (list ado-re 'lin-end) 1653 #'(lambda (mtcd) 1654 (when mtcd 1655 (point)))))) 1656 (und-wng ; Wrong underline found starting here. 1657 (and ttl-blw 1658 (not und-fnd) 1659 (rst-forward-line-looking-at 1660 +2 'ado-beg-2-1 1661 #'(lambda (mtcd) 1662 (when mtcd 1663 (point)))))) 1664 (ovr-wng ; Wrong overline found starting here. 1665 (and ttl-abv (not ovr-fnd) 1666 (rst-forward-line-looking-at 1667 -2 'ado-beg-2-1 1668 #'(lambda (mtcd) 1669 (when (and 1670 mtcd 1671 ;; An adornment above may be a legal 1672 ;; adornment for the line above - consider it 1673 ;; a wrong overline only when it is equally 1674 ;; long. 1675 (equal 1676 (length (match-string-no-properties 1)) 1677 (length adornment))) 1678 (point))))))) 1679 (cond 1680 ((and nxt-emp prv-emp) 1681 ;; A transition. 1682 (rst-Ttl-from-buffer (rst-Ado-new-transition) 1683 nil beg-pnt nil nil)) 1684 (ovr-fnd ; Prefer overline match over underline match. 1685 ;; An overline with an underline. 1686 (rst-Ttl-from-buffer (rst-Ado-new-over-and-under ado-ch) 1687 ovr-fnd ttl-abv beg-pnt txt-abv)) 1688 (und-fnd 1689 ;; An overline with an underline. 1690 (rst-Ttl-from-buffer (rst-Ado-new-over-and-under ado-ch) 1691 beg-pnt ttl-blw und-fnd txt-blw)) 1692 ((and ttl-abv (not ovr-wng)) 1693 ;; An underline. 1694 (rst-Ttl-from-buffer (rst-Ado-new-simple ado-ch) 1695 nil ttl-abv beg-pnt txt-abv)) 1696 ((and accept-over-only ttl-blw (not und-wng)) 1697 ;; An overline with a missing underline. 1698 (rst-Ttl-from-buffer (rst-Ado-new-over-and-under ado-ch) 1699 beg-pnt ttl-blw nil txt-blw)) 1700 (t 1701 ;; Invalid adornment. 1702 nil))))))) 1703 1704(defun rst-ttl-at-point () 1705 ;; testcover: ok. 1706 "Find a section title line around point and return its characteristics. 1707If the point is on an adornment line find the respective title 1708line. If the point is on an empty line check previous or next 1709line whether it is a suitable title line and use it if so. If 1710point is on a suitable title line use it. Return a `rst-Ttl' for 1711a section header or nil if no title line is found." 1712 (save-excursion 1713 (save-match-data 1714 (1value 1715 (rst-forward-line-strict 0)) 1716 (let* (cnd-beg ; Beginning of a title candidate. 1717 cnd-txt ; Text of a title candidate. 1718 (cnd-fun #'(lambda (mtcd) ; Function setting title candidate data. 1719 (when mtcd 1720 (setq cnd-beg (match-beginning 0)) 1721 (setq cnd-txt (match-string-no-properties 1)) 1722 t))) 1723 ttl) 1724 (cond 1725 ((looking-at (rst-re 'ado-beg-2-1)) 1726 ;; Adornment found - consider it. 1727 (setq ttl (rst-classify-adornment (match-string-no-properties 0) 1728 (match-end 0) t))) 1729 ((looking-at (rst-re 'lin-end)) 1730 ;; Empty line found - check surrounding lines for a title. 1731 (or 1732 (rst-forward-line-looking-at -1 'ttl-beg-1 cnd-fun) 1733 (rst-forward-line-looking-at +1 'ttl-beg-1 cnd-fun))) 1734 ((looking-at (rst-re 'ttl-beg-1)) 1735 ;; Title line found - check for a following underline. 1736 (setq ttl (rst-forward-line-looking-at 1737 1 'ado-beg-2-1 1738 #'(lambda (mtcd) 1739 (when mtcd 1740 (rst-classify-adornment 1741 (match-string-no-properties 0) (match-end 0)))))) 1742 ;; Title candidate found if no valid adornment found. 1743 (funcall cnd-fun (not ttl)))) 1744 (cond 1745 ((and ttl (rst-Ttl-is-section ttl)) 1746 ttl) 1747 (cnd-beg 1748 (rst-Ttl-from-buffer nil nil cnd-beg nil cnd-txt))))))) 1749 1750;; The following function and variables are used to maintain information about 1751;; current section adornment in a buffer local cache. Thus they can be used for 1752;; font-locking and manipulation commands. 1753 1754(defvar-local rst-all-ttls-cache nil 1755 "All section adornments in the buffer as found by `rst-all-ttls'. 1756Set to t when no section adornments were found.") 1757 1758;; FIXME: If this variable is set to a different value font-locking of section 1759;; headers is wrong. 1760(defvar-local rst-hdr-hierarchy-cache nil 1761 "Section hierarchy in the buffer as determined by `rst-hdr-hierarchy'. 1762Set to t when no section adornments were found. 1763Value depends on `rst-all-ttls-cache'.") 1764 1765(rst-testcover-add-1value 'rst-reset-section-caches) 1766(defun rst-reset-section-caches () 1767 "Reset all section cache variables. 1768Should be called by interactive functions which deal with sections." 1769 (setq rst-all-ttls-cache nil 1770 rst-hdr-hierarchy-cache nil)) 1771 1772(defun rst-all-ttls-compute () 1773 ;; testcover: ok. 1774 "Return a list of `rst-Ttl' for current buffer with ascending line number." 1775 (save-excursion 1776 (save-match-data 1777 (let (ttls) 1778 (goto-char (point-min)) 1779 ;; Iterate over all the section titles/adornments in the file. 1780 (while (re-search-forward (rst-re 'ado-beg-2-1) nil t) 1781 (let ((ttl (rst-classify-adornment 1782 (match-string-no-properties 0) (point)))) 1783 (when (and ttl (rst-Ttl-is-section ttl)) 1784 (when (rst-Ttl-hdr ttl) 1785 (push ttl ttls)) 1786 (goto-char (rst-Ttl-get-end ttl))))) 1787 (nreverse ttls))))) 1788 1789(defun rst-all-ttls () 1790 "Return all the section adornments in the current buffer. 1791Return a list of `rst-Ttl' with ascending line number. 1792 1793Uses and sets `rst-all-ttls-cache'." 1794 (unless rst-all-ttls-cache 1795 (setq rst-all-ttls-cache (or (rst-all-ttls-compute) t))) 1796 (if (eq rst-all-ttls-cache t) 1797 nil 1798 (copy-sequence rst-all-ttls-cache))) 1799 1800(defun rst-infer-hdr-hierarchy (hdrs) 1801 ;; testcover: ok. 1802 "Build a hierarchy from HDRS. 1803HDRS reflects the order in which the headers appear in the 1804buffer. Return a `rst-Hdr' list representing the hierarchy of 1805headers in the buffer. Indentation is unified." 1806 (let (ado2indents) ; Associates `rst-Ado' with the set of indents seen for it. 1807 (dolist (hdr hdrs) 1808 (let* ((ado (rst-Hdr-ado hdr)) 1809 (indent (rst-Hdr-indent hdr)) 1810 (found (assoc ado ado2indents))) 1811 (if found 1812 (setcdr found (cl-adjoin indent (cdr found))) 1813 (push (list ado indent) ado2indents)))) 1814 (mapcar (cl-function 1815 (lambda ((ado consistent &rest inconsistent)) 1816 (rst-Hdr-new ado (if inconsistent 1817 rst-default-indent 1818 consistent)))) 1819 (nreverse ado2indents)))) 1820 1821(defun rst-hdr-hierarchy (&optional ignore-position) 1822 ;; testcover: ok. 1823 "Return the hierarchy of section titles in the file as a `rst-Hdr' list. 1824Each returned element may be used directly to create a section 1825adornment on that level. If IGNORE-POSITION a title containing 1826this position is not taken into account when building the 1827hierarchy unless it appears again elsewhere. This catches cases 1828where the current title is edited and may not be final regarding 1829its level. 1830 1831Uses and sets `rst-hdr-hierarchy-cache' unless IGNORE-POSITION is 1832given." 1833 (let* ((all-ttls (rst-all-ttls)) 1834 (ignore-ttl 1835 (if ignore-position 1836 (cl-find-if 1837 #'(lambda (ttl) 1838 (equal (rst-Ttl-contains ttl ignore-position) 0)) 1839 all-ttls))) 1840 (really-ignore 1841 (if ignore-ttl 1842 (<= (cl-count-if 1843 #'(lambda (ttl) 1844 (rst-Ado-equal (rst-Ttl-ado ignore-ttl) 1845 (rst-Ttl-ado ttl))) 1846 all-ttls) 1847 1))) 1848 (real-ttls (delq (if really-ignore ignore-ttl) all-ttls))) 1849 (copy-sequence ; Protect cache. 1850 (if (and (not ignore-position) rst-hdr-hierarchy-cache) 1851 (if (eq rst-hdr-hierarchy-cache t) 1852 nil 1853 rst-hdr-hierarchy-cache) 1854 (let ((r (rst-infer-hdr-hierarchy (mapcar #'rst-Ttl-hdr real-ttls)))) 1855 (setq rst-hdr-hierarchy-cache 1856 (if ignore-position 1857 ;; Clear cache reflecting that a possible update is not 1858 ;; reflected. 1859 nil 1860 (or r t))) 1861 r))))) 1862 1863(defun rst-all-ttls-with-level () 1864 ;; testcover: ok. 1865 "Return the section adornments with levels set according to hierarchy. 1866Return a list of (`rst-Ttl' . LEVEL) with ascending line number." 1867 (let ((hier (rst-Hdr-ado-map (rst-hdr-hierarchy)))) 1868 (mapcar 1869 #'(lambda (ttl) 1870 (cons ttl (rst-Ado-position (rst-Ttl-ado ttl) hier))) 1871 (rst-all-ttls)))) 1872 1873(defun rst-get-previous-hdr () 1874 "Return the `rst-Hdr' before point or nil if none." 1875 (let ((prev (cl-find-if #'(lambda (ttl) 1876 (< (rst-Ttl-contains ttl (point)) 0)) 1877 (rst-all-ttls) 1878 :from-end t))) 1879 (and prev (rst-Ttl-hdr prev)))) 1880 1881(defun rst-adornment-complete-p (ado indent) 1882 ;; testcover: ok. 1883 "Return t if the adornment ADO around point is complete using INDENT. 1884The adornment is complete if it is a completely correct 1885reStructuredText adornment for the title line at point. This 1886includes indentation and correct length of adornment lines." 1887 ;; Note: we assume that the detection of the overline as being the underline 1888 ;; of a preceding title has already been detected, and has been eliminated 1889 ;; from the adornment that is given to us. 1890 (let ((exps (list "^" (rst-Ado-char ado) 1891 (format "\\{%d\\}" 1892 (+ (save-excursion 1893 ;; Determine last column of title. 1894 (end-of-line) 1895 (current-column)) 1896 indent)) "$"))) 1897 (and (rst-forward-line-looking-at +1 exps) 1898 (or (rst-Ado-is-simple ado) 1899 (rst-forward-line-looking-at -1 exps)) 1900 t))) ; Normalize return value. 1901 1902(defun rst-next-hdr (hdr hier prev down) 1903 ;; testcover: ok. 1904 "Return the next best `rst-Hdr' upward from HDR. 1905Consider existing hierarchy HIER and preferred headers. PREV may 1906be a previous `rst-Hdr' which may be taken into account. If DOWN 1907return the next best `rst-Hdr' downward instead. Return nil if 1908HIER is nil." 1909 (let* ((normalized-hier (if down 1910 hier 1911 (reverse hier))) 1912 (fnd (rst-Hdr-member-ado hdr normalized-hier)) 1913 (prev-fnd (and prev (rst-Hdr-member-ado prev normalized-hier)))) 1914 (or 1915 ;; Next entry in existing hierarchy if it exists. 1916 (cadr fnd) 1917 (if fnd 1918 ;; If current header is found try introducing a new one from preferred 1919 ;; hierarchy. 1920 (rst-new-preferred-hdr hier prev) 1921 ;; If not found try using previous header. 1922 (if down 1923 (cadr prev-fnd) 1924 (car prev-fnd))) 1925 ;; All failed - rotate by using first from normalized existing hierarchy. 1926 (car normalized-hier)))) 1927 1928;; FIXME: A line "``/`` full" is not accepted as a section title. 1929(defun rst-adjust (pfxarg) 1930 ;; testcover: ok. 1931 "Auto-adjust the adornment around point. 1932Adjust/rotate the section adornment for the section title around 1933point or promote/demote the adornments inside the region, 1934depending on whether the region is active. This function is meant 1935to be invoked possibly multiple times, and can vary its behavior 1936with a positive PFXARG (toggle style), or with a negative 1937PFXARG (alternate behavior). 1938 1939This function is a bit of a swiss knife. It is meant to adjust 1940the adornments of a section title in reStructuredText. It tries 1941to deal with all the possible cases gracefully and to do \"the 1942right thing\" in all cases. 1943 1944See the documentations of `rst-adjust-section' and 1945`rst-adjust-region' for full details. 1946 1947The method can take either (but not both) of 1948 1949a. a (non-negative) prefix argument, which means to toggle the 1950 adornment style. Invoke with a prefix argument for example; 1951 1952b. a negative numerical argument, which generally inverts the 1953 direction of search in the file or hierarchy. Invoke with C-- 1954 prefix for example." 1955 (interactive "P") 1956 (let* ((origpt (point-marker)) 1957 (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0))) 1958 (toggle-style (and pfxarg (not reverse-direction)))) 1959 (if (use-region-p) 1960 (rst-adjust-region (and pfxarg t)) 1961 (let ((msg (rst-adjust-section toggle-style reverse-direction))) 1962 (when msg 1963 (apply #'message msg)))) 1964 (run-hooks 'rst-adjust-hook) 1965 (rst-reset-section-caches) 1966 (set-marker 1967 (goto-char origpt) nil))) 1968 1969(defcustom rst-adjust-hook nil 1970 "Hooks to be run after running `rst-adjust'." 1971 :group 'rst-adjust 1972 :type '(hook) 1973 :package-version '(rst . "1.1.0")) 1974 1975(defcustom rst-new-adornment-down nil 1976 "Controls level of new adornment for section headers." 1977 :group 'rst-adjust 1978 :type '(choice 1979 (const :tag "Same level as previous one" nil) 1980 (const :tag "One level down relative to the previous one" t)) 1981 :package-version '(rst . "1.1.0")) 1982 1983(defun rst-adjust-adornment (pfxarg) 1984 "Call `rst-adjust-section' interactively. 1985Keep this for compatibility for older bindings (are there any?). 1986Argument PFXARG has the same meaning as for `rst-adjust'." 1987 (interactive "P") 1988 1989 (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0))) 1990 (toggle-style (and pfxarg (not reverse-direction)))) 1991 (rst-adjust-section toggle-style reverse-direction))) 1992 1993(defun rst-adjust-new-hdr (toggle-style reverse ttl) 1994 ;; testcover: ok. 1995 "Return a new `rst-Hdr' for `rst-adjust-section' related to TTL. 1996TOGGLE-STYLE and REVERSE are from 1997`rst-adjust-section'. TOGGLE-STYLE may be consumed and thus is 1998returned. 1999 2000Return a list (HDR TOGGLE-STYLE MSG...). HDR is the result or 2001nil. TOGGLE-STYLE is the new TOGGLE-STYLE to use in the 2002caller. MSG is a list which is non-empty in case HDR is nil 2003giving an argument list for `message'." 2004 (save-excursion 2005 (goto-char (rst-Ttl-get-title-beginning ttl)) 2006 (let ((indent (rst-Ttl-indent ttl)) 2007 (ado (rst-Ttl-ado ttl)) 2008 (prev (rst-get-previous-hdr)) 2009 hdr-msg) 2010 (setq 2011 hdr-msg 2012 (cond 2013 ((rst-Ttl-is-candidate ttl) 2014 ;; Case 1: No adornment at all. 2015 (let ((hier (rst-hdr-hierarchy))) 2016 (if prev 2017 ;; Previous header exists - use it. 2018 (cond 2019 ;; Customization and parameters require that the previous level 2020 ;; is used - use it as is. 2021 ((or (and rst-new-adornment-down reverse) 2022 (and (not rst-new-adornment-down) (not reverse))) 2023 prev) 2024 ;; Advance one level down. 2025 ((rst-next-hdr prev hier prev t)) 2026 ("Neither hierarchy nor preferences can suggest a deeper header")) 2027 ;; First header in the buffer - use the first adornment from 2028 ;; preferences or hierarchy. 2029 (let ((p (car (rst-Hdr-preferred-adornments))) 2030 (h (car hier))) 2031 (cond 2032 ((if reverse 2033 ;; Prefer hierarchy for downwards 2034 (or h p) 2035 ;; Prefer preferences for upwards 2036 (or p h))) 2037 ("No preferences to suggest a top level from")))))) 2038 ((not (rst-adornment-complete-p ado indent)) 2039 ;; Case 2: Incomplete adornment. 2040 ;; Use lax since indentation might not match suggestion. 2041 (rst-Hdr-new-lax ado indent)) 2042 ;; Case 3: Complete adornment exists from here on. 2043 (toggle-style 2044 ;; Simply switch the style of the current adornment. 2045 (setq toggle-style nil) ; Remember toggling has been done. 2046 (rst-Hdr-new-invert ado rst-default-indent)) 2047 (t 2048 ;; Rotate, ignoring a sole adornment around the current line. 2049 (let ((hier (rst-hdr-hierarchy (point)))) 2050 (cond 2051 ;; Next header can be determined from hierarchy or preferences. 2052 ((rst-next-hdr 2053 ;; Use lax since indentation might not match suggestion. 2054 (rst-Hdr-new-lax ado indent) hier prev reverse)) 2055 ;; No next header found. 2056 ("No preferences or hierarchy to suggest another level from")))))) 2057 (if (stringp hdr-msg) 2058 (list nil toggle-style hdr-msg) 2059 (list hdr-msg toggle-style))))) 2060 2061(defun rst-adjust-section (toggle-style reverse) 2062 ;; testcover: ok. 2063 "Adjust/rotate the section adornment for the section title around point. 2064The action this function takes depends on context around the 2065point, and it is meant to be invoked possibly more than once to 2066rotate among the various possibilities. Basically, this function 2067deals with: 2068 2069- adding an adornment if the title does not have one; 2070 2071- adjusting the length of the underline characters to fit a 2072 modified title; 2073 2074- rotating the adornment in the set of already existing 2075 sectioning adornments used in the file; 2076 2077- switching between simple and over-and-under styles by giving 2078 TOGGLE-STYLE. 2079 2080Return nil if the function did something. If the function were 2081not able to do something return an argument list for `message' to 2082inform the user about what failed. 2083 2084The following is a detailed description but you should normally 2085not have to read it. 2086 2087Before applying the adornment change, the cursor is placed on the 2088closest line that could contain a section title if such is found 2089around the cursor. Then the following cases are distinguished. 2090 2091* Case 1: No Adornment 2092 2093 If the current line has no adornment around it, 2094 2095 - search for a previous adornment, and apply this adornment (unless 2096 `rst-new-adornment-down') or one level lower (otherwise) to the current 2097 line. If there is no defined level below this previous adornment, we 2098 suggest the most appropriate of the `rst-preferred-adornments'. 2099 2100 If REVERSE is true, we simply use the previous adornment found 2101 directly. 2102 2103 - if there is no adornment found in the given direction, we use the first of 2104 `rst-preferred-adornments'. 2105 2106 TOGGLE-STYLE forces a toggle of the prescribed adornment style. 2107 2108* Case 2: Incomplete Adornment 2109 2110 If the current line does have an existing adornment, but the adornment is 2111 incomplete, that is, the underline/overline does not extend to exactly the 2112 end of the title line (it is either too short or too long), we simply extend 2113 the length of the underlines/overlines to fit exactly the section title. 2114 2115 If TOGGLE-STYLE we toggle the style of the adornment as well. 2116 2117 REVERSE has no effect in this case. 2118 2119* Case 3: Complete Existing Adornment 2120 2121 If the adornment is complete (i.e. the underline (overline) length is already 2122 adjusted to the end of the title line), we rotate the current title's 2123 adornment according to the adornment hierarchy found in the buffer. This is 2124 meant to be used potentially multiple times, until the desired adornment is 2125 found around the title. 2126 2127 If we hit the boundary of the hierarchy, exactly one choice from the list of 2128 preferred adornments is suggested/chosen, the first of those adornment that 2129 has not been seen in the buffer yet, and the next invocation rolls over to 2130 the other end of the hierarchy (i.e. it cycles). 2131 2132 If REVERSE is we go up in the hierarchy. Otherwise we go down. 2133 2134 However, if TOGGLE-STYLE, we do not rotate the adornment, but instead simply 2135 toggle the style of the current adornment." 2136 (rst-reset-section-caches) 2137 (let ((ttl (rst-ttl-at-point))) 2138 (if (not ttl) 2139 '("No section header or candidate at point") 2140 (cl-destructuring-bind 2141 (hdr toggle-style &rest msg 2142 &aux 2143 (indent (rst-Ttl-indent ttl)) 2144 (moved (- (line-number-at-pos (rst-Ttl-get-title-beginning ttl)) 2145 (line-number-at-pos)))) 2146 (rst-adjust-new-hdr toggle-style reverse ttl) 2147 (if msg 2148 msg 2149 (when toggle-style 2150 (setq hdr (rst-Hdr-new-invert (rst-Hdr-ado hdr) indent))) 2151 ;; Override indent with present indent if there is some. 2152 (when (> indent 0) 2153 ;; Use lax since existing indent may not be valid for new style. 2154 (setq hdr (rst-Hdr-new-lax (rst-Hdr-ado hdr) indent))) 2155 (goto-char (rst-Ttl-get-title-beginning ttl)) 2156 (rst-update-section hdr) 2157 ;; Correct the position of the cursor to more accurately reflect 2158 ;; where it was located when the function was invoked. 2159 (unless (zerop moved) 2160 (1value ; No lines may be left to move. 2161 (rst-forward-line-strict (- moved))) 2162 (end-of-line)) 2163 nil))))) 2164 2165;; Maintain an alias for compatibility. 2166(defalias 'rst-adjust-section-title 'rst-adjust) 2167 2168(defun rst-adjust-region (demote) 2169 ;; testcover: ok. 2170 "Promote the section titles within the region. 2171With argument DEMOTE or a prefix argument, demote the section 2172titles instead. The algorithm used at the boundaries of the 2173hierarchy is similar to that used by `rst-adjust-section'." 2174 (interactive "P") 2175 (rst-reset-section-caches) 2176 (let* ((beg (region-beginning)) 2177 (end (region-end)) 2178 (ttls-reg (cl-remove-if-not 2179 #'(lambda (ttl) 2180 (and 2181 (>= (rst-Ttl-contains ttl beg) 0) 2182 (< (rst-Ttl-contains ttl end) 0))) 2183 (rst-all-ttls)))) 2184 (save-excursion 2185 ;; Apply modifications. 2186 (rst-destructuring-dolist 2187 ((marker &rest hdr 2188 &aux (hier (rst-hdr-hierarchy))) 2189 (mapcar #'(lambda (ttl) 2190 (cons (copy-marker (rst-Ttl-get-title-beginning ttl)) 2191 (rst-Ttl-hdr ttl))) 2192 ttls-reg)) 2193 (set-marker 2194 (goto-char marker) nil) 2195 ;; `rst-next-hdr' cannot return nil because we apply to a section 2196 ;; header so there is some hierarchy. 2197 (rst-update-section (rst-next-hdr hdr hier nil demote))) 2198 (setq deactivate-mark nil)))) 2199 2200(defun rst-display-hdr-hierarchy () 2201 ;; testcover: ok. 2202 "Display the current file's section title adornments hierarchy. 2203Hierarchy is displayed in a temporary buffer." 2204 (interactive) 2205 (rst-reset-section-caches) 2206 (let ((hdrs (rst-hdr-hierarchy)) 2207 (level 1)) 2208 (with-output-to-temp-buffer "*rest section hierarchy*" 2209 (with-current-buffer standard-output 2210 (dolist (hdr hdrs) 2211 (insert (format "\nSection Level %d" level)) 2212 (rst-update-section hdr) 2213 (goto-char (point-max)) 2214 (insert "\n") 2215 (cl-incf level)))))) 2216 2217;; Maintain an alias for backward compatibility. 2218(defalias 'rst-display-adornments-hierarchy 'rst-display-hdr-hierarchy) 2219 2220;; FIXME: Should accept an argument giving the hierarchy level to start with 2221;; instead of the top of the hierarchy. 2222(defun rst-straighten-sections () 2223 ;; testcover: ok. 2224 "Redo the adornments of all section titles in the current buffer. 2225This is done using the preferred set of adornments. This can be 2226used, for example, when using somebody else's copy of a document, 2227in order to adapt it to our preferred style." 2228 (interactive) 2229 (rst-reset-section-caches) 2230 (save-excursion 2231 (rst-destructuring-dolist 2232 ((marker &rest level) 2233 (mapcar 2234 (cl-function 2235 (lambda ((ttl &rest level)) 2236 ;; Use markers so edits don't disturb the position. 2237 (cons (copy-marker (rst-Ttl-get-title-beginning ttl)) level))) 2238 (rst-all-ttls-with-level))) 2239 (set-marker 2240 (goto-char marker) nil) 2241 (rst-update-section (nth level (rst-Hdr-preferred-adornments)))))) 2242 2243;; Maintain an alias for compatibility. 2244(defalias 'rst-straighten-adornments 'rst-straighten-sections) 2245 2246 2247;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2248;; Insert list items 2249 2250;; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>. I 2251;; needed to make some tiny changes to the functions, so I put it here. 2252;; -- Wei-Wei Guo 2253 2254(defconst rst-arabic-to-roman 2255 '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD") 2256 (100 . "C") (90 . "XC") (50 . "L") (40 . "XL") 2257 (10 . "X") (9 . "IX") (5 . "V") (4 . "IV") 2258 (1 . "I")) 2259 "List of maps between Arabic numbers and their Roman numeral equivalents.") 2260 2261(defun rst-arabic-to-roman (num) 2262 ;; testcover: ok. 2263 "Convert Arabic number NUM to its Roman numeral representation. 2264 2265Obviously, NUM must be greater than zero. Don't blame me, blame the 2266Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with 2267apologies to Monty Python)." 2268 (cl-check-type num (integer 1 *)) 2269 (let ((map rst-arabic-to-roman) 2270 (r "")) 2271 (while (and map (> num 0)) 2272 (cl-destructuring-bind ((val &rest sym) &rest next) map 2273 (if (>= num val) 2274 (setq r (concat r sym) 2275 num (- num val)) 2276 (setq map next)))) 2277 r)) 2278 2279(defun rst-roman-to-arabic (string) 2280 ;; testcover: ok. 2281 "Convert STRING of Roman numerals to an Arabic number. 2282If STRING contains a letter which isn't a valid Roman numeral, 2283the rest of the string from that point onwards is ignored. 2284Hence: 2285MMD == 2500 2286and 2287MMDFLXXVI == 2500." 2288 (cl-check-type string string) 2289 (cl-check-type string (satisfies (lambda (s) 2290 (not (equal s "")))) 2291 "Roman number may not be an empty string.") 2292 (let ((res 0) 2293 (map rst-arabic-to-roman)) 2294 (save-match-data 2295 (while map 2296 (cl-destructuring-bind ((val &rest sym) &rest next) map 2297 (if (string-match (concat "^" sym) string) 2298 (setq res (+ res val) 2299 string (replace-match "" nil t string)) 2300 (setq map next)))) 2301 (cl-check-type string (satisfies (lambda (s) 2302 (equal s ""))) 2303 "Invalid characters in roman number") 2304 res))) 2305 2306;; End of borrow. 2307 2308;; FIXME: All the following code should not consider single lines as items but 2309;; paragraphs as reST does. 2310 2311(defun rst-insert-list-new-tag (tag) 2312 ;; testcover: ok. 2313 "Insert first item of a new list tagged with TAG. 2314 2315Adding a new list might consider three situations: 2316 2317 (a) Current line is a blank line. 2318 (b) Previous line is a blank line. 2319 (c) Following line is a blank line. 2320 2321When (a) and (b), just add the new list at current line. 2322 2323when (a) and not (b), a blank line is added before adding the new list. 2324 2325When not (a), first forward point to the end of the line, and add two 2326blank lines, then add the new list. 2327 2328Other situations are just ignored and left to users themselves." 2329 ;; FIXME: Following line is not considered at all. 2330 (let ((pfx-nls 2331 ;; FIXME: Doesn't work properly for white-space line. See 2332 ;; `rst-insert-list-new-BUGS'. 2333 (if (rst-forward-line-looking-at 0 'lin-end) 2334 (if (not (rst-forward-line-looking-at -1 'lin-end #'not)) 2335 0 2336 1) 2337 2))) 2338 (end-of-line) 2339 ;; FIXME: The indentation is not fixed to a single space by the syntax. May 2340 ;; be this should be configurable or rather taken from the context. 2341 (insert (make-string pfx-nls ?\n) tag " "))) 2342 2343(defconst rst-initial-items 2344 (append (mapcar #'char-to-string rst-bullets) 2345 (let (vals) 2346 (dolist (fmt '("%s." "(%s)" "%s)")) 2347 (dolist (c '("#" "1" "a" "A" "I" "i")) 2348 (push (format fmt c) vals))) 2349 (nreverse vals))) 2350 "List of initial items. It's a collection of bullets and enumerations.") 2351 2352(defun rst-insert-list-new-item () 2353 ;; testcover: ok. 2354 "Insert a new list item. 2355 2356User is asked to select the item style first, for example (a), i), +. 2357Use TAB for completion and choices. 2358 2359If user selects bullets or #, it's just added with position arranged by 2360`rst-insert-list-new-tag'. 2361 2362If user selects enumerations, a further prompt is given. User need to 2363input a starting item, for example 'e' for 'A)' style. The position is 2364also arranged by `rst-insert-list-new-tag'." 2365 (let* ((itemstyle (completing-read 2366 "Select preferred item style [#.]: " 2367 rst-initial-items nil t nil nil "#.")) 2368 (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle) 2369 (match-string 0 itemstyle))) 2370 (no 2371 (save-match-data 2372 (cond 2373 ((equal cnt "a") 2374 (let ((itemno (read-string "Give starting value [a]: " 2375 nil nil "a"))) 2376 (downcase (substring itemno 0 1)))) 2377 ((equal cnt "A") 2378 (let ((itemno (read-string "Give starting value [A]: " 2379 nil nil "A"))) 2380 (upcase (substring itemno 0 1)))) 2381 ((equal cnt "I") 2382 (let ((itemno (read-number "Give starting value [1]: " 1))) 2383 (rst-arabic-to-roman itemno))) 2384 ((equal cnt "i") 2385 (let ((itemno (read-number "Give starting value [1]: " 1))) 2386 (downcase (rst-arabic-to-roman itemno)))) 2387 ((equal cnt "1") 2388 (let ((itemno (read-number "Give starting value [1]: " 1))) 2389 (number-to-string itemno))))))) 2390 (if no 2391 (setq itemstyle (replace-match no t t itemstyle))) 2392 (rst-insert-list-new-tag itemstyle))) 2393 2394(defcustom rst-preferred-bullets 2395 '(?* ?- ?+) 2396 "List of favorite bullets." 2397 :group 'rst 2398 :type `(repeat 2399 (choice ,@(mapcar #'(lambda (char) 2400 (list 'const 2401 :tag (char-to-string char) char)) 2402 rst-bullets))) 2403 :package-version '(rst . "1.1.0")) 2404 2405(defun rst-insert-list-continue (ind tag tab prefer-roman) 2406 ;; testcover: ok. 2407 "Insert a new list tag after the current line according to style. 2408Style is defined by indentation IND, TAG and suffix TAB. If 2409PREFER-ROMAN roman numbering is preferred over using letters." 2410 (end-of-line) 2411 (insert 2412 ;; FIXME: Separating lines must be possible. 2413 "\n" 2414 ind 2415 (save-match-data 2416 (if (not (string-match (rst-re 'cntexp-tag) tag)) 2417 tag 2418 (let ((pfx (substring tag 0 (match-beginning 0))) 2419 (cnt (match-string 0 tag)) 2420 (sfx (substring tag (match-end 0)))) 2421 (concat 2422 pfx 2423 (cond 2424 ((string-match (rst-re 'num-tag) cnt) 2425 (number-to-string (1+ (string-to-number (match-string 0 cnt))))) 2426 ((and 2427 (string-match (rst-re 'rom-tag) cnt) 2428 (save-match-data 2429 (if (string-match (rst-re 'ltr-tag) cnt) ; Also a letter tag. 2430 (save-excursion 2431 ;; FIXME: Assumes one line list items without separating 2432 ;; empty lines. 2433 ;; Use of `rst-forward-line-looking-at' is very difficult 2434 ;; here so don't do it. 2435 (if (and (rst-forward-line-strict -1) 2436 (looking-at (rst-re 'enmexp-beg))) 2437 (string-match 2438 (rst-re 'rom-tag) 2439 (match-string 0)) ; Previous was a roman tag. 2440 prefer-roman)) ; Don't know - use flag. 2441 t))) ; Not a letter tag. 2442 (let* ((old (match-string 0 cnt)) 2443 (new (rst-arabic-to-roman 2444 (1+ (rst-roman-to-arabic (upcase old)))))) 2445 (if (equal old (upcase old)) 2446 (upcase new) 2447 (downcase new)))) 2448 ((string-match (rst-re 'ltr-tag) cnt) 2449 (char-to-string (1+ (string-to-char (match-string 0 cnt)))))) 2450 sfx)))) 2451 tab)) 2452 2453;; FIXME: At least the continuation may be folded into 2454;; `newline-and-indent`. However, this may not be wanted by everyone so 2455;; it should be possible to switch this off. 2456(defun rst-insert-list (&optional prefer-roman) 2457 ;; testcover: ok. 2458 "Insert a list item at the current point. 2459 2460The command can insert a new list or a continuing list. When it is called at a 2461non-list line, it will promote to insert new list. When it is called at a list 2462line, it will insert a list with the same list style. 2463 24641. When inserting a new list: 2465 2466User is asked to select the item style first, for example (a), i), +. Use TAB 2467for completion and choices. 2468 2469 (a) If user selects bullets or #, it's just added. 2470 (b) If user selects enumerations, a further prompt is given. User needs to 2471 input a starting item, for example `e' for `A)' style. 2472 2473The position of the new list is arranged according to whether or not the 2474current line and the previous line are blank lines. 2475 24762. When continuing a list, one thing needs to be noticed: 2477 2478List style alphabetical list, such as `a.', and roman numerical list, such as 2479`i.', have some overlapping items, for example `v.' The function can deal with 2480the problem elegantly in most situations. But when those overlapped list are 2481preceded by a blank line, it is hard to determine which type to use 2482automatically. The function uses alphabetical list by default. If you want 2483roman numerical list, just use a prefix to set PREFER-ROMAN." 2484 (interactive "P") 2485 (save-match-data 2486 (1value 2487 (rst-forward-line-strict 0)) 2488 ;; FIXME: Finds only tags in single line items. Multi-line items should be 2489 ;; considered as well. 2490 ;; Using `rst-forward-line-looking-at' is more complicated so don't do it. 2491 (if (looking-at (rst-re 'itmany-beg-1)) 2492 (rst-insert-list-continue 2493 (buffer-substring-no-properties 2494 (match-beginning 0) (match-beginning 1)) 2495 (match-string 1) 2496 (buffer-substring-no-properties (match-end 1) (match-end 0)) 2497 prefer-roman) 2498 (rst-insert-list-new-item)))) 2499 2500;; FIXME: This is wrong because it misses prefixed lines without intervening 2501;; new line. See `rst-straighten-bullets-region-BUGS' and 2502;; `rst-find-begs-BUGS'. 2503(defun rst-find-begs (beg end rst-re-beg) 2504 ;; testcover: ok. 2505 "Return the positions of begs in region BEG to END. 2506RST-RE-BEG is a `rst-re' argument and matched at the beginning of 2507a line. Return a list of (POINT . COLUMN) where POINT gives the 2508point after indentation and COLUMN gives its column. The list is 2509ordered by POINT." 2510 (let (r) 2511 (save-match-data 2512 (save-excursion 2513 ;; FIXME refactoring: Consider making this construct a macro looping 2514 ;; over the lines. 2515 (goto-char beg) 2516 (1value 2517 (rst-forward-line-strict 0)) 2518 (while (< (point) end) 2519 (let ((clm (current-indentation))) 2520 ;; FIXME refactoring: Consider using `rst-forward-line-looking-at'. 2521 (when (and 2522 (looking-at (rst-re rst-re-beg)) ; Start found 2523 (not (rst-forward-line-looking-at 2524 -1 'lin-end 2525 #'(lambda (mtcd) ; Previous line exists and is... 2526 (and 2527 (not mtcd) ; non-empty, 2528 (<= (current-indentation) clm) ; less indented 2529 (not (and (= (current-indentation) clm) 2530 ; not a beg at same level. 2531 (looking-at (rst-re rst-re-beg))))))))) 2532 (back-to-indentation) 2533 (push (cons (point) clm) r))) 2534 (1value ; At least one line is moved in this loop. 2535 (rst-forward-line-strict 1 end))))) 2536 (nreverse r))) 2537 2538(defun rst-straighten-bullets-region (beg end) 2539 ;; testcover: ok. 2540 "Make all the bulleted list items in the region from BEG to END consistent. 2541Use this after you have merged multiple bulleted lists to make 2542them use the preferred bullet characters given by 2543`rst-preferred-bullets' for each level. If bullets are found on 2544levels beyond the `rst-preferred-bullets' list, they are not 2545modified." 2546 (interactive "r") 2547 (save-excursion 2548 (let (clm2pnts) ; Map a column to a list of points at this column. 2549 (rst-destructuring-dolist 2550 ((point &rest column 2551 &aux (found (assoc column clm2pnts))) 2552 (rst-find-begs beg end 'bul-beg)) 2553 (if found 2554 ;;; (push point (cdr found)) ; FIXME: Doesn't work with `testcover'. 2555 (setcdr found (cons point (cdr found))) ; Synonym. 2556 (push (list column point) clm2pnts))) 2557 (rst-destructuring-dolist 2558 ((bullet _clm &rest pnts) 2559 ;; Zip preferred bullets and sorted columns associating a bullet 2560 ;; with a column and all the points this column is found. 2561 (cl-mapcar #'(lambda (bullet clm2pnt) 2562 (cons bullet clm2pnt)) 2563 rst-preferred-bullets 2564 (sort clm2pnts #'car-less-than-car))) 2565 ;; Replace the bullets by the preferred ones. 2566 (dolist (pnt pnts) 2567 (goto-char pnt) 2568 ;; FIXME: Assumes bullet to replace is a single char. 2569 (delete-char 1) 2570 (insert bullet)))))) 2571 2572 2573;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2574;; Table of contents 2575 2576(defun rst-all-stn () 2577 ;; testcover: ok. 2578 "Return the hierarchical tree of sections as a top level `rst-Stn'. 2579Return value satisfies `rst-Stn-is-top' or is nil for no 2580sections." 2581 (cdr (rst-remaining-stn (rst-all-ttls-with-level) -1))) 2582 2583(defun rst-remaining-stn (unprocessed expected) 2584 ;; testcover: ok. 2585 "Process the first entry of UNPROCESSED expected to be on level EXPECTED. 2586UNPROCESSED is the remaining list of (`rst-Ttl' . LEVEL) entries. 2587Return (REMAINING . STN) for the first entry of UNPROCESSED. 2588REMAINING is the list of still unprocessed entries. STN is a 2589`rst-Stn' or nil if UNPROCESSED is empty." 2590 (if (not unprocessed) 2591 (1value 2592 (cons nil nil)) 2593 (cl-destructuring-bind 2594 ((ttl &rest level) &rest next 2595 &aux fnd children) 2596 unprocessed 2597 (when (= level expected) 2598 ;; Consume the current entry and create the current node with it. 2599 (setq fnd ttl) 2600 (setq unprocessed next)) 2601 ;; Build the child nodes as long as they have deeper level. 2602 (while (and unprocessed (> (cdar unprocessed) expected)) 2603 (cl-destructuring-bind (remaining &rest stn) 2604 (rst-remaining-stn unprocessed (1+ expected)) 2605 (when stn 2606 (push stn children)) 2607 (setq unprocessed remaining))) 2608 (cons unprocessed 2609 (when (or fnd children) 2610 (rst-Stn-new fnd expected (nreverse children))))))) 2611 2612(defun rst-stn-containing-point (stn &optional point) 2613 ;; testcover: ok. 2614 "Return `rst-Stn' in STN before POINT or nil if in no section. 2615POINT defaults to the current point. STN may be nil for no 2616section headers at all." 2617 (when stn 2618 (setq point (or point (point))) 2619 (when (>= point (rst-Stn-get-title-beginning stn)) 2620 ;; Point may be in this section or a child. 2621 (let ((in-child (cl-find-if 2622 #'(lambda (child) 2623 (>= point (rst-Stn-get-title-beginning child))) 2624 (rst-Stn-children stn) 2625 :from-end t))) 2626 (if in-child 2627 (rst-stn-containing-point in-child point) 2628 stn))))) 2629 2630(defgroup rst-toc nil 2631 "Settings for reStructuredText table of contents." 2632 :group 'rst 2633 :version "21.1") 2634 2635(defcustom rst-toc-indent 2 2636 "Indentation for table-of-contents display. 2637Also used for formatting insertion, when numbering is disabled." 2638 :type 'integer 2639 :group 'rst-toc) 2640 2641(defcustom rst-toc-insert-style 'fixed 2642 "Insertion style for table-of-contents. 2643Set this to one of the following values to determine numbering and 2644indentation style: 2645- `plain': no numbering (fixed indentation) 2646- `fixed': numbering, but fixed indentation 2647- `aligned': numbering, titles aligned under each other 2648- `listed': titles as list items" 2649 :type '(choice (const plain) 2650 (const fixed) 2651 (const aligned) 2652 (const listed)) 2653 :group 'rst-toc) 2654 2655(defcustom rst-toc-insert-number-separator " " 2656 "Separator that goes between the TOC number and the title." 2657 :type 'string 2658 :group 'rst-toc) 2659 2660(defcustom rst-toc-insert-max-level nil 2661 "If non-nil, maximum depth of the inserted TOC." 2662 :type '(choice (const nil) integer) 2663 :group 'rst-toc) 2664 2665(defconst rst-toc-link-keymap 2666 (let ((map (make-sparse-keymap))) 2667 (define-key map [mouse-1] 'rst-toc-mouse-follow-link) 2668 map) 2669 "Keymap used for links in TOC.") 2670 2671(defun rst-toc-insert (&optional max-level) 2672 ;; testcover: ok. 2673 "Insert the table of contents of the current section at the current column. 2674By default the top level is ignored if there is only one, because 2675we assume that the document will have a single title. A numeric 2676prefix argument MAX-LEVEL overrides `rst-toc-insert-max-level'. 2677Text in the line beyond column is deleted." 2678 (interactive "P") 2679 (rst-reset-section-caches) 2680 (let ((pt-stn (rst-stn-containing-point (rst-all-stn)))) 2681 (when pt-stn 2682 (let ((max 2683 (if (and (integerp max-level) 2684 (> (prefix-numeric-value max-level) 0)) 2685 (prefix-numeric-value max-level) 2686 rst-toc-insert-max-level)) 2687 (ind (current-column)) 2688 (buf (current-buffer)) 2689 (tabs indent-tabs-mode) ; Copy buffer local value. 2690 txt) 2691 (setq txt 2692 ;; Render to temporary buffer so markers are created correctly. 2693 (with-temp-buffer 2694 (rst-toc-insert-tree pt-stn buf rst-toc-insert-style max 2695 rst-toc-link-keymap nil) 2696 (goto-char (point-min)) 2697 (when (rst-forward-line-strict 1) 2698 ;; There are lines to indent. 2699 (let ((indent-tabs-mode tabs)) 2700 (indent-rigidly (point) (point-max) ind))) 2701 (buffer-string))) 2702 (unless (zerop (length txt)) 2703 ;; Delete possible trailing text. 2704 (delete-region (point) (line-beginning-position 2)) 2705 (insert txt) 2706 (backward-char 1)))))) 2707 2708(defun rst-toc-insert-link (pfx stn buf keymap) 2709 ;; testcover: ok. 2710 "Insert text of STN in BUF as a linked section reference at point. 2711If KEYMAP use this as keymap property. PFX is inserted before text." 2712 (let ((beg (point))) 2713 (insert pfx) 2714 (insert (rst-Stn-get-text stn)) 2715 (put-text-property beg (point) 'mouse-face 'highlight) 2716 (insert "\n") 2717 (put-text-property 2718 beg (point) 'rst-toc-target 2719 (set-marker (make-marker) (rst-Stn-get-title-beginning stn) buf)) 2720 (when keymap 2721 (put-text-property beg (point) 'keymap keymap)))) 2722 2723(defun rst-toc-get-link (link-buf link-pnt) 2724 ;; testcover: ok. 2725 "Return the link from text property at LINK-PNT in LINK-BUF." 2726 (let ((mrkr (get-text-property link-pnt 'rst-toc-target link-buf))) 2727 (unless mrkr 2728 (error "No section on this line")) 2729 (unless (buffer-live-p (marker-buffer mrkr)) 2730 (error "Buffer for this section was killed")) 2731 mrkr)) 2732 2733(defun rst-toc-insert-tree (stn buf style depth keymap tgt-stn) 2734 ;; testcover: ok. 2735 "Insert table of contents of tree below top node STN in buffer BUF. 2736STYLE is the style to use and must be one of the symbols allowed 2737for `rst-toc-insert-style'. DEPTH is the maximum relative depth 2738from STN to insert or nil for no maximum depth. See 2739`rst-toc-insert-link' for KEYMAP. Return beginning of title line 2740if TGT-STN is rendered or nil if not rendered or TGT-STN is nil. 2741Just return nil if STN is nil." 2742 (when stn 2743 (rst-toc-insert-children (rst-Stn-children stn) buf style depth 0 "" keymap 2744 tgt-stn))) 2745 2746(defun rst-toc-insert-children (children buf style depth indent numbering 2747 keymap tgt-stn) 2748 ;; testcover: ok. 2749 "In the current buffer at point insert CHILDREN in BUF to table of contents. 2750See `rst-toc-insert-tree' for STYLE, DEPTH and TGT-STN. See 2751`rst-toc-insert-stn' for INDENT and NUMBERING. See 2752`rst-toc-insert-link' for KEYMAP." 2753 (let ((count 1) 2754 ;; Child numbering is done from the parent. 2755 (num-fmt (format "%%%dd" 2756 (1+ (floor (log (1+ (length children)) 10))))) 2757 fnd) 2758 (when (not (equal numbering "")) 2759 ;; Add separating dot to existing numbering. 2760 (setq numbering (concat numbering "."))) 2761 (dolist (child children fnd) 2762 (setq fnd 2763 (or (rst-toc-insert-stn child buf style depth indent 2764 (concat numbering (format num-fmt count)) 2765 keymap tgt-stn) fnd)) 2766 (cl-incf count)))) 2767 2768;; FIXME refactoring: Use `rst-Stn-buffer' instead of `buf'. 2769(defun rst-toc-insert-stn (stn buf style depth indent numbering keymap tgt-stn) 2770 ;; testcover: ok. 2771 "In the current buffer at point insert STN in BUF into table of contents. 2772See `rst-toc-insert-tree' for STYLE, DEPTH and TGT-STN. INDENT 2773is the indentation depth to use for STN. NUMBERING is the prefix 2774numbering for STN. See `rst-toc-insert-link' for KEYMAP." 2775 (when (or (not depth) (> depth 0)) 2776 (cl-destructuring-bind 2777 (pfx add 2778 &aux (fnd (when (and tgt-stn 2779 (equal (rst-Stn-get-title-beginning stn) 2780 (rst-Stn-get-title-beginning tgt-stn))) 2781 (point)))) 2782 (cond 2783 ((eq style 'plain) 2784 (list "" rst-toc-indent)) 2785 ((eq style 'fixed) 2786 (list (concat numbering rst-toc-insert-number-separator) 2787 rst-toc-indent)) 2788 ((eq style 'aligned) 2789 (list (concat numbering rst-toc-insert-number-separator) 2790 (+ (length numbering) 2791 (length rst-toc-insert-number-separator)))) 2792 ((eq style 'listed) 2793 (list (format "%c " (car rst-preferred-bullets)) 2))) 2794 ;; Indent using spaces so buffer characteristics like `indent-tabs-mode' 2795 ;; do not matter. 2796 (rst-toc-insert-link (concat (make-string indent ? ) pfx) stn buf keymap) 2797 (or (rst-toc-insert-children (rst-Stn-children stn) buf style 2798 (when depth 2799 (1- depth)) 2800 (+ indent add) numbering keymap tgt-stn) 2801 fnd)))) 2802 2803(defun rst-toc-update () 2804 ;; testcover: ok. 2805 "Automatically find the contents section of a document and update. 2806Updates the inserted TOC if present. You can use this in your 2807file-write hook to always make it up-to-date automatically." 2808 (interactive) 2809 (save-match-data 2810 (save-excursion 2811 ;; Find and delete an existing comment after the first contents 2812 ;; directive. Delete that region. 2813 (goto-char (point-min)) 2814 ;; FIXME: Should accept indentation of the whole block. 2815 ;; We look for the following and the following only (in other words, if 2816 ;; your syntax differs, this won't work.). 2817 ;; 2818 ;; .. contents:: [...anything here...] 2819 ;; [:field: value]... 2820 ;; .. 2821 ;; XXXXXXXX 2822 ;; XXXXXXXX 2823 ;; [more lines] 2824 ;; FIXME: Works only for the first of these tocs. There should be a 2825 ;; fixed text after the comment such as "RST-MODE ELECTRIC TOC". 2826 ;; May be parameters such as `max-level' should be appended. 2827 (let ((beg (re-search-forward 2828 (1value 2829 (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n" 2830 "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag)) 2831 nil t)) 2832 fnd) 2833 (when 2834 (and beg 2835 (rst-forward-line-looking-at 2836 1 'lin-end 2837 #'(lambda (mtcd) 2838 (unless mtcd 2839 (rst-apply-indented-blocks 2840 (point) (point-max) (current-indentation) 2841 #'(lambda (count _in-first _in-sub in-super in-empty 2842 _relind) 2843 (cond 2844 ((or (> count 1) in-super)) 2845 ((not in-empty) 2846 (setq fnd (line-end-position)) 2847 nil))))) 2848 t))) 2849 (when fnd 2850 (delete-region beg fnd)) 2851 (goto-char beg) 2852 (insert "\n ") 2853 ;; FIXME: Ignores an `max-level' given to the original 2854 ;; `rst-toc-insert'. `max-level' could be rendered to the first 2855 ;; line. 2856 (rst-toc-insert))))) 2857 ;; Note: always return nil, because this may be used as a hook. 2858 nil) 2859 2860;; FIXME: Updating the toc on saving would be nice. However, this doesn't work 2861;; correctly: 2862;; 2863;; (add-hook 'write-contents-hooks 'rst-toc-update-fun) 2864;; (defun rst-toc-update-fun () 2865;; ;; Disable undo for the write file hook. 2866;; (let ((buffer-undo-list t)) (rst-toc-update) )) 2867 2868;; Maintain an alias for compatibility. 2869(defalias 'rst-toc-insert-update 'rst-toc-update) 2870 2871(defconst rst-toc-buffer-name "*Table of Contents*" 2872 "Name of the Table of Contents buffer.") 2873 2874(defvar-local rst-toc-mode-return-wincfg nil 2875 "Window configuration to which to return when leaving the TOC.") 2876 2877(defun rst-toc () 2878 ;; testcover: ok. 2879 "Display a table of contents for current buffer. 2880Displays all section titles found in the current buffer in a 2881hierarchical list. The resulting buffer can be navigated, and 2882selecting a section title moves the cursor to that section." 2883 (interactive) 2884 (rst-reset-section-caches) 2885 (let* ((wincfg (list (current-window-configuration) (point-marker))) 2886 (sectree (rst-all-stn)) 2887 (target-stn (rst-stn-containing-point sectree)) 2888 (target-buf (current-buffer)) 2889 (buf (get-buffer-create rst-toc-buffer-name)) 2890 target-pos) 2891 (with-current-buffer buf 2892 (let ((inhibit-read-only t)) 2893 (rst-toc-mode) 2894 (delete-region (point-min) (point-max)) 2895 ;; FIXME: Could use a customizable style. 2896 (setq target-pos (rst-toc-insert-tree 2897 sectree target-buf 'plain nil nil target-stn)))) 2898 (display-buffer buf) 2899 (pop-to-buffer buf) 2900 (setq rst-toc-mode-return-wincfg wincfg) 2901 (goto-char (or target-pos (point-min))))) 2902 2903;; Maintain an alias for compatibility. 2904(defalias 'rst-goto-section 'rst-toc-follow-link) 2905 2906(defun rst-toc-follow-link (link-buf link-pnt kill) 2907 ;; testcover: ok. 2908 "Follow the link to the section at LINK-PNT in LINK-BUF. 2909LINK-PNT and LINK-BUF default to the point in the current buffer. 2910With prefix argument KILL a TOC buffer is destroyed. Throw an 2911error if there is no working link at the given position." 2912 (interactive "i\nd\nP") 2913 (unless link-buf 2914 (setq link-buf (current-buffer))) 2915 ;; Do not catch errors from `rst-toc-get-link' because otherwise the error is 2916 ;; suppressed and invisible in interactive use. 2917 (let ((mrkr (rst-toc-get-link link-buf link-pnt))) 2918 (condition-case nil 2919 (rst-toc-mode-return kill) 2920 ;; Catch errors when not in `toc-mode'. 2921 (error nil)) 2922 (pop-to-buffer (marker-buffer mrkr)) 2923 (goto-char mrkr) 2924 ;; FIXME: Should be a customizable number of lines from beginning or end of 2925 ;; window just like the argument to `recenter`. It would be ideal if 2926 ;; the adornment is always completely visible. 2927 (recenter 5))) 2928 2929;; Maintain an alias for compatibility. 2930(defalias 'rst-toc-mode-goto-section 'rst-toc-mode-follow-link-kill) 2931 2932;; FIXME: Cursor before or behind the list must be handled properly; before the 2933;; list should jump to the top and behind the list to the last normal 2934;; paragraph. 2935(defun rst-toc-mode-follow-link-kill () 2936 ;; testcover: ok. 2937 "Follow the link to the section at point and kill the TOC buffer." 2938 (interactive) 2939 (rst-toc-follow-link (current-buffer) (point) t)) 2940 2941;; Maintain an alias for compatibility. 2942(defalias 'rst-toc-mode-mouse-goto 'rst-toc-mouse-follow-link) 2943 2944(defun rst-toc-mouse-follow-link (event kill) 2945 ;; testcover: uncovered. 2946 "In `rst-toc' mode, go to the occurrence whose line you click on. 2947EVENT is the input event. Kill TOC buffer if KILL." 2948 (interactive "e\ni") 2949 (rst-toc-follow-link (window-buffer (posn-window (event-end event))) 2950 (posn-point (event-end event)) kill)) 2951 2952;; Maintain an alias for compatibility. 2953(defalias 'rst-toc-mode-mouse-goto-kill 'rst-toc-mode-mouse-follow-link-kill) 2954 2955(defun rst-toc-mode-mouse-follow-link-kill (event) 2956 ;; testcover: uncovered. 2957 "Same as `rst-toc-mouse-follow-link', but kill TOC buffer as well. 2958EVENT is the input event." 2959 (interactive "e") 2960 (rst-toc-mouse-follow-link event t)) 2961 2962;; Maintain an alias for compatibility. 2963(defalias 'rst-toc-quit-window 'rst-toc-mode-return) 2964 2965(defun rst-toc-mode-return (kill) 2966 ;; testcover: ok. 2967 "Leave the current TOC buffer and return to the previous environment. 2968With prefix argument KILL non-nil, kill the buffer instead of 2969burying it." 2970 (interactive "P") 2971 (unless rst-toc-mode-return-wincfg 2972 (error "Not in a `toc-mode' buffer")) 2973 (cl-destructuring-bind 2974 (wincfg pos 2975 &aux (toc-buf (current-buffer))) 2976 rst-toc-mode-return-wincfg 2977 (set-window-configuration wincfg) 2978 (goto-char pos) 2979 (if kill 2980 (kill-buffer toc-buf) 2981 (bury-buffer toc-buf)))) 2982 2983(defun rst-toc-mode-return-kill () 2984 ;; testcover: uncovered. 2985 "Like `rst-toc-mode-return' but kill TOC buffer." 2986 (interactive) 2987 (rst-toc-mode-return t)) 2988 2989(defvar rst-toc-mode-map 2990 (let ((map (make-sparse-keymap))) 2991 (define-key map [mouse-1] #'rst-toc-mode-mouse-follow-link-kill) 2992 (define-key map [mouse-2] #'rst-toc-mouse-follow-link) 2993 (define-key map "\C-m" #'rst-toc-mode-follow-link-kill) 2994 (define-key map "f" #'rst-toc-mode-follow-link-kill) 2995 (define-key map "n" #'next-line) 2996 (define-key map "p" #'previous-line) 2997 (define-key map "q" #'rst-toc-mode-return) 2998 (define-key map "z" #'rst-toc-mode-return-kill) 2999 map) 3000 "Keymap for `rst-toc-mode'.") 3001 3002(define-derived-mode rst-toc-mode special-mode "ReST-TOC" 3003 "Major mode for output from \\[rst-toc], the table-of-contents for the document. 3004\\{rst-toc-mode-map}" 3005 ;; FIXME: `revert-buffer-function` must be defined so `revert-buffer` works 3006 ;; as expected for a special mode. In particular the referred buffer 3007 ;; needs to be rescanned and the TOC must be updated accordingly. 3008 ;; FIXME: Should contain the name of the buffer this is the toc of. 3009 (setq header-line-format "Table of Contents")) 3010 3011;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3012;; Section movement 3013 3014;; FIXME testcover: Use `testcover'. Mark up a function with sufficient test 3015;; coverage by a comment tagged with `testcover' after the 3016;; `defun'. Then move this comment. 3017 3018(defun rst-forward-section (offset) 3019 "Jump forward OFFSET section titles ending up at the start of the title line. 3020OFFSET defaults to 1 and may be negative to move backward. An 3021OFFSET of 0 does not move unless point is inside a title. Go to 3022end or beginning of buffer if no more section titles in the desired 3023direction." 3024 (interactive "p") 3025 (rst-reset-section-caches) 3026 (let* ((ttls (rst-all-ttls)) 3027 (count (length ttls)) 3028 (pnt (point)) 3029 (contained nil) ; Title contains point (or is after point otherwise). 3030 (found (or (cl-position-if 3031 ;; Find a title containing or after point. 3032 #'(lambda (ttl) 3033 (let ((cmp (rst-Ttl-contains ttl pnt))) 3034 (cond 3035 ((= cmp 0) ; Title contains point. 3036 (setq contained t) 3037 t) 3038 ((> cmp 0) ; Title after point. 3039 t)))) 3040 ttls) 3041 ;; Point after all titles. 3042 count)) 3043 (target (+ found offset 3044 ;; If point is in plain text found title is already one 3045 ;; step forward. 3046 (if (and (not contained) (>= offset 0)) -1 0)))) 3047 (goto-char (cond 3048 ((< target 0) 3049 (point-min)) 3050 ((>= target count) 3051 (point-max)) 3052 ((and (not contained) (= offset 0)) 3053 ;; Point not in title and should not move - do not move. 3054 pnt) 3055 ((rst-Ttl-get-title-beginning (nth target ttls))))))) 3056 3057(defun rst-backward-section (offset) 3058 "Like `rst-forward-section', except move backward by OFFSET." 3059 (interactive "p") 3060 (rst-forward-section (- offset))) 3061 3062;; FIXME: What is `allow-extend' for? See `mark-paragraph' for an explanation. 3063(defun rst-mark-section (&optional count allow-extend) 3064 "Select COUNT sections around point. 3065Mark following sections for positive COUNT or preceding sections 3066for negative COUNT." 3067 ;; Cloned from mark-paragraph. 3068 (interactive "p\np") 3069 (unless count (setq count 1)) 3070 (when (zerop count) 3071 (error "Cannot mark zero sections")) 3072 (cond ((and allow-extend 3073 (or (and (eq last-command this-command) (mark t)) 3074 (use-region-p))) 3075 (set-mark 3076 (save-excursion 3077 (goto-char (mark)) 3078 (rst-forward-section count) 3079 (point)))) 3080 (t 3081 (rst-forward-section count) 3082 (push-mark nil t t) 3083 (rst-forward-section (- count))))) 3084 3085 3086;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3087;; Indentation 3088 3089(defun rst-find-leftmost-column (beg end) 3090 "Return the leftmost column spanned by region BEG to END. 3091The line containing the start of the region is always considered 3092spanned. If the region ends at the beginning of a line this line 3093is not considered spanned, otherwise it is spanned." 3094 (let (mincol) 3095 (save-match-data 3096 (save-excursion 3097 (goto-char beg) 3098 (1value 3099 (rst-forward-line-strict 0)) 3100 (while (< (point) end) 3101 (unless (looking-at (rst-re 'lin-end)) 3102 (setq mincol (if mincol 3103 (min mincol (current-indentation)) 3104 (current-indentation)))) 3105 (rst-forward-line-strict 1 end))) 3106 mincol))) 3107 3108;; FIXME: At the moment only block comments with leading empty comment line are 3109;; supported. Comment lines with leading comment markup should be also 3110;; supported. May be a customizable option could control which style to 3111;; prefer. 3112 3113(defgroup rst-indent nil "Settings for indentation in reStructuredText. 3114 3115In reStructuredText indentation points are usually determined by 3116preceding lines. Sometimes the syntax allows arbitrary indentation 3117points such as where to start the first line following a directive. 3118These indentation widths can be customized here." 3119 :group 'rst 3120 :package-version '(rst . "1.1.0")) 3121 3122(define-obsolete-variable-alias 3123 'rst-shift-basic-offset 'rst-indent-width "rst 1.0.0") 3124(defcustom rst-indent-width 2 3125 "Indentation when there is no more indentation point given." 3126 :group 'rst-indent 3127 :type '(integer)) 3128 3129(defcustom rst-indent-field 3 3130 "Indentation for first line after a field or 0 to always indent for content." 3131 :group 'rst-indent 3132 :package-version '(rst . "1.1.0") 3133 :type '(integer)) 3134 3135(defcustom rst-indent-literal-normal 3 3136 "Default indentation for literal block after a markup on an own line." 3137 :group 'rst-indent 3138 :package-version '(rst . "1.1.0") 3139 :type '(integer)) 3140 3141(defcustom rst-indent-literal-minimized 2 3142 "Default indentation for literal block after a minimized markup." 3143 :group 'rst-indent 3144 :package-version '(rst . "1.1.0") 3145 :type '(integer)) 3146 3147(defcustom rst-indent-comment 3 3148 "Default indentation for first line of a comment." 3149 :group 'rst-indent 3150 :package-version '(rst . "1.1.0") 3151 :type '(integer)) 3152 3153;; FIXME: Must consider other tabs: 3154;; * Line blocks 3155;; * Definition lists 3156;; * Option lists 3157(defun rst-line-tabs () 3158 "Return tabs of the current line or nil for no tab. 3159The list is sorted so the tab where writing continues most likely 3160is the first one. Each tab is of the form (COLUMN . INNER). 3161COLUMN is the column of the tab. INNER is non-nil if this is an 3162inner tab. I.e. a tab which does come from the basic indentation 3163and not from inner alignment points." 3164 (save-excursion 3165 (rst-forward-line-strict 0) 3166 (save-match-data 3167 (unless (looking-at (rst-re 'lin-end)) 3168 (back-to-indentation) 3169 ;; Current indentation is always the least likely tab. 3170 (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER) 3171 ;; Push inner tabs more likely to continue writing. 3172 (cond 3173 ;; Item. 3174 ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?")) 3175 (when (match-string 2) 3176 (push (list (match-beginning 2) 0 t) tabs))) 3177 ;; Field. 3178 ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag) 3179 '(:grp "\\S ") "?")) 3180 (unless (zerop rst-indent-field) 3181 (push (list (match-beginning 1) rst-indent-field t) tabs)) 3182 (if (match-string 3) 3183 (push (list (match-beginning 3) 0 t) tabs) 3184 (if (zerop rst-indent-field) 3185 (push (list (match-end 2) 3186 (if (string= (match-string 2) "") 1 0) 3187 t) 3188 tabs)))) 3189 ;; Directive. 3190 ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?")) 3191 (push (list (match-end 1) 0 t) tabs) 3192 (unless (string= (match-string 2) "") 3193 (push (list (match-end 2) 0 t) tabs)) 3194 (when (match-string 4) 3195 (push (list (match-beginning 4) 0 t) tabs))) 3196 ;; Footnote or citation definition. 3197 ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?")) 3198 (push (list (match-end 1) 0 t) tabs) 3199 (when (match-string 3) 3200 (push (list (match-beginning 3) 0 t) tabs))) 3201 ;; Comment. 3202 ((looking-at (rst-re 'cmt-sta-1)) 3203 (push (list (point) rst-indent-comment t) tabs))) 3204 ;; Start of literal block. 3205 (when (looking-at (rst-re 'lit-sta-2)) 3206 (cl-destructuring-bind (point offset _inner) (car tabs) 3207 (push (list point 3208 (+ offset 3209 (if (match-string 1) 3210 rst-indent-literal-minimized 3211 rst-indent-literal-normal)) 3212 t) 3213 tabs))) 3214 (mapcar (cl-function 3215 (lambda ((point offset inner)) 3216 (goto-char point) 3217 (cons (+ (current-column) offset) inner))) 3218 tabs)))))) 3219 3220(defun rst-compute-tabs (pt) 3221 "Build the list of possible tabs for all lines above. 3222Search backwards from point PT to build the list of possible tabs. 3223Return a list of tabs sorted by likeliness to continue writing 3224like `rst-line-tabs'. Nearer lines have generally a higher 3225likeliness than farther lines. Return nil if no tab is found in 3226the text above." 3227 ;; FIXME: See test `indent-for-tab-command-BUGS`. 3228 (save-excursion 3229 (goto-char pt) 3230 (let (leftmost ; Leftmost column found so far. 3231 innermost ; Leftmost column for inner tab. 3232 tablist) 3233 (while (and (rst-forward-line-strict -1) 3234 (or (not leftmost) 3235 (> leftmost 0))) 3236 (let ((tabs (rst-line-tabs))) 3237 (when tabs 3238 (let ((leftcol (apply #'min (mapcar #'car tabs)))) 3239 ;; Consider only lines indented less or same if not INNERMOST. 3240 (when (or (not leftmost) 3241 (< leftcol leftmost) 3242 (and (not innermost) (= leftcol leftmost))) 3243 (rst-destructuring-dolist ((column &rest inner) tabs) 3244 (when (or 3245 (and (not inner) 3246 (or (not leftmost) 3247 (< column leftmost))) 3248 (and inner 3249 (or (not innermost) 3250 (< column innermost)))) 3251 (setq tablist (cl-adjoin column tablist)))) 3252 (setq innermost (if (cl-some #'cdr tabs) ; Has inner. 3253 leftcol 3254 innermost)) 3255 (setq leftmost leftcol)))))) 3256 (nreverse tablist)))) 3257 3258(defun rst-indent-line (&optional dflt) 3259 "Indent current line to next best reStructuredText tab. 3260The next best tab is taken from the tab list returned by 3261`rst-compute-tabs' which is used in a cyclic manner. If the 3262current indentation does not end on a tab use the first one. If 3263the current indentation is on a tab use the next tab. This allows 3264a repeated use of \\[indent-for-tab-command] to cycle through all 3265possible tabs. If no indentation is possible return `noindent' or 3266use DFLT. Return the indentation indented to. When point is in 3267indentation it ends up at its end. Otherwise the point is kept 3268relative to the content." 3269 (let* ((pt (point-marker)) 3270 (cur (current-indentation)) 3271 (clm (current-column)) 3272 (tabs (rst-compute-tabs (point))) 3273 (fnd (cl-position cur tabs :test #'equal)) 3274 ind) 3275 (if (and (not tabs) (not dflt)) 3276 'noindent 3277 (if (not tabs) 3278 (setq ind dflt) 3279 (if (not fnd) 3280 (setq fnd 0) 3281 (setq fnd (1+ fnd)) 3282 (if (>= fnd (length tabs)) 3283 (setq fnd 0))) 3284 (setq ind (nth fnd tabs))) 3285 (indent-line-to ind) 3286 (if (> clm cur) 3287 (goto-char pt)) 3288 (set-marker pt nil) 3289 ind))) 3290 3291(defun rst-shift-region (beg end cnt) 3292 "Shift region BEG to END by CNT tabs. 3293Shift by one tab to the right (CNT > 0) or left (CNT < 0) or 3294remove all indentation (CNT = 0). A tab is taken from the text 3295above. If no suitable tab is found `rst-indent-width' is used." 3296 (interactive "r\np") 3297 (let ((tabs (sort (rst-compute-tabs beg) 3298 #'(lambda (x y) 3299 (<= x y)))) 3300 (leftmostcol (rst-find-leftmost-column beg end))) 3301 (when (or (> leftmostcol 0) (> cnt 0)) 3302 ;; Apply the indent. 3303 (indent-rigidly 3304 beg end 3305 (if (zerop cnt) 3306 (- leftmostcol) 3307 ;; Find the next tab after the leftmost column. 3308 (let* ((cmp (if (> cnt 0) #'> #'<)) 3309 (tabs (if (> cnt 0) tabs (reverse tabs))) 3310 (len (length tabs)) 3311 (dir (cl-signum cnt)) ; Direction to take. 3312 (abs (abs cnt)) ; Absolute number of steps to take. 3313 ;; Get the position of the first tab beyond leftmostcol. 3314 (fnd (cl-position-if #'(lambda (elt) 3315 (funcall cmp elt leftmostcol)) 3316 tabs)) 3317 ;; Virtual position of tab. 3318 (pos (+ (or fnd len) (1- abs))) 3319 (tab (if (< pos len) 3320 ;; Tab exists - use it. 3321 (nth pos tabs) 3322 ;; Column needs to be computed. 3323 (let ((col (+ (or (car (last tabs)) leftmostcol) 3324 ;; Base on last known column. 3325 (* (- pos (1- len)) ; Distance left. 3326 dir ; Direction to take. 3327 rst-indent-width)))) 3328 (if (< col 0) 0 col))))) 3329 (- tab leftmostcol))))))) 3330 3331;; FIXME: A paragraph with an (incorrectly) indented second line is not filled 3332;; correctly:: 3333;; 3334;; Some start 3335;; continued wrong 3336(defun rst-adaptive-fill () 3337 "Return fill prefix found at point. 3338Value for `adaptive-fill-function'." 3339 (save-match-data 3340 (let ((fnd (if (looking-at adaptive-fill-regexp) 3341 (match-string-no-properties 0)))) 3342 (if (save-match-data 3343 (not (string-match comment-start-skip fnd))) 3344 ;; An non-comment prefix is fine. 3345 fnd 3346 ;; Matches a comment - return whitespace instead. 3347 (make-string (- 3348 (save-excursion 3349 (goto-char (match-end 0)) 3350 (current-column)) 3351 (save-excursion 3352 (goto-char (match-beginning 0)) 3353 (current-column))) ? ))))) 3354 3355;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3356;; Comments 3357 3358(defun rst-comment-line-break (&optional soft) 3359 "Break line and indent, continuing reStructuredText comment if within one. 3360Value for `comment-line-break-function'. If SOFT use soft 3361newlines as mandated by `comment-line-break-function'." 3362 (if soft 3363 (insert-and-inherit ?\n) 3364 (newline 1)) 3365 (save-excursion 3366 (forward-char -1) 3367 (delete-horizontal-space)) 3368 (delete-horizontal-space) 3369 (let ((tabs (rst-compute-tabs (point)))) 3370 (when tabs 3371 (indent-line-to (car tabs))))) 3372 3373(defun rst-comment-indent () 3374 "Return indentation for current comment line." 3375 (car (rst-compute-tabs (point)))) 3376 3377(defun rst-comment-insert-comment () 3378 "Insert a comment in the current line." 3379 (rst-indent-line 0) 3380 (insert comment-start)) 3381 3382(defun rst-comment-region (beg end &optional arg) 3383 "Comment or uncomment the current region. 3384Region is from BEG to END. Uncomment if ARG." 3385 (save-excursion 3386 (if (consp arg) 3387 (rst-uncomment-region beg end arg) 3388 (goto-char beg) 3389 (rst-forward-line-strict 0) 3390 (let ((ind (current-indentation)) 3391 (bol (point))) 3392 (indent-rigidly bol end rst-indent-comment) 3393 (goto-char bol) 3394 (open-line 1) 3395 (indent-line-to ind) 3396 (insert (comment-string-strip comment-start t t)))))) 3397 3398(defun rst-uncomment-region (beg end &optional _arg) 3399 "Uncomment the current region. 3400Region is from BEG to END. _ARG is ignored." 3401 (save-excursion 3402 (goto-char beg) 3403 (rst-forward-line-strict 0) 3404 (let ((bol (point))) 3405 (rst-forward-line-strict 1 end) 3406 (indent-rigidly (point) end (- rst-indent-comment)) 3407 (goto-char bol) 3408 (rst-delete-entire-line 0)))) 3409 3410;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3411;; Apply to indented block 3412 3413;; FIXME: These next functions should become part of a larger effort to redo 3414;; the bullets in bulleted lists. The enumerate would just be one of 3415;; the possible outputs. 3416;; 3417;; FIXME: We need to do the enumeration removal as well. 3418 3419(defun rst-apply-indented-blocks (beg end ind fun) 3420 "Apply FUN to all lines from BEG to END in blocks indented to IND. 3421The first indented block starts with the first non-empty line 3422containing or after BEG and indented to IND. After the first 3423line the indented block may contain more lines with same 3424indentation (the paragraph) followed by empty lines and lines 3425more indented (the sub-blocks). A following line indented to IND 3426starts the next paragraph. A non-empty line with less 3427indentation than IND terminates the current paragraph. FUN is 3428applied to each line like this 3429 3430 (FUN COUNT IN-FIRST IN-SUB IN-SUPER IN-EMPTY RELIND) 3431 3432COUNT is 0 before the first paragraph and increments for every 3433paragraph found on level IND. IN-FIRST is non-nil if this is the 3434first line of such a paragraph. IN-SUB is non-nil if this line 3435is part of a sub-block while IN-SUPER is non-nil if this line is 3436part of a less indented block (super-block). IN-EMPTY is non-nil 3437if this line is empty where an empty line is considered being 3438part of the previous block. RELIND is nil for an empty line, 0 3439for a line indented to IND, and the positive or negative number 3440of columns more or less indented otherwise. When FUN is called 3441point is immediately behind indentation of that line. FUN may 3442change everything as long as a marker at END and at the beginning 3443of the following line is handled correctly by the change. A 3444non-nil return value from FUN breaks the loop and is returned. 3445Otherwise return nil." 3446 (let ((endm (copy-marker end t)) 3447 (count 0) ; Before first indented block. 3448 (nxt (when (< beg end) 3449 (copy-marker beg t))) 3450 (broken t) 3451 in-sub in-super stop) 3452 (save-match-data 3453 (save-excursion 3454 (while (and (not stop) nxt) 3455 (set-marker 3456 (goto-char nxt) nil) 3457 (setq nxt (save-excursion 3458 ;; FIXME refactoring: Replace `(forward-line) 3459 ;; (back-to-indentation)` by 3460 ;; `(forward-to-indentation)` 3461 (when (and (rst-forward-line-strict 1 endm) 3462 (< (point) endm)) 3463 (copy-marker (point) t)))) 3464 (back-to-indentation) 3465 (let ((relind (- (current-indentation) ind)) 3466 (in-empty (looking-at (rst-re 'lin-end))) 3467 in-first) 3468 (cond 3469 (in-empty 3470 (setq relind nil)) 3471 ((< relind 0) 3472 (setq in-sub nil) 3473 (setq in-super t)) 3474 ((> relind 0) 3475 (setq in-sub t) 3476 (setq in-super nil)) 3477 (t ; Non-empty line in indented block. 3478 (when (or broken in-sub in-super) 3479 (setq in-first t) 3480 (cl-incf count)) 3481 (setq in-sub nil) 3482 (setq in-super nil))) 3483 (save-excursion 3484 (setq 3485 stop 3486 (funcall fun count in-first in-sub in-super in-empty relind))) 3487 (setq broken in-empty))) 3488 (set-marker endm nil) 3489 stop)))) 3490 3491(defun rst-enumerate-region (beg end all) 3492 "Add enumeration to all the leftmost paragraphs in the given region. 3493The region is specified between BEG and END. With ALL, 3494do all lines instead of just paragraphs." 3495 (interactive "r\nP") 3496 (let ((enum 0) 3497 (indent "")) 3498 (rst-apply-indented-blocks 3499 beg end (rst-find-leftmost-column beg end) 3500 #'(lambda (count in-first in-sub in-super in-empty _relind) 3501 (cond 3502 (in-empty) 3503 (in-super) 3504 ((zerop count)) 3505 (in-sub 3506 (insert indent)) 3507 ((or in-first all) 3508 (let ((tag (format "%d. " (cl-incf enum)))) 3509 (setq indent (make-string (length tag) ? )) 3510 (insert tag))) 3511 (t 3512 (insert indent))) 3513 nil)))) 3514 3515;; FIXME: Does not deal with deeper indentation - although 3516;; `rst-apply-indented-blocks' could. 3517(defun rst-bullet-list-region (beg end all) 3518 "Add bullets to all the leftmost paragraphs in the given region. 3519The region is specified between BEG and END. With ALL, 3520do all lines instead of just paragraphs." 3521 (interactive "r\nP") 3522 (unless rst-preferred-bullets 3523 (error "No preferred bullets defined")) 3524 (let* ((bul (format "%c " (car rst-preferred-bullets))) 3525 (indent (make-string (length bul) ? ))) 3526 (rst-apply-indented-blocks 3527 beg end (rst-find-leftmost-column beg end) 3528 #'(lambda (count in-first in-sub in-super in-empty _relind) 3529 (cond 3530 (in-empty) 3531 (in-super) 3532 ((zerop count)) 3533 (in-sub 3534 (insert indent)) 3535 ((or in-first all) 3536 (insert bul)) 3537 (t 3538 (insert indent))) 3539 nil)))) 3540 3541;; FIXME: Does not deal with a varying number of digits appropriately. 3542;; FIXME: Does not deal with multiple levels independently. 3543;; FIXME: Does not indent a multiline item correctly. 3544(defun rst-convert-bullets-to-enumeration (beg end) 3545 "Convert the bulleted and enumerated items in the region to enumerated lists. 3546Renumber as necessary. Region is from BEG to END." 3547 (interactive "r") 3548 (let ((count 1)) 3549 (save-match-data 3550 (save-excursion 3551 (dolist (marker (mapcar 3552 (cl-function 3553 (lambda ((pnt &rest clm)) 3554 (copy-marker pnt))) 3555 (rst-find-begs beg end 'itmany-beg-1))) 3556 (set-marker 3557 (goto-char marker) nil) 3558 (looking-at (rst-re 'itmany-beg-1)) 3559 (replace-match (format "%d." count) nil nil nil 1) 3560 (cl-incf count)))))) 3561 3562(defun rst-line-block-region (beg end &optional with-empty) 3563 "Add line block prefixes for a region. 3564Region is from BEG to END. With WITH-EMPTY prefix empty lines too." 3565 (interactive "r\nP") 3566 (let ((ind (rst-find-leftmost-column beg end))) 3567 (rst-apply-indented-blocks 3568 beg end ind 3569 #'(lambda (_count _in-first _in-sub in-super in-empty _relind) 3570 (when (and (not in-super) (or with-empty (not in-empty))) 3571 (move-to-column ind t) 3572 (insert "| ")) 3573 nil)))) 3574 3575 3576;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3577;; Font lock 3578 3579(require 'font-lock) 3580 3581;; FIXME: The obsolete variables need to disappear. 3582 3583;; The following versions have been done inside Emacs and should not be 3584;; replaced by `:package-version' attributes until a change. 3585 3586(defgroup rst-faces nil "Faces used in Rst Mode." 3587 :group 'rst 3588 :group 'faces 3589 :version "21.1") 3590 3591(defface rst-block '((t :inherit font-lock-keyword-face)) 3592 "Face used for all syntax marking up a special block." 3593 :version "24.1" 3594 :group 'rst-faces) 3595 3596(defcustom rst-block-face 'rst-block 3597 "All syntax marking up a special block." 3598 :version "24.1" 3599 :group 'rst-faces 3600 :type '(face)) 3601(make-obsolete-variable 'rst-block-face 3602 "customize the face `rst-block' instead." 3603 "24.1") 3604 3605(defface rst-external '((t :inherit font-lock-type-face)) 3606 "Face used for field names and interpreted text." 3607 :version "24.1" 3608 :group 'rst-faces) 3609 3610(defcustom rst-external-face 'rst-external 3611 "Field names and interpreted text." 3612 :version "24.1" 3613 :group 'rst-faces 3614 :type '(face)) 3615(make-obsolete-variable 'rst-external-face 3616 "customize the face `rst-external' instead." 3617 "24.1") 3618 3619(defface rst-definition '((t :inherit font-lock-function-name-face)) 3620 "Face used for all other defining constructs." 3621 :version "24.1" 3622 :group 'rst-faces) 3623 3624(defcustom rst-definition-face 'rst-definition 3625 "All other defining constructs." 3626 :version "24.1" 3627 :group 'rst-faces 3628 :type '(face)) 3629(make-obsolete-variable 'rst-definition-face 3630 "customize the face `rst-definition' instead." 3631 "24.1") 3632 3633;; XEmacs compatibility (?). 3634(defface rst-directive (if (boundp 'font-lock-builtin-face) 3635 '((t :inherit font-lock-builtin-face)) 3636 '((t :inherit font-lock-preprocessor-face))) 3637 "Face used for directives and roles." 3638 :version "24.1" 3639 :group 'rst-faces) 3640 3641(defcustom rst-directive-face 'rst-directive 3642 "Directives and roles." 3643 :group 'rst-faces 3644 :type '(face)) 3645(make-obsolete-variable 'rst-directive-face 3646 "customize the face `rst-directive' instead." 3647 "24.1") 3648 3649(defface rst-comment '((t :inherit font-lock-comment-face)) 3650 "Face used for comments." 3651 :version "24.1" 3652 :group 'rst-faces) 3653 3654(defcustom rst-comment-face 'rst-comment 3655 "Comments." 3656 :version "24.1" 3657 :group 'rst-faces 3658 :type '(face)) 3659(make-obsolete-variable 'rst-comment-face 3660 "customize the face `rst-comment' instead." 3661 "24.1") 3662 3663(defface rst-emphasis1 '((t :inherit italic)) 3664 "Face used for simple emphasis." 3665 :version "24.1" 3666 :group 'rst-faces) 3667 3668(defcustom rst-emphasis1-face 'rst-emphasis1 3669 "Simple emphasis." 3670 :version "24.1" 3671 :group 'rst-faces 3672 :type '(face)) 3673(make-obsolete-variable 'rst-emphasis1-face 3674 "customize the face `rst-emphasis1' instead." 3675 "24.1") 3676 3677(defface rst-emphasis2 '((t :inherit bold)) 3678 "Face used for double emphasis." 3679 :version "24.1" 3680 :group 'rst-faces) 3681 3682(defcustom rst-emphasis2-face 'rst-emphasis2 3683 "Double emphasis." 3684 :group 'rst-faces 3685 :type '(face)) 3686(make-obsolete-variable 'rst-emphasis2-face 3687 "customize the face `rst-emphasis2' instead." 3688 "24.1") 3689 3690(defface rst-literal '((t :inherit font-lock-string-face)) 3691 "Face used for literal text." 3692 :version "24.1" 3693 :group 'rst-faces) 3694 3695(defcustom rst-literal-face 'rst-literal 3696 "Literal text." 3697 :version "24.1" 3698 :group 'rst-faces 3699 :type '(face)) 3700(make-obsolete-variable 'rst-literal-face 3701 "customize the face `rst-literal' instead." 3702 "24.1") 3703 3704(defface rst-reference '((t :inherit font-lock-variable-name-face)) 3705 "Face used for references to a definition." 3706 :version "24.1" 3707 :group 'rst-faces) 3708 3709(defcustom rst-reference-face 'rst-reference 3710 "References to a definition." 3711 :version "24.1" 3712 :group 'rst-faces 3713 :type '(face)) 3714(make-obsolete-variable 'rst-reference-face 3715 "customize the face `rst-reference' instead." 3716 "24.1") 3717 3718(defface rst-transition '((t :inherit font-lock-keyword-face)) 3719 "Face used for a transition." 3720 :package-version '(rst . "1.3.0") 3721 :group 'rst-faces) 3722 3723(defface rst-adornment '((t :inherit font-lock-keyword-face)) 3724 "Face used for the adornment of a section header." 3725 :package-version '(rst . "1.3.0") 3726 :group 'rst-faces) 3727 3728;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3729 3730(dolist (var '(rst-level-face-max rst-level-face-base-color 3731 rst-level-face-base-light 3732 rst-level-face-format-light 3733 rst-level-face-step-light 3734 rst-level-1-face 3735 rst-level-2-face 3736 rst-level-3-face 3737 rst-level-4-face 3738 rst-level-5-face 3739 rst-level-6-face)) 3740 (make-obsolete-variable var "customize the faces `rst-level-*' instead." 3741 "24.3")) 3742 3743;; Define faces for the first 6 levels. More levels are possible, however. 3744(defface rst-level-1 '((((background light)) (:background "grey85")) 3745 (((background dark)) (:background "grey15"))) 3746 "Default face for section title text at level 1." 3747 :package-version '(rst . "1.4.0")) 3748 3749(defface rst-level-2 '((((background light)) (:background "grey78")) 3750 (((background dark)) (:background "grey22"))) 3751 "Default face for section title text at level 2." 3752 :package-version '(rst . "1.4.0")) 3753 3754(defface rst-level-3 '((((background light)) (:background "grey71")) 3755 (((background dark)) (:background "grey29"))) 3756 "Default face for section title text at level 3." 3757 :package-version '(rst . "1.4.0")) 3758 3759(defface rst-level-4 '((((background light)) (:background "grey64")) 3760 (((background dark)) (:background "grey36"))) 3761 "Default face for section title text at level 4." 3762 :package-version '(rst . "1.4.0")) 3763 3764(defface rst-level-5 '((((background light)) (:background "grey57")) 3765 (((background dark)) (:background "grey43"))) 3766 "Default face for section title text at level 5." 3767 :package-version '(rst . "1.4.0")) 3768 3769(defface rst-level-6 '((((background light)) (:background "grey50")) 3770 (((background dark)) (:background "grey50"))) 3771 "Default face for section title text at level 6." 3772 :package-version '(rst . "1.4.0")) 3773 3774(defcustom rst-adornment-faces-alist 3775 '((t . rst-transition) 3776 (nil . rst-adornment) 3777 (1 . rst-level-1) 3778 (2 . rst-level-2) 3779 (3 . rst-level-3) 3780 (4 . rst-level-4) 3781 (5 . rst-level-5) 3782 (6 . rst-level-6)) 3783 "Faces for the various adornment types. 3784Key is a number (for the section title text of that level 3785starting with 1), t (for transitions) or nil (for section title 3786adornment). If you need levels beyond 6 you have to define faces 3787of your own." 3788 :group 'rst-faces 3789 :type '(alist 3790 :key-type 3791 (choice 3792 (integer :tag "Section level") 3793 (const :tag "transitions" t) 3794 (const :tag "section title adornment" nil)) 3795 :value-type (face))) 3796 3797;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3798 3799(defvar rst-font-lock-keywords 3800 ;; The reST-links in the comments below all relate to sections in 3801 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html. 3802 `(;; FIXME: Block markup is not recognized in blocks after explicit markup 3803 ;; start. 3804 3805 ;; Simple `Body Elements`_ 3806 ;; `Bullet Lists`_ 3807 ;; FIXME: A bullet directly after a field name is not recognized. 3808 (,(rst-re 'lin-beg '(:grp bul-sta)) 3809 1 rst-block-face) 3810 ;; `Enumerated Lists`_ 3811 (,(rst-re 'lin-beg '(:grp enmany-sta)) 3812 1 rst-block-face) 3813 ;; `Definition Lists`_ 3814 ;; FIXME: missing. 3815 ;; `Field Lists`_ 3816 (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx) 3817 1 rst-external-face) 3818 ;; `Option Lists`_ 3819 (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*") 3820 '(:alt "$" (:seq hws-prt "\\{2\\}"))) 3821 1 rst-block-face) 3822 ;; `Line Blocks`_ 3823 ;; Only for lines containing no more bar - to distinguish from tables. 3824 (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$") 3825 1 rst-block-face) 3826 3827 ;; `Tables`_ 3828 ;; FIXME: missing 3829 3830 ;; All the `Explicit Markup Blocks`_ 3831 ;; `Footnotes`_ / `Citations`_ 3832 (,(rst-re 'lin-beg 'fnc-sta-2) 3833 (1 rst-definition-face) 3834 (2 rst-definition-face)) 3835 ;; `Directives`_ / `Substitution Definitions`_ 3836 (,(rst-re 'lin-beg 'dir-sta-3) 3837 (1 rst-directive-face) 3838 (2 rst-definition-face) 3839 (3 rst-directive-face)) 3840 ;; `Hyperlink Targets`_ 3841 (,(rst-re 'lin-beg 3842 '(:grp exm-sta "_" (:alt 3843 (:seq "`" ilcbkqdef-tag "`") 3844 (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":") 3845 'bli-sfx) 3846 1 rst-definition-face) 3847 (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx) 3848 1 rst-definition-face) 3849 3850 ;; All `Inline Markup`_ 3851 ;; Most of them may be multiline though this is uninteresting. 3852 3853 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented 3854 ;; `Strong Emphasis`_. 3855 (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx) 3856 1 rst-emphasis2-face) 3857 ;; `Emphasis`_ 3858 (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx) 3859 1 rst-emphasis1-face) 3860 ;; `Inline Literals`_ 3861 (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx) 3862 1 rst-literal-face) 3863 ;; `Inline Internal Targets`_ 3864 (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx) 3865 1 rst-definition-face) 3866 ;; `Hyperlink References`_ 3867 ;; FIXME: `Embedded URIs and Aliases`_ not considered. 3868 ;; FIXME: Directly adjacent marked up words are not fontified correctly 3869 ;; unless they are not separated by two spaces: foo_ bar_. 3870 (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`") 3871 (:seq "\\sw" (:alt "\\sw" "-") "+\\sw")) 3872 "__?") 'ilm-sfx) 3873 1 rst-reference-face) 3874 ;; `Interpreted Text`_ 3875 (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?") 3876 '(:grp "`" ilcbkq-tag "`") 3877 '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx) 3878 (1 rst-directive-face) 3879 (2 rst-external-face) 3880 (3 rst-directive-face)) 3881 ;; `Footnote References`_ / `Citation References`_ 3882 (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx) 3883 1 rst-reference-face) 3884 ;; `Substitution References`_ 3885 ;; FIXME: References substitutions like |this|_ or |this|__ are not 3886 ;; fontified correctly. 3887 (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx) 3888 1 rst-reference-face) 3889 ;; `Standalone Hyperlinks`_ 3890 ;; FIXME: This takes it easy by using a whitespace as delimiter. 3891 (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx) 3892 1 rst-definition-face) 3893 (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx) 3894 1 rst-definition-face) 3895 3896 ;; Do all block fontification as late as possible so 'append works. 3897 3898 ;; Sections_ / Transitions_ 3899 ;; For sections this is multiline. 3900 (,(rst-re 'ado-beg-2-1) 3901 (rst-font-lock-handle-adornment-matcher 3902 (rst-font-lock-handle-adornment-pre-match-form 3903 (match-string-no-properties 1) (match-end 1)) 3904 nil 3905 (1 (cdr (assoc nil rst-adornment-faces-alist)) append t) 3906 (2 (cdr (assoc rst-font-lock-adornment-level 3907 rst-adornment-faces-alist)) append t) 3908 (3 (cdr (assoc nil rst-adornment-faces-alist)) append t))) 3909 3910 ;; FIXME: FACESPEC could be used instead of ordinary faces to set 3911 ;; properties on comments and literal blocks so they are *not* 3912 ;; inline fontified. See (elisp)Search-based Fontification. 3913 3914 ;; FIXME: And / or use `syntax-propertize' functions as in `octave-mod.el' 3915 ;; and other V24 modes. May make `font-lock-extend-region' 3916 ;; superfluous. 3917 3918 ;; `Comments`_ 3919 ;; This is multiline. 3920 (,(rst-re 'lin-beg 'cmt-sta-1) 3921 (1 rst-comment-face) 3922 (rst-font-lock-find-unindented-line-match 3923 (rst-font-lock-find-unindented-line-limit (match-end 1)) 3924 nil 3925 (0 rst-comment-face append))) 3926 (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$") 3927 (1 rst-comment-face) 3928 (2 rst-comment-face) 3929 (rst-font-lock-find-unindented-line-match 3930 (rst-font-lock-find-unindented-line-limit 'next) 3931 nil 3932 (0 rst-comment-face append))) 3933 3934 ;; FIXME: This is not rendered as comment:: 3935 ;; .. .. list-table:: 3936 ;; :stub-columns: 1 3937 ;; :header-rows: 1 3938 3939 ;; FIXME: This is rendered wrong:: 3940 ;; 3941 ;; xxx yyy:: 3942 ;; 3943 ;; ----|> KKKKK <|---- 3944 ;; / \ 3945 ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|- 3946 ;; | | | | 3947 ;; | | | | 3948 ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB 3949 ;; 3950 ;; Indentation needs to be taken from the line with the ``::`` and not from 3951 ;; the first content line. 3952 3953 ;; `Indented Literal Blocks`_ 3954 ;; This is multiline. 3955 (,(rst-re 'lin-beg 'lit-sta-2) 3956 (2 rst-block-face) 3957 (rst-font-lock-find-unindented-line-match 3958 (rst-font-lock-find-unindented-line-limit t) 3959 nil 3960 (0 rst-literal-face append))) 3961 3962 ;; FIXME: `Quoted Literal Blocks`_ missing. 3963 ;; This is multiline. 3964 3965 ;; `Doctest Blocks`_ 3966 ;; FIXME: This is wrong according to the specification: 3967 ;; 3968 ;; Doctest blocks are text blocks which begin with ">>> ", the Python 3969 ;; interactive interpreter main prompt, and end with a blank line. 3970 ;; Doctest blocks are treated as a special case of literal blocks, 3971 ;; without requiring the literal block syntax. If both are present, the 3972 ;; literal block syntax takes priority over Doctest block syntax: 3973 ;; 3974 ;; This is an ordinary paragraph. 3975 ;; 3976 ;; >>> print 'this is a Doctest block' 3977 ;; this is a Doctest block 3978 ;; 3979 ;; The following is a literal block:: 3980 ;; 3981 ;; >>> This is not recognized as a doctest block by 3982 ;; reStructuredText. It *will* be recognized by the doctest 3983 ;; module, though! 3984 ;; 3985 ;; Indentation is not required for doctest blocks. 3986 (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+")) 3987 (1 rst-block-face) 3988 (2 rst-literal-face))) 3989 "Keywords to highlight in rst mode.") 3990 3991(defvar font-lock-beg) 3992(defvar font-lock-end) 3993 3994(defun rst-font-lock-extend-region () 3995 "Extend the font-lock region if it might be in a multi-line construct. 3996Return non-nil if so. Font-lock region is from `font-lock-beg' 3997to `font-lock-end'." 3998 (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end))) 3999 (when r 4000 (setq font-lock-beg (car r)) 4001 (setq font-lock-end (cdr r)) 4002 t))) 4003 4004(defun rst-font-lock-extend-region-internal (beg end) 4005 "Check the region BEG / END for being in the middle of a multi-line construct. 4006Return nil if not or a cons with new values for BEG / END." 4007 (let ((nbeg (rst-font-lock-extend-region-extend beg -1)) 4008 (nend (rst-font-lock-extend-region-extend end 1))) 4009 (if (or nbeg nend) 4010 (cons (or nbeg beg) (or nend end))))) 4011 4012;; FIXME refactoring: Use `rst-forward-line-strict' instead. 4013(defun rst-forward-line (&optional n) 4014 "Like `forward-line' but always end up in column 0 and return accordingly. 4015Move N lines forward just as `forward-line'." 4016 (let ((left (forward-line n))) 4017 (if (bolp) 4018 left 4019 ;; FIXME: This may move back for positive n - is this desired? 4020 (forward-line 0) 4021 (- left (cl-signum n))))) 4022 4023;; FIXME: If a single line is made a section header by `rst-adjust' the header 4024;; is not always fontified immediately. 4025(defun rst-font-lock-extend-region-extend (pt dir) 4026 "Extend the region starting at point PT and extending in direction DIR. 4027Return extended point or nil if not moved." 4028 ;; There are many potential multiline constructs but there are two groups 4029 ;; which are really relevant. The first group consists of 4030 ;; 4031 ;; * comment lines without leading explicit markup tag and 4032 ;; 4033 ;; * literal blocks following "::" 4034 ;; 4035 ;; which are both indented. Thus indentation is the first thing recognized 4036 ;; here. The second criteria is an explicit markup tag which may be a comment 4037 ;; or a double colon at the end of a line. 4038 ;; 4039 ;; The second group consists of the adornment cases. 4040 (if (not (get-text-property pt 'font-lock-multiline)) 4041 ;; Move only if we don't start inside a multiline construct already. 4042 (save-match-data 4043 (save-excursion 4044 (let ( ; Non-empty non-indented line, explicit markup tag or literal 4045 ; block tag. 4046 (stop-re (rst-re '(:alt "[^ \t\n]" 4047 (:seq hws-tag exm-tag) 4048 (:seq ".*" dcl-tag lin-end))))) 4049 ;; The comments below are for dir == -1 / dir == 1. 4050 (goto-char pt) 4051 (rst-forward-line-strict 0) 4052 (setq pt (point)) 4053 (while (and (not (looking-at stop-re)) 4054 (zerop (rst-forward-line dir)))) ; try previous / next 4055 ; line if it exists. 4056 (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline / 4057 ; overline. 4058 (if (zerop (rst-forward-line dir)) 4059 (if (looking-at (rst-re 'ttl-beg-1)) ; title found, i.e. 4060 ; underline / overline 4061 ; found. 4062 (if (zerop (rst-forward-line dir)) 4063 (if (not 4064 (looking-at (rst-re 'ado-beg-2-1))) ; no 4065 ; overline 4066 ; / 4067 ; underline. 4068 (rst-forward-line (- dir)))) ; step back to 4069 ; title / 4070 ; adornment. 4071 (if (< dir 0) ; keep downward adornment. 4072 (rst-forward-line (- dir))))) ; step back to adornment. 4073 (if (looking-at (rst-re 'ttl-beg-1)) ; may be a title. 4074 (if (zerop (rst-forward-line dir)) 4075 (if (not 4076 (looking-at (rst-re 'ado-beg-2-1))) ; no overline / 4077 ; underline. 4078 (rst-forward-line (- dir)))))) ; step back to line. 4079 (if (not (= (point) pt)) 4080 (point))))))) 4081 4082;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4083;; Indented blocks 4084 4085(defun rst-forward-indented-block (&optional column limit) 4086 ;; testcover: ok. 4087 "Move forward across one indented block. 4088Find the next (i.e. excluding the current line) non-empty line 4089which is not indented at least to COLUMN (defaults to the column 4090of the point). Move point to first character of this line or the 4091first of the empty lines immediately before it and return that 4092position. If there is no such line before LIMIT (defaults to the 4093end of the buffer) return nil and do not move point." 4094 (let (fnd candidate) 4095 (setq fnd (rst-apply-indented-blocks 4096 (line-beginning-position 2) ; Skip the current line 4097 (or limit (point-max)) (or column (current-column)) 4098 #'(lambda (_count _in-first _in-sub in-super in-empty _relind) 4099 (cond 4100 (in-empty 4101 (setq candidate (or candidate (line-beginning-position))) 4102 nil) 4103 (in-super 4104 (or candidate (line-beginning-position))) 4105 (t ; Non-empty, same or more indented line. 4106 (setq candidate nil) 4107 nil))))) 4108 (when fnd 4109 (goto-char fnd)))) 4110 4111(defvar rst-font-lock-find-unindented-line-begin nil 4112 "Beginning of the match if `rst-font-lock-find-unindented-line-end'.") 4113 4114(defvar rst-font-lock-find-unindented-line-end nil 4115 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'. 4116Also used as a trigger for `rst-font-lock-find-unindented-line-match'.") 4117 4118(defun rst-font-lock-find-unindented-line-limit (ind-pnt) 4119 "Find the next unindented line relative to indentation at IND-PNT. 4120Return this point, the end of the buffer or nil if nothing found. 4121If IND-PNT is `next' take the indentation from the next line if 4122this is not empty and indented more than the current one. If 4123IND-PNT is non-nil but not a number take the indentation from the 4124next non-empty line if this is indented more than the current one." 4125 (setq rst-font-lock-find-unindented-line-begin ind-pnt) 4126 (setq rst-font-lock-find-unindented-line-end 4127 (save-match-data 4128 (save-excursion 4129 (when (not (numberp ind-pnt)) 4130 ;; Find indentation point in next line if any. 4131 (setq ind-pnt 4132 ;; FIXME: Should be refactored to two different functions 4133 ;; giving their result to this function, may be 4134 ;; integrated in caller. 4135 (save-match-data 4136 (let ((cur-ind (current-indentation))) 4137 (if (eq ind-pnt 'next) 4138 (when (and (rst-forward-line-strict 1 (point-max)) 4139 (< (point) (point-max))) 4140 ;; Not at EOF. 4141 (setq rst-font-lock-find-unindented-line-begin 4142 (point)) 4143 (when (and (not (looking-at (rst-re 'lin-end))) 4144 (> (current-indentation) cur-ind)) 4145 ;; Use end of indentation if non-empty line. 4146 (looking-at (rst-re 'hws-tag)) 4147 (match-end 0))) 4148 ;; Skip until non-empty line or EOF. 4149 (while (and (rst-forward-line-strict 1 (point-max)) 4150 (< (point) (point-max)) 4151 (looking-at (rst-re 'lin-end)))) 4152 (when (< (point) (point-max)) 4153 ;; Not at EOF. 4154 (setq rst-font-lock-find-unindented-line-begin 4155 (point)) 4156 (when (> (current-indentation) cur-ind) 4157 ;; Indentation bigger than line of departure. 4158 (looking-at (rst-re 'hws-tag)) 4159 (match-end 0)))))))) 4160 (when ind-pnt 4161 (goto-char ind-pnt) 4162 (or (rst-forward-indented-block nil (point-max)) 4163 (point-max))))))) 4164 4165(defun rst-font-lock-find-unindented-line-match (_limit) 4166 "Set the match found earlier if match were found. 4167Match has been found by `rst-font-lock-find-unindented-line-limit' 4168the first time called or no match is found. Return non-nil if 4169match was found. _LIMIT is not used but mandated by the caller." 4170 (when rst-font-lock-find-unindented-line-end 4171 (set-match-data 4172 (list rst-font-lock-find-unindented-line-begin 4173 rst-font-lock-find-unindented-line-end)) 4174 (put-text-property rst-font-lock-find-unindented-line-begin 4175 rst-font-lock-find-unindented-line-end 4176 'font-lock-multiline t) 4177 ;; Make sure this is called only once. 4178 (setq rst-font-lock-find-unindented-line-end nil) 4179 t)) 4180 4181;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4182;; Adornments 4183 4184(defvar rst-font-lock-adornment-level nil 4185 "Storage for `rst-font-lock-handle-adornment-matcher'. 4186Either section level of the current adornment or t for a transition.") 4187 4188(defun rst-adornment-level (ado) 4189 "Return section level for ADO or t for a transition. 4190If ADO is found in the hierarchy return its level. Otherwise 4191return a level one beyond the existing hierarchy." 4192 (if (rst-Ado-is-transition ado) 4193 t 4194 (let ((hier (rst-Hdr-ado-map (rst-hdr-hierarchy)))) 4195 (1+ (or (rst-Ado-position ado hier) 4196 (length hier)))))) 4197 4198(defvar rst-font-lock-adornment-match nil 4199 "Storage for match for current adornment. 4200Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used 4201as a trigger for `rst-font-lock-handle-adornment-matcher'.") 4202 4203(defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end) 4204 "Determine limit for adornments. 4205Determine all things necessary for font-locking section titles 4206and transitions and put the result to `rst-font-lock-adornment-match' 4207and `rst-font-lock-adornment-level'. ADO is the complete adornment 4208matched. ADO-END is the point where ADO ends. Return the point 4209where the whole adorned construct ends. 4210 4211Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'." 4212 (let ((ttl (rst-classify-adornment ado ado-end))) 4213 (if (not ttl) 4214 (setq rst-font-lock-adornment-level nil 4215 rst-font-lock-adornment-match nil) 4216 (setq rst-font-lock-adornment-level 4217 (rst-adornment-level (rst-Ttl-ado ttl))) 4218 (setq rst-font-lock-adornment-match (rst-Ttl-match ttl)) 4219 (goto-char (rst-Ttl-get-beginning ttl)) 4220 (rst-Ttl-get-end ttl)))) 4221 4222(defun rst-font-lock-handle-adornment-matcher (_limit) 4223 "Set the match found earlier if match were found. 4224Match has been found by 4225`rst-font-lock-handle-adornment-pre-match-form' the first time 4226called or no match is found. Return non-nil if match was found. 4227 4228Called as a MATCHER in the sense of `font-lock-keywords'. 4229_LIMIT is not used but mandated by the caller." 4230 (let ((match rst-font-lock-adornment-match)) 4231 ;; May run only once - enforce this. 4232 (setq rst-font-lock-adornment-match nil) 4233 (when match 4234 (set-match-data match) 4235 (goto-char (match-end 0)) 4236 (put-text-property (match-beginning 0) (match-end 0) 4237 'font-lock-multiline t) 4238 t))) 4239 4240 4241;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4242;; Compilation 4243 4244(defgroup rst-compile nil 4245 "Settings for support of conversion of reStructuredText 4246document with \\[rst-compile]." 4247 :group 'rst 4248 :version "21.1") 4249 4250(defcustom rst-compile-toolsets 4251 `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html") 4252 ".html" nil) 4253 (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex") 4254 ".tex" nil) 4255 (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py" 4256 "rst2newlatex") 4257 ".tex" nil) 4258 (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py" 4259 "rst2pseudoxml") 4260 ".xml" nil) 4261 (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml") 4262 ".xml" nil) 4263 (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf") 4264 ".pdf" nil) 4265 (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5") 4266 ".html" nil)) 4267 ;; FIXME: Add at least those converters officially supported like `rst2odt' 4268 ;; and `rst2man'. 4269 ;; FIXME: To make this really useful there should be a generic command the 4270 ;; user gives one of the symbols and this way select the conversion to 4271 ;; run. This should replace the toolset stuff somehow. 4272 ;; FIXME: Allow a template for the conversion command so `rst2pdf ... -o ...' 4273 ;; can be supported. 4274 "Table describing the command to use for each tool-set. 4275An association list of the tool-set to a list of the (command to use, 4276extension of produced filename, options to the tool (nil or a 4277string)) to be used for converting the document." 4278 ;; FIXME: These are not options but symbols which may be referenced by 4279 ;; `rst-compile-*-toolset` below. The `:validate' keyword of 4280 ;; `defcustom' may help to define this properly in newer Emacs 4281 ;; versions (> 23.1). 4282 :type '(alist :options (html latex newlatex pseudoxml xml pdf s5) 4283 :key-type symbol 4284 :value-type (list :tag "Specification" 4285 (file :tag "Command") 4286 (string :tag "File extension") 4287 (choice :tag "Command options" 4288 (const :tag "No options" nil) 4289 (string :tag "Options")))) 4290 :group 'rst-compile 4291 :package-version "1.2.0") 4292 4293;; FIXME: Must be defcustom. 4294(defvar rst-compile-primary-toolset 'html 4295 "The default tool-set for `rst-compile'.") 4296 4297;; FIXME: Must be defcustom. 4298(defvar rst-compile-secondary-toolset 'latex 4299 "The default tool-set for `rst-compile' with a prefix argument.") 4300 4301(defun rst-compile-find-conf () 4302 "Look for the configuration file in the parents of the current path." 4303 (interactive) 4304 (let ((file-name "docutils.conf") 4305 (buffer-file (buffer-file-name))) 4306 ;; Move up in the dir hierarchy till we find a change log file. 4307 (let* ((dir (file-name-directory buffer-file)) 4308 (prevdir nil)) 4309 (while (and (or (not (string= dir prevdir)) 4310 (setq dir nil) 4311 nil) 4312 (not (file-exists-p (concat dir file-name)))) 4313 ;; Move up to the parent dir and try again. 4314 (setq prevdir dir) 4315 (setq dir (expand-file-name (file-name-directory 4316 (directory-file-name 4317 (file-name-directory dir)))))) 4318 (or (and dir (concat dir file-name)) nil)))) 4319 4320(require 'compile) 4321 4322(defun rst-compile (&optional use-alt) 4323 "Compile command to convert reST document into some output file. 4324Attempts to find configuration file, if it can, overrides the 4325options. There are two commands to choose from; with USE-ALT, 4326select the alternative tool-set." 4327 (interactive "P") 4328 ;; Note: maybe we want to check if there is a Makefile too and not do anything 4329 ;; if that is the case. I dunno. 4330 (cl-destructuring-bind 4331 (command extension options 4332 &aux (conffile (rst-compile-find-conf)) 4333 (bufname (file-name-nondirectory buffer-file-name))) 4334 (cdr (assq (if use-alt 4335 rst-compile-secondary-toolset 4336 rst-compile-primary-toolset) 4337 rst-compile-toolsets)) 4338 ;; Set compile-command before invocation of compile. 4339 (setq-local 4340 compile-command 4341 (mapconcat 4342 #'identity 4343 (list command 4344 (or options "") 4345 (if conffile 4346 (concat "--config=" (shell-quote-argument conffile)) 4347 "") 4348 (shell-quote-argument bufname) 4349 (shell-quote-argument (concat (file-name-sans-extension bufname) 4350 extension))) 4351 " ")) 4352 ;; Invoke the compile command. 4353 (if (or compilation-read-command use-alt) 4354 (call-interactively #'compile) 4355 (compile compile-command)))) 4356 4357(defun rst-compile-alt-toolset () 4358 "Compile command with the alternative tool-set." 4359 (interactive) 4360 (rst-compile t)) 4361 4362(defun rst-compile-pseudo-region () 4363 "Show pseudo-XML rendering. 4364Rendering is done of the current active region, or of the entire 4365buffer, if the region is not selected." 4366 ;; FIXME: The region should be given interactively. 4367 (interactive) 4368 (with-output-to-temp-buffer "*pseudoxml*" 4369 (shell-command-on-region 4370 (if mark-active (region-beginning) (point-min)) 4371 (if mark-active (region-end) (point-max)) 4372 (cadr (assq 'pseudoxml rst-compile-toolsets)) 4373 standard-output))) 4374 4375;; FIXME: Should be integrated in `rst-compile-toolsets'. 4376(defvar rst-pdf-program "xpdf" 4377 "Program used to preview PDF files.") 4378 4379(defun rst-compile-pdf-preview () 4380 "Convert the document to a PDF file and launch a preview program." 4381 (interactive) 4382 (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf")) 4383 (pdf-compile-program (cadr (assq 'pdf rst-compile-toolsets))) 4384 (command (format "%s %s %s && %s %s ; rm %s" 4385 pdf-compile-program 4386 buffer-file-name tmp-filename 4387 rst-pdf-program tmp-filename tmp-filename))) 4388 (unless (executable-find pdf-compile-program) 4389 (error "Cannot find executable `%s'" pdf-compile-program)) 4390 (unless (executable-find rst-pdf-program) 4391 (error "Cannot find executable `%s'" rst-pdf-program)) 4392 (start-process-shell-command "rst-pdf-preview" nil command) 4393 ;; Note: you could also use (compile command) to view the compilation 4394 ;; output. 4395 )) 4396 4397;; FIXME: Should be integrated in `rst-compile-toolsets' defaulting to 4398;; something like `browse-url'. 4399(defvar rst-slides-program "firefox" 4400 "Program used to preview S5 slides.") 4401 4402(defun rst-compile-slides-preview () 4403 "Convert the document to an S5 slide presentation and launch a preview program." 4404 (interactive) 4405 (let* ((tmp-filename (make-temp-file "rst_el" nil ".html")) 4406 (command (format "%s %s %s && %s %s ; rm %s" 4407 (cadr (assq 's5 rst-compile-toolsets)) 4408 buffer-file-name tmp-filename 4409 rst-slides-program tmp-filename tmp-filename))) 4410 (start-process-shell-command "rst-slides-preview" nil command) 4411 ;; Note: you could also use (compile command) to view the compilation 4412 ;; output. 4413 )) 4414 4415;; FIXME: Add `rst-compile-html-preview'. 4416 4417;; FIXME: Add support for `restview` (http://mg.pov.lt/restview/). May be a 4418;; more general facility for calling commands on a reST file would make 4419;; sense. 4420 4421 4422;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4423;; Imenu support 4424 4425;; FIXME: Consider a key binding. A key binding needs to definitely switch on 4426;; `which-func-mode' - i.e. `which-func-modes' must be set properly. 4427 4428;; Based on ideas from Masatake YAMATO <yamato@redhat.com>. 4429 4430(defun rst-imenu-convert-cell (stn) 4431 "Convert a STN to an Imenu index node and return it." 4432 (let ((ttl (rst-Stn-ttl stn)) 4433 (children (rst-Stn-children stn)) 4434 (pos (rst-Stn-get-title-beginning stn)) 4435 (txt (rst-Stn-get-text stn "")) 4436 (pfx " ") 4437 (sfx "") 4438 name) 4439 (when ttl 4440 (let ((hdr (rst-Ttl-hdr ttl))) 4441 (setq pfx (char-to-string (rst-Hdr-get-char hdr))) 4442 (when (rst-Hdr-is-over-and-under hdr) 4443 (setq sfx pfx)))) 4444 ;; FIXME: Overline adornment characters need to be in front so they 4445 ;; become visible even for long title lines. May be an additional 4446 ;; level number is also useful. 4447 (setq name (format "%s%s%s" pfx txt sfx)) 4448 (cons name ; The name of the entry. 4449 (if children 4450 (cons ; The entry has a submenu. 4451 (cons name pos) ; The entry itself. 4452 (mapcar #'rst-imenu-convert-cell children)) ; The children. 4453 pos)))) ; The position of a plain entry. 4454 4455;; FIXME: Document title and subtitle need to be handled properly. They should 4456;; get an own "Document" top level entry. 4457(defun rst-imenu-create-index () 4458 "Create index for Imenu. 4459Return as described for `imenu--index-alist'." 4460 (rst-reset-section-caches) 4461 (let ((root (rst-all-stn))) 4462 (when root 4463 (mapcar #'rst-imenu-convert-cell (rst-Stn-children root))))) 4464 4465 4466;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4467;; Convenience functions 4468 4469;; FIXME: Unbound command - should be bound or removed. 4470(defun rst-replace-lines (fromchar tochar) 4471 "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR." 4472 (interactive "\ 4473cSearch for flush-left lines of char: 4474cand replace with char: ") 4475 (save-excursion 4476 (let ((searchre (rst-re "^" fromchar "+\\( *\\)$")) 4477 (found 0)) 4478 (while (search-forward-regexp searchre nil t) 4479 (setq found (1+ found)) 4480 (goto-char (match-beginning 1)) 4481 (let ((width (current-column))) 4482 (rst-delete-entire-line 0) 4483 (insert-char tochar width))) 4484 (message "%d lines replaced." found)))) 4485 4486;; FIXME: Unbound command - should be bound or removed. 4487(defun rst-join-paragraph () 4488 "Join lines in current paragraph into one line, removing end-of-lines." 4489 (interactive) 4490 (let ((fill-column 65000)) ; Some big number. 4491 (call-interactively #'fill-paragraph))) 4492 4493;; FIXME: Unbound command - should be bound or removed. 4494(defun rst-force-fill-paragraph () 4495 "Fill paragraph at point, first joining the paragraph's lines into one. 4496This is useful for filling list item paragraphs." 4497 (interactive) 4498 (rst-join-paragraph) 4499 (fill-paragraph nil)) 4500 4501 4502;; FIXME: Unbound command - should be bound or removed. 4503;; Generic character repeater function. 4504;; For sections, better to use the specialized function above, but this can 4505;; be useful for creating separators. 4506(defun rst-repeat-last-character (use-next) 4507 "Fill the current line using the last character on the current line. 4508Fill up to the length of the preceding line or up to `fill-column' if preceding 4509line is empty. 4510 4511If USE-NEXT, use the next line rather than the preceding line. 4512 4513If the current line is longer than the desired length, shave the characters off 4514the current line to fit the desired length. 4515 4516As an added convenience, if the command is repeated immediately, the alternative 4517column is used (fill-column vs. end of previous/next line)." 4518 (interactive "P") 4519 (let* ((curcol (current-column)) 4520 (curline (+ (count-lines (point-min) (point)) 4521 (if (zerop curcol) 1 0))) 4522 (lbp (line-beginning-position 0)) 4523 (prevcol (if (and (= curline 1) (not use-next)) 4524 fill-column 4525 (save-excursion 4526 (forward-line (if use-next 1 -1)) 4527 (end-of-line) 4528 (skip-chars-backward " \t" lbp) 4529 (let ((cc (current-column))) 4530 (if (zerop cc) fill-column cc))))) 4531 (rightmost-column 4532 (cond ((equal last-command 'rst-repeat-last-character) 4533 (if (= curcol fill-column) prevcol fill-column)) 4534 (t (save-excursion 4535 (if (zerop prevcol) fill-column prevcol)))))) 4536 (end-of-line) 4537 (if (> (current-column) rightmost-column) 4538 ;; Shave characters off the end. 4539 (delete-region (- (point) 4540 (- (current-column) rightmost-column)) 4541 (point)) 4542 ;; Fill with last characters. 4543 (insert-char (preceding-char) 4544 (- rightmost-column (current-column)))))) 4545 4546 4547 4548;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex 4549;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc 4550;; LocalWords: XML PNT propertized init referenceable 4551 4552(provide 'rst) 4553 4554;; Local Variables: 4555;; sentence-end-double-space: t 4556;; End: 4557 4558;;; rst.el ends here 4559