forked from emacs-mirror/emacs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrst.el
4558 lines (4091 loc) · 162 KB
/
rst.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; rst.el --- Mode for viewing and editing reStructuredText-documents -*- lexical-binding: t -*-
;; Copyright (C) 2003-2020 Free Software Foundation, Inc.
;; Maintainer: Stefan Merten <stefan at merten-home dot de>
;; Author: Stefan Merten <stefan at merten-home dot de>,
;; Martin Blais <[email protected]>,
;; David Goodger <[email protected]>,
;; Wei-Wei Guo <[email protected]>
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides major mode rst-mode, which supports documents marked
;; up using the reStructuredText format. Support includes font locking as well
;; as a lot of convenience functions for editing. It does this by defining a
;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode.
;; This package also contains:
;;
;; - Functions to automatically adjust and cycle the section underline
;; adornments;
;; - A mode that displays the table of contents and allows you to jump anywhere
;; from it;
;; - Functions to insert and automatically update a TOC in your source
;; document;
;; - Function to insert list, processing item bullets and enumerations
;; automatically;
;; - Font-lock highlighting of most reStructuredText structures;
;; - Indentation and filling according to reStructuredText syntax;
;; - Cursor movement according to reStructuredText syntax;
;; - Some other convenience functions.
;;
;; See the accompanying document in the docutils documentation about
;; the contents of this package and how to use it.
;;
;; For more information about reStructuredText, see
;; http://docutils.sourceforge.net/rst.html
;;
;; For full details on how to use the contents of this file, see
;; http://docutils.sourceforge.net/docs/user/emacs.html
;;
;; There are a number of convenient key bindings provided by rst-mode. For the
;; bindings, try C-c C-h when in rst-mode. There are also many variables that
;; can be customized, look for defcustom in this file or look for the "rst"
;; customization group contained in the "wp" group.
;;
;; If you use the table-of-contents feature, you may want to add a hook to
;; update the TOC automatically every time you adjust a section title::
;;
;; (add-hook 'rst-adjust-hook 'rst-toc-update)
;;
;; Syntax highlighting: font-lock is enabled by default. If you want to turn
;; off syntax highlighting to rst-mode, you can use the following::
;;
;; (setq font-lock-global-modes '(not rst-mode ...))
;;
;;; DOWNLOAD
;; The latest release of this file lies in the docutils source code repository:
;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el
;;; INSTALLATION
;; Add the following lines to your init file:
;;
;; (require 'rst)
;;
;; If you are using `.txt' as a standard extension for reST files as
;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
;; provides to set the major mode automatically. For instance you may use::
;;
;; .. -*- mode: rst -*-
;;
;; in the very first line of your file. The following code is useful if you
;; want automatically enter rst-mode from any file with compatible extensions:
;;
;; (setq auto-mode-alist
;; (append '(("\\.txt\\'" . rst-mode)
;; ("\\.rst\\'" . rst-mode)
;; ("\\.rest\\'" . rst-mode)) auto-mode-alist))
;;
;;; Code:
;; FIXME: Check through major mode conventions again.
;; FIXME: Embed complicated `defconst's in `eval-when-compile'.
;; Common Lisp stuff
(require 'cl-lib)
;; Correct wrong declaration.
(def-edebug-spec push
(&or [form symbolp] [form gv-place]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support for `testcover'
(defun rst-testcover-add-compose (fun)
"Add FUN to `testcover-compose-functions'."
(when (boundp 'testcover-compose-functions)
(add-to-list 'testcover-compose-functions fun)))
(defun rst-testcover-add-1value (fun)
"Add FUN to `testcover-1value-functions'."
(when (boundp 'testcover-1value-functions)
(add-to-list 'testcover-1value-functions fun)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Helpers.
(cl-defmacro rst-destructuring-dolist
((arglist list &optional result) &rest body)
"`cl-dolist' with destructuring of the list elements.
ARGLIST is a Common List argument list which may include
destructuring. LIST, RESULT and BODY are as for `cl-dolist'.
Note that definitions in ARGLIST are visible only in the BODY and
neither in RESULT nor in LIST."
;; FIXME: It would be very useful if the definitions in ARGLIST would be
;; visible in RESULT. But may be this is rather a
;; `rst-destructuring-do' then.
(declare (debug
(&define ([&or symbolp cl-macro-list] def-form &optional def-form)
cl-declarations def-body))
(indent 1))
(let ((var (make-symbol "--rst-destructuring-dolist-var--")))
`(cl-dolist (,var ,list ,result)
(cl-destructuring-bind ,arglist ,var
,@body))))
(defun rst-forward-line-strict (n &optional limit)
;; testcover: ok.
"Try to move point to beginning of line I + N where I is the current line.
Return t if movement is successful. Otherwise don't move point
and return nil. If a position is given by LIMIT, movement
happened but the following line is missing and thus its beginning
can not be reached but the movement reached at least LIMIT
consider this a successful movement. LIMIT is ignored in other
cases."
(let ((start (point)))
(if (and (zerop (forward-line n))
(or (bolp)
(and limit
(>= (point) limit))))
t
(goto-char start)
nil)))
(defun rst-forward-line-looking-at (n rst-re-args &optional fun)
;; testcover: ok.
"Move forward N lines and if successful check whether RST-RE-ARGS is matched.
Moving forward is done by `rst-forward-line-strict'. RST-RE-ARGS
is a single or a list of arguments for `rst-re'. FUN is a
function defaulting to `identity' which is called after the call
to `looking-at' receiving its return value as the first argument.
When FUN is called match data is just set by `looking-at' and
point is at the beginning of the line. Return nil if moving
forward failed or otherwise the return value of FUN. Preserve
global match data, point, mark and current buffer."
(unless (listp rst-re-args)
(setq rst-re-args (list rst-re-args)))
(unless fun
(setq fun #'identity))
(save-match-data
(save-excursion
(when (rst-forward-line-strict n)
(funcall fun (looking-at (apply #'rst-re rst-re-args)))))))
(rst-testcover-add-1value 'rst-delete-entire-line)
(defun rst-delete-entire-line (n)
"Move N lines and delete the entire line."
(delete-region (line-beginning-position (+ n 1))
(line-beginning-position (+ n 2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Versions
(defun rst-extract-version (delim-re head-re re tail-re var &optional default)
;; testcover: ok.
"Extract the version from a variable according to the given regexes.
Return the version after regex DELIM-RE and HEAD-RE matching RE
and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match."
(if (string-match
(concat delim-re head-re "\\(" re "\\)" tail-re delim-re)
var)
(match-string 1 var)
default))
;; Use CVSHeader to really get information from CVS and not other version
;; control systems.
(defconst rst-cvs-header
"$CVSHeader: sm/rst_el/rst.el,v 1.1058.2.9 2017/01/08 09:54:50 stefan Exp $")
(defconst rst-cvs-rev
(rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
" .*" rst-cvs-header "0.0")
"The CVS revision of this file. CVS revision is the development revision.")
(defconst rst-cvs-timestamp
(rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
"[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
rst-cvs-header "1970-01-01 00:00:00")
"The CVS time stamp of this file.")
;; Use LastChanged... to really get information from SVN.
(defconst rst-svn-rev
(rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
"$LastChangedRevision: 8015 $")
"The SVN revision of this file.
SVN revision is the upstream (docutils) revision.")
(defconst rst-svn-timestamp
(rst-extract-version "\\$" "LastChangedDate: " ".+" " "
"$LastChangedDate: 2017-01-08 10:54:35 +0100 (Sun, 08 Jan 2017) $")
"The SVN time stamp of this file.")
;; Maintained by the release process.
(defconst rst-official-version
(rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
"%OfficialVersion: 1.5.2 %")
"Official version of the package.")
(defconst rst-official-cvs-rev
(rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
"$Revision: 1.1058.2.9 $")
"CVS revision of this file in the official version.")
(defconst rst-version
(if (equal rst-official-cvs-rev rst-cvs-rev)
rst-official-version
(format "%s (development %s [%s])" rst-official-version
rst-cvs-rev rst-cvs-timestamp))
"The version string.
Starts with the current official version. For developer versions
in parentheses follows the development revision and the time stamp.")
(defconst rst-package-emacs-version-alist
'(("1.0.0" . "24.3")
("1.1.0" . "24.3")
("1.2.0" . "24.3")
("1.2.1" . "24.3")
("1.3.0" . "24.3")
("1.3.1" . "24.3")
("1.4.0" . "24.3")
("1.4.1" . "25.1")
("1.4.2" . "25.1")
("1.5.0" . "26.1")
("1.5.1" . "26.1")
("1.5.2" . "26.1")
;; Whatever the Emacs version is this rst.el version ends up in.
))
(unless (assoc rst-official-version rst-package-emacs-version-alist)
(error "Version %s not listed in `rst-package-emacs-version-alist'"
rst-version))
(add-to-list 'customize-package-emacs-version-alist
(cons 'ReST rst-package-emacs-version-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize customization
(defgroup rst nil "Support for reStructuredText documents."
:group 'text
:version "23.1"
:link '(url-link "http://docutils.sourceforge.net/rst.html"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Facilities for regular expressions used everywhere
;; The trailing numbers in the names give the number of referenceable regex
;; groups contained in the regex.
;; Used to be customizable but really is not customizable but fixed by the reST
;; syntax.
(defconst rst-bullets
;; Sorted so they can form a character class when concatenated.
'(?- ?* ?+ ?• ?‣ ?⁃)
"List of all possible bullet characters for bulleted lists.")
(defconst rst-uri-schemes
'("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
"ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
"service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
"Supported URI schemes.")
(defconst rst-adornment-chars
;; Sorted so they can form a character class when concatenated.
'(?\]
?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
?^ ?_ ?` ?{ ?| ?} ?~
?-)
"Characters which may be used in adornments for sections and transitions.")
(defconst rst-max-inline-length
1000
"Maximum length of inline markup to recognize.")
(defconst rst-re-alist-def
;; `*-beg' matches * at the beginning of a line.
;; `*-end' matches * at the end of a line.
;; `*-prt' matches a part of *.
;; `*-tag' matches *.
;; `*-sta' matches the start of * which may be followed by respective content.
;; `*-pfx' matches the delimiter left of *.
;; `*-sfx' matches the delimiter right of *.
;; `*-hlp' helper for *.
;;
;; A trailing number says how many referenceable groups are contained.
`(
;; Horizontal white space (`hws')
(hws-prt "[\t ]")
(hws-tag hws-prt "*") ; Optional sequence of horizontal white space.
(hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space.
;; Lines (`lin')
(lin-beg "^" hws-tag) ; Beginning of a possibly indented line.
(lin-end hws-tag "$") ; End of a line with optional trailing white space.
(linemp-tag "^" hws-tag "$") ; Empty line with optional white space.
;; Various tags and parts
(ell-tag "\\.\\.\\.") ; Ellipsis
(bul-tag ,(concat "[" rst-bullets "]")) ; A bullet.
(ltr-tag "[a-zA-Z]") ; A letter enumerator tag.
(num-prt "[0-9]") ; A number enumerator part.
(num-tag num-prt "+") ; A number enumerator tag.
(rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part.
(rom-tag rom-prt "+") ; A roman enumerator tag.
(aut-tag "#") ; An automatic enumerator tag.
(dcl-tag "::") ; Double colon.
;; Block lead in (`bli')
(bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
; immediate content.
;; Various starts
(bul-sta bul-tag bli-sfx) ; Start of a bulleted item.
(bul-beg lin-beg bul-sta) ; A bullet item at the beginning of a line.
;; Explicit markup tag (`exm')
(exm-tag "\\.\\.")
(exm-sta exm-tag hws-sta)
(exm-beg lin-beg exm-sta)
;; Counters in enumerations (`cnt')
(cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter.
(cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter.
;; Enumerator (`enm')
(enmany-tag (:alt
(:seq cntany-tag "\\.")
(:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator.
(enmexp-tag (:alt
(:seq cntexp-tag "\\.")
(:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
; enumerator.
(enmaut-tag (:alt
(:seq aut-tag "\\.")
(:seq "(?" aut-tag ")"))) ; An automatic enumerator.
(enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start.
(enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start.
(enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
; at the beginning of a line.
;; Items may be enumerated or bulleted (`itm')
(itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag.
(itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
; is the item tag.
(itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
; beginning of a line, group is the
; item tag.
;; Inline markup (`ilm')
(ilm-pfx (:alt "^" hws-prt "['\"([{<‘“«’/:-]"))
(ilm-sfx (:alt "$" hws-prt "[]'\")}>’”»/:.,;!?\\-]"))
;; Inline markup content (`ilc')
(ilcsgl-tag "\\S ") ; A single non-white character.
(ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content.
(ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content.
(ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
; definition.
(ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content.
(ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
; definition.
(ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content.
(ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content.
(ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content.
(ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count.
(ilcast-tag (:alt ilcsgl-tag
(:seq ilcsgl-tag
ilcast-prt ilcrep-hlp
ilcast-sfx))) ; Non-asterisk content.
(ilcbkq-tag (:alt ilcsgl-tag
(:seq ilcsgl-tag
ilcbkq-prt ilcrep-hlp
ilcbkq-sfx))) ; Non-backquote content.
(ilcbkqdef-tag (:alt ilcsgl-tag
(:seq ilcsgl-tag
ilcbkqdef-prt ilcrep-hlp
ilcbkq-sfx))) ; Non-backquote definition.
(ilcbar-tag (:alt ilcsgl-tag
(:seq ilcsgl-tag
ilcbar-prt ilcrep-hlp
ilcbar-sfx))) ; Non-vertical-bar content.
(ilcbardef-tag (:alt ilcsgl-tag
(:seq ilcsgl-tag
ilcbardef-prt ilcrep-hlp
ilcbar-sfx))) ; Non-vertical-bar definition.
;; Fields (`fld')
(fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name.
(fldnam-tag fldnam-prt "+") ; A field name.
(fld-tag ":" fldnam-tag ":") ; A field marker.
;; Options (`opt')
(optsta-tag (:alt "[+/-]" "--")) ; Start of an option.
(optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option.
(optarg-tag (:shy "[ =]\\S +")) ; Option argument.
(optsep-tag (:shy "," hws-prt)) ; Separator between options.
(opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option.
;; Footnotes and citations (`fnc')
(fncnam-prt "[^]\n]") ; Part of a footnote or citation name.
(fncnam-tag fncnam-prt "+") ; A footnote or citation name.
(fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag.
(fncdef-tag-2 (:grp exm-sta)
(:grp fnc-tag)) ; A complete footnote or citation definition
; tag. First group is the explicit markup
; start, second group is the footnote /
; citation tag.
(fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation
; definition. First group is the explicit
; markup start, second group is the
; footnote / citation tag.
;; Substitutions (`sub')
(sub-tag "|" ilcbar-tag "|") ; A complete substitution tag.
(subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
; tag.
;; Symbol (`sym')
(sym-prt "[+.:_-]") ; Non-word part of a symbol.
(sym-tag (:shy "\\sw+" (:shy sym-prt "\\sw+") "*"))
;; URIs (`uri')
(uri-tag (:alt ,@rst-uri-schemes))
;; Adornment (`ado')
(ado-prt "[" ,(concat rst-adornment-chars) "]")
(adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
; otherwise explicit markup start would be
; recognized.
(adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
; characters is matched differently.
(ado-tag-1-1 (:grp ado-prt)
"\\1" adorep2-hlp) ; A complete adornment, group is the first
; adornment character and MUST be the FIRST
; group in the whole expression.
(ado-tag-1-2 (:grp ado-prt)
"\\2" adorep2-hlp) ; A complete adornment, group is the first
; adornment character and MUST be the
; SECOND group in the whole expression.
(ado-beg-2-1 "^" (:grp ado-tag-1-2)
lin-end) ; A complete adornment line; first group is the whole
; adornment and MUST be the FIRST group in the whole
; expression; second group is the first adornment
; character.
;; Titles (`ttl')
(ttl-tag "\\S *\\w.*\\S ") ; A title text.
(ttl-beg-1 lin-beg (:grp ttl-tag)) ; A title text at the beginning of a
; line. First group is the complete,
; trimmed title text.
;; Directives and substitution definitions (`dir')
(dir-tag-3 (:grp exm-sta)
(:grp (:shy subdef-tag hws-sta) "?")
(:grp sym-tag dcl-tag)) ; A directive or substitution definition
; tag. First group is explicit markup
; start, second group is a possibly
; empty substitution tag, third group is
; the directive tag including the double
; colon.
(dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution
; definition. Groups are as in dir-tag-3.
;; Literal block (`lit')
(lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
(:grp dcl-tag) "$") ; Start of a literal block. First group is
; any text before the double colon tag which
; may not exist, second group is the double
; colon tag.
;; Comments (`cmt')
(cmt-sta-1 (:grp exm-sta) "[^[|_\n]"
(:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$")))
"*$") ; Start of a comment block; first group is explicit markup
; start.
;; Paragraphs (`par')
(par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag)
) ; Tag at the beginning of a paragraph; there may be groups in
; certain cases.
)
"Definition alist of relevant regexes.
Each entry consists of the symbol naming the regex and an
argument list for `rst-re'.")
(defvar rst-re-alist) ; Forward declare to use it in `rst-re'.
;; FIXME: Use `sregex' or `rx' instead of re-inventing the wheel.
(rst-testcover-add-compose 'rst-re)
(defun rst-re (&rest args)
;; testcover: ok.
"Interpret ARGS as regular expressions and return a regex string.
Each element of ARGS may be one of the following:
A string which is inserted unchanged.
A character which is resolved to a quoted regex.
A symbol which is resolved to a string using `rst-re-alist-def'.
A list with a keyword in the car. Each element of the cdr of such
a list is recursively interpreted as ARGS. The results of this
interpretation are concatenated according to the keyword.
For the keyword `:seq' the results are simply concatenated.
For the keyword `:shy' the results are concatenated and
surrounded by a shy-group (\"\\(?:...\\)\").
For the keyword `:alt' the results form an alternative (\"\\|\")
which is shy-grouped (\"\\(?:...\\)\").
For the keyword `:grp' the results are concatenated and form a
referenceable group (\"\\(...\\)\").
After interpretation of ARGS the results are concatenated as for
`:seq'."
(apply #'concat
(mapcar
#'(lambda (re)
(cond
((stringp re)
re)
((symbolp re)
(cadr (assoc re rst-re-alist)))
((characterp re)
(regexp-quote (char-to-string re)))
((listp re)
(let ((nested
(mapcar (lambda (elt)
(rst-re elt))
(cdr re))))
(cond
((eq (car re) :seq)
(mapconcat #'identity nested ""))
((eq (car re) :shy)
(concat "\\(?:" (mapconcat #'identity nested "") "\\)"))
((eq (car re) :grp)
(concat "\\(" (mapconcat #'identity nested "") "\\)"))
((eq (car re) :alt)
(concat "\\(?:" (mapconcat #'identity nested "\\|") "\\)"))
(t
(error "Unknown list car: %s" (car re))))))
(t
(error "Unknown object type for building regex: %s" re))))
args)))
;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'.
(with-no-warnings ; Silence byte-compiler about this construction.
(defconst rst-re-alist
;; Shadow global value we are just defining so we can construct it step by
;; step.
(let (rst-re-alist)
(dolist (re rst-re-alist-def rst-re-alist)
(setq rst-re-alist
(nconc rst-re-alist
(list (list (car re) (apply #'rst-re (cdr re))))))))
"Alist mapping symbols from `rst-re-alist-def' to regex strings."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Concepts
;; Each of the following classes represents an own concept. The suffix of the
;; class name is used in the code to represent entities of the respective
;; class.
;;
;; In addition a reStructuredText section header in the buffer is called
;; "section".
;;
;; For lists a "s" is added to the name of the concepts.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Class rst-Ado
(cl-defstruct
(rst-Ado
(:constructor nil) ; Prevent creating unchecked values.
;; Construct a transition.
(:constructor
rst-Ado-new-transition
(&aux
(char nil)
(-style 'transition)))
;; Construct a simple section header.
(:constructor
rst-Ado-new-simple
(char-arg
&aux
(char (rst-Ado--validate-char char-arg))
(-style 'simple)))
;; Construct an over-and-under section header.
(:constructor
rst-Ado-new-over-and-under
(char-arg
&aux
(char (rst-Ado--validate-char char-arg))
(-style 'over-and-under)))
;; Construct from adornment with inverted style.
(:constructor
rst-Ado-new-invert
(ado-arg
&aux
(char (rst-Ado-char ado-arg))
(-style (let ((sty (rst-Ado--style ado-arg)))
(cond
((eq sty 'simple)
'over-and-under)
((eq sty 'over-and-under)
'simple)
(sty)))))))
"Representation of a reStructuredText adornment.
Adornments are either section markers where they markup the
section header or transitions.
This type is immutable."
;; The character used for the adornment.
(char nil :read-only t)
;; The style of the adornment. This is a private attribute.
(-style nil :read-only t))
;; Private class methods
(defun rst-Ado--validate-char (char)
;; testcover: ok.
"Validate CHAR to be a valid adornment character.
Return CHAR if so or signal an error otherwise."
(cl-check-type char character)
(cl-check-type char (satisfies
(lambda (c)
(memq c rst-adornment-chars)))
"Character must be a valid adornment character")
char)
;; Public methods
(defun rst-Ado-is-transition (self)
;; testcover: ok.
"Return non-nil if SELF is a transition adornment."
(cl-check-type self rst-Ado)
(eq (rst-Ado--style self) 'transition))
(defun rst-Ado-is-section (self)
;; testcover: ok.
"Return non-nil if SELF is a section adornment."
(cl-check-type self rst-Ado)
(not (rst-Ado-is-transition self)))
(defun rst-Ado-is-simple (self)
;; testcover: ok.
"Return non-nil if SELF is a simple section adornment."
(cl-check-type self rst-Ado)
(eq (rst-Ado--style self) 'simple))
(defun rst-Ado-is-over-and-under (self)
;; testcover: ok.
"Return non-nil if SELF is an over-and-under section adornment."
(cl-check-type self rst-Ado)
(eq (rst-Ado--style self) 'over-and-under))
(defun rst-Ado-equal (self other)
;; testcover: ok.
"Return non-nil when SELF and OTHER are equal."
(cl-check-type self rst-Ado)
(cl-check-type other rst-Ado)
(cond
((not (eq (rst-Ado--style self) (rst-Ado--style other)))
nil)
((rst-Ado-is-transition self))
((equal (rst-Ado-char self) (rst-Ado-char other)))))
(defun rst-Ado-position (self ados)
;; testcover: ok.
"Return position of SELF in ADOS or nil."
(cl-check-type self rst-Ado)
(cl-position-if #'(lambda (e)
(rst-Ado-equal self e))
ados))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Class rst-Hdr
(cl-defstruct
(rst-Hdr
(:constructor nil) ; Prevent creating unchecked values.
;; Construct while all parameters must be valid.
(:constructor
rst-Hdr-new
(ado-arg
indent-arg
&aux
(ado (rst-Hdr--validate-ado ado-arg))
(indent (rst-Hdr--validate-indent indent-arg ado nil))))
;; Construct while all parameters but `indent' must be valid.
(:constructor
rst-Hdr-new-lax
(ado-arg
indent-arg
&aux
(ado (rst-Hdr--validate-ado ado-arg))
(indent (rst-Hdr--validate-indent indent-arg ado t))))
;; Construct a header with same characteristics but opposite style as `ado'.
(:constructor
rst-Hdr-new-invert
(ado-arg
indent-arg
&aux
(ado (rst-Hdr--validate-ado (rst-Ado-new-invert ado-arg)))
(indent (rst-Hdr--validate-indent indent-arg ado t))))
(:copier nil)) ; Not really needed for an immutable type.
"Representation of reStructuredText section header characteristics.
This type is immutable."
;; The adornment of the header.
(ado nil :read-only t)
;; The indentation of a title text or nil if not given.
(indent nil :read-only t))
;; Private class methods
(defun rst-Hdr--validate-indent (indent ado lax)
;; testcover: ok.
"Validate INDENT to be a valid indentation for ADO.
Return INDENT if so or signal an error otherwise. If LAX don't
signal an error and return a valid indent."
(cl-check-type indent integer)
(cond
((zerop indent)
indent)
((rst-Ado-is-simple ado)
(if lax
0
(signal 'args-out-of-range
'("Indentation must be 0 for style simple"))))
((< indent 0)
(if lax
0
(signal 'args-out-of-range
'("Indentation must not be negative"))))
;; Implicitly over-and-under.
(indent)))
(defun rst-Hdr--validate-ado (ado)
;; testcover: ok.
"Validate ADO to be a valid adornment.
Return ADO if so or signal an error otherwise."
(cl-check-type ado rst-Ado)
(cond
((rst-Ado-is-transition ado)
(signal 'args-out-of-range
'("Adornment for header must not be transition.")))
(ado)))
;; Public class methods
(define-obsolete-variable-alias
'rst-preferred-decorations 'rst-preferred-adornments "rst 1.0.0")
(defvar rst-preferred-adornments) ; Forward declaration.
(defun rst-Hdr-preferred-adornments ()
;; testcover: ok.
"Return preferred adornments as list of `rst-Hdr'."
(mapcar (cl-function
(lambda ((character style indent))
(rst-Hdr-new-lax
(if (eq style 'over-and-under)
(rst-Ado-new-over-and-under character)
(rst-Ado-new-simple character))
indent)))
rst-preferred-adornments))
;; Public methods
(defun rst-Hdr-member-ado (self hdrs)
;; testcover: ok.
"Return sublist of HDRS whose car's adornment equals that of SELF or nil."
(cl-check-type self rst-Hdr)
(let ((ado (rst-Hdr-ado self)))
(cl-member-if #'(lambda (hdr)
(rst-Ado-equal ado (rst-Hdr-ado hdr)))
hdrs)))
(defun rst-Hdr-ado-map (selves)
;; testcover: ok.
"Return `rst-Ado' list extracted from elements of SELVES."
(mapcar #'rst-Hdr-ado selves))
(defun rst-Hdr-get-char (self)
;; testcover: ok.
"Return character of the adornment of SELF."
(cl-check-type self rst-Hdr)
(rst-Ado-char (rst-Hdr-ado self)))
(defun rst-Hdr-is-over-and-under (self)
;; testcover: ok.
"Return non-nil if SELF is an over-and-under section header."
(cl-check-type self rst-Hdr)
(rst-Ado-is-over-and-under (rst-Hdr-ado self)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Class rst-Ttl
(cl-defstruct
(rst-Ttl
(:constructor nil) ; Prevent creating unchecked values.
;; Construct with valid parameters for all attributes.
(:constructor ; Private constructor
rst-Ttl--new
(ado-arg
match-arg
indent-arg
text-arg
&aux
(ado (rst-Ttl--validate-ado ado-arg))
(match (rst-Ttl--validate-match match-arg ado))
(indent (rst-Ttl--validate-indent indent-arg ado))
(text (rst-Ttl--validate-text text-arg ado))
(hdr (condition-case nil
(rst-Hdr-new ado indent)
(error nil)))))
(:copier nil)) ; Not really needed for an immutable type.
"Representation of a reStructuredText section header as found in a buffer.
This type gathers information about an adorned part in the buffer.
This type is immutable."
;; The adornment characteristics or nil for a title candidate.
(ado nil :read-only t)
;; The match-data for `ado' in a form similarly returned by `match-data' (but
;; not necessarily with markers in buffers). Match group 0 matches the whole
;; construct. Match group 1 matches the overline adornment if present.
;; Match group 2 matches the section title text or the transition. Match
;; group 3 matches the underline adornment.
(match nil :read-only t)
;; An indentation found for the title line or nil for a transition.
(indent nil :read-only t)
;; The text of the title or nil for a transition.
(text nil :read-only t)
;; The header characteristics if it is a valid section header.
(hdr nil :read-only t)
;; FIXME refactoring: Should have an attribute `buffer' for the buffer this
;; title is found in. This breaks lots and lots of tests.
;; However, with private constructor they may not be
;; necessary any more. In case it is really a buffer then
;; also `match' could be real data from `match-data' which
;; contains markers instead of integers.
)
;; Private class methods
(defun rst-Ttl--validate-ado (ado)
;; testcover: ok.
"Return valid ADO or signal error."
(cl-check-type ado (or null rst-Ado))
ado)
(defun rst-Ttl--validate-match (match ado)
;; testcover: ok.
"Return valid MATCH matching ADO or signal error."
(cl-check-type ado (or null rst-Ado))
(cl-check-type match list)
(cl-check-type match (satisfies (lambda (m)
(equal (length m) 8)))
"Match data must consist of exactly 8 buffer positions.")
(dolist (pos match)
(cl-check-type pos (or null integer-or-marker)))
(cl-destructuring-bind (all-beg all-end
ovr-beg ovr-end
txt-beg txt-end
und-beg und-end) match
(unless (and (integer-or-marker-p all-beg) (integer-or-marker-p all-end))
(signal 'args-out-of-range
'("First two elements of match data must be buffer positions.")))
(cond
((null ado)
(unless (and (null ovr-beg) (null ovr-end)
(integer-or-marker-p txt-beg) (integer-or-marker-p txt-end)
(null und-beg) (null und-end))
(signal 'args-out-of-range
'("For a title candidate exactly the third match pair must be set."))))
((rst-Ado-is-transition ado)
(unless (and (null ovr-beg) (null ovr-end)
(integer-or-marker-p txt-beg) (integer-or-marker-p txt-end)
(null und-beg) (null und-end))
(signal 'args-out-of-range
'("For a transition exactly the third match pair must be set."))))
((rst-Ado-is-simple ado)
(unless (and (null ovr-beg) (null ovr-end)
(integer-or-marker-p txt-beg) (integer-or-marker-p txt-end)
(integer-or-marker-p und-beg) (integer-or-marker-p und-end))
(signal 'args-out-of-range
'("For a simple section adornment exactly the third and fourth match pair must be set."))))
(t ; over-and-under
(unless (and (integer-or-marker-p ovr-beg) (integer-or-marker-p ovr-end)
(integer-or-marker-p txt-beg) (integer-or-marker-p txt-end)
(or (null und-beg) (integer-or-marker-p und-beg))
(or (null und-end) (integer-or-marker-p und-end)))
(signal 'args-out-of-range
'("For an over-and-under section adornment all match pairs must be set."))))))
match)
(defun rst-Ttl--validate-indent (indent ado)
;; testcover: ok.
"Return valid INDENT for ADO or signal error."
(if (and ado (rst-Ado-is-transition ado))
(cl-check-type indent null
"Indent for a transition must be nil.")
(cl-check-type indent (integer 0 *)
"Indent for a section header must be non-negative."))
indent)
(defun rst-Ttl--validate-text (text ado)
;; testcover: ok.
"Return valid TEXT for ADO or signal error."
(if (and ado (rst-Ado-is-transition ado))
(cl-check-type text null
"Transitions may not have title text.")
(cl-check-type text string))
text)
;; Public class methods
(defun rst-Ttl-from-buffer (ado beg-ovr beg-txt beg-und txt)
;; testcover: ok.
"Return a `rst-Ttl' constructed from information in the current buffer.
ADO is the adornment or nil for a title candidate. BEG-OVR and
BEG-UND are the starting points of the overline or underline,
respectively. They may be nil if the respective thing is missing.
BEG-TXT is the beginning of the title line or the transition and
must be given. The end of the line is used as the end point. TXT
is the title text or nil. If TXT is given the indentation of the
line containing BEG-TXT is used as indentation. Match group 0 is
derived from the remaining information."
(cl-check-type beg-txt integer-or-marker)
(save-excursion
(let ((end-ovr (when beg-ovr
(goto-char beg-ovr)
(line-end-position)))
(end-txt (progn
(goto-char beg-txt)
(line-end-position)))
(end-und (when beg-und
(goto-char beg-und)
(line-end-position)))
(ind (when txt
(goto-char beg-txt)
(current-indentation))))
(rst-Ttl--new ado
(list
(or beg-ovr beg-txt) (or end-und end-txt)
beg-ovr end-ovr
beg-txt end-txt
beg-und end-und)
ind txt))))
;; Public methods