-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorg-element.el
8742 lines (7987 loc) · 359 KB
/
org-element.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
;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
;; Copyright (C) 2012-2025 Free Software Foundation, Inc.
;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
;; Maintainer: Ihor Radchenko <yantar92 at posteo dot net>
;; Keywords: outlines, hypermedia, calendar, text
;; 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:
;;
;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
;; Org syntax.
;;
;; Lisp-wise, a syntax object can be represented as a list.
;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
;; TYPE is a symbol describing the object.
;; PROPERTIES is the property list attached to it. See docstring of
;; appropriate parsing function to get an exhaustive list.
;; CONTENTS is a list of syntax objects or raw strings contained
;; in the current object, when applicable.
;;
;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
;;
;; The first part of this file defines constants for the Org syntax,
;; while the second one provide accessors and setters functions.
;;
;; The next part implements a parser and an interpreter for each
;; element and object type in Org syntax.
;;
;; The following part creates a fully recursive buffer parser. It
;; also provides a tool to map a function to elements or objects
;; matching some criteria in the parse tree. Functions of interest
;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
;; extent, `org-element-parse-secondary-string'.
;;
;; The penultimate part is the cradle of an interpreter for the
;; obtained parse tree: `org-element-interpret-data'.
;;
;; The library ends by furnishing `org-element-at-point' function, and
;; a way to give information about document structure around point
;; with `org-element-context'. A cache mechanism is also provided for
;; these functions.
;;; Code:
(require 'org-macs)
(org-assert-version)
(require 'avl-tree)
(require 'ring)
(require 'cl-lib)
(require 'ol)
(require 'org)
(require 'org-persist)
(require 'org-compat)
(require 'org-entities)
(require 'org-footnote)
(require 'org-list)
(require 'org-macs)
(require 'org-table)
(require 'org-fold-core)
(declare-function org-at-heading-p "org" (&optional _))
(declare-function org-escape-code-in-string "org-src" (s))
(declare-function org-src-preserve-indentation-p "org-src" (&optional node))
(declare-function org-macro-escape-arguments "org-macro" (&rest args))
(declare-function org-macro-extract-arguments "org-macro" (s))
(declare-function org-reduced-level "org" (l))
(declare-function org-unescape-code-in-string "org-src" (s))
(declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
(declare-function outline-next-heading "outline" ())
(declare-function outline-previous-heading "outline" ())
(defvar org-complex-heading-regexp)
(defvar org-done-keywords)
(defvar org-edit-src-content-indentation)
(defvar org-match-substring-regexp)
(defvar org-odd-levels-only)
(defvar org-property-drawer-re)
(defvar org-property-format)
(defvar org-property-re)
(defvar org-tags-column)
(defvar org-todo-regexp)
(defvar org-ts-regexp-both)
;;; Definitions And Rules
;;
;; Define elements, greater elements and specify recursive objects,
;; along with the affiliated keywords recognized. Also set up
;; restrictions on recursive objects combinations.
;;
;; `org-element-update-syntax' builds proper syntax regexps according
;; to current setup.
(defconst org-element-archive-tag "ARCHIVE"
"Tag marking a subtree as archived.")
(defconst org-element-citation-key-re
(rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
"Regexp matching a citation key.
Key is located in match group 1.")
(defconst org-element-citation-prefix-re
(rx "[cite"
(opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
":"
(zero-or-more (any "\t\n ")))
"Regexp matching a citation prefix.
Style, if any, is located in match group 1.")
(defconst org-element-clock-line-re
(let ((duration ; "=> 212:12"
'(seq
(1+ (or ?\t ?\s)) "=>" (1+ (or ?\t ?\s))
(1+ digit) ":" digit digit)))
(rx-to-string
`(seq
line-start (0+ (or ?\t ?\s))
"CLOCK:"
(or
(seq
(1+ (or ?\t ?\s))
(regexp ,org-ts-regexp-inactive)
(opt "--"
(regexp ,org-ts-regexp-inactive)
,duration))
,duration)
(0+ (or ?\t ?\s))
line-end)))
"Regexp matching a clock line.")
(defconst org-element-comment-string "COMMENT"
"String marker for commented headlines.")
(defconst org-element-closed-keyword "CLOSED:"
"Keyword used to close TODO entries.")
(defconst org-element-deadline-keyword "DEADLINE:"
"Keyword used to mark deadline entries.")
(defconst org-element-scheduled-keyword "SCHEDULED:"
"Keyword used to mark scheduled entries.")
(defconst org-element-planning-keywords-re
(regexp-opt (list org-element-closed-keyword
org-element-deadline-keyword
org-element-scheduled-keyword))
"Regexp matching any planning line keyword.")
(defconst org-element-planning-line-re
(rx-to-string
`(seq line-start (0+ (any ?\s ?\t))
(group (regexp ,org-element-planning-keywords-re))))
"Regexp matching a planning line.")
(defconst org-element-drawer-re
(rx line-start (0+ (any ?\s ?\t))
":" (group (1+ (any ?- ?_ word))) ":"
(0+ (any ?\s ?\t)) line-end)
"Regexp matching opening or closing line of a drawer.
Drawer's name is located in match group 1.")
(defconst org-element-drawer-re-nogroup
(rx line-start (0+ (any ?\s ?\t))
":" (1+ (any ?- ?_ word)) ":"
(0+ (any ?\s ?\t)) line-end)
"Regexp matching opening or closing line of a drawer.")
(defconst org-element-dynamic-block-open-re
(rx line-start (0+ (any ?\s ?\t))
"#+BEGIN:" (0+ (any ?\s ?\t))
(group (1+ word))
(opt
(1+ (any ?\s ?\t))
(group (1+ nonl))))
"Regexp matching the opening line of a dynamic block.
Dynamic block's name is located in match group 1.
Parameters are in match group 2.")
(defconst org-element-dynamic-block-open-re-nogroup
(rx line-start (0+ (any ?\s ?\t))
"#+BEGIN:" (0+ (any ?\s ?\t)) word)
"Regexp matching the opening line of a dynamic block.")
(defconst org-element-headline-re
(rx line-start (1+ "*") " ")
"Regexp matching a headline.")
(defvar org-element-paragraph-separate nil
"Regexp to separate paragraphs in an Org buffer.
In the case of lines starting with \"#\" and \":\", this regexp
is not sufficient to know if point is at a paragraph ending. See
`org-element-paragraph-parser' for more information.")
(defvar org-element--object-regexp nil
"Regexp possibly matching the beginning of an object.
This regexp allows false positives. Dedicated parser (e.g.,
`org-element-bold-parser') will take care of further filtering.
Radio links are not matched by this regexp, as they are treated
specially in `org-element--object-lex'.")
(defun org-element--set-regexps ()
"Build variable syntax regexps."
(setq org-element-paragraph-separate
(concat "^\\(?:"
;; Headlines, inlinetasks.
"\\*+ " "\\|"
;; Footnote definitions.
"\\[fn:[-_[:word:]]+\\]" "\\|"
;; Diary sexps.
"%%(" "\\|"
"[ \t]*\\(?:"
;; Empty lines.
"$" "\\|"
;; Tables (any type).
"|" "\\|"
"\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
;; Comments, keyword-like or block-like constructs.
;; Blocks and keywords with dual values need to be
;; double-checked.
"#\\(?: \\|$\\|\\+\\(?:"
"BEGIN_\\S-+" "\\|"
"\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
"\\|"
;; Drawers (any type) and fixed-width areas. Drawers
;; need to be double-checked.
":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
;; Horizontal rules.
"-\\{5,\\}[ \t]*$" "\\|"
;; LaTeX environments.
"\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
;; Clock lines.
org-element-clock-line-re "\\|"
;; Lists.
(let ((term (pcase org-plain-list-ordered-item-terminator
(?\) ")") (?. "\\.") (_ "[.)]")))
(alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
(concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
"\\(?:[ \t]\\|$\\)"))
"\\)\\)")
org-element--object-regexp
(mapconcat #'identity
(let ((link-types (regexp-opt (org-link-types))))
(list
;; Sub/superscript.
"\\(?:[_^][-{(*+.,[:alnum:]]\\)"
;; Bold, code, italic, strike-through, underline
;; and verbatim.
(rx (or "*" "~" "=" "+" "_" "/") (not space))
;; Plain links.
(concat "\\<" link-types ":")
;; Objects starting with "[": citations,
;; footnote reference, statistics cookie,
;; timestamp (inactive) and regular link.
(format "\\[\\(?:%s\\)"
(mapconcat
#'identity
(list "cite[:/]"
"fn:"
"\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
"\\[")
"\\|"))
;; Objects starting with "@": export snippets.
"@@"
;; Objects starting with "{": macro.
"{{{"
;; Objects starting with "<" : timestamp
;; (active, diary), target, radio target and
;; angular links.
(concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
;; Objects starting with "$": latex fragment.
"\\$"
;; Objects starting with "\": line break,
;; entity, latex fragment.
"\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
;; Objects starting with raw text: inline Babel
;; source block, inline Babel call.
"\\(?:call\\|src\\)_"))
"\\|")))
(org-element--set-regexps)
;;;###autoload
(defun org-element-update-syntax ()
"Update parser internals."
(interactive)
(org-element--set-regexps)
(org-element-cache-reset 'all))
(defconst org-element-all-elements
'(babel-call center-block clock comment comment-block diary-sexp drawer
dynamic-block example-block export-block fixed-width
footnote-definition headline horizontal-rule inlinetask item
keyword latex-environment node-property paragraph plain-list
planning property-drawer quote-block section
special-block src-block table table-row verse-block)
"Complete list of element types.")
(defconst org-element-greater-elements
'(center-block drawer dynamic-block footnote-definition headline inlinetask
item plain-list property-drawer quote-block section
special-block table org-data)
"List of recursive element types aka Greater Elements.")
(defconst org-element-all-objects
'(bold citation citation-reference code entity export-snippet
footnote-reference inline-babel-call inline-src-block italic line-break
latex-fragment link macro radio-target statistics-cookie strike-through
subscript superscript table-cell target timestamp underline verbatim)
"Complete list of object types.")
(defconst org-element-recursive-objects
'(bold citation footnote-reference italic link subscript radio-target
strike-through superscript table-cell underline)
"List of recursive object types.")
(defconst org-element-object-containers
(append org-element-recursive-objects '(paragraph table-row verse-block))
"List of object or element types that can directly contain objects.")
(defconst org-element-affiliated-keywords
'("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
"RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
"List of affiliated keywords as strings.
By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
are affiliated keywords and need not to be in this list.")
(defconst org-element-keyword-translation-alist
'(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
"Alist of usual translations for keywords.
The key is the old name and the value the new one. The property
holding their value will be named after the translated name.")
(defconst org-element-multiple-keywords '("CAPTION" "HEADER")
"List of affiliated keywords that can occur more than once in an element.
Their value will be consed into a list of strings, which will be
returned as the value of the property.
This list is checked after translations have been applied. See
`org-element-keyword-translation-alist'.
By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
allow multiple occurrences and need not to be in this list.")
(defconst org-element-parsed-keywords '("CAPTION")
"List of affiliated keywords whose value can be parsed.
Their value will be stored as a secondary string: a list of
strings and objects.
This list is checked after translations have been applied. See
`org-element-keyword-translation-alist'.")
(defconst org-element--parsed-properties-alist
(mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
org-element-parsed-keywords)
"Alist of parsed keywords and associated properties.
This is generated from `org-element-parsed-keywords', which
see.")
(defconst org-element-dual-keywords '("CAPTION" "RESULTS")
"List of affiliated keywords which can have a secondary value.
In Org syntax, they can be written with optional square brackets
before the colons. For example, RESULTS keyword can be
associated to a hash value with the following:
#+RESULTS[hash-string]: some-source
This list is checked after translations have been applied. See
`org-element-keyword-translation-alist'.")
(defconst org-element--affiliated-re
(format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
(concat
;; Dual affiliated keywords.
(format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
(regexp-opt org-element-dual-keywords))
"\\|"
;; Regular affiliated keywords.
(format "\\(?1:%s\\)"
(regexp-opt
(cl-remove-if
(lambda (k) (member k org-element-dual-keywords))
org-element-affiliated-keywords)))
"\\|"
;; Export attributes.
"\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
"Regexp matching any affiliated keyword.
Keyword name is put in match group 1. Moreover, if keyword
belongs to `org-element-dual-keywords', put the dual value in
match group 2.
Don't modify it, set `org-element-affiliated-keywords' instead.")
(defconst org-element-object-restrictions
(let* ((minimal-set '(bold code entity italic latex-fragment strike-through
subscript superscript underline verbatim))
(standard-set
(remq 'citation-reference (remq 'table-cell org-element-all-objects)))
(standard-set-no-line-break (remq 'line-break standard-set))
(standard-set-for-citations (seq-difference
standard-set-no-line-break
'( citation citation-reference
footnote-reference link))))
`((bold ,@standard-set)
(citation citation-reference)
(citation-reference ,@standard-set-for-citations)
(footnote-reference ,@standard-set)
(headline ,@standard-set-no-line-break)
(inlinetask ,@standard-set-no-line-break)
(italic ,@standard-set)
(item ,@standard-set-no-line-break)
(keyword ,@(remq 'footnote-reference standard-set))
;; Ignore all links in a link description. Also ignore
;; radio-targets and line breaks.
(link export-snippet inline-babel-call inline-src-block macro
statistics-cookie ,@minimal-set)
(paragraph ,@standard-set)
;; Remove any variable object from radio target as it would
;; prevent it from being properly recognized.
(radio-target ,@minimal-set)
(strike-through ,@standard-set)
(subscript ,@standard-set)
(superscript ,@standard-set)
;; Ignore inline babel call and inline source block as formulas
;; are possible. Also ignore line breaks and statistics
;; cookies.
(table-cell citation export-snippet footnote-reference link macro
radio-target target timestamp ,@minimal-set)
(table-row table-cell)
(underline ,@standard-set)
(verse-block ,@standard-set)))
"Alist of objects restrictions.
key is an element or object type containing objects and value is
a list of types that can be contained within an element or object
of such type.
This alist also applies to secondary string. For example, an
`headline' type element doesn't directly contain objects, but
still has an entry since one of its properties (`:title') does.")
(defconst org-element-secondary-value-alist
'((citation :prefix :suffix)
(headline :title)
(inlinetask :title)
(item :tag)
(citation-reference :prefix :suffix))
"Alist between element types and locations of secondary values.")
(defconst org-element--pair-round-table
(let ((table (make-char-table 'syntax-table '(2))))
(modify-syntax-entry ?\( "()" table)
(modify-syntax-entry ?\) ")(" table)
table)
"Table used internally to pair only round brackets.")
(defconst org-element--pair-square-table
(let ((table (make-char-table 'syntax-table '(2))))
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
table)
"Table used internally to pair only square brackets.")
(defconst org-element--pair-curly-table
(let ((table (make-char-table 'syntax-table '(2))))
(modify-syntax-entry ?\{ "(}" table)
(modify-syntax-entry ?\} "){" table)
table)
"Table used internally to pair only curly brackets.")
(defun org-element--parse-paired-brackets (char)
"Parse paired brackets at point.
CHAR is the opening bracket to consider, as a character. Return
contents between brackets, as a string, or nil. Also move point
past the brackets."
(when (eq char (char-after))
(let ((syntax-table (pcase char
(?\{ org-element--pair-curly-table)
(?\[ org-element--pair-square-table)
(?\( org-element--pair-round-table)
(_ nil)))
(pos (point)))
(when syntax-table
(with-syntax-table syntax-table
(let ((end (ignore-errors (scan-lists pos 1 0))))
(when end
(goto-char end)
(buffer-substring-no-properties (1+ pos) (1- end)))))))))
(defconst org-element--cache-variables
'( org-element--cache org-element--cache-size
org-element--headline-cache org-element--headline-cache-size
org-element--cache-hash-left org-element--cache-hash-right
org-element--cache-sync-requests org-element--cache-sync-timer
org-element--cache-sync-keys-value org-element--cache-change-tic
org-element--cache-last-buffer-size
org-element--cache-diagnostics-ring
org-element--cache-diagnostics-ring-size
org-element--cache-gapless
org-element--cache-change-warning)
"List of variable symbols holding cache state.")
(defconst org-element-ignored-local-variables
`( org-font-lock-keywords
,@org-element--cache-variables)
"List of variables not copied through upon Org buffer duplication.
Export process and parsing in `org-element-parse-secondary-string'
takes place on a copy of the original buffer. When this copy is
created, all Org related local variables not in this list are copied
to the new buffer. Variables with an unreadable value are also
ignored.")
(cl-defun org-element--generate-copy-script (buffer
&key
copy-unreadable
drop-visibility
drop-narrowing
drop-contents
drop-locals)
"Generate a function duplicating BUFFER.
The copy will preserve local variables, visibility, contents and
narrowing of the original buffer. If a region was active in
BUFFER, contents will be narrowed to that region instead.
When optional key COPY-UNREADABLE is non-nil, do not ensure that all
the copied local variables will be readable in another Emacs session.
When optional keys DROP-VISIBILITY, DROP-NARROWING, DROP-CONTENTS, or
DROP-LOCALS are non-nil, do not preserve visibility, narrowing,
contents, or local variables correspondingly.
The resulting function can be evaluated at a later time, from
another buffer, effectively cloning the original buffer there.
The function assumes BUFFER's major mode is `org-mode'."
(declare-function org-fold-core--update-buffer-folds "org-fold-core" ())
(require 'org-fold-core)
(with-current-buffer buffer
(let ((str (unless drop-contents (org-with-wide-buffer (buffer-string))))
(narrowing
(unless drop-narrowing
(if (org-region-active-p)
(list (region-beginning) (region-end))
(list (point-min) (point-max)))))
(pos (point))
(varvals
(unless drop-locals
(let ((varvals nil))
(dolist (entry (buffer-local-variables (buffer-base-buffer)))
(when (consp entry)
(let ((var (car entry))
(val (cdr entry)))
(and (not (memq var org-element-ignored-local-variables))
(or (memq var
'(default-directory
;; Required to convert file
;; links in the #+INCLUDEd
;; files. See
;; `org-export--prepare-file-contents'.
buffer-file-name
buffer-file-coding-system
;; Needed to preserve folding state
char-property-alias-alist))
(string-match-p "^\\(org-\\|orgtbl-\\)"
(symbol-name var)))
;; Skip unreadable values, as they cannot be
;; sent to external process.
(or copy-unreadable (not val)
(ignore-errors (read (format "%S" val))))
(push (cons var val) varvals)))))
varvals)))
(ols
(unless drop-visibility
(let (ov-set)
(dolist (ov (overlays-in (point-min) (point-max)))
(let ((invis-prop (overlay-get ov 'invisible)))
(when invis-prop
(push (list (overlay-start ov) (overlay-end ov)
(overlay-properties ov))
ov-set))))
ov-set))))
(lambda ()
(let ((inhibit-modification-hooks t))
;; Set major mode. Ignore `org-mode-hook' and other hooks as
;; they have been run already in BUFFER.
(unless (eq major-mode 'org-mode)
(delay-mode-hooks
(let ((org-inhibit-startup t)) (org-mode))))
;; Copy specific buffer local variables.
(pcase-dolist (`(,var . ,val) varvals)
(set (make-local-variable var) val))
;; Whole buffer contents when requested.
(when str
(let ((inhibit-read-only t))
(erase-buffer) (insert str)))
;; Make org-element-cache not complain about changed buffer
;; state.
(org-element-cache-reset nil 'no-persistence)
;; Narrowing.
(when narrowing
(apply #'narrow-to-region narrowing))
;; Current position of point.
(goto-char pos)
;; Overlays with invisible property.
(pcase-dolist (`(,start ,end ,props) ols)
(let ((ov (make-overlay start end)))
(while props
(overlay-put ov (pop props) (pop props)))))
;; Text property folds.
(unless drop-visibility (org-fold-core--update-buffer-folds))
;; Never write the buffer copy to disk, despite
;; `buffer-file-name' not being nil.
(setq write-contents-functions (list (lambda (&rest _) t))))))))
(cl-defun org-element-copy-buffer (&key to-buffer drop-visibility
drop-narrowing drop-contents
drop-locals)
"Return a copy of the current buffer.
The copy preserves Org buffer-local variables, visibility and
narrowing.
IMPORTANT: The buffer copy may also have variable `buffer-file-name'
copied.
To prevent Emacs overwriting the original buffer file,
`write-contents-functions' is set to \\='(always). Do not alter this
variable and do not do anything that might alter it (like calling a
major mode) to prevent data corruption. Also, do note that Emacs may
jump into the created buffer if the original file buffer is closed and
then re-opened. Making edits in the buffer copy may also trigger
Emacs save dialog. Prefer using `org-element-with-buffer-copy' macro
when possible.
When optional key TO-BUFFER is non-nil, copy into BUFFER.
Optional keys DROP-VISIBILITY, DROP-NARROWING, DROP-CONTENTS, and
DROP-LOCALS are passed to `org-element--generate-copy-script'."
(let ((copy-buffer-fun (org-element--generate-copy-script
(current-buffer)
:copy-unreadable 'do-not-check
:drop-visibility drop-visibility
:drop-narrowing drop-narrowing
:drop-contents drop-contents
:drop-locals drop-locals))
(new-buf (or to-buffer (generate-new-buffer (buffer-name)))))
(with-current-buffer new-buf
(funcall copy-buffer-fun)
(set-buffer-modified-p nil))
new-buf))
(cl-defmacro org-element-with-buffer-copy ( &rest body
&key to-buffer drop-visibility
drop-narrowing drop-contents
drop-locals
&allow-other-keys)
"Apply BODY in a copy of the current buffer.
The copy preserves local variables, visibility and contents of
the original buffer. Point is at the beginning of the buffer
when BODY is applied.
Optional keys can modify what is being copied and the generated buffer
copy. TO-BUFFER, DROP-VISIBILITY, DROP-NARROWING, DROP-CONTENTS, and
DROP-LOCALS are passed as arguments to `org-element-copy-buffer'."
(declare (debug t))
;; Drop keyword arguments from BODY.
(while (keywordp (car body)) (pop body) (pop body))
(org-with-gensyms (buf-copy)
`(let ((,buf-copy (org-element-copy-buffer
:to-buffer ,to-buffer
:drop-visibility ,drop-visibility
:drop-narrowing ,drop-narrowing
:drop-contents ,drop-contents
:drop-locals ,drop-locals)))
(unwind-protect
(with-current-buffer ,buf-copy
(goto-char (point-min))
(prog1
(progn ,@body)
;; `org-element-copy-buffer' carried the value of
;; `buffer-file-name' from the original buffer. When not
;; killed, the new buffer copy may become a target of
;; `find-file'. Prevent this.
(setq buffer-file-name nil)))
(and (buffer-live-p ,buf-copy)
;; Kill copy without confirmation.
(progn (with-current-buffer ,buf-copy
(restore-buffer-modified-p nil))
(unless ,to-buffer
(kill-buffer ,buf-copy))))))))
;;; Accessors and Setters
;;
;; Provide four accessors: `org-element-type', `org-element-property'
;; `org-element-contents' and `org-element-restriction'.
;;
;; Setter functions allow modification of elements by side effect.
;; There is `org-element-put-property', `org-element-set-contents'.
;; These low-level functions are useful to build a parse tree.
;;
;; `org-element-adopt', `org-element-set', `org-element-extract' and
;; `org-element-insert-before' are high-level functions useful to
;; modify a parse tree.
;;
;; `org-element-secondary-p' is a predicate used to know if a given
;; object belongs to a secondary string. `org-element-class' tells if
;; some parsed data is an element or an object, handling pseudo
;; elements and objects. `org-element-copy' returns an element or
;; object, stripping its parent property and resolving deferred values
;; in the process.
(require 'org-element-ast)
(defsubst org-element-restriction (element)
"Return restriction associated to ELEMENT.
ELEMENT can be an element, an object or a symbol representing an
element or object type."
(cdr (assq (if (symbolp element) element (org-element-type element))
org-element-object-restrictions)))
(defsubst org-element-class (datum &optional parent)
"Return class for ELEMENT, as a symbol.
Class is either `element' or `object'. Optional argument PARENT
is the element or object containing DATUM. It defaults to the
value of DATUM `:parent' property."
(let ((type (org-element-type datum t))
(parent (or parent (org-element-parent datum))))
(cond
;; Trivial cases.
((memq type org-element-all-objects) 'object)
((memq type org-element-all-elements) 'element)
;; Special cases.
((eq type 'org-data) 'element)
((eq type 'plain-text) 'object)
((eq type 'anonymous) 'object)
((not type) nil)
;; Pseudo object or elements. Make a guess about its class.
;; Basically a pseudo object is contained within another object,
;; a secondary string or a container element.
((not parent) 'element)
(t
(let ((parent-type (org-element-type parent t)))
(cond ((eq 'anonymous parent-type) 'object)
((memq parent-type org-element-object-containers) 'object)
((org-element-secondary-p datum) 'object)
(t 'element)))))))
(defsubst org-element-parent-element (object)
"Return first element containing OBJECT or nil.
OBJECT is the object to consider."
(org-element-lineage object org-element-all-elements))
(defsubst org-element-begin (node)
"Get `:begin' property of NODE."
(org-element-property :begin node))
(gv-define-setter org-element-begin (value node)
`(org-element-put-property ,node :begin ,value))
(defsubst org-element-end (node)
"Get `:end' property of NODE."
(org-element-property :end node))
(gv-define-setter org-element-end (value node)
`(org-element-put-property ,node :end ,value))
(defsubst org-element-contents-begin (node)
"Get `:contents-begin' property of NODE."
(org-element-property :contents-begin node))
(gv-define-setter org-element-contents-begin (value node)
`(org-element-put-property ,node :contents-begin ,value))
(defsubst org-element-contents-end (node)
"Get `:contents-end' property of NODE."
(org-element-property :contents-end node))
(gv-define-setter org-element-contents-end (value node)
`(org-element-put-property ,node :contents-end ,value))
(defsubst org-element-post-affiliated (node)
"Get `:post-affiliated' property of NODE."
(org-element-property :post-affiliated node))
(gv-define-setter org-element-post-affiliated (value node)
`(org-element-put-property ,node :post-affiliated ,value))
(defsubst org-element-post-blank (node)
"Get `:post-blank' property of NODE."
(org-element-property :post-blank node))
(gv-define-setter org-element-post-blank (value node)
`(org-element-put-property ,node :post-blank ,value))
(defconst org-element--cache-element-properties
'(:cached
:org-element--cache-sync-key
:buffer)
"List of element properties used internally by cache.")
(defvar org-element--string-cache (make-hash-table :test #'equal)
"Hash table holding tag strings and todo keyword objects.
We use shared string storage to reduce memory footprint of the syntax
tree.")
(defsubst org-element--get-cached-string (string)
"Return cached object equal to STRING.
Return nil if STRING is nil."
(when string
(or (gethash string org-element--string-cache)
(puthash string string org-element--string-cache))))
(defun org-element--substring (element beg-offset end-offset)
"Get substring inside ELEMENT according to BEG-OFFSET and END-OFFSET."
(with-current-buffer (org-element-property :buffer element)
(org-with-wide-buffer
(let ((beg (org-element-begin element)))
(buffer-substring-no-properties
(+ beg beg-offset) (+ beg end-offset))))))
(defun org-element--unescape-substring (element beg-offset end-offset)
"Call `org-element--substring' and unescape the result.
See `org-element--substring' for the meaning of ELEMENT, BEG-OFFSET,
and END-OFFSET."
(org-unescape-code-in-string
(org-element--substring element beg-offset end-offset)))
;;; Greater elements
;;
;; For each greater element type, we define a parser and an
;; interpreter.
;;
;; A parser returns the element or object as the list described above.
;; Most of them accepts no argument. Though, exceptions exist. Hence
;; every element containing a secondary string (see
;; `org-element-secondary-value-alist') will accept an optional
;; argument to toggle parsing of these secondary strings. Moreover,
;; `item' parser requires current list's structure as its first
;; element.
;;
;; An interpreter accepts two arguments: the list representation of
;; the element or object, and its contents. The latter may be nil,
;; depending on the element or object considered. It returns the
;; appropriate Org syntax, as a string.
;;
;; Parsing functions must follow the naming convention:
;; org-element-TYPE-parser, where TYPE is greater element's type, as
;; defined in `org-element-greater-elements'.
;;
;; Similarly, interpreting functions must follow the naming
;; convention: org-element-TYPE-interpreter.
;;
;; With the exception of `headline' and `item' types, greater elements
;; cannot contain other greater elements of their own type.
;;
;; Beside implementing a parser and an interpreter, adding a new
;; greater element requires tweaking `org-element--current-element'.
;; Moreover, the newly defined type must be added to both
;; `org-element-all-elements' and `org-element-greater-elements'.
;;
;; When adding or modifying the parser, please keep in mind the
;; following rules. They are important to keep parser performance
;; optimal.
;;
;; 1. When you can use `looking-at-p' or `string-match-p' instead of
;; `looking-at' or `string-match' and keep match data unmodified,
;; do it.
;; 2. When regexps can be grouped together, avoiding multiple regexp
;; match calls, they should be grouped.
;; 3. When `save-match-data' can be avoided, avoid it.
;; 4. When simpler regexps can be used for analysis, use the simpler
;; regexps.
;; 5. When regexps can be calculated in advance, not dynamically, they
;; should be calculated in advance.
;; 6 Note that it is not an obligation of a given function to preserve
;; match data - `save-match-data' is costly and must be arranged by
;; the caller if necessary.
;;
;; See https://debbugs.gnu.org/cgi/bugreport.cgi?bug=63225
;;;; Center Block
(defun org-element-center-block-parser (limit affiliated)
"Parse a center block.
LIMIT bounds the search. AFFILIATED is a list of which CAR is
the buffer position at the beginning of the first affiliated
keyword and CDR is a plist of affiliated keywords along with
their value.
Return a new syntax node of `center-block' type containing `:begin',
`:end', `:contents-begin', `:contents-end', `:post-blank' and
`:post-affiliated' properties.
Assume point is at the beginning of the block."
(let ((case-fold-search t))
(if (not (save-excursion
(re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
;; Incomplete block: parse it as a paragraph.
(org-element-paragraph-parser limit affiliated)
(let ((block-end-line (match-beginning 0)))
(let* ((begin (car affiliated))
(post-affiliated (point))
;; Empty blocks have no contents.
(contents-begin (progn (forward-line)
(and (< (point) block-end-line)
(point))))
(contents-end (and contents-begin block-end-line))
(pos-before-blank (progn (goto-char block-end-line)
(forward-line)
(point)))
(end (save-excursion
(skip-chars-forward " \r\t\n" limit)
(if (eobp) (point) (line-beginning-position)))))
(org-element-create
'center-block
(nconc
(list :begin begin
:end end
:contents-begin contents-begin
:contents-end contents-end
:post-blank (count-lines pos-before-blank end)
:post-affiliated post-affiliated)
(cdr affiliated))))))))
(defun org-element-center-block-interpreter (_ contents)
"Interpret a center-block element as Org syntax.
CONTENTS is the contents of the element."
(format "#+begin_center\n%s#+end_center" contents))
;;;; Drawer
(defun org-element-drawer-parser (limit affiliated)
"Parse a drawer.
LIMIT bounds the search. AFFILIATED is a list of which CAR is
the buffer position at the beginning of the first affiliated
keyword and CDR is a plist of affiliated keywords along with
their value.
Return a new syntax node of `drawer' type containing `:drawer-name',
`:begin', `:end', `:contents-begin', `:contents-end', `:post-blank'
and `:post-affiliated' properties.
Assume point is at beginning of drawer."
(let ((case-fold-search t))
(if (not (save-excursion
(goto-char (min limit (line-end-position)))
(re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
;; Incomplete drawer: parse it as a paragraph.
(org-element-paragraph-parser limit affiliated)
(save-excursion
(let* ((drawer-end-line (match-beginning 0))
(name
(progn
(looking-at org-element-drawer-re)
(org-element--get-cached-string (match-string-no-properties 1))))
(begin (car affiliated))
(post-affiliated (point))
;; Empty drawers have no contents.
(contents-begin (progn (forward-line)
(and (< (point) drawer-end-line)
(point))))
(contents-end (and contents-begin drawer-end-line))
(pos-before-blank (progn (goto-char drawer-end-line)
(forward-line)
(point)))
(end (progn (skip-chars-forward " \r\t\n" limit)
(if (eobp) (point) (line-beginning-position)))))
(org-element-create
'drawer
(nconc
(list :begin begin
:end end