1 ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; Elements are related to the structure of the document. Indeed, all
29 ;; elements are a cover for the document: each position within belongs
30 ;; to at least one element.
32 ;; An element always starts and ends at the beginning of a line. With
33 ;; a few exceptions (`clock', `headline', `inlinetask', `item',
34 ;; `planning', `property-drawer', `node-property', `section' and
35 ;; `table-row' types), it can also accept a fixed set of keywords as
36 ;; attributes. Those are called "affiliated keywords" to distinguish
37 ;; them from other keywords, which are full-fledged elements. Almost
38 ;; all affiliated keywords are referenced in
39 ;; `org-element-affiliated-keywords'; the others are export attributes
40 ;; and start with "ATTR_" prefix.
42 ;; Element containing other elements (and only elements) are called
43 ;; greater elements. Concerned types are: `center-block', `drawer',
44 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
45 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
46 ;; and `special-block'.
48 ;; Other element types are: `babel-call', `clock', `comment',
49 ;; `comment-block', `diary-sexp', `example-block', `export-block',
50 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
51 ;; `node-property', `paragraph', `planning', `src-block', `table',
52 ;; `table-row' and `verse-block'. Among them, `paragraph' and
53 ;; `verse-block' types can contain Org objects and plain text.
55 ;; Objects are related to document's contents. Some of them are
56 ;; recursive. Associated types are of the following: `bold', `code',
57 ;; `entity', `export-snippet', `footnote-reference',
58 ;; `inline-babel-call', `inline-src-block', `italic',
59 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
60 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
61 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
63 ;; Some elements also have special properties whose value can hold
64 ;; objects themselves (e.g. an item tag or a headline name). Such
65 ;; values are called "secondary strings". Any object belongs to
66 ;; either an element or a secondary string.
68 ;; Notwithstanding affiliated keywords, each greater element, element
69 ;; and object has a fixed set of properties attached to it. Among
70 ;; them, four are shared by all types: `:begin' and `:end', which
71 ;; refer to the beginning and ending buffer positions of the
72 ;; considered element or object, `:post-blank', which holds the number
73 ;; of blank lines, or white spaces, at its end and `:parent' which
74 ;; refers to the element or object containing it. Greater elements,
75 ;; elements and objects containing objects will also have
76 ;; `:contents-begin' and `:contents-end' properties to delimit
77 ;; contents. Eventually, All elements have a `:post-affiliated'
78 ;; property referring to the buffer position after all affiliated
79 ;; keywords, if any, or to their beginning position otherwise.
81 ;; At the lowest level, a `:parent' property is also attached to any
82 ;; string, as a text property.
84 ;; Lisp-wise, an element or an object can be represented as a list.
85 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
86 ;; TYPE is a symbol describing the Org element or object.
87 ;; PROPERTIES is the property list attached to it. See docstring of
88 ;; appropriate parsing function to get an exhaustive
90 ;; CONTENTS is a list of elements, objects or raw strings contained
91 ;; in the current element or object, when applicable.
93 ;; An Org buffer is a nested list of such elements and objects, whose
94 ;; type is `org-data' and properties is nil.
96 ;; The first part of this file defines Org syntax, while the second
97 ;; one provide accessors and setters functions.
99 ;; The next part implements a parser and an interpreter for each
100 ;; element and object type in Org syntax.
102 ;; The following part creates a fully recursive buffer parser. It
103 ;; also provides a tool to map a function to elements or objects
104 ;; matching some criteria in the parse tree. Functions of interest
105 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
106 ;; extent, `org-element-parse-secondary-string'.
108 ;; The penultimate part is the cradle of an interpreter for the
109 ;; obtained parse tree: `org-element-interpret-data'.
111 ;; The library ends by furnishing `org-element-at-point' function, and
112 ;; a way to give information about document structure around point
113 ;; with `org-element-context'. A cache mechanism is also provided for
125 ;;; Definitions And Rules
127 ;; Define elements, greater elements and specify recursive objects,
128 ;; along with the affiliated keywords recognized. Also set up
129 ;; restrictions on recursive objects combinations.
131 ;; `org-element-update-syntax' builds proper syntax regexps according
134 (defvar org-element-paragraph-separate nil
135 "Regexp to separate paragraphs in an Org buffer.
136 In the case of lines starting with \"#\" and \":\", this regexp
137 is not sufficient to know if point is at a paragraph ending. See
138 `org-element-paragraph-parser' for more information.")
140 (defvar org-element--object-regexp nil
141 "Regexp possibly matching the beginning of an object.
142 This regexp allows false positives. Dedicated parser (e.g.,
143 `org-export-bold-parser') will take care of further filtering.
144 Radio links are not matched by this regexp, as they are treated
145 specially in `org-element--object-lex'.")
147 (defun org-element--set-regexps ()
148 "Build variable syntax regexps."
149 (setq org-element-paragraph-separate
151 ;; Headlines, inlinetasks.
152 org-outline-regexp
"\\|"
153 ;; Footnote definitions.
154 "\\[fn:[-_[:word:]]+\\]" "\\|"
160 ;; Tables (any type).
162 "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
163 ;; Comments, keyword-like or block-like constructs.
164 ;; Blocks and keywords with dual values need to be
166 "#\\(?: \\|$\\|\\+\\(?:"
168 "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
170 ;; Drawers (any type) and fixed-width areas. Drawers
171 ;; need to be double-checked.
172 ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
174 "-\\{5,\\}[ \t]*$" "\\|"
175 ;; LaTeX environments.
176 "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
178 (regexp-quote org-clock-string
) "\\|"
180 (let ((term (pcase org-plain-list-ordered-item-terminator
181 (?\
) ")") (?.
"\\.") (_ "[.)]")))
182 (alpha (and org-list-allow-alphabetical
"\\|[A-Za-z]")))
183 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha
"\\)" term
"\\)"
184 "\\(?:[ \t]\\|$\\)"))
186 org-element--object-regexp
187 (mapconcat #'identity
188 (let ((link-types (regexp-opt (org-link-types))))
191 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
192 ;; Bold, code, italic, strike-through, underline
196 (nth 2 org-emphasis-regexp-components
)))
198 (concat "\\<" link-types
":")
199 ;; Objects starting with "[": regular link,
200 ;; footnote reference, statistics cookie,
201 ;; timestamp (inactive).
205 "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" "\\|"
206 "[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
208 ;; Objects starting with "@": export snippets.
210 ;; Objects starting with "{": macro.
212 ;; Objects starting with "<" : timestamp
213 ;; (active, diary), target, radio target and
215 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
216 ;; Objects starting with "$": latex fragment.
218 ;; Objects starting with "\": line break,
219 ;; entity, latex fragment.
220 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
221 ;; Objects starting with raw text: inline Babel
222 ;; source block, inline Babel call.
223 "\\(?:call\\|src\\)_"))
226 (org-element--set-regexps)
229 (defun org-element-update-syntax ()
230 "Update parser internals."
232 (org-element--set-regexps)
233 (org-element-cache-reset 'all
))
235 (defconst org-element-all-elements
236 '(babel-call center-block clock comment comment-block diary-sexp drawer
237 dynamic-block example-block export-block fixed-width
238 footnote-definition headline horizontal-rule inlinetask item
239 keyword latex-environment node-property paragraph plain-list
240 planning property-drawer quote-block section
241 special-block src-block table table-row verse-block
)
242 "Complete list of element types.")
244 (defconst org-element-greater-elements
245 '(center-block drawer dynamic-block footnote-definition headline inlinetask
246 item plain-list property-drawer quote-block section
248 "List of recursive element types aka Greater Elements.")
250 (defconst org-element-all-objects
251 '(bold code entity export-snippet footnote-reference inline-babel-call
252 inline-src-block italic line-break latex-fragment link macro
253 radio-target statistics-cookie strike-through subscript superscript
254 table-cell target timestamp underline verbatim
)
255 "Complete list of object types.")
257 (defconst org-element-recursive-objects
258 '(bold footnote-reference italic link subscript radio-target strike-through
259 superscript table-cell underline
)
260 "List of recursive object types.")
262 (defconst org-element-object-containers
263 (append org-element-recursive-objects
'(paragraph table-row verse-block
))
264 "List of object or element types that can directly contain objects.")
266 (defconst org-element-affiliated-keywords
267 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
268 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
269 "List of affiliated keywords as strings.
270 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
271 are affiliated keywords and need not to be in this list.")
273 (defconst org-element-keyword-translation-alist
274 '(("DATA" .
"NAME") ("LABEL" .
"NAME") ("RESNAME" .
"NAME")
275 ("SOURCE" .
"NAME") ("SRCNAME" .
"NAME") ("TBLNAME" .
"NAME")
276 ("RESULT" .
"RESULTS") ("HEADERS" .
"HEADER"))
277 "Alist of usual translations for keywords.
278 The key is the old name and the value the new one. The property
279 holding their value will be named after the translated name.")
281 (defconst org-element-multiple-keywords
'("CAPTION" "HEADER")
282 "List of affiliated keywords that can occur more than once in an element.
284 Their value will be consed into a list of strings, which will be
285 returned as the value of the property.
287 This list is checked after translations have been applied. See
288 `org-element-keyword-translation-alist'.
290 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
291 allow multiple occurrences and need not to be in this list.")
293 (defconst org-element-parsed-keywords
'("CAPTION")
294 "List of affiliated keywords whose value can be parsed.
296 Their value will be stored as a secondary string: a list of
299 This list is checked after translations have been applied. See
300 `org-element-keyword-translation-alist'.")
302 (defconst org-element--parsed-properties-alist
303 (mapcar (lambda (k) (cons k
(intern (concat ":" (downcase k
)))))
304 org-element-parsed-keywords
)
305 "Alist of parsed keywords and associated properties.
306 This is generated from `org-element-parsed-keywords', which
309 (defconst org-element-dual-keywords
'("CAPTION" "RESULTS")
310 "List of affiliated keywords which can have a secondary value.
312 In Org syntax, they can be written with optional square brackets
313 before the colons. For example, RESULTS keyword can be
314 associated to a hash value with the following:
316 #+RESULTS[hash-string]: some-source
318 This list is checked after translations have been applied. See
319 `org-element-keyword-translation-alist'.")
321 (defconst org-element--affiliated-re
322 (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
324 ;; Dual affiliated keywords.
325 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
326 (regexp-opt org-element-dual-keywords
))
328 ;; Regular affiliated keywords.
329 (format "\\(?1:%s\\)"
332 (lambda (k) (member k org-element-dual-keywords
))
333 org-element-affiliated-keywords
)))
335 ;; Export attributes.
336 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
337 "Regexp matching any affiliated keyword.
339 Keyword name is put in match group 1. Moreover, if keyword
340 belongs to `org-element-dual-keywords', put the dual value in
343 Don't modify it, set `org-element-affiliated-keywords' instead.")
345 (defconst org-element-object-restrictions
346 (let* ((standard-set (remq 'table-cell org-element-all-objects
))
347 (standard-set-no-line-break (remq 'line-break standard-set
)))
348 `((bold ,@standard-set
)
349 (footnote-reference ,@standard-set
)
350 (headline ,@standard-set-no-line-break
)
351 (inlinetask ,@standard-set-no-line-break
)
352 (italic ,@standard-set
)
353 (item ,@standard-set-no-line-break
)
354 (keyword ,@(remq 'footnote-reference standard-set
))
355 ;; Ignore all links excepted plain links and angular links in
356 ;; a link description. Also ignore radio-targets and line
358 (link bold code entity export-snippet inline-babel-call inline-src-block
359 italic latex-fragment macro simple-link statistics-cookie
360 strike-through subscript superscript underline verbatim
)
361 (paragraph ,@standard-set
)
362 ;; Remove any variable object from radio target as it would
363 ;; prevent it from being properly recognized.
364 (radio-target bold code entity italic latex-fragment strike-through
365 subscript superscript underline superscript
)
366 (strike-through ,@standard-set
)
367 (subscript ,@standard-set
)
368 (superscript ,@standard-set
)
369 ;; Ignore inline babel call and inline src block as formulas are
370 ;; possible. Also ignore line breaks and statistics cookies.
371 (table-cell bold code entity export-snippet footnote-reference italic
372 latex-fragment link macro radio-target strike-through
373 subscript superscript target timestamp underline verbatim
)
374 (table-row table-cell
)
375 (underline ,@standard-set
)
376 (verse-block ,@standard-set
)))
377 "Alist of objects restrictions.
379 key is an element or object type containing objects and value is
380 a list of types that can be contained within an element or object
383 For example, in a `radio-target' object, one can only find
384 entities, latex-fragments, subscript, superscript and text
387 This alist also applies to secondary string. For example, an
388 `headline' type element doesn't directly contain objects, but
389 still has an entry since one of its properties (`:title') does.")
391 (defconst org-element-secondary-value-alist
395 "Alist between element types and locations of secondary values.")
397 (defconst org-element--pair-round-table
398 (let ((table (make-syntax-table)))
399 (modify-syntax-entry ?\
( "()" table
)
400 (modify-syntax-entry ?\
) ")(" table
)
401 (dolist (char '(?\
{ ?\
} ?\
[ ?\
] ?\
< ?\
>) table
)
402 (modify-syntax-entry char
" " table
)))
403 "Table used internally to pair only round brackets.
404 Other brackets are treated as spaces.")
406 (defconst org-element--pair-square-table
407 (let ((table (make-syntax-table)))
408 (modify-syntax-entry ?\
[ "(]" table
)
409 (modify-syntax-entry ?\
] ")[" table
)
410 (dolist (char '(?\
{ ?\
} ?\
( ?\
) ?\
< ?\
>) table
)
411 (modify-syntax-entry char
" " table
)))
412 "Table used internally to pair only square brackets.
413 Other brackets are treated as spaces.")
415 (defconst org-element--pair-curly-table
416 (let ((table (make-syntax-table)))
417 (modify-syntax-entry ?\
{ "(}" table
)
418 (modify-syntax-entry ?\
} "){" table
)
419 (dolist (char '(?\
[ ?\
] ?\
( ?\
) ?\
< ?\
>) table
)
420 (modify-syntax-entry char
" " table
)))
421 "Table used internally to pair only curly brackets.
422 Other brackets are treated as spaces.")
424 (defun org-element--parse-paired-brackets (char)
425 "Parse paired brackets at point.
426 CHAR is the opening bracket to consider, as a character. Return
427 contents between brackets, as a string, or nil. Also move point
429 (when (eq char
(char-after))
430 (let ((syntax-table (pcase char
431 (?\
{ org-element--pair-curly-table
)
432 (?\
[ org-element--pair-square-table
)
433 (?\
( org-element--pair-round-table
)
437 (with-syntax-table syntax-table
438 (let ((end (ignore-errors (scan-lists pos
1 0))))
441 (buffer-substring-no-properties (1+ pos
) (1- end
)))))))))
444 ;;; Accessors and Setters
446 ;; Provide four accessors: `org-element-type', `org-element-property'
447 ;; `org-element-contents' and `org-element-restriction'.
449 ;; Setter functions allow modification of elements by side effect.
450 ;; There is `org-element-put-property', `org-element-set-contents'.
451 ;; These low-level functions are useful to build a parse tree.
453 ;; `org-element-adopt-element', `org-element-set-element',
454 ;; `org-element-extract-element' and `org-element-insert-before' are
455 ;; high-level functions useful to modify a parse tree.
457 ;; `org-element-secondary-p' is a predicate used to know if a given
458 ;; object belongs to a secondary string. `org-element-class' tells if
459 ;; some parsed data is an element or an object, handling pseudo
460 ;; elements and objects. `org-element-copy' returns an element or
461 ;; object, stripping its parent property in the process.
463 (defsubst org-element-type
(element)
464 "Return type of ELEMENT.
466 The function returns the type of the element or object provided.
467 It can also return the following special value:
468 `plain-text' for a string
469 `org-data' for a complete document
470 nil in any other case."
472 ((not (consp element
)) (and (stringp element
) 'plain-text
))
473 ((symbolp (car element
)) (car element
))))
475 (defsubst org-element-property
(property element
)
476 "Extract the value from the PROPERTY of an ELEMENT."
477 (if (stringp element
) (get-text-property 0 property element
)
478 (plist-get (nth 1 element
) property
)))
480 (defsubst org-element-contents
(element)
481 "Extract contents from an ELEMENT."
482 (cond ((not (consp element
)) nil
)
483 ((symbolp (car element
)) (nthcdr 2 element
))
486 (defsubst org-element-restriction
(element)
487 "Return restriction associated to ELEMENT.
488 ELEMENT can be an element, an object or a symbol representing an
489 element or object type."
490 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
491 org-element-object-restrictions
)))
493 (defsubst org-element-put-property
(element property value
)
494 "In ELEMENT set PROPERTY to VALUE.
495 Return modified element."
496 (if (stringp element
) (org-add-props element nil property value
)
497 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
500 (defsubst org-element-set-contents
(element &rest contents
)
501 "Set ELEMENT's contents to CONTENTS.
503 (cond ((null element
) contents
)
504 ((not (symbolp (car element
))) contents
)
505 ((cdr element
) (setcdr (cdr element
) contents
) element
)
506 (t (nconc element contents
))))
508 (defun org-element-secondary-p (object)
509 "Non-nil when OBJECT directly belongs to a secondary string.
510 Return value is the property name, as a keyword, or nil."
511 (let* ((parent (org-element-property :parent object
))
512 (properties (cdr (assq (org-element-type parent
)
513 org-element-secondary-value-alist
))))
515 (dolist (p properties
)
516 (and (memq object
(org-element-property p parent
))
519 (defun org-element-class (datum &optional parent
)
520 "Return class for ELEMENT, as a symbol.
521 Class is either `element' or `object'. Optional argument PARENT
522 is the element or object containing DATUM. It defaults to the
523 value of DATUM `:parent' property."
524 (let ((type (org-element-type datum
))
525 (parent (or parent
(org-element-property :parent datum
))))
528 ((memq type org-element-all-objects
) 'object
)
529 ((memq type org-element-all-elements
) 'element
)
531 ((eq type
'org-data
) 'element
)
532 ((eq type
'plain-text
) 'object
)
534 ;; Pseudo object or elements. Make a guess about its class.
535 ;; Basically a pseudo object is contained within another object,
536 ;; a secondary string or a container element.
537 ((not parent
) 'element
)
539 (let ((parent-type (org-element-type parent
)))
540 (cond ((not parent-type
) 'object
)
541 ((memq parent-type org-element-object-containers
) 'object
)
542 ((org-element-secondary-p datum
) 'object
)
545 (defsubst org-element-adopt-elements
(parent &rest children
)
546 "Append elements to the contents of another element.
548 PARENT is an element or object. CHILDREN can be elements,
549 objects, or a strings.
551 The function takes care of setting `:parent' property for CHILD.
552 Return parent element."
553 (if (not children
) parent
554 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
555 ;; string: parent is the list itself.
556 (dolist (child children
)
557 (org-element-put-property child
:parent
(or parent children
)))
558 ;; Add CHILDREN at the end of PARENT contents.
560 (apply #'org-element-set-contents
562 (nconc (org-element-contents parent
) children
)))
563 ;; Return modified PARENT element.
564 (or parent children
)))
566 (defun org-element-extract-element (element)
567 "Extract ELEMENT from parse tree.
568 Remove element from the parse tree by side-effect, and return it
569 with its `:parent' property stripped out."
570 (let ((parent (org-element-property :parent element
))
571 (secondary (org-element-secondary-p element
)))
573 (org-element-put-property
575 (delq element
(org-element-property secondary parent
)))
576 (apply #'org-element-set-contents
578 (delq element
(org-element-contents parent
))))
579 ;; Return ELEMENT with its :parent removed.
580 (org-element-put-property element
:parent nil
)))
582 (defun org-element-insert-before (element location
)
583 "Insert ELEMENT before LOCATION in parse tree.
584 LOCATION is an element, object or string within the parse tree.
585 Parse tree is modified by side effect."
586 (let* ((parent (org-element-property :parent location
))
587 (property (org-element-secondary-p location
))
588 (siblings (if property
(org-element-property property parent
)
589 (org-element-contents parent
)))
590 ;; Special case: LOCATION is the first element of an
591 ;; independent secondary string (e.g. :title property). Add
593 (specialp (and (not property
)
595 (eq (car parent
) location
))))
596 ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
598 ((or (null siblings
) (eq (car siblings
) location
))
599 (push element siblings
))
600 ((null location
) (nconc siblings
(list element
)))
602 (let ((index (cl-position location siblings
)))
603 (unless index
(error "No location found to insert element"))
604 (push element
(cdr (nthcdr (1- index
) siblings
))))))
605 ;; Store SIBLINGS at appropriate place in parse tree.
607 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
608 (property (org-element-put-property parent property siblings
))
609 (t (apply #'org-element-set-contents parent siblings
)))
610 ;; Set appropriate :parent property.
611 (org-element-put-property element
:parent parent
)))
613 (defun org-element-set-element (old new
)
614 "Replace element or object OLD with element or object NEW.
615 The function takes care of setting `:parent' property for NEW."
616 ;; Ensure OLD and NEW have the same parent.
617 (org-element-put-property new
:parent
(org-element-property :parent old
))
618 (if (or (memq (org-element-type old
) '(plain-text nil
))
619 (memq (org-element-type new
) '(plain-text nil
)))
620 ;; We cannot replace OLD with NEW since one of them is not an
621 ;; object or element. We take the long path.
622 (progn (org-element-insert-before new old
)
623 (org-element-extract-element old
))
624 ;; Since OLD is going to be changed into NEW by side-effect, first
625 ;; make sure that every element or object within NEW has OLD as
627 (dolist (blob (org-element-contents new
))
628 (org-element-put-property blob
:parent old
))
629 ;; Transfer contents.
630 (apply #'org-element-set-contents old
(org-element-contents new
))
631 ;; Overwrite OLD's properties with NEW's.
632 (setcar (cdr old
) (nth 1 new
))
634 (setcar old
(car new
))))
636 (defun org-element-create (type &optional props
&rest children
)
637 "Create a new element of type TYPE.
638 Optional argument PROPS, when non-nil, is a plist defining the
639 properties of the element. CHILDREN can be elements, objects or
641 (apply #'org-element-adopt-elements
(list type props
) children
))
643 (defun org-element-copy (datum)
644 "Return a copy of DATUM.
645 DATUM is an element, object, string or nil. `:parent' property
646 is cleared and contents are removed in the process."
648 (let ((type (org-element-type datum
)))
650 (`org-data
(list 'org-data nil
))
651 (`plain-text
(substring-no-properties datum
))
652 (`nil
(copy-sequence datum
))
654 (list type
(plist-put (copy-sequence (nth 1 datum
)) :parent nil
)))))))
660 ;; For each greater element type, we define a parser and an
663 ;; A parser returns the element or object as the list described above.
664 ;; Most of them accepts no argument. Though, exceptions exist. Hence
665 ;; every element containing a secondary string (see
666 ;; `org-element-secondary-value-alist') will accept an optional
667 ;; argument to toggle parsing of these secondary strings. Moreover,
668 ;; `item' parser requires current list's structure as its first
671 ;; An interpreter accepts two arguments: the list representation of
672 ;; the element or object, and its contents. The latter may be nil,
673 ;; depending on the element or object considered. It returns the
674 ;; appropriate Org syntax, as a string.
676 ;; Parsing functions must follow the naming convention:
677 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
678 ;; defined in `org-element-greater-elements'.
680 ;; Similarly, interpreting functions must follow the naming
681 ;; convention: org-element-TYPE-interpreter.
683 ;; With the exception of `headline' and `item' types, greater elements
684 ;; cannot contain other greater elements of their own type.
686 ;; Beside implementing a parser and an interpreter, adding a new
687 ;; greater element requires tweaking `org-element--current-element'.
688 ;; Moreover, the newly defined type must be added to both
689 ;; `org-element-all-elements' and `org-element-greater-elements'.
694 (defun org-element-center-block-parser (limit affiliated
)
695 "Parse a center block.
697 LIMIT bounds the search. AFFILIATED is a list of which CAR is
698 the buffer position at the beginning of the first affiliated
699 keyword and CDR is a plist of affiliated keywords along with
702 Return a list whose CAR is `center-block' and CDR is a plist
703 containing `:begin', `:end', `:contents-begin', `:contents-end',
704 `:post-blank' and `:post-affiliated' keywords.
706 Assume point is at the beginning of the block."
707 (let ((case-fold-search t
))
708 (if (not (save-excursion
709 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
710 ;; Incomplete block: parse it as a paragraph.
711 (org-element-paragraph-parser limit affiliated
)
712 (let ((block-end-line (match-beginning 0)))
713 (let* ((begin (car affiliated
))
714 (post-affiliated (point))
715 ;; Empty blocks have no contents.
716 (contents-begin (progn (forward-line)
717 (and (< (point) block-end-line
)
719 (contents-end (and contents-begin block-end-line
))
720 (pos-before-blank (progn (goto-char block-end-line
)
724 (skip-chars-forward " \r\t\n" limit
)
725 (if (eobp) (point) (line-beginning-position)))))
730 :contents-begin contents-begin
731 :contents-end contents-end
732 :post-blank
(count-lines pos-before-blank end
)
733 :post-affiliated post-affiliated
)
734 (cdr affiliated
))))))))
736 (defun org-element-center-block-interpreter (_ contents
)
737 "Interpret a center-block element as Org syntax.
738 CONTENTS is the contents of the element."
739 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
744 (defun org-element-drawer-parser (limit affiliated
)
747 LIMIT bounds the search. AFFILIATED is a list of which CAR is
748 the buffer position at the beginning of the first affiliated
749 keyword and CDR is a plist of affiliated keywords along with
752 Return a list whose CAR is `drawer' and CDR is a plist containing
753 `:drawer-name', `:begin', `:end', `:contents-begin',
754 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
756 Assume point is at beginning of drawer."
757 (let ((case-fold-search t
))
758 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
759 ;; Incomplete drawer: parse it as a paragraph.
760 (org-element-paragraph-parser limit affiliated
)
762 (let* ((drawer-end-line (match-beginning 0))
763 (name (progn (looking-at org-drawer-regexp
)
764 (match-string-no-properties 1)))
765 (begin (car affiliated
))
766 (post-affiliated (point))
767 ;; Empty drawers have no contents.
768 (contents-begin (progn (forward-line)
769 (and (< (point) drawer-end-line
)
771 (contents-end (and contents-begin drawer-end-line
))
772 (pos-before-blank (progn (goto-char drawer-end-line
)
775 (end (progn (skip-chars-forward " \r\t\n" limit
)
776 (if (eobp) (point) (line-beginning-position)))))
782 :contents-begin contents-begin
783 :contents-end contents-end
784 :post-blank
(count-lines pos-before-blank end
)
785 :post-affiliated post-affiliated
)
786 (cdr affiliated
))))))))
788 (defun org-element-drawer-interpreter (drawer contents
)
789 "Interpret DRAWER element as Org syntax.
790 CONTENTS is the contents of the element."
791 (format ":%s:\n%s:END:"
792 (org-element-property :drawer-name drawer
)
798 (defun org-element-dynamic-block-parser (limit affiliated
)
799 "Parse a dynamic block.
801 LIMIT bounds the search. AFFILIATED is a list of which CAR is
802 the buffer position at the beginning of the first affiliated
803 keyword and CDR is a plist of affiliated keywords along with
806 Return a list whose CAR is `dynamic-block' and CDR is a plist
807 containing `:block-name', `:begin', `:end', `:contents-begin',
808 `:contents-end', `:arguments', `:post-blank' and
809 `:post-affiliated' keywords.
811 Assume point is at beginning of dynamic block."
812 (let ((case-fold-search t
))
813 (if (not (save-excursion
814 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
815 ;; Incomplete block: parse it as a paragraph.
816 (org-element-paragraph-parser limit affiliated
)
817 (let ((block-end-line (match-beginning 0)))
819 (let* ((name (progn (looking-at org-dblock-start-re
)
820 (match-string-no-properties 1)))
821 (arguments (match-string-no-properties 3))
822 (begin (car affiliated
))
823 (post-affiliated (point))
824 ;; Empty blocks have no contents.
825 (contents-begin (progn (forward-line)
826 (and (< (point) block-end-line
)
828 (contents-end (and contents-begin block-end-line
))
829 (pos-before-blank (progn (goto-char block-end-line
)
832 (end (progn (skip-chars-forward " \r\t\n" limit
)
833 (if (eobp) (point) (line-beginning-position)))))
840 :contents-begin contents-begin
841 :contents-end contents-end
842 :post-blank
(count-lines pos-before-blank end
)
843 :post-affiliated post-affiliated
)
844 (cdr affiliated
)))))))))
846 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
847 "Interpret DYNAMIC-BLOCK element as Org syntax.
848 CONTENTS is the contents of the element."
849 (format "#+BEGIN: %s%s\n%s#+END:"
850 (org-element-property :block-name dynamic-block
)
851 (let ((args (org-element-property :arguments dynamic-block
)))
852 (and args
(concat " " args
)))
856 ;;;; Footnote Definition
858 (defconst org-element--footnote-separator
859 (concat org-outline-regexp-bol
"\\|"
860 org-footnote-definition-re
"\\|"
861 "^\\([ \t]*\n\\)\\{2,\\}")
862 "Regexp used as a footnote definition separator.")
864 (defun org-element-footnote-definition-parser (limit affiliated
)
865 "Parse a footnote definition.
867 LIMIT bounds the search. AFFILIATED is a list of which CAR is
868 the buffer position at the beginning of the first affiliated
869 keyword and CDR is a plist of affiliated keywords along with
872 Return a list whose CAR is `footnote-definition' and CDR is
873 a plist containing `:label', `:begin' `:end', `:contents-begin',
874 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
876 Assume point is at the beginning of the footnote definition."
878 (let* ((label (progn (looking-at org-footnote-definition-re
)
879 (match-string-no-properties 1)))
880 (begin (car affiliated
))
881 (post-affiliated (point))
887 (re-search-forward org-element--footnote-separator limit t
))
889 ((eq (char-after (match-beginning 0)) ?\
[)
890 ;; At a new footnote definition, make sure we end
891 ;; before any affiliated keyword above.
893 (while (and (> (point) post-affiliated
)
894 (looking-at-p org-element--affiliated-re
))
896 (line-beginning-position 2))
897 (t (match-beginning 0)))))
901 (skip-chars-forward " \r\t\n" ending
)
902 (cond ((= (point) ending
) nil
)
903 ((= (line-beginning-position) post-affiliated
) (point))
904 (t (line-beginning-position)))))
905 (contents-end (and contents-begin ending
))
906 (end (progn (goto-char ending
)
907 (skip-chars-forward " \r\t\n" limit
)
908 (if (eobp) (point) (line-beginning-position)))))
909 (list 'footnote-definition
914 :contents-begin contents-begin
915 :contents-end contents-end
916 :post-blank
(count-lines ending end
)
917 :post-affiliated post-affiliated
)
918 (cdr affiliated
))))))
920 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
921 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
922 CONTENTS is the contents of the footnote-definition."
923 (concat (format "[fn:%s]" (org-element-property :label footnote-definition
))
930 (defun org-element--get-node-properties ()
931 "Return node properties associated to headline at point.
932 Upcase property names. It avoids confusion between properties
933 obtained through property drawer and default properties from the
934 parser (e.g. `:end' and :END:). Return value is a plist."
937 (when (looking-at-p org-planning-line-re
) (forward-line))
938 (when (looking-at org-property-drawer-re
)
940 (let ((end (match-end 0)) properties
)
941 (while (< (line-end-position) end
)
942 (looking-at org-property-re
)
943 (push (match-string-no-properties 3) properties
)
944 (push (intern (concat ":" (upcase (match-string 2)))) properties
)
948 (defun org-element--get-time-properties ()
949 "Return time properties associated to headline at point.
950 Return value is a plist."
952 (when (progn (forward-line) (looking-at org-planning-line-re
))
953 (let ((end (line-end-position)) plist
)
954 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
955 (goto-char (match-end 1))
956 (skip-chars-forward " \t")
957 (let ((keyword (match-string 1))
958 (time (org-element-timestamp-parser)))
959 (cond ((equal keyword org-scheduled-string
)
960 (setq plist
(plist-put plist
:scheduled time
)))
961 ((equal keyword org-deadline-string
)
962 (setq plist
(plist-put plist
:deadline time
)))
963 (t (setq plist
(plist-put plist
:closed time
))))))
966 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
969 Return a list whose CAR is `headline' and CDR is a plist
970 containing `:raw-value', `:title', `:begin', `:end',
971 `:pre-blank', `:contents-begin' and `:contents-end', `:level',
972 `:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
973 `:deadline', `:closed', `:archivedp', `:commentedp'
974 `:footnote-section-p', `:post-blank' and `:post-affiliated'
977 The plist also contains any property set in the property drawer,
978 with its name in upper cases and colons added at the
979 beginning (e.g., `:CUSTOM_ID').
981 LIMIT is a buffer position bounding the search.
983 When RAW-SECONDARY-P is non-nil, headline's title will not be
984 parsed as a secondary string, but as a plain string instead.
986 Assume point is at beginning of the headline."
988 (let* ((begin (point))
989 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
990 (skip-chars-forward " \t")))
991 (todo (and org-todo-regexp
992 (let (case-fold-search) (looking-at org-todo-regexp
))
993 (progn (goto-char (match-end 0))
994 (skip-chars-forward " \t")
997 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
998 (priority (and (looking-at "\\[#.\\][ \t]*")
999 (progn (goto-char (match-end 0))
1000 (aref (match-string 0) 2))))
1002 (and (let (case-fold-search) (looking-at org-comment-string
))
1003 (goto-char (match-end 0))))
1004 (title-start (point))
1005 (tags (when (re-search-forward
1006 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
1009 (goto-char (match-beginning 0))
1010 (org-split-string (match-string 1) ":")))
1012 (raw-value (org-trim
1013 (buffer-substring-no-properties title-start title-end
)))
1014 (archivedp (member org-archive-tag tags
))
1015 (footnote-section-p (and org-footnote-section
1016 (string= org-footnote-section raw-value
)))
1017 (standard-props (org-element--get-node-properties))
1018 (time-props (org-element--get-time-properties))
1019 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
1020 (contents-begin (save-excursion
1022 (skip-chars-forward " \r\t\n" end
)
1023 (and (/= (point) end
) (line-beginning-position))))
1024 (contents-end (and contents-begin
1025 (progn (goto-char end
)
1026 (skip-chars-backward " \r\t\n")
1027 (line-beginning-position 2)))))
1031 (list :raw-value raw-value
1035 (if (not contents-begin
) 0
1036 (1- (count-lines begin contents-begin
)))
1037 :contents-begin contents-begin
1038 :contents-end contents-end
1043 :todo-type todo-type
1046 (count-lines contents-end end
)
1047 (1- (count-lines begin end
)))
1048 :footnote-section-p footnote-section-p
1049 :archivedp archivedp
1050 :commentedp commentedp
1051 :post-affiliated begin
)
1054 (org-element-put-property
1056 (if raw-secondary-p raw-value
1057 (org-element--parse-objects
1058 (progn (goto-char title-start
)
1059 (skip-chars-forward " \t")
1061 (progn (goto-char title-end
)
1062 (skip-chars-backward " \t")
1065 (org-element-restriction 'headline
)
1068 (defun org-element-headline-interpreter (headline contents
)
1069 "Interpret HEADLINE element as Org syntax.
1070 CONTENTS is the contents of the element."
1071 (let* ((level (org-element-property :level headline
))
1072 (todo (org-element-property :todo-keyword headline
))
1073 (priority (org-element-property :priority headline
))
1074 (title (org-element-interpret-data
1075 (org-element-property :title headline
)))
1076 (tags (let ((tag-list (org-element-property :tags headline
)))
1078 (format ":%s:" (mapconcat #'identity tag-list
":")))))
1079 (commentedp (org-element-property :commentedp headline
))
1080 (pre-blank (or (org-element-property :pre-blank headline
) 0))
1082 (concat (make-string (if org-odd-levels-only
(1- (* level
2)) level
)
1084 (and todo
(concat " " todo
))
1085 (and commentedp
(concat " " org-comment-string
))
1086 (and priority
(format " [#%c]" priority
))
1088 (if (and org-footnote-section
1089 (org-element-property :footnote-section-p headline
))
1090 org-footnote-section
1097 ((zerop org-tags-column
) (format " %s" tags
))
1098 ((< org-tags-column
0)
1101 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
1106 (make-string (max (- org-tags-column
(length heading
)) 1) ?\s
)
1108 (make-string (1+ pre-blank
) ?
\n)
1114 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
1115 "Parse an inline task.
1117 Return a list whose CAR is `inlinetask' and CDR is a plist
1118 containing `:title', `:begin', `:end', `:pre-blank',
1119 `:contents-begin' and `:contents-end', `:level', `:priority',
1120 `:raw-value', `:tags', `:todo-keyword', `:todo-type',
1121 `:scheduled', `:deadline', `:closed', `:post-blank' and
1122 `:post-affiliated' keywords.
1124 The plist also contains any property set in the property drawer,
1125 with its name in upper cases and colons added at the
1126 beginning (e.g., `:CUSTOM_ID').
1128 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
1129 title will not be parsed as a secondary string, but as a plain
1132 Assume point is at beginning of the inline task."
1134 (let* ((begin (point))
1135 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1136 (skip-chars-forward " \t")))
1137 (todo (and org-todo-regexp
1138 (let (case-fold-search) (looking-at org-todo-regexp
))
1139 (progn (goto-char (match-end 0))
1140 (skip-chars-forward " \t")
1142 (todo-type (and todo
1143 (if (member todo org-done-keywords
) 'done
'todo
)))
1144 (priority (and (looking-at "\\[#.\\][ \t]*")
1145 (progn (goto-char (match-end 0))
1146 (aref (match-string 0) 2))))
1147 (title-start (point))
1148 (tags (when (re-search-forward
1149 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
1152 (goto-char (match-beginning 0))
1153 (org-split-string (match-string 1) ":")))
1155 (raw-value (org-trim
1156 (buffer-substring-no-properties title-start title-end
)))
1157 (task-end (save-excursion
1159 (and (re-search-forward org-outline-regexp-bol limit t
)
1160 (looking-at-p "[ \t]*END[ \t]*$")
1161 (line-beginning-position))))
1162 (standard-props (and task-end
(org-element--get-node-properties)))
1163 (time-props (and task-end
(org-element--get-time-properties)))
1164 (contents-begin (and task-end
1165 (< (point) task-end
)
1168 (skip-chars-forward " \t\n")
1169 (line-beginning-position))))
1170 (contents-end (and contents-begin task-end
))
1171 (end (progn (when task-end
(goto-char task-end
))
1173 (skip-chars-forward " \r\t\n" limit
)
1174 (if (eobp) (point) (line-beginning-position))))
1178 (list :raw-value raw-value
1182 (if (not contents-begin
) 0
1183 (1- (count-lines begin contents-begin
)))
1184 :contents-begin contents-begin
1185 :contents-end contents-end
1190 :todo-type todo-type
1191 :post-blank
(1- (count-lines (or task-end begin
) end
))
1192 :post-affiliated begin
)
1195 (org-element-put-property
1197 (if raw-secondary-p raw-value
1198 (org-element--parse-objects
1199 (progn (goto-char title-start
)
1200 (skip-chars-forward " \t")
1202 (progn (goto-char title-end
)
1203 (skip-chars-backward " \t")
1206 (org-element-restriction 'inlinetask
)
1209 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1210 "Interpret INLINETASK element as Org syntax.
1211 CONTENTS is the contents of inlinetask."
1212 (let* ((level (org-element-property :level inlinetask
))
1213 (todo (org-element-property :todo-keyword inlinetask
))
1214 (priority (org-element-property :priority inlinetask
))
1215 (title (org-element-interpret-data
1216 (org-element-property :title inlinetask
)))
1217 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1219 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1220 (task (concat (make-string level ?
*)
1221 (and todo
(concat " " todo
))
1222 (and priority
(format " [#%c]" priority
))
1223 (and title
(concat " " title
)))))
1228 ((zerop org-tags-column
) (format " %s" tags
))
1229 ((< org-tags-column
0)
1232 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1237 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1239 ;; Prefer degenerate inlinetasks when there are no
1244 (make-string level ?
*) " END")))))
1249 (defun org-element-item-parser (_ struct
&optional raw-secondary-p
)
1252 STRUCT is the structure of the plain list.
1254 Return a list whose CAR is `item' and CDR is a plist containing
1255 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1256 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1257 `:post-affiliated' keywords.
1259 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1260 any, will not be parsed as a secondary string, but as a plain
1263 Assume point is at the beginning of the item."
1266 (looking-at org-list-full-item-re
)
1267 (let* ((begin (point))
1268 (bullet (match-string-no-properties 1))
1269 (checkbox (let ((box (match-string 3)))
1270 (cond ((equal "[ ]" box
) 'off
)
1271 ((equal "[X]" box
) 'on
)
1272 ((equal "[-]" box
) 'trans
))))
1273 (counter (let ((c (match-string 2)))
1277 ((string-match "[A-Za-z]" c
)
1278 (- (string-to-char (upcase (match-string 0 c
)))
1280 ((string-match "[0-9]+" c
)
1281 (string-to-number (match-string 0 c
)))))))
1282 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1283 (if (bolp) (point) (line-beginning-position 2))))
1286 ;; Ignore tags in un-ordered lists: they are just
1287 ;; a part of item's body.
1288 (if (and (match-beginning 4)
1289 (save-match-data (string-match "[.)]" bullet
)))
1292 (skip-chars-forward " \r\t\n" end
)
1293 (cond ((= (point) end
) nil
)
1294 ;; If first line isn't empty, contents really
1295 ;; start at the text after item's meta-data.
1296 ((= (line-beginning-position) begin
) (point))
1297 (t (line-beginning-position)))))
1298 (contents-end (and contents-begin
1299 (progn (goto-char end
)
1300 (skip-chars-backward " \r\t\n")
1301 (line-beginning-position 2))))
1304 (list :bullet bullet
1307 :contents-begin contents-begin
1308 :contents-end contents-end
1312 :post-blank
(count-lines (or contents-end begin
) end
)
1313 :post-affiliated begin
))))
1314 (org-element-put-property
1316 (let ((raw (org-list-get-tag begin struct
)))
1318 (if raw-secondary-p raw
1319 (org-element--parse-objects
1320 (match-beginning 4) (match-end 4) nil
1321 (org-element-restriction 'item
)
1324 (defun org-element-item-interpreter (item contents
)
1325 "Interpret ITEM element as Org syntax.
1326 CONTENTS is the contents of the element."
1327 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1328 (org-list-bullet-string
1329 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1330 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1332 (checkbox (org-element-property :checkbox item
))
1333 (counter (org-element-property :counter item
))
1334 (tag (let ((tag (org-element-property :tag item
)))
1335 (and tag
(org-element-interpret-data tag
))))
1336 ;; Compute indentation.
1337 (ind (make-string (length bullet
) 32))
1338 (item-starts-with-par-p
1339 (eq (org-element-type (car (org-element-contents item
)))
1344 (and counter
(format "[@%d] " counter
))
1350 (and tag
(format "%s :: " tag
))
1352 (let ((contents (replace-regexp-in-string
1353 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1354 (if item-starts-with-par-p
(org-trim contents
)
1355 (concat "\n" contents
)))))))
1360 (defun org-element--list-struct (limit)
1361 ;; Return structure of list at point. Internal function. See
1362 ;; `org-list-struct' for details.
1363 (let ((case-fold-search t
)
1365 (item-re (org-item-re))
1366 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1372 ;; At limit: end all items.
1375 (let ((end (progn (skip-chars-backward " \r\t\n")
1378 (dolist (item items
(sort (nconc items struct
)
1379 'car-less-than-car
))
1380 (setcar (nthcdr 6 item
) end
)))))
1381 ;; At list end: end all items.
1382 ((looking-at org-list-end-re
)
1383 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1384 'car-less-than-car
))
1385 (setcar (nthcdr 6 item
) (point)))))
1386 ;; At a new item: end previous sibling.
1387 ((looking-at item-re
)
1388 (let ((ind (save-excursion (skip-chars-forward " \t")
1390 (setq top-ind
(min top-ind ind
))
1391 (while (and items
(<= ind
(nth 1 (car items
))))
1392 (let ((item (pop items
)))
1393 (setcar (nthcdr 6 item
) (point))
1394 (push item struct
)))
1395 (push (progn (looking-at org-list-full-item-re
)
1396 (let ((bullet (match-string-no-properties 1)))
1400 (match-string-no-properties 2) ; counter
1401 (match-string-no-properties 3) ; checkbox
1403 (and (save-match-data
1404 (string-match "[-+*]" bullet
))
1405 (match-string-no-properties 4))
1406 ;; Ending position, unknown so far.
1410 ;; Skip empty lines.
1411 ((looking-at "^[ \t]*$") (forward-line))
1412 ;; Skip inline tasks and blank lines along the way.
1413 ((and inlinetask-re
(looking-at inlinetask-re
))
1415 (let ((origin (point)))
1416 (when (re-search-forward inlinetask-re limit t
)
1417 (if (looking-at-p "END[ \t]*$") (forward-line)
1418 (goto-char origin
)))))
1419 ;; At some text line. Check if it ends any previous item.
1421 (let ((ind (save-excursion (skip-chars-forward " \t")
1423 (when (<= ind top-ind
)
1424 (skip-chars-backward " \r\t\n")
1426 (while (<= ind
(nth 1 (car items
)))
1427 (let ((item (pop items
)))
1428 (setcar (nthcdr 6 item
) (line-beginning-position))
1431 (throw 'exit
(sort struct
#'car-less-than-car
))))))
1432 ;; Skip blocks (any type) and drawers contents.
1434 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1436 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1438 ((and (looking-at org-drawer-regexp
)
1439 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1440 (forward-line))))))))
1442 (defun org-element-plain-list-parser (limit affiliated structure
)
1443 "Parse a plain list.
1445 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1446 the buffer position at the beginning of the first affiliated
1447 keyword and CDR is a plist of affiliated keywords along with
1448 their value. STRUCTURE is the structure of the plain list being
1451 Return a list whose CAR is `plain-list' and CDR is a plist
1452 containing `:type', `:begin', `:end', `:contents-begin' and
1453 `:contents-end', `:structure', `:post-blank' and
1454 `:post-affiliated' keywords.
1456 Assume point is at the beginning of the list."
1458 (let* ((struct (or structure
(org-element--list-struct limit
)))
1459 (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1460 ((nth 5 (assq (point) struct
)) 'descriptive
)
1462 (contents-begin (point))
1463 (begin (car affiliated
))
1464 (contents-end (let* ((item (assq contents-begin struct
))
1467 (while (and (setq item
(assq pos struct
))
1468 (= (nth 1 item
) ind
))
1469 (setq pos
(nth 6 item
)))
1471 (end (progn (goto-char contents-end
)
1472 (skip-chars-forward " \r\t\n" limit
)
1473 (if (= (point) limit
) limit
(line-beginning-position)))))
1480 :contents-begin contents-begin
1481 :contents-end contents-end
1483 :post-blank
(count-lines contents-end end
)
1484 :post-affiliated contents-begin
)
1485 (cdr affiliated
))))))
1487 (defun org-element-plain-list-interpreter (_ contents
)
1488 "Interpret plain-list element as Org syntax.
1489 CONTENTS is the contents of the element."
1492 (goto-char (point-min))
1497 ;;;; Property Drawer
1499 (defun org-element-property-drawer-parser (limit)
1500 "Parse a property drawer.
1502 LIMIT bounds the search.
1504 Return a list whose car is `property-drawer' and cdr is a plist
1505 containing `:begin', `:end', `:contents-begin', `:contents-end',
1506 `:post-blank' and `:post-affiliated' keywords.
1508 Assume point is at the beginning of the property drawer."
1510 (let ((case-fold-search t
)
1512 (contents-begin (line-beginning-position 2)))
1513 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)
1514 (let ((contents-end (and (> (match-beginning 0) contents-begin
)
1515 (match-beginning 0)))
1516 (before-blank (progn (forward-line) (point)))
1517 (end (progn (skip-chars-forward " \r\t\n" limit
)
1518 (if (eobp) (point) (line-beginning-position)))))
1519 (list 'property-drawer
1522 :contents-begin
(and contents-end contents-begin
)
1523 :contents-end contents-end
1524 :post-blank
(count-lines before-blank end
)
1525 :post-affiliated begin
))))))
1527 (defun org-element-property-drawer-interpreter (_ contents
)
1528 "Interpret property-drawer element as Org syntax.
1529 CONTENTS is the properties within the drawer."
1530 (format ":PROPERTIES:\n%s:END:" contents
))
1535 (defun org-element-quote-block-parser (limit affiliated
)
1536 "Parse a quote block.
1538 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1539 the buffer position at the beginning of the first affiliated
1540 keyword and CDR is a plist of affiliated keywords along with
1543 Return a list whose CAR is `quote-block' and CDR is a plist
1544 containing `:begin', `:end', `:contents-begin', `:contents-end',
1545 `:post-blank' and `:post-affiliated' keywords.
1547 Assume point is at the beginning of the block."
1548 (let ((case-fold-search t
))
1549 (if (not (save-excursion
1550 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1551 ;; Incomplete block: parse it as a paragraph.
1552 (org-element-paragraph-parser limit affiliated
)
1553 (let ((block-end-line (match-beginning 0)))
1555 (let* ((begin (car affiliated
))
1556 (post-affiliated (point))
1557 ;; Empty blocks have no contents.
1558 (contents-begin (progn (forward-line)
1559 (and (< (point) block-end-line
)
1561 (contents-end (and contents-begin block-end-line
))
1562 (pos-before-blank (progn (goto-char block-end-line
)
1565 (end (progn (skip-chars-forward " \r\t\n" limit
)
1566 (if (eobp) (point) (line-beginning-position)))))
1571 :contents-begin contents-begin
1572 :contents-end contents-end
1573 :post-blank
(count-lines pos-before-blank end
)
1574 :post-affiliated post-affiliated
)
1575 (cdr affiliated
)))))))))
1577 (defun org-element-quote-block-interpreter (_ contents
)
1578 "Interpret quote-block element as Org syntax.
1579 CONTENTS is the contents of the element."
1580 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1585 (defun org-element-section-parser (_)
1588 Return a list whose CAR is `section' and CDR is a plist
1589 containing `:begin', `:end', `:contents-begin', `contents-end',
1590 `:post-blank' and `:post-affiliated' keywords."
1592 ;; Beginning of section is the beginning of the first non-blank
1593 ;; line after previous headline.
1594 (let ((begin (point))
1595 (end (progn (org-with-limited-levels (outline-next-heading))
1597 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1598 (line-beginning-position 2))))
1602 :contents-begin begin
1603 :contents-end pos-before-blank
1604 :post-blank
(count-lines pos-before-blank end
)
1605 :post-affiliated begin
)))))
1607 (defun org-element-section-interpreter (_ contents
)
1608 "Interpret section element as Org syntax.
1609 CONTENTS is the contents of the element."
1615 (defun org-element-special-block-parser (limit affiliated
)
1616 "Parse a special block.
1618 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1619 the buffer position at the beginning of the first affiliated
1620 keyword and CDR is a plist of affiliated keywords along with
1623 Return a list whose CAR is `special-block' and CDR is a plist
1624 containing `:type', `:begin', `:end', `:contents-begin',
1625 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1627 Assume point is at the beginning of the block."
1628 (let* ((case-fold-search t
)
1629 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1630 (match-string-no-properties 1))))
1631 (if (not (save-excursion
1633 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1635 ;; Incomplete block: parse it as a paragraph.
1636 (org-element-paragraph-parser limit affiliated
)
1637 (let ((block-end-line (match-beginning 0)))
1639 (let* ((begin (car affiliated
))
1640 (post-affiliated (point))
1641 ;; Empty blocks have no contents.
1642 (contents-begin (progn (forward-line)
1643 (and (< (point) block-end-line
)
1645 (contents-end (and contents-begin block-end-line
))
1646 (pos-before-blank (progn (goto-char block-end-line
)
1649 (end (progn (skip-chars-forward " \r\t\n" limit
)
1650 (if (eobp) (point) (line-beginning-position)))))
1651 (list 'special-block
1656 :contents-begin contents-begin
1657 :contents-end contents-end
1658 :post-blank
(count-lines pos-before-blank end
)
1659 :post-affiliated post-affiliated
)
1660 (cdr affiliated
)))))))))
1662 (defun org-element-special-block-interpreter (special-block contents
)
1663 "Interpret SPECIAL-BLOCK element as Org syntax.
1664 CONTENTS is the contents of the element."
1665 (let ((block-type (org-element-property :type special-block
)))
1666 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1672 ;; For each element, a parser and an interpreter are also defined.
1673 ;; Both follow the same naming convention used for greater elements.
1675 ;; Also, as for greater elements, adding a new element type is done
1676 ;; through the following steps: implement a parser and an interpreter,
1677 ;; tweak `org-element--current-element' so that it recognizes the new
1678 ;; type and add that new type to `org-element-all-elements'.
1683 (defun org-element-babel-call-parser (limit affiliated
)
1684 "Parse a babel call.
1686 LIMIT bounds the search. AFFILIATED is a list of which car is
1687 the buffer position at the beginning of the first affiliated
1688 keyword and cdr is a plist of affiliated keywords along with
1691 Return a list whose car is `babel-call' and cdr is a plist
1692 containing `:call', `:inside-header', `:arguments',
1693 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1694 `:post-affiliated' as keywords."
1696 (let* ((begin (car affiliated
))
1697 (post-affiliated (point))
1698 (value (progn (search-forward ":" nil t
)
1700 (buffer-substring-no-properties
1701 (point) (line-end-position)))))
1702 (pos-before-blank (progn (forward-line) (point)))
1703 (end (progn (skip-chars-forward " \r\t\n" limit
)
1704 (if (eobp) (point) (line-beginning-position))))
1707 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*\\))[ \t]*\\(.*\\)"
1711 (list :call
(and valid-value
(match-string 1 value
))
1712 :inside-header
(and valid-value
1713 (org-string-nw-p (match-string 2 value
)))
1714 :arguments
(and valid-value
1715 (org-string-nw-p (match-string 3 value
)))
1716 :end-header
(and valid-value
1717 (org-string-nw-p (match-string 4 value
)))
1721 :post-blank
(count-lines pos-before-blank end
)
1722 :post-affiliated post-affiliated
)
1723 (cdr affiliated
))))))
1725 (defun org-element-babel-call-interpreter (babel-call _
)
1726 "Interpret BABEL-CALL element as Org syntax."
1728 (org-element-property :call babel-call
)
1729 (let ((h (org-element-property :inside-header babel-call
)))
1730 (and h
(format "[%s]" h
)))
1731 (concat "(" (org-element-property :arguments babel-call
) ")")
1732 (let ((h (org-element-property :end-header babel-call
)))
1733 (and h
(concat " " h
)))))
1738 (defun org-element-clock-parser (limit)
1741 LIMIT bounds the search.
1743 Return a list whose CAR is `clock' and CDR is a plist containing
1744 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1745 `:post-affiliated' as keywords."
1747 (let* ((case-fold-search nil
)
1749 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1750 (skip-chars-forward " \t")
1751 (org-element-timestamp-parser)))
1752 (duration (and (search-forward " => " (line-end-position) t
)
1753 (progn (skip-chars-forward " \t")
1754 (looking-at "\\(\\S-+\\)[ \t]*$"))
1755 (match-string-no-properties 1)))
1756 (status (if duration
'closed
'running
))
1757 (post-blank (let ((before-blank (progn (forward-line) (point))))
1758 (skip-chars-forward " \r\t\n" limit
)
1759 (skip-chars-backward " \t")
1760 (unless (bolp) (end-of-line))
1761 (count-lines before-blank
(point))))
1764 (list :status status
1769 :post-blank post-blank
1770 :post-affiliated begin
)))))
1772 (defun org-element-clock-interpreter (clock _
)
1773 "Interpret CLOCK element as Org syntax."
1774 (concat org-clock-string
" "
1775 (org-element-timestamp-interpreter
1776 (org-element-property :value clock
) nil
)
1777 (let ((duration (org-element-property :duration clock
)))
1782 (org-split-string duration
":")))))))
1787 (defun org-element-comment-parser (limit affiliated
)
1790 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1791 the buffer position at the beginning of the first affiliated
1792 keyword and CDR is a plist of affiliated keywords along with
1795 Return a list whose CAR is `comment' and CDR is a plist
1796 containing `:begin', `:end', `:value', `:post-blank',
1797 `:post-affiliated' keywords.
1799 Assume point is at comment beginning."
1801 (let* ((begin (car affiliated
))
1802 (post-affiliated (point))
1803 (value (prog2 (looking-at "[ \t]*# ?")
1804 (buffer-substring-no-properties
1805 (match-end 0) (line-end-position))
1808 ;; Get comments ending.
1810 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1811 ;; Accumulate lines without leading hash and first
1816 (buffer-substring-no-properties
1817 (match-end 0) (line-end-position))))
1820 (end (progn (goto-char com-end
)
1821 (skip-chars-forward " \r\t\n" limit
)
1822 (if (eobp) (point) (line-beginning-position)))))
1828 :post-blank
(count-lines com-end end
)
1829 :post-affiliated post-affiliated
)
1830 (cdr affiliated
))))))
1832 (defun org-element-comment-interpreter (comment _
)
1833 "Interpret COMMENT element as Org syntax.
1835 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1840 (defun org-element-comment-block-parser (limit affiliated
)
1841 "Parse an export block.
1843 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1844 the buffer position at the beginning of the first affiliated
1845 keyword and CDR is a plist of affiliated keywords along with
1848 Return a list whose CAR is `comment-block' and CDR is a plist
1849 containing `:begin', `:end', `:value', `:post-blank' and
1850 `:post-affiliated' keywords.
1852 Assume point is at comment block beginning."
1853 (let ((case-fold-search t
))
1854 (if (not (save-excursion
1855 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1856 ;; Incomplete block: parse it as a paragraph.
1857 (org-element-paragraph-parser limit affiliated
)
1858 (let ((contents-end (match-beginning 0)))
1860 (let* ((begin (car affiliated
))
1861 (post-affiliated (point))
1862 (contents-begin (progn (forward-line) (point)))
1863 (pos-before-blank (progn (goto-char contents-end
)
1866 (end (progn (skip-chars-forward " \r\t\n" limit
)
1867 (if (eobp) (point) (line-beginning-position))))
1868 (value (buffer-substring-no-properties
1869 contents-begin contents-end
)))
1870 (list 'comment-block
1875 :post-blank
(count-lines pos-before-blank end
)
1876 :post-affiliated post-affiliated
)
1877 (cdr affiliated
)))))))))
1879 (defun org-element-comment-block-interpreter (comment-block _
)
1880 "Interpret COMMENT-BLOCK element as Org syntax."
1881 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1882 (org-element-normalize-string
1883 (org-remove-indentation
1884 (org-element-property :value comment-block
)))))
1889 (defun org-element-diary-sexp-parser (limit affiliated
)
1890 "Parse a diary sexp.
1892 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1893 the buffer position at the beginning of the first affiliated
1894 keyword and CDR is a plist of affiliated keywords along with
1897 Return a list whose CAR is `diary-sexp' and CDR is a plist
1898 containing `:begin', `:end', `:value', `:post-blank' and
1899 `:post-affiliated' keywords."
1901 (let ((begin (car affiliated
))
1902 (post-affiliated (point))
1903 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1904 (match-string-no-properties 1)))
1905 (pos-before-blank (progn (forward-line) (point)))
1906 (end (progn (skip-chars-forward " \r\t\n" limit
)
1907 (if (eobp) (point) (line-beginning-position)))))
1913 :post-blank
(count-lines pos-before-blank end
)
1914 :post-affiliated post-affiliated
)
1915 (cdr affiliated
))))))
1917 (defun org-element-diary-sexp-interpreter (diary-sexp _
)
1918 "Interpret DIARY-SEXP as Org syntax."
1919 (org-element-property :value diary-sexp
))
1924 (defun org-element-example-block-parser (limit affiliated
)
1925 "Parse an example block.
1927 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1928 the buffer position at the beginning of the first affiliated
1929 keyword and CDR is a plist of affiliated keywords along with
1932 Return a list whose CAR is `example-block' and CDR is a plist
1933 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1934 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1935 `:value', `:post-blank' and `:post-affiliated' keywords."
1936 (let ((case-fold-search t
))
1937 (if (not (save-excursion
1938 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1939 ;; Incomplete block: parse it as a paragraph.
1940 (org-element-paragraph-parser limit affiliated
)
1941 (let ((contents-end (match-beginning 0)))
1945 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1946 (match-string-no-properties 1)))
1947 ;; Switches analysis.
1950 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
1953 (if (equal (match-string 1 switches
) "-")
1956 (if (not (match-end 2)) 0
1957 ;; Subtract 1 to give number of lines before
1959 (1- (string-to-number (match-string 2 switches
)))))))
1961 (and switches
(string-match "-i\\>" switches
)))
1962 ;; Should labels be retained in (or stripped from) example
1966 (not (string-match "-r\\>" switches
))
1967 (and number-lines
(string-match "-k\\>" switches
))))
1968 ;; What should code-references use - labels or
1973 (not (string-match "-k\\>" switches
)))))
1976 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1977 (match-string 1 switches
)))
1978 ;; Standard block parsing.
1979 (begin (car affiliated
))
1980 (post-affiliated (point))
1981 (contents-begin (line-beginning-position 2))
1982 (value (org-unescape-code-in-string
1983 (buffer-substring-no-properties
1984 contents-begin contents-end
)))
1985 (pos-before-blank (progn (goto-char contents-end
)
1988 (end (progn (skip-chars-forward " \r\t\n" limit
)
1989 (if (eobp) (point) (line-beginning-position)))))
1990 (list 'example-block
1996 :number-lines number-lines
1997 :preserve-indent preserve-indent
1998 :retain-labels retain-labels
1999 :use-labels use-labels
2000 :label-fmt label-fmt
2001 :post-blank
(count-lines pos-before-blank end
)
2002 :post-affiliated post-affiliated
)
2003 (cdr affiliated
)))))))))
2005 (defun org-element-example-block-interpreter (example-block _
)
2006 "Interpret EXAMPLE-BLOCK element as Org syntax."
2007 (let ((switches (org-element-property :switches example-block
))
2008 (value (org-element-property :value example-block
)))
2009 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
2010 (org-element-normalize-string
2011 (org-escape-code-in-string
2012 (if (or org-src-preserve-indentation
2013 (org-element-property :preserve-indent example-block
))
2015 (org-remove-indentation value
))))
2021 (defun org-element-export-block-parser (limit affiliated
)
2022 "Parse an export block.
2024 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2025 the buffer position at the beginning of the first affiliated
2026 keyword and CDR is a plist of affiliated keywords along with
2029 Return a list whose CAR is `export-block' and CDR is a plist
2030 containing `:begin', `:end', `:type', `:value', `:post-blank' and
2031 `:post-affiliated' keywords.
2033 Assume point is at export-block beginning."
2034 (let* ((case-fold-search t
))
2035 (if (not (save-excursion
2036 (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t
)))
2037 ;; Incomplete block: parse it as a paragraph.
2038 (org-element-paragraph-parser limit affiliated
)
2040 (let* ((contents-end (match-beginning 0))
2044 "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
2045 (match-string-no-properties 1)))
2046 (begin (car affiliated
))
2047 (post-affiliated (point))
2048 (contents-begin (progn (forward-line) (point)))
2049 (pos-before-blank (progn (goto-char contents-end
)
2052 (end (progn (skip-chars-forward " \r\t\n" limit
)
2053 (if (eobp) (point) (line-beginning-position))))
2054 (value (org-unescape-code-in-string
2055 (buffer-substring-no-properties contents-begin
2059 (list :type
(and backend
(upcase backend
))
2063 :post-blank
(count-lines pos-before-blank end
)
2064 :post-affiliated post-affiliated
)
2065 (cdr affiliated
))))))))
2067 (defun org-element-export-block-interpreter (export-block _
)
2068 "Interpret EXPORT-BLOCK element as Org syntax."
2069 (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT"
2070 (org-element-property :type export-block
)
2071 (org-element-property :value export-block
)))
2076 (defun org-element-fixed-width-parser (limit affiliated
)
2077 "Parse a fixed-width section.
2079 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2080 the buffer position at the beginning of the first affiliated
2081 keyword and CDR is a plist of affiliated keywords along with
2084 Return a list whose CAR is `fixed-width' and CDR is a plist
2085 containing `:begin', `:end', `:value', `:post-blank' and
2086 `:post-affiliated' keywords.
2088 Assume point is at the beginning of the fixed-width area."
2090 (let* ((begin (car affiliated
))
2091 (post-affiliated (point))
2095 (while (and (< (point) limit
)
2096 (looking-at "[ \t]*:\\( \\|$\\)"))
2097 ;; Accumulate text without starting colons.
2100 (buffer-substring-no-properties
2101 (match-end 0) (point-at-eol))
2105 (end (progn (skip-chars-forward " \r\t\n" limit
)
2106 (if (eobp) (point) (line-beginning-position)))))
2112 :post-blank
(count-lines end-area end
)
2113 :post-affiliated post-affiliated
)
2114 (cdr affiliated
))))))
2116 (defun org-element-fixed-width-interpreter (fixed-width _
)
2117 "Interpret FIXED-WIDTH element as Org syntax."
2118 (let ((value (org-element-property :value fixed-width
)))
2120 (replace-regexp-in-string
2122 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
2125 ;;;; Horizontal Rule
2127 (defun org-element-horizontal-rule-parser (limit affiliated
)
2128 "Parse an horizontal rule.
2130 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2131 the buffer position at the beginning of the first affiliated
2132 keyword and CDR is a plist of affiliated keywords along with
2135 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2136 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2139 (let ((begin (car affiliated
))
2140 (post-affiliated (point))
2141 (post-hr (progn (forward-line) (point)))
2142 (end (progn (skip-chars-forward " \r\t\n" limit
)
2143 (if (eobp) (point) (line-beginning-position)))))
2144 (list 'horizontal-rule
2148 :post-blank
(count-lines post-hr end
)
2149 :post-affiliated post-affiliated
)
2150 (cdr affiliated
))))))
2152 (defun org-element-horizontal-rule-interpreter (&rest _
)
2153 "Interpret HORIZONTAL-RULE element as Org syntax."
2159 (defun org-element-keyword-parser (limit affiliated
)
2160 "Parse a keyword at point.
2162 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2163 the buffer position at the beginning of the first affiliated
2164 keyword and CDR is a plist of affiliated keywords along with
2167 Return a list whose CAR is `keyword' and CDR is a plist
2168 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2169 `:post-affiliated' keywords."
2171 ;; An orphaned affiliated keyword is considered as a regular
2172 ;; keyword. In this case AFFILIATED is nil, so we take care of
2173 ;; this corner case.
2174 (let ((begin (or (car affiliated
) (point)))
2175 (post-affiliated (point))
2176 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2177 (upcase (match-string-no-properties 1))))
2178 (value (org-trim (buffer-substring-no-properties
2179 (match-end 0) (point-at-eol))))
2180 (pos-before-blank (progn (forward-line) (point)))
2181 (end (progn (skip-chars-forward " \r\t\n" limit
)
2182 (if (eobp) (point) (line-beginning-position)))))
2189 :post-blank
(count-lines pos-before-blank end
)
2190 :post-affiliated post-affiliated
)
2191 (cdr affiliated
))))))
2193 (defun org-element-keyword-interpreter (keyword _
)
2194 "Interpret KEYWORD element as Org syntax."
2196 (org-element-property :key keyword
)
2197 (org-element-property :value keyword
)))
2200 ;;;; Latex Environment
2202 (defconst org-element--latex-begin-environment
2203 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2204 "Regexp matching the beginning of a LaTeX environment.
2205 The environment is captured by the first group.
2207 See also `org-element--latex-end-environment'.")
2209 (defconst org-element--latex-end-environment
2210 "\\\\end{%s}[ \t]*$"
2211 "Format string matching the ending of a LaTeX environment.
2212 See also `org-element--latex-begin-environment'.")
2214 (defun org-element-latex-environment-parser (limit affiliated
)
2215 "Parse a LaTeX environment.
2217 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2218 the buffer position at the beginning of the first affiliated
2219 keyword and CDR is a plist of affiliated keywords along with
2222 Return a list whose CAR is `latex-environment' and CDR is a plist
2223 containing `:begin', `:end', `:value', `:post-blank' and
2224 `:post-affiliated' keywords.
2226 Assume point is at the beginning of the latex environment."
2228 (let ((case-fold-search t
)
2229 (code-begin (point)))
2230 (looking-at org-element--latex-begin-environment
)
2231 (if (not (re-search-forward (format org-element--latex-end-environment
2232 (regexp-quote (match-string 1)))
2234 ;; Incomplete latex environment: parse it as a paragraph.
2235 (org-element-paragraph-parser limit affiliated
)
2236 (let* ((code-end (progn (forward-line) (point)))
2237 (begin (car affiliated
))
2238 (value (buffer-substring-no-properties code-begin code-end
))
2239 (end (progn (skip-chars-forward " \r\t\n" limit
)
2240 (if (eobp) (point) (line-beginning-position)))))
2241 (list 'latex-environment
2246 :post-blank
(count-lines code-end end
)
2247 :post-affiliated code-begin
)
2248 (cdr affiliated
))))))))
2250 (defun org-element-latex-environment-interpreter (latex-environment _
)
2251 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2252 (org-element-property :value latex-environment
))
2257 (defun org-element-node-property-parser (limit)
2258 "Parse a node-property at point.
2260 LIMIT bounds the search.
2262 Return a list whose CAR is `node-property' and CDR is a plist
2263 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2264 `:post-affiliated' keywords."
2265 (looking-at org-property-re
)
2266 (let ((case-fold-search t
)
2268 (key (match-string-no-properties 2))
2269 (value (match-string-no-properties 3))
2270 (end (save-excursion
2272 (if (re-search-forward org-property-re limit t
)
2273 (line-beginning-position)
2275 (list 'node-property
2281 :post-affiliated begin
))))
2283 (defun org-element-node-property-interpreter (node-property _
)
2284 "Interpret NODE-PROPERTY element as Org syntax."
2285 (format org-property-format
2286 (format ":%s:" (org-element-property :key node-property
))
2287 (or (org-element-property :value node-property
) "")))
2292 (defun org-element-paragraph-parser (limit affiliated
)
2295 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2296 the buffer position at the beginning of the first affiliated
2297 keyword and CDR is a plist of affiliated keywords along with
2300 Return a list whose CAR is `paragraph' and CDR is a plist
2301 containing `:begin', `:end', `:contents-begin' and
2302 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2304 Assume point is at the beginning of the paragraph."
2306 (let* ((begin (car affiliated
))
2307 (contents-begin (point))
2309 (let ((case-fold-search t
))
2311 ;; A matching `org-element-paragraph-separate' is not
2312 ;; necessarily the end of the paragraph. In particular,
2313 ;; drawers, blocks or LaTeX environments opening lines
2314 ;; must be closed. Moreover keywords with a secondary
2315 ;; value must belong to "dual keywords".
2318 ((not (and (re-search-forward
2319 org-element-paragraph-separate limit
'move
)
2320 (progn (beginning-of-line) t
))))
2321 ((looking-at org-drawer-regexp
)
2323 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
2324 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2327 (format "^[ \t]*#\\+END_%s[ \t]*$"
2328 (regexp-quote (match-string 1)))
2330 ((looking-at org-element--latex-begin-environment
)
2333 (format org-element--latex-end-environment
2334 (regexp-quote (match-string 1)))
2336 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2337 (member-ignore-case (match-string 1)
2338 org-element-dual-keywords
))
2339 ;; Everything else is unambiguous.
2342 (if (= (point) limit
) limit
2343 (goto-char (line-beginning-position)))))
2344 (contents-end (save-excursion
2345 (skip-chars-backward " \r\t\n" contents-begin
)
2346 (line-beginning-position 2)))
2347 (end (progn (skip-chars-forward " \r\t\n" limit
)
2348 (if (eobp) (point) (line-beginning-position)))))
2353 :contents-begin contents-begin
2354 :contents-end contents-end
2355 :post-blank
(count-lines before-blank end
)
2356 :post-affiliated contents-begin
)
2357 (cdr affiliated
))))))
2359 (defun org-element-paragraph-interpreter (_ contents
)
2360 "Interpret paragraph element as Org syntax.
2361 CONTENTS is the contents of the element."
2367 (defun org-element-planning-parser (limit)
2370 LIMIT bounds the search.
2372 Return a list whose CAR is `planning' and CDR is a plist
2373 containing `:closed', `:deadline', `:scheduled', `:begin',
2374 `:end', `:post-blank' and `:post-affiliated' keywords."
2376 (let* ((case-fold-search nil
)
2378 (post-blank (let ((before-blank (progn (forward-line) (point))))
2379 (skip-chars-forward " \r\t\n" limit
)
2380 (skip-chars-backward " \t")
2381 (unless (bolp) (end-of-line))
2382 (count-lines before-blank
(point))))
2384 closed deadline scheduled
)
2386 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2387 (goto-char (match-end 1))
2388 (skip-chars-forward " \t" end
)
2389 (let ((keyword (match-string 1))
2390 (time (org-element-timestamp-parser)))
2391 (cond ((equal keyword org-closed-string
) (setq closed time
))
2392 ((equal keyword org-deadline-string
) (setq deadline time
))
2393 (t (setq scheduled time
)))))
2395 (list :closed closed
2397 :scheduled scheduled
2400 :post-blank post-blank
2401 :post-affiliated begin
)))))
2403 (defun org-element-planning-interpreter (planning _
)
2404 "Interpret PLANNING element as Org syntax."
2408 (list (let ((deadline (org-element-property :deadline planning
)))
2410 (concat org-deadline-string
" "
2411 (org-element-timestamp-interpreter deadline nil
))))
2412 (let ((scheduled (org-element-property :scheduled planning
)))
2414 (concat org-scheduled-string
" "
2415 (org-element-timestamp-interpreter scheduled nil
))))
2416 (let ((closed (org-element-property :closed planning
)))
2418 (concat org-closed-string
" "
2419 (org-element-timestamp-interpreter closed nil
))))))
2425 (defun org-element-src-block-parser (limit affiliated
)
2428 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2429 the buffer position at the beginning of the first affiliated
2430 keyword and CDR is a plist of affiliated keywords along with
2433 Return a list whose CAR is `src-block' and CDR is a plist
2434 containing `:language', `:switches', `:parameters', `:begin',
2435 `:end', `:number-lines', `:retain-labels', `:use-labels',
2436 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2437 `:post-affiliated' keywords.
2439 Assume point is at the beginning of the block."
2440 (let ((case-fold-search t
))
2441 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2443 ;; Incomplete block: parse it as a paragraph.
2444 (org-element-paragraph-parser limit affiliated
)
2445 (let ((contents-end (match-beginning 0)))
2447 (let* ((begin (car affiliated
))
2448 (post-affiliated (point))
2449 ;; Get language as a string.
2453 "^[ \t]*#\\+BEGIN_SRC\
2454 \\(?: +\\(\\S-+\\)\\)?\
2455 \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
2457 (match-string-no-properties 1)))
2459 (switches (match-string-no-properties 2))
2461 (parameters (match-string-no-properties 3))
2462 ;; Switches analysis.
2465 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
2468 (if (equal (match-string 1 switches
) "-")
2471 (if (not (match-end 2)) 0
2472 ;; Subtract 1 to give number of lines before
2474 (1- (string-to-number (match-string 2 switches
)))))))
2475 (preserve-indent (and switches
2476 (string-match "-i\\>" switches
)))
2479 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2480 (match-string 1 switches
)))
2481 ;; Should labels be retained in (or stripped from)
2485 (not (string-match "-r\\>" switches
))
2486 (and number-lines
(string-match "-k\\>" switches
))))
2487 ;; What should code-references use - labels or
2492 (not (string-match "-k\\>" switches
)))))
2494 (value (org-unescape-code-in-string
2495 (buffer-substring-no-properties
2496 (line-beginning-position 2) contents-end
)))
2497 (pos-before-blank (progn (goto-char contents-end
)
2500 ;; Get position after ending blank lines.
2501 (end (progn (skip-chars-forward " \r\t\n" limit
)
2502 (if (eobp) (point) (line-beginning-position)))))
2505 (list :language language
2506 :switches
(and (org-string-nw-p switches
)
2507 (org-trim switches
))
2508 :parameters
(and (org-string-nw-p parameters
)
2509 (org-trim parameters
))
2512 :number-lines number-lines
2513 :preserve-indent preserve-indent
2514 :retain-labels retain-labels
2515 :use-labels use-labels
2516 :label-fmt label-fmt
2518 :post-blank
(count-lines pos-before-blank end
)
2519 :post-affiliated post-affiliated
)
2520 (cdr affiliated
)))))))))
2522 (defun org-element-src-block-interpreter (src-block _
)
2523 "Interpret SRC-BLOCK element as Org syntax."
2524 (let ((lang (org-element-property :language src-block
))
2525 (switches (org-element-property :switches src-block
))
2526 (params (org-element-property :parameters src-block
))
2528 (let ((val (org-element-property :value src-block
)))
2530 ((or org-src-preserve-indentation
2531 (org-element-property :preserve-indent src-block
))
2533 ((zerop org-edit-src-content-indentation
)
2534 (org-remove-indentation val
))
2536 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2537 (replace-regexp-in-string
2538 "^" ind
(org-remove-indentation val
))))))))
2539 (concat (format "#+BEGIN_SRC%s\n"
2540 (concat (and lang
(concat " " lang
))
2541 (and switches
(concat " " switches
))
2542 (and params
(concat " " params
))))
2543 (org-element-normalize-string (org-escape-code-in-string value
))
2549 (defun org-element-table-parser (limit affiliated
)
2550 "Parse a table at point.
2552 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2553 the buffer position at the beginning of the first affiliated
2554 keyword and CDR is a plist of affiliated keywords along with
2557 Return a list whose CAR is `table' and CDR is a plist containing
2558 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2559 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2562 Assume point is at the beginning of the table."
2564 (let* ((case-fold-search t
)
2565 (table-begin (point))
2566 (type (if (looking-at "[ \t]*|") 'org
'table.el
))
2567 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2568 (if (eq type
'org
) "" "+")))
2569 (begin (car affiliated
))
2571 (if (re-search-forward end-re limit
'move
)
2572 (goto-char (match-beginning 0))
2575 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2576 (push (match-string-no-properties 1) acc
)
2579 (pos-before-blank (point))
2580 (end (progn (skip-chars-forward " \r\t\n" limit
)
2581 (if (eobp) (point) (line-beginning-position)))))
2588 ;; Only `org' tables have contents. `table.el' tables
2589 ;; use a `:value' property to store raw table as
2591 :contents-begin
(and (eq type
'org
) table-begin
)
2592 :contents-end
(and (eq type
'org
) table-end
)
2593 :value
(and (eq type
'table.el
)
2594 (buffer-substring-no-properties
2595 table-begin table-end
))
2596 :post-blank
(count-lines pos-before-blank end
)
2597 :post-affiliated table-begin
)
2598 (cdr affiliated
))))))
2600 (defun org-element-table-interpreter (table contents
)
2601 "Interpret TABLE element as Org syntax.
2602 CONTENTS is a string, if table's type is `org', or nil."
2603 (if (eq (org-element-property :type table
) 'table.el
)
2604 (org-remove-indentation (org-element-property :value table
))
2605 (concat (with-temp-buffer (insert contents
)
2608 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2609 (reverse (org-element-property :tblfm table
))
2615 (defun org-element-table-row-parser (_)
2616 "Parse table row at point.
2618 Return a list whose CAR is `table-row' and CDR is a plist
2619 containing `:begin', `:end', `:contents-begin', `:contents-end',
2620 `:type', `:post-blank' and `:post-affiliated' keywords."
2622 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2624 ;; A table rule has no contents. In that case, ensure
2625 ;; CONTENTS-BEGIN matches CONTENTS-END.
2626 (contents-begin (and (eq type
'standard
) (search-forward "|")))
2627 (contents-end (and (eq type
'standard
)
2630 (skip-chars-backward " \t")
2632 (end (line-beginning-position 2)))
2637 :contents-begin contents-begin
2638 :contents-end contents-end
2640 :post-affiliated begin
)))))
2642 (defun org-element-table-row-interpreter (table-row contents
)
2643 "Interpret TABLE-ROW element as Org syntax.
2644 CONTENTS is the contents of the table row."
2645 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2646 (concat "|" contents
)))
2651 (defun org-element-verse-block-parser (limit affiliated
)
2652 "Parse a verse block.
2654 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2655 the buffer position at the beginning of the first affiliated
2656 keyword and CDR is a plist of affiliated keywords along with
2659 Return a list whose CAR is `verse-block' and CDR is a plist
2660 containing `:begin', `:end', `:contents-begin', `:contents-end',
2661 `:post-blank' and `:post-affiliated' keywords.
2663 Assume point is at beginning of the block."
2664 (let ((case-fold-search t
))
2665 (if (not (save-excursion
2666 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2667 ;; Incomplete block: parse it as a paragraph.
2668 (org-element-paragraph-parser limit affiliated
)
2669 (let ((contents-end (match-beginning 0)))
2671 (let* ((begin (car affiliated
))
2672 (post-affiliated (point))
2673 (contents-begin (progn (forward-line) (point)))
2674 (pos-before-blank (progn (goto-char contents-end
)
2677 (end (progn (skip-chars-forward " \r\t\n" limit
)
2678 (if (eobp) (point) (line-beginning-position)))))
2683 :contents-begin contents-begin
2684 :contents-end contents-end
2685 :post-blank
(count-lines pos-before-blank end
)
2686 :post-affiliated post-affiliated
)
2687 (cdr affiliated
)))))))))
2689 (defun org-element-verse-block-interpreter (_ contents
)
2690 "Interpret verse-block element as Org syntax.
2691 CONTENTS is verse block contents."
2692 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2698 ;; Unlike to elements, raw text can be found between objects. Hence,
2699 ;; `org-element--object-lex' is provided to find the next object in
2702 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2703 ;; object types they can contain will be specified in
2704 ;; `org-element-object-restrictions'.
2706 ;; Creating a new type of object requires to alter
2707 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2708 ;; new type in `org-element-all-objects', and possibly add
2709 ;; restrictions in `org-element-object-restrictions'.
2713 (defun org-element-bold-parser ()
2714 "Parse bold object at point, if any.
2716 When at a bold object, return a list whose car is `bold' and cdr
2717 is a plist with `:begin', `:end', `:contents-begin' and
2718 `:contents-end' and `:post-blank' keywords. Otherwise, return
2721 Assume point is at the first star marker."
2723 (unless (bolp) (backward-char 1))
2724 (when (looking-at org-emph-re
)
2725 (let ((begin (match-beginning 2))
2726 (contents-begin (match-beginning 4))
2727 (contents-end (match-end 4))
2728 (post-blank (progn (goto-char (match-end 2))
2729 (skip-chars-forward " \t")))
2734 :contents-begin contents-begin
2735 :contents-end contents-end
2736 :post-blank post-blank
))))))
2738 (defun org-element-bold-interpreter (_ contents
)
2739 "Interpret bold object as Org syntax.
2740 CONTENTS is the contents of the object."
2741 (format "*%s*" contents
))
2746 (defun org-element-code-parser ()
2747 "Parse code object at point, if any.
2749 When at a code object, return a list whose car is `code' and cdr
2750 is a plist with `:value', `:begin', `:end' and `:post-blank'
2751 keywords. Otherwise, return nil.
2753 Assume point is at the first tilde marker."
2755 (unless (bolp) (backward-char 1))
2756 (when (looking-at org-emph-re
)
2757 (let ((begin (match-beginning 2))
2758 (value (match-string-no-properties 4))
2759 (post-blank (progn (goto-char (match-end 2))
2760 (skip-chars-forward " \t")))
2766 :post-blank post-blank
))))))
2768 (defun org-element-code-interpreter (code _
)
2769 "Interpret CODE object as Org syntax."
2770 (format "~%s~" (org-element-property :value code
)))
2775 (defun org-element-entity-parser ()
2776 "Parse entity at point, if any.
2778 When at an entity, return a list whose car is `entity' and cdr
2779 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2780 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2781 `:post-blank' as keywords. Otherwise, return nil.
2783 Assume point is at the beginning of the entity."
2785 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2787 (let* ((value (or (org-entity-get (match-string 1))
2788 (throw 'no-object nil
)))
2789 (begin (match-beginning 0))
2790 (bracketsp (string= (match-string 2) "{}"))
2791 (post-blank (progn (goto-char (match-end 1))
2792 (when bracketsp
(forward-char 2))
2793 (skip-chars-forward " \t")))
2796 (list :name
(car value
)
2797 :latex
(nth 1 value
)
2798 :latex-math-p
(nth 2 value
)
2800 :ascii
(nth 4 value
)
2801 :latin1
(nth 5 value
)
2802 :utf-8
(nth 6 value
)
2805 :use-brackets-p bracketsp
2806 :post-blank post-blank
)))))))
2808 (defun org-element-entity-interpreter (entity _
)
2809 "Interpret ENTITY object as Org syntax."
2811 (org-element-property :name entity
)
2812 (when (org-element-property :use-brackets-p entity
) "{}")))
2817 (defun org-element-export-snippet-parser ()
2818 "Parse export snippet at point.
2820 When at an export snippet, return a list whose car is
2821 `export-snippet' and cdr a plist with `:begin', `:end',
2822 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2825 Assume point is at the beginning of the snippet."
2828 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2830 (save-match-data (goto-char (match-end 0))
2831 (re-search-forward "@@" nil t
)
2832 (match-beginning 0))))
2833 (let* ((begin (match-beginning 0))
2834 (back-end (match-string-no-properties 1))
2835 (value (buffer-substring-no-properties
2836 (match-end 0) contents-end
))
2837 (post-blank (skip-chars-forward " \t"))
2839 (list 'export-snippet
2840 (list :back-end back-end
2844 :post-blank post-blank
)))))))
2846 (defun org-element-export-snippet-interpreter (export-snippet _
)
2847 "Interpret EXPORT-SNIPPET object as Org syntax."
2849 (org-element-property :back-end export-snippet
)
2850 (org-element-property :value export-snippet
)))
2853 ;;;; Footnote Reference
2855 (defun org-element-footnote-reference-parser ()
2856 "Parse footnote reference at point, if any.
2858 When at a footnote reference, return a list whose car is
2859 `footnote-reference' and cdr a plist with `:label', `:type',
2860 `:begin', `:end', `:content-begin', `:contents-end' and
2861 `:post-blank' as keywords. Otherwise, return nil."
2862 (when (looking-at org-footnote-re
)
2863 (let ((closing (with-syntax-table org-element--pair-square-table
2864 (ignore-errors (scan-lists (point) 1 0)))))
2867 (let* ((begin (point))
2868 (label (match-string-no-properties 1))
2869 (inner-begin (match-end 0))
2870 (inner-end (1- closing
))
2871 (type (if (match-end 2) 'inline
'standard
))
2872 (post-blank (progn (goto-char closing
)
2873 (skip-chars-forward " \t")))
2875 (list 'footnote-reference
2880 :contents-begin
(and (eq type
'inline
) inner-begin
)
2881 :contents-end
(and (eq type
'inline
) inner-end
)
2882 :post-blank post-blank
))))))))
2884 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2885 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2886 CONTENTS is its definition, when inline, or nil."
2888 (or (org-element-property :label footnote-reference
) "")
2889 (if contents
(concat ":" contents
) "")))
2892 ;;;; Inline Babel Call
2894 (defun org-element-inline-babel-call-parser ()
2895 "Parse inline babel call at point, if any.
2897 When at an inline babel call, return a list whose car is
2898 `inline-babel-call' and cdr a plist with `:call',
2899 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2900 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2902 Assume point is at the beginning of the babel call."
2905 (when (let ((case-fold-search nil
))
2906 (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
2907 (goto-char (match-end 1))
2908 (let* ((begin (match-beginning 0))
2909 (call (match-string-no-properties 1))
2911 (let ((p (org-element--parse-paired-brackets ?\
[)))
2912 (and (org-string-nw-p p
)
2913 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2914 (arguments (org-string-nw-p
2915 (or (org-element--parse-paired-brackets ?\
()
2916 ;; Parenthesis are mandatory.
2917 (throw :no-object nil
))))
2919 (let ((p (org-element--parse-paired-brackets ?\
[)))
2920 (and (org-string-nw-p p
)
2921 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2922 (value (buffer-substring-no-properties begin
(point)))
2923 (post-blank (skip-chars-forward " \t"))
2925 (list 'inline-babel-call
2927 :inside-header inside-header
2928 :arguments arguments
2929 :end-header end-header
2933 :post-blank post-blank
)))))))
2935 (defun org-element-inline-babel-call-interpreter (inline-babel-call _
)
2936 "Interpret INLINE-BABEL-CALL object as Org syntax."
2938 (org-element-property :call inline-babel-call
)
2939 (let ((h (org-element-property :inside-header inline-babel-call
)))
2940 (and h
(format "[%s]" h
)))
2941 "(" (org-element-property :arguments inline-babel-call
) ")"
2942 (let ((h (org-element-property :end-header inline-babel-call
)))
2943 (and h
(format "[%s]" h
)))))
2946 ;;;; Inline Src Block
2948 (defun org-element-inline-src-block-parser ()
2949 "Parse inline source block at point, if any.
2951 When at an inline source block, return a list whose car is
2952 `inline-src-block' and cdr a plist with `:begin', `:end',
2953 `:language', `:value', `:parameters' and `:post-blank' as
2954 keywords. Otherwise, return nil.
2956 Assume point is at the beginning of the inline src block."
2959 (when (let ((case-fold-search nil
))
2960 (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
2961 (goto-char (match-end 1))
2962 (let ((begin (match-beginning 0))
2963 (language (match-string-no-properties 1))
2965 (let ((p (org-element--parse-paired-brackets ?\
[)))
2966 (and (org-string-nw-p p
)
2967 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2968 (value (or (org-element--parse-paired-brackets ?\
{)
2969 (throw :no-object nil
)))
2970 (post-blank (skip-chars-forward " \t")))
2971 (list 'inline-src-block
2972 (list :language language
2974 :parameters parameters
2977 :post-blank post-blank
)))))))
2979 (defun org-element-inline-src-block-interpreter (inline-src-block _
)
2980 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2981 (let ((language (org-element-property :language inline-src-block
))
2982 (arguments (org-element-property :parameters inline-src-block
))
2983 (body (org-element-property :value inline-src-block
)))
2984 (format "src_%s%s{%s}"
2986 (if arguments
(format "[%s]" arguments
) "")
2991 (defun org-element-italic-parser ()
2992 "Parse italic object at point, if any.
2994 When at an italic object, return a list whose car is `italic' and
2995 cdr is a plist with `:begin', `:end', `:contents-begin' and
2996 `:contents-end' and `:post-blank' keywords. Otherwise, return
2999 Assume point is at the first slash marker."
3001 (unless (bolp) (backward-char 1))
3002 (when (looking-at org-emph-re
)
3003 (let ((begin (match-beginning 2))
3004 (contents-begin (match-beginning 4))
3005 (contents-end (match-end 4))
3006 (post-blank (progn (goto-char (match-end 2))
3007 (skip-chars-forward " \t")))
3012 :contents-begin contents-begin
3013 :contents-end contents-end
3014 :post-blank post-blank
))))))
3016 (defun org-element-italic-interpreter (_ contents
)
3017 "Interpret italic object as Org syntax.
3018 CONTENTS is the contents of the object."
3019 (format "/%s/" contents
))
3024 (defun org-element-latex-fragment-parser ()
3025 "Parse LaTeX fragment at point, if any.
3027 When at a LaTeX fragment, return a list whose car is
3028 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
3029 and `:post-blank' as keywords. Otherwise, return nil.
3031 Assume point is at the beginning of the LaTeX fragment."
3034 (let* ((begin (point))
3036 (if (eq (char-after) ?$
)
3037 (if (eq (char-after (1+ (point))) ?$
)
3038 (search-forward "$$" nil t
2)
3039 (and (not (eq (char-before) ?$
))
3040 (search-forward "$" nil t
2)
3041 (not (memq (char-before (match-beginning 0))
3042 '(?\s ?
\t ?
\n ?
, ?.
)))
3043 (looking-at "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|$\\)")
3045 (pcase (char-after (1+ (point)))
3046 (?\
( (search-forward "\\)" nil t
))
3047 (?\
[ (search-forward "\\]" nil t
))
3050 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
3051 \\|\\({[^{}\n]*}\\)\\)*")
3053 (post-blank (if (not after-fragment
) (throw 'no-object nil
)
3054 (goto-char after-fragment
)
3055 (skip-chars-forward " \t")))
3057 (list 'latex-fragment
3058 (list :value
(buffer-substring-no-properties begin after-fragment
)
3061 :post-blank post-blank
))))))
3063 (defun org-element-latex-fragment-interpreter (latex-fragment _
)
3064 "Interpret LATEX-FRAGMENT object as Org syntax."
3065 (org-element-property :value latex-fragment
))
3069 (defun org-element-line-break-parser ()
3070 "Parse line break at point, if any.
3072 When at a line break, return a list whose car is `line-break',
3073 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3074 Otherwise, return nil.
3076 Assume point is at the beginning of the line break."
3077 (when (and (looking-at-p "\\\\\\\\[ \t]*$")
3078 (not (eq (char-before) ?
\\)))
3080 (list :begin
(point)
3081 :end
(line-beginning-position 2)
3084 (defun org-element-line-break-interpreter (&rest _
)
3085 "Interpret LINE-BREAK object as Org syntax."
3091 (defun org-element-link-parser ()
3092 "Parse link at point, if any.
3094 When at a link, return a list whose car is `link' and cdr a plist
3095 with `:type', `:path', `:format', `:raw-link', `:application',
3096 `:search-option', `:begin', `:end', `:contents-begin',
3097 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3100 Assume point is at the beginning of the link."
3102 (let ((begin (point))
3103 end contents-begin contents-end link-end post-blank path type format
3104 raw-link search-option application
)
3106 ;; Type 1: Text targeted from a radio target.
3107 ((and org-target-link-regexp
3108 (save-excursion (or (bolp) (backward-char))
3109 (looking-at org-target-link-regexp
)))
3111 (setq format
'plain
)
3112 (setq link-end
(match-end 1))
3113 (setq path
(match-string-no-properties 1))
3114 (setq contents-begin
(match-beginning 1))
3115 (setq contents-end
(match-end 1)))
3116 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3117 ((looking-at org-bracket-link-regexp
)
3118 (setq format
'bracket
)
3119 (setq contents-begin
(match-beginning 3))
3120 (setq contents-end
(match-end 3))
3121 (setq link-end
(match-end 0))
3122 ;; RAW-LINK is the original link. Expand any
3123 ;; abbreviation in it.
3125 ;; Also treat any newline character and associated
3126 ;; indentation as a single space character. This is not
3127 ;; compatible with RFC 3986, which requires to ignore
3128 ;; them altogether. However, doing so would require
3129 ;; users to encode spaces on the fly when writing links
3130 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3131 ;; [[shell:ls *.org]], which defeats Org's focus on
3133 (setq raw-link
(org-link-expand-abbrev
3134 (replace-regexp-in-string
3135 "[ \t]*\n[ \t]*" " "
3136 (match-string-no-properties 1))))
3137 ;; Determine TYPE of link and set PATH accordingly. According
3138 ;; to RFC 3986, remove whitespaces from URI in external links.
3139 ;; In internal ones, treat indentation as a single space.
3142 ((or (file-name-absolute-p raw-link
)
3143 (string-match "\\`\\.\\.?/" raw-link
))
3145 (setq path raw-link
))
3146 ;; Explicit type (http, irc, bbdb...).
3147 ((string-match org-link-types-re raw-link
)
3148 (setq type
(match-string 1 raw-link
))
3149 (setq path
(substring raw-link
(match-end 0))))
3150 ;; Code-ref type: PATH is the name of the reference.
3151 ((and (string-match-p "\\`(" raw-link
)
3152 (string-match-p ")\\'" raw-link
))
3153 (setq type
"coderef")
3154 (setq path
(substring raw-link
1 -
1)))
3155 ;; Custom-id type: PATH is the name of the custom id.
3156 ((= (string-to-char raw-link
) ?
#)
3157 (setq type
"custom-id")
3158 (setq path
(substring raw-link
1)))
3159 ;; Fuzzy type: Internal link either matches a target, an
3160 ;; headline name or nothing. PATH is the target or
3164 (setq path raw-link
))))
3165 ;; Type 3: Plain link, e.g., http://orgmode.org
3166 ((looking-at org-plain-link-re
)
3167 (setq format
'plain
)
3168 (setq raw-link
(match-string-no-properties 0))
3169 (setq type
(match-string-no-properties 1))
3170 (setq link-end
(match-end 0))
3171 (setq path
(match-string-no-properties 2)))
3172 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3173 ;; bracket links, follow RFC 3986 and remove any extra
3174 ;; whitespace in URI.
3175 ((looking-at org-angle-link-re
)
3176 (setq format
'angle
)
3177 (setq type
(match-string-no-properties 1))
3178 (setq link-end
(match-end 0))
3180 (buffer-substring-no-properties
3181 (match-beginning 1) (match-end 2)))
3182 (setq path
(replace-regexp-in-string
3183 "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
3184 (t (throw 'no-object nil
)))
3185 ;; In any case, deduce end point after trailing white space from
3186 ;; LINK-END variable.
3189 (progn (goto-char link-end
) (skip-chars-forward " \t")))
3191 ;; Special "file" type link processing. Extract opening
3192 ;; application and search option, if any. Also normalize URI.
3193 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type
)
3194 (setq application
(match-string 1 type
) type
"file")
3195 (when (string-match "::\\(.*\\)\\'" path
)
3196 (setq search-option
(match-string 1 path
))
3197 (setq path
(replace-match "" nil nil path
)))
3198 (setq path
(replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path
)))
3199 ;; Translate link, if `org-link-translation-function' is set.
3200 (let ((trans (and (functionp org-link-translation-function
)
3201 (funcall org-link-translation-function type path
))))
3203 (setq type
(car trans
))
3204 (setq path
(cdr trans
))))
3209 :raw-link
(or raw-link path
)
3210 :application application
3211 :search-option search-option
3214 :contents-begin contents-begin
3215 :contents-end contents-end
3216 :post-blank post-blank
)))))
3218 (defun org-element-link-interpreter (link contents
)
3219 "Interpret LINK object as Org syntax.
3220 CONTENTS is the contents of the object, or nil."
3221 (let ((type (org-element-property :type link
))
3222 (path (org-element-property :path link
)))
3223 (if (string= type
"radio") path
3224 (let ((fmt (pcase (org-element-property :format link
)
3225 ;; Links with contents and internal links have to
3226 ;; use bracket syntax. Ignore `:format' in these
3227 ;; cases. This is also the default syntax when the
3228 ;; property is not defined, e.g., when the object
3229 ;; was crafted by the user.
3231 (format "[[%%s][%s]]"
3232 ;; Since this is going to be used as
3233 ;; a format string, escape percent signs
3235 (replace-regexp-in-string "%" "%%" contents
)))
3238 (guard (member type
'("coderef" "custom-id" "fuzzy"))))
3240 ;; Otherwise, just obey to `:format'.
3243 (f (error "Wrong `:format' value: %s" f
)))))
3246 ("coderef" (format "(%s)" path
))
3247 ("custom-id" (concat "#" path
))
3249 (let ((app (org-element-property :application link
))
3250 (opt (org-element-property :search-option link
)))
3251 (concat type
(and app
(concat "+" app
)) ":"
3253 (and opt
(concat "::" opt
)))))
3255 (_ (concat type
":" path
))))))))
3260 (defun org-element-macro-parser ()
3261 "Parse macro at point, if any.
3263 When at a macro, return a list whose car is `macro' and cdr
3264 a plist with `:key', `:args', `:begin', `:end', `:value' and
3265 `:post-blank' as keywords. Otherwise, return nil.
3267 Assume point is at the macro."
3269 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3270 (let ((begin (point))
3271 (key (downcase (match-string-no-properties 1)))
3272 (value (match-string-no-properties 0))
3273 (post-blank (progn (goto-char (match-end 0))
3274 (skip-chars-forward " \t")))
3276 (args (let ((args (match-string-no-properties 3)))
3277 (and args
(org-macro-extract-arguments args
)))))
3284 :post-blank post-blank
))))))
3286 (defun org-element-macro-interpreter (macro _
)
3287 "Interpret MACRO object as Org syntax."
3288 (org-element-property :value macro
))
3293 (defun org-element-radio-target-parser ()
3294 "Parse radio target at point, if any.
3296 When at a radio target, return a list whose car is `radio-target'
3297 and cdr a plist with `:begin', `:end', `:contents-begin',
3298 `:contents-end', `:value' and `:post-blank' as keywords.
3299 Otherwise, return nil.
3301 Assume point is at the radio target."
3303 (when (looking-at org-radio-target-regexp
)
3304 (let ((begin (point))
3305 (contents-begin (match-beginning 1))
3306 (contents-end (match-end 1))
3307 (value (match-string-no-properties 1))
3308 (post-blank (progn (goto-char (match-end 0))
3309 (skip-chars-forward " \t")))
3314 :contents-begin contents-begin
3315 :contents-end contents-end
3316 :post-blank post-blank
3319 (defun org-element-radio-target-interpreter (_ contents
)
3320 "Interpret target object as Org syntax.
3321 CONTENTS is the contents of the object."
3322 (concat "<<<" contents
">>>"))
3325 ;;;; Statistics Cookie
3327 (defun org-element-statistics-cookie-parser ()
3328 "Parse statistics cookie at point, if any.
3330 When at a statistics cookie, return a list whose car is
3331 `statistics-cookie', and cdr a plist with `:begin', `:end',
3332 `:value' and `:post-blank' keywords. Otherwise, return nil.
3334 Assume point is at the beginning of the statistics-cookie."
3336 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3337 (let* ((begin (point))
3338 (value (buffer-substring-no-properties
3339 (match-beginning 0) (match-end 0)))
3340 (post-blank (progn (goto-char (match-end 0))
3341 (skip-chars-forward " \t")))
3343 (list 'statistics-cookie
3347 :post-blank post-blank
))))))
3349 (defun org-element-statistics-cookie-interpreter (statistics-cookie _
)
3350 "Interpret STATISTICS-COOKIE object as Org syntax."
3351 (org-element-property :value statistics-cookie
))
3356 (defun org-element-strike-through-parser ()
3357 "Parse strike-through object at point, if any.
3359 When at a strike-through object, return a list whose car is
3360 `strike-through' and cdr is a plist with `:begin', `:end',
3361 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3362 Otherwise, return nil.
3364 Assume point is at the first plus sign marker."
3366 (unless (bolp) (backward-char 1))
3367 (when (looking-at org-emph-re
)
3368 (let ((begin (match-beginning 2))
3369 (contents-begin (match-beginning 4))
3370 (contents-end (match-end 4))
3371 (post-blank (progn (goto-char (match-end 2))
3372 (skip-chars-forward " \t")))
3374 (list 'strike-through
3377 :contents-begin contents-begin
3378 :contents-end contents-end
3379 :post-blank post-blank
))))))
3381 (defun org-element-strike-through-interpreter (_ contents
)
3382 "Interpret strike-through object as Org syntax.
3383 CONTENTS is the contents of the object."
3384 (format "+%s+" contents
))
3389 (defun org-element-subscript-parser ()
3390 "Parse subscript at point, if any.
3392 When at a subscript object, return a list whose car is
3393 `subscript' and cdr a plist with `:begin', `:end',
3394 `:contents-begin', `:contents-end', `:use-brackets-p' and
3395 `:post-blank' as keywords. Otherwise, return nil.
3397 Assume point is at the underscore."
3399 (unless (bolp) (backward-char))
3400 (when (looking-at org-match-substring-regexp
)
3401 (let ((bracketsp (match-beginning 4))
3402 (begin (match-beginning 2))
3403 (contents-begin (or (match-beginning 4)
3404 (match-beginning 3)))
3405 (contents-end (or (match-end 4) (match-end 3)))
3406 (post-blank (progn (goto-char (match-end 0))
3407 (skip-chars-forward " \t")))
3412 :use-brackets-p bracketsp
3413 :contents-begin contents-begin
3414 :contents-end contents-end
3415 :post-blank post-blank
))))))
3417 (defun org-element-subscript-interpreter (subscript contents
)
3418 "Interpret SUBSCRIPT object as Org syntax.
3419 CONTENTS is the contents of the object."
3421 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3427 (defun org-element-superscript-parser ()
3428 "Parse superscript at point, if any.
3430 When at a superscript object, return a list whose car is
3431 `superscript' and cdr a plist with `:begin', `:end',
3432 `:contents-begin', `:contents-end', `:use-brackets-p' and
3433 `:post-blank' as keywords. Otherwise, return nil.
3435 Assume point is at the caret."
3437 (unless (bolp) (backward-char))
3438 (when (looking-at org-match-substring-regexp
)
3439 (let ((bracketsp (match-beginning 4))
3440 (begin (match-beginning 2))
3441 (contents-begin (or (match-beginning 4)
3442 (match-beginning 3)))
3443 (contents-end (or (match-end 4) (match-end 3)))
3444 (post-blank (progn (goto-char (match-end 0))
3445 (skip-chars-forward " \t")))
3450 :use-brackets-p bracketsp
3451 :contents-begin contents-begin
3452 :contents-end contents-end
3453 :post-blank post-blank
))))))
3455 (defun org-element-superscript-interpreter (superscript contents
)
3456 "Interpret SUPERSCRIPT object as Org syntax.
3457 CONTENTS is the contents of the object."
3459 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3465 (defun org-element-table-cell-parser ()
3466 "Parse table cell at point.
3467 Return a list whose car is `table-cell' and cdr is a plist
3468 containing `:begin', `:end', `:contents-begin', `:contents-end'
3469 and `:post-blank' keywords."
3470 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3471 (let* ((begin (match-beginning 0))
3473 (contents-begin (match-beginning 1))
3474 (contents-end (match-end 1)))
3478 :contents-begin contents-begin
3479 :contents-end contents-end
3482 (defun org-element-table-cell-interpreter (_ contents
)
3483 "Interpret table-cell element as Org syntax.
3484 CONTENTS is the contents of the cell, or nil."
3485 (concat " " contents
" |"))
3490 (defun org-element-target-parser ()
3491 "Parse target at point, if any.
3493 When at a target, return a list whose car is `target' and cdr
3494 a plist with `:begin', `:end', `:value' and `:post-blank' as
3495 keywords. Otherwise, return nil.
3497 Assume point is at the target."
3499 (when (looking-at org-target-regexp
)
3500 (let ((begin (point))
3501 (value (match-string-no-properties 1))
3502 (post-blank (progn (goto-char (match-end 0))
3503 (skip-chars-forward " \t")))
3509 :post-blank post-blank
))))))
3511 (defun org-element-target-interpreter (target _
)
3512 "Interpret TARGET object as Org syntax."
3513 (format "<<%s>>" (org-element-property :value target
)))
3518 (defconst org-element--timestamp-regexp
3519 (concat org-ts-regexp-both
3521 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3523 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3524 "Regexp matching any timestamp type object.")
3526 (defun org-element-timestamp-parser ()
3527 "Parse time stamp at point, if any.
3529 When at a time stamp, return a list whose car is `timestamp', and
3530 cdr a plist with `:type', `:raw-value', `:year-start',
3531 `:month-start', `:day-start', `:hour-start', `:minute-start',
3532 `:year-end', `:month-end', `:day-end', `:hour-end',
3533 `:minute-end', `:repeater-type', `:repeater-value',
3534 `:repeater-unit', `:warning-type', `:warning-value',
3535 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3536 Otherwise, return nil.
3538 Assume point is at the beginning of the timestamp."
3539 (when (looking-at-p org-element--timestamp-regexp
)
3541 (let* ((begin (point))
3542 (activep (eq (char-after) ?
<))
3545 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3546 (match-string-no-properties 0)))
3547 (date-start (match-string-no-properties 1))
3548 (date-end (match-string 3))
3549 (diaryp (match-beginning 2))
3550 (post-blank (progn (goto-char (match-end 0))
3551 (skip-chars-forward " \t")))
3556 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3558 (cons (string-to-number (match-string 2 date-start
))
3559 (string-to-number (match-string 3 date-start
)))))
3560 (type (cond (diaryp 'diary
)
3561 ((and activep
(or date-end time-range
)) 'active-range
)
3563 ((or date-end time-range
) 'inactive-range
)
3567 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3571 (let ((type (match-string 1 raw-value
)))
3572 (cond ((equal "++" type
) 'catch-up
)
3573 ((equal ".+" type
) 'restart
)
3575 :repeater-value
(string-to-number (match-string 2 raw-value
))
3577 (pcase (string-to-char (match-string 3 raw-value
))
3578 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (_ 'year
)))))
3581 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3583 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3584 :warning-value
(string-to-number (match-string 2 raw-value
))
3586 (pcase (string-to-char (match-string 3 raw-value
))
3587 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (_ 'year
)))))
3588 year-start month-start day-start hour-start minute-start year-end
3589 month-end day-end hour-end minute-end
)
3590 ;; Parse date-start.
3592 (let ((date (org-parse-time-string date-start t
)))
3593 (setq year-start
(nth 5 date
)
3594 month-start
(nth 4 date
)
3595 day-start
(nth 3 date
)
3596 hour-start
(nth 2 date
)
3597 minute-start
(nth 1 date
))))
3598 ;; Compute date-end. It can be provided directly in time-stamp,
3599 ;; or extracted from time range. Otherwise, it defaults to the
3600 ;; same values as date-start.
3602 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3603 (setq year-end
(or (nth 5 date
) year-start
)
3604 month-end
(or (nth 4 date
) month-start
)
3605 day-end
(or (nth 3 date
) day-start
)
3606 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3607 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3609 (nconc (list :type type
3610 :raw-value raw-value
3611 :year-start year-start
3612 :month-start month-start
3613 :day-start day-start
3614 :hour-start hour-start
3615 :minute-start minute-start
3617 :month-end month-end
3620 :minute-end minute-end
3623 :post-blank post-blank
)
3627 (defun org-element-timestamp-interpreter (timestamp _
)
3628 "Interpret TIMESTAMP object as Org syntax."
3629 (let* ((repeat-string
3631 (pcase (org-element-property :repeater-type timestamp
)
3632 (`cumulate
"+") (`catch-up
"++") (`restart
".+"))
3633 (let ((val (org-element-property :repeater-value timestamp
)))
3634 (and val
(number-to-string val
)))
3635 (pcase (org-element-property :repeater-unit timestamp
)
3636 (`hour
"h") (`day
"d") (`week
"w") (`month
"m") (`year
"y"))))
3639 (pcase (org-element-property :warning-type timestamp
)
3640 (`first
"--") (`all
"-"))
3641 (let ((val (org-element-property :warning-value timestamp
)))
3642 (and val
(number-to-string val
)))
3643 (pcase (org-element-property :warning-unit timestamp
)
3644 (`hour
"h") (`day
"d") (`week
"w") (`month
"m") (`year
"y"))))
3646 ;; Build an Org timestamp string from TIME. ACTIVEP is
3647 ;; non-nil when time stamp is active. If WITH-TIME-P is
3648 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3649 ;; specify a time range in the timestamp. REPEAT-STRING is
3650 ;; the repeater string, if any.
3651 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3652 (let ((ts (format-time-string
3653 (funcall (if with-time-p
#'cdr
#'car
)
3654 org-time-stamp-formats
)
3656 (when (and hour-end minute-end
)
3657 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3660 (format "\\&-%02d:%02d" hour-end minute-end
)
3662 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3663 (dolist (s (list repeat-string warning-string
))
3664 (when (org-string-nw-p s
)
3665 (setq ts
(concat (substring ts
0 -
1)
3668 (substring ts -
1)))))
3671 (type (org-element-property :type timestamp
)))
3673 ((or `active
`inactive
)
3674 (let* ((minute-start (org-element-property :minute-start timestamp
))
3675 (minute-end (org-element-property :minute-end timestamp
))
3676 (hour-start (org-element-property :hour-start timestamp
))
3677 (hour-end (org-element-property :hour-end timestamp
))
3678 (time-range-p (and hour-start hour-end minute-start minute-end
3679 (or (/= hour-start hour-end
)
3680 (/= minute-start minute-end
)))))
3686 (org-element-property :day-start timestamp
)
3687 (org-element-property :month-start timestamp
)
3688 (org-element-property :year-start timestamp
))
3690 (and hour-start minute-start
)
3691 (and time-range-p hour-end
)
3692 (and time-range-p minute-end
))))
3693 ((or `active-range
`inactive-range
)
3694 (let ((minute-start (org-element-property :minute-start timestamp
))
3695 (minute-end (org-element-property :minute-end timestamp
))
3696 (hour-start (org-element-property :hour-start timestamp
))
3697 (hour-end (org-element-property :hour-end timestamp
)))
3700 build-ts-string
(encode-time
3704 (org-element-property :day-start timestamp
)
3705 (org-element-property :month-start timestamp
)
3706 (org-element-property :year-start timestamp
))
3707 (eq type
'active-range
)
3708 (and hour-start minute-start
))
3710 (funcall build-ts-string
3714 (org-element-property :day-end timestamp
)
3715 (org-element-property :month-end timestamp
)
3716 (org-element-property :year-end timestamp
))
3717 (eq type
'active-range
)
3718 (and hour-end minute-end
)))))
3719 (_ (org-element-property :raw-value timestamp
)))))
3724 (defun org-element-underline-parser ()
3725 "Parse underline object at point, if any.
3727 When at an underline object, return a list whose car is
3728 `underline' and cdr is a plist with `:begin', `:end',
3729 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3730 Otherwise, return nil.
3732 Assume point is at the first underscore marker."
3734 (unless (bolp) (backward-char 1))
3735 (when (looking-at org-emph-re
)
3736 (let ((begin (match-beginning 2))
3737 (contents-begin (match-beginning 4))
3738 (contents-end (match-end 4))
3739 (post-blank (progn (goto-char (match-end 2))
3740 (skip-chars-forward " \t")))
3745 :contents-begin contents-begin
3746 :contents-end contents-end
3747 :post-blank post-blank
))))))
3749 (defun org-element-underline-interpreter (_ contents
)
3750 "Interpret underline object as Org syntax.
3751 CONTENTS is the contents of the object."
3752 (format "_%s_" contents
))
3757 (defun org-element-verbatim-parser ()
3758 "Parse verbatim object at point, if any.
3760 When at a verbatim object, return a list whose car is `verbatim'
3761 and cdr is a plist with `:value', `:begin', `:end' and
3762 `:post-blank' keywords. Otherwise, return nil.
3764 Assume point is at the first equal sign marker."
3766 (unless (bolp) (backward-char 1))
3767 (when (looking-at org-emph-re
)
3768 (let ((begin (match-beginning 2))
3769 (value (match-string-no-properties 4))
3770 (post-blank (progn (goto-char (match-end 2))
3771 (skip-chars-forward " \t")))
3777 :post-blank post-blank
))))))
3779 (defun org-element-verbatim-interpreter (verbatim _
)
3780 "Interpret VERBATIM object as Org syntax."
3781 (format "=%s=" (org-element-property :value verbatim
)))
3785 ;;; Parsing Element Starting At Point
3787 ;; `org-element--current-element' is the core function of this section.
3788 ;; It returns the Lisp representation of the element starting at
3791 ;; `org-element--current-element' makes use of special modes. They
3792 ;; are activated for fixed element chaining (e.g., `plain-list' >
3793 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3794 ;; `section'). Special modes are: `first-section', `item',
3795 ;; `node-property', `section' and `table-row'.
3797 (defun org-element--current-element (limit &optional granularity mode structure
)
3798 "Parse the element starting at point.
3800 Return value is a list like (TYPE PROPS) where TYPE is the type
3801 of the element and PROPS a plist of properties associated to the
3804 Possible types are defined in `org-element-all-elements'.
3806 LIMIT bounds the search.
3808 Optional argument GRANULARITY determines the depth of the
3809 recursion. Allowed values are `headline', `greater-element',
3810 `element', `object' or nil. When it is broader than `object' (or
3811 nil), secondary values will not be parsed, since they only
3814 Optional argument MODE, when non-nil, can be either
3815 `first-section', `section', `planning', `item', `node-property'
3818 If STRUCTURE isn't provided but MODE is set to `item', it will be
3821 This function assumes point is always at the beginning of the
3822 element it has to parse."
3824 (let ((case-fold-search t
)
3825 ;; Determine if parsing depth allows for secondary strings
3826 ;; parsing. It only applies to elements referenced in
3827 ;; `org-element-secondary-value-alist'.
3828 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3832 (org-element-item-parser limit structure raw-secondary-p
))
3834 ((eq mode
'table-row
) (org-element-table-row-parser limit
))
3836 ((eq mode
'node-property
) (org-element-node-property-parser limit
))
3838 ((org-with-limited-levels (org-at-heading-p))
3839 (org-element-headline-parser limit raw-secondary-p
))
3840 ;; Sections (must be checked after headline).
3841 ((eq mode
'section
) (org-element-section-parser limit
))
3842 ((eq mode
'first-section
)
3843 (org-element-section-parser
3844 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3847 ((and (eq mode
'planning
)
3848 (eq ?
* (char-after (line-beginning-position 0)))
3849 (looking-at org-planning-line-re
))
3850 (org-element-planning-parser limit
))
3852 ((and (memq mode
'(planning property-drawer
))
3853 (eq ?
* (char-after (line-beginning-position
3854 (if (eq mode
'planning
) 0 -
1))))
3855 (looking-at org-property-drawer-re
))
3856 (org-element-property-drawer-parser limit
))
3857 ;; When not at bol, point is at the beginning of an item or
3858 ;; a footnote definition: next item is always a paragraph.
3859 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3861 ((looking-at org-clock-line-re
) (org-element-clock-parser limit
))
3864 (org-element-inlinetask-parser limit raw-secondary-p
))
3865 ;; From there, elements can have affiliated keywords.
3866 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3868 ;; Jumping over affiliated keywords put point off-limits.
3869 ;; Parse them as regular keywords.
3870 ((and (cdr affiliated
) (>= (point) limit
))
3871 (goto-char (car affiliated
))
3872 (org-element-keyword-parser limit nil
))
3873 ;; LaTeX Environment.
3874 ((looking-at org-element--latex-begin-environment
)
3875 (org-element-latex-environment-parser limit affiliated
))
3876 ;; Drawer and Property Drawer.
3877 ((looking-at org-drawer-regexp
)
3878 (org-element-drawer-parser limit affiliated
))
3880 ((looking-at "[ \t]*:\\( \\|$\\)")
3881 (org-element-fixed-width-parser limit affiliated
))
3882 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3884 ((looking-at "[ \t]*#")
3885 (goto-char (match-end 0))
3887 ((looking-at "\\(?: \\|$\\)")
3889 (org-element-comment-parser limit affiliated
))
3890 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3892 (funcall (pcase (upcase (match-string 1))
3893 ("CENTER" #'org-element-center-block-parser
)
3894 ("COMMENT" #'org-element-comment-block-parser
)
3895 ("EXAMPLE" #'org-element-example-block-parser
)
3896 ("EXPORT" #'org-element-export-block-parser
)
3897 ("QUOTE" #'org-element-quote-block-parser
)
3898 ("SRC" #'org-element-src-block-parser
)
3899 ("VERSE" #'org-element-verse-block-parser
)
3900 (_ #'org-element-special-block-parser
))
3903 ((looking-at "\\+CALL:")
3905 (org-element-babel-call-parser limit affiliated
))
3906 ((looking-at "\\+BEGIN:? ")
3908 (org-element-dynamic-block-parser limit affiliated
))
3909 ((looking-at "\\+\\S-+:")
3911 (org-element-keyword-parser limit affiliated
))
3914 (org-element-paragraph-parser limit affiliated
))))
3915 ;; Footnote Definition.
3916 ((looking-at org-footnote-definition-re
)
3917 (org-element-footnote-definition-parser limit affiliated
))
3919 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3920 (org-element-horizontal-rule-parser limit affiliated
))
3923 (org-element-diary-sexp-parser limit affiliated
))
3925 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3926 (org-element-table-parser limit affiliated
))
3928 ((looking-at (org-item-re))
3929 (org-element-plain-list-parser
3931 (or structure
(org-element--list-struct limit
))))
3932 ;; Default element: Paragraph.
3933 (t (org-element-paragraph-parser limit affiliated
)))))))))
3936 ;; Most elements can have affiliated keywords. When looking for an
3937 ;; element beginning, we want to move before them, as they belong to
3938 ;; that element, and, in the meantime, collect information they give
3939 ;; into appropriate properties. Hence the following function.
3941 (defun org-element--collect-affiliated-keywords (limit)
3942 "Collect affiliated keywords from point down to LIMIT.
3944 Return a list whose CAR is the position at the first of them and
3945 CDR a plist of keywords and values and move point to the
3946 beginning of the first line after them.
3948 As a special case, if element doesn't start at the beginning of
3949 the line (e.g., a paragraph starting an item), CAR is current
3950 position of point and CDR is nil."
3951 (if (not (bolp)) (list (point))
3952 (let ((case-fold-search t
)
3954 ;; RESTRICT is the list of objects allowed in parsed
3956 (restrict (org-element-restriction 'keyword
))
3958 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3959 (let* ((raw-kwd (upcase (match-string 1)))
3960 ;; Apply translation to RAW-KWD. From there, KWD is
3961 ;; the official keyword.
3962 (kwd (or (cdr (assoc raw-kwd
3963 org-element-keyword-translation-alist
))
3965 ;; Find main value for any keyword.
3969 (buffer-substring-no-properties
3970 (match-end 0) (line-end-position)))))
3971 ;; PARSEDP is non-nil when keyword should have its
3973 (parsedp (member kwd org-element-parsed-keywords
))
3974 ;; If KWD is a dual keyword, find its secondary
3975 ;; value. Maybe parse it.
3976 (dualp (member kwd org-element-dual-keywords
))
3979 (let ((sec (match-string-no-properties 2)))
3980 (if (or (not sec
) (not parsedp
)) sec
3982 (org-element--parse-objects
3983 (match-beginning 2) (match-end 2) nil restrict
))))))
3984 ;; Attribute a property name to KWD.
3985 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3986 ;; Now set final shape for VALUE.
3989 (org-element--parse-objects
3991 (progn (end-of-line) (skip-chars-backward " \t") (point))
3994 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3995 (when (or (member kwd org-element-multiple-keywords
)
3996 ;; Attributes can always appear on multiple lines.
3997 (string-match "^ATTR_" kwd
))
3998 (setq value
(cons value
(plist-get output kwd-sym
))))
3999 ;; Eventually store the new value in OUTPUT.
4000 (setq output
(plist-put output kwd-sym value
))
4001 ;; Move to next keyword.
4003 ;; If affiliated keywords are orphaned: move back to first one.
4004 ;; They will be parsed as a paragraph.
4005 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
4007 (cons origin output
))))
4013 ;; The two major functions here are `org-element-parse-buffer', which
4014 ;; parses Org syntax inside the current buffer, taking into account
4015 ;; region, narrowing, or even visibility if specified, and
4016 ;; `org-element-parse-secondary-string', which parses objects within
4019 ;; The (almost) almighty `org-element-map' allows applying a function
4020 ;; on elements or objects matching some type, and accumulating the
4021 ;; resulting values. In an export situation, it also skips unneeded
4022 ;; parts of the parse tree.
4024 (defun org-element-parse-buffer (&optional granularity visible-only
)
4025 "Recursively parse the buffer and return structure.
4026 If narrowing is in effect, only parse the visible part of the
4029 Optional argument GRANULARITY determines the depth of the
4030 recursion. It can be set to the following symbols:
4032 `headline' Only parse headlines.
4033 `greater-element' Don't recurse into greater elements excepted
4034 headlines and sections. Thus, elements
4035 parsed are the top-level ones.
4036 `element' Parse everything but objects and plain text.
4037 `object' Parse the complete buffer (default).
4039 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4042 An element or an objects is represented as a list with the
4043 pattern (TYPE PROPERTIES CONTENTS), where :
4045 TYPE is a symbol describing the element or object. See
4046 `org-element-all-elements' and `org-element-all-objects' for an
4047 exhaustive list of such symbols. One can retrieve it with
4048 `org-element-type' function.
4050 PROPERTIES is the list of attributes attached to the element or
4051 object, as a plist. Although most of them are specific to the
4052 element or object type, all types share `:begin', `:end',
4053 `:post-blank' and `:parent' properties, which respectively
4054 refer to buffer position where the element or object starts,
4055 ends, the number of white spaces or blank lines after it, and
4056 the element or object containing it. Properties values can be
4057 obtained by using `org-element-property' function.
4059 CONTENTS is a list of elements, objects or raw strings
4060 contained in the current element or object, when applicable.
4061 One can access them with `org-element-contents' function.
4063 The Org buffer has `org-data' as type and nil as properties.
4064 `org-element-map' function can be used to find specific elements
4065 or objects within the parse tree.
4067 This function assumes that current major mode is `org-mode'."
4069 (goto-char (point-min))
4070 (org-skip-whitespace)
4071 (org-element--parse-elements
4072 (point-at-bol) (point-max)
4073 ;; Start in `first-section' mode so text before the first
4074 ;; headline belongs to a section.
4075 'first-section nil granularity visible-only
(list 'org-data nil
))))
4077 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
4078 "Recursively parse objects in STRING and return structure.
4080 RESTRICTION is a symbol limiting the object types that will be
4083 Optional argument PARENT, when non-nil, is the element or object
4084 containing the secondary string. It is used to set correctly
4085 `:parent' property within the string.
4087 If STRING is the empty string or nil, return nil."
4090 ((equal string
"") nil
)
4091 (t (let ((local-variables (buffer-local-variables)))
4093 (dolist (v local-variables
)
4095 (if (symbolp v
) (makunbound v
)
4096 (set (make-local-variable (car v
)) (cdr v
)))))
4098 (restore-buffer-modified-p nil
)
4099 (org-element--parse-objects
4100 (point-min) (point-max) nil restriction parent
))))))
4102 (defun org-element-map
4103 (data types fun
&optional info first-match no-recursion with-affiliated
)
4104 "Map a function on selected elements or objects.
4106 DATA is a parse tree, an element, an object, a string, or a list
4107 of such constructs. TYPES is a symbol or list of symbols of
4108 elements or objects types (see `org-element-all-elements' and
4109 `org-element-all-objects' for a complete list of types). FUN is
4110 the function called on the matching element or object. It has to
4111 accept one argument: the element or object itself.
4113 When optional argument INFO is non-nil, it should be a plist
4114 holding export options. In that case, parts of the parse tree
4115 not exportable according to that property list will be skipped.
4117 When optional argument FIRST-MATCH is non-nil, stop at the first
4118 match for which FUN doesn't return nil, and return that value.
4120 Optional argument NO-RECURSION is a symbol or a list of symbols
4121 representing elements or objects types. `org-element-map' won't
4122 enter any recursive element or object whose type belongs to that
4123 list. Though, FUN can still be applied on them.
4125 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4126 apply to matching objects within parsed affiliated keywords (see
4127 `org-element-parsed-keywords').
4129 Nil values returned from FUN do not appear in the results.
4135 Assuming TREE is a variable containing an Org buffer parse tree,
4136 the following example will return a flat list of all `src-block'
4137 and `example-block' elements in it:
4139 (org-element-map tree \\='(example-block src-block) #\\='identity)
4141 The following snippet will find the first headline with a level
4142 of 1 and a \"phone\" tag, and will return its beginning position:
4144 (org-element-map tree \\='headline
4146 (and (= (org-element-property :level hl) 1)
4147 (member \"phone\" (org-element-property :tags hl))
4148 (org-element-property :begin hl)))
4151 The next example will return a flat list of all `plain-list' type
4152 elements in TREE that are not a sub-list themselves:
4154 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4156 Eventually, this example will return a flat list of all `bold'
4157 type objects containing a `latex-snippet' type object, even
4158 looking into captions:
4160 (org-element-map tree \\='bold
4162 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4164 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4165 (let* ((types (if (listp types
) types
(list types
)))
4166 (no-recursion (if (listp no-recursion
) no-recursion
4167 (list no-recursion
)))
4168 ;; Recursion depth is determined by --CATEGORY.
4171 (let ((category 'greater-elements
)
4172 (all-objects (cons 'plain-text org-element-all-objects
)))
4173 (dolist (type types category
)
4174 (cond ((memq type all-objects
)
4175 ;; If one object is found, the function has
4176 ;; to recurse into every object.
4177 (throw :--found
'objects
))
4178 ((not (memq type org-element-greater-elements
))
4179 ;; If one regular element is found, the
4180 ;; function has to recurse, at least, into
4181 ;; every element it encounters.
4182 (and (not (eq category
'elements
))
4183 (setq category
'elements
))))))))
4185 (letrec ((--walk-tree
4187 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4188 ;; holding contextual information.
4189 (let ((--type (org-element-type --data
)))
4192 ;; Ignored element in an export context.
4193 ((and info
(memq --data
(plist-get info
:ignore-list
))))
4194 ;; List of elements or objects.
4195 ((not --type
) (mapc --walk-tree --data
))
4196 ;; Unconditionally enter parse trees.
4197 ((eq --type
'org-data
)
4198 (mapc --walk-tree
(org-element-contents --data
)))
4200 ;; Check if TYPE is matching among TYPES. If so,
4201 ;; apply FUN to --DATA and accumulate return value
4202 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4203 (when (memq --type types
)
4204 (let ((result (funcall fun --data
)))
4205 (cond ((not result
))
4206 (first-match (throw :--map-first-match result
))
4207 (t (push result --acc
)))))
4208 ;; If --DATA has a secondary string that can contain
4209 ;; objects with their type among TYPES, look inside.
4210 (when (and (eq --category
'objects
) (not (stringp --data
)))
4211 (dolist (p (cdr (assq --type
4212 org-element-secondary-value-alist
)))
4213 (funcall --walk-tree
(org-element-property p --data
))))
4214 ;; If --DATA has any parsed affiliated keywords and
4215 ;; WITH-AFFILIATED is non-nil, look for objects in
4217 (when (and with-affiliated
4218 (eq --category
'objects
)
4219 (eq (org-element-class --data
) 'element
))
4220 (dolist (kwd-pair org-element--parsed-properties-alist
)
4221 (let ((kwd (car kwd-pair
))
4222 (value (org-element-property (cdr kwd-pair
) --data
)))
4223 ;; Pay attention to the type of parsed
4224 ;; keyword. In particular, preserve order for
4225 ;; multiple keywords.
4228 ((member kwd org-element-dual-keywords
)
4229 (if (member kwd org-element-multiple-keywords
)
4230 (dolist (line (reverse value
))
4231 (funcall --walk-tree
(cdr line
))
4232 (funcall --walk-tree
(car line
)))
4233 (funcall --walk-tree
(cdr value
))
4234 (funcall --walk-tree
(car value
))))
4235 ((member kwd org-element-multiple-keywords
)
4236 (mapc --walk-tree
(reverse value
)))
4237 (t (funcall --walk-tree value
))))))
4238 ;; Determine if a recursion into --DATA is possible.
4240 ;; --TYPE is explicitly removed from recursion.
4241 ((memq --type no-recursion
))
4242 ;; --DATA has no contents.
4243 ((not (org-element-contents --data
)))
4244 ;; Looking for greater elements but --DATA is
4245 ;; simply an element or an object.
4246 ((and (eq --category
'greater-elements
)
4247 (not (memq --type org-element-greater-elements
))))
4248 ;; Looking for elements but --DATA is an object.
4249 ((and (eq --category
'elements
)
4250 (eq (org-element-class --data
) 'object
)))
4251 ;; In any other case, map contents.
4252 (t (mapc --walk-tree
(org-element-contents --data
))))))))))
4253 (catch :--map-first-match
4254 (funcall --walk-tree data
)
4255 ;; Return value in a proper order.
4256 (nreverse --acc
)))))
4257 (put 'org-element-map
'lisp-indent-function
2)
4259 ;; The following functions are internal parts of the parser.
4261 ;; The first one, `org-element--parse-elements' acts at the element's
4264 ;; The second one, `org-element--parse-objects' applies on all objects
4265 ;; of a paragraph or a secondary string. It calls
4266 ;; `org-element--object-lex' to find the next object in the current
4269 (defsubst org-element--next-mode
(type parentp
)
4270 "Return next special mode according to TYPE, or nil.
4271 TYPE is a symbol representing the type of an element or object
4272 containing next element if PARENTP is non-nil, or before it
4273 otherwise. Modes can be either `first-section', `item',
4274 `node-property', `planning', `property-drawer', `section',
4275 `table-row' or nil."
4278 (`headline
'section
)
4279 (`inlinetask
'planning
)
4281 (`property-drawer
'node-property
)
4282 (`section
'planning
)
4283 (`table
'table-row
))
4286 (`node-property
'node-property
)
4287 (`planning
'property-drawer
)
4288 (`table-row
'table-row
))))
4290 (defun org-element--parse-elements
4291 (beg end mode structure granularity visible-only acc
)
4292 "Parse elements between BEG and END positions.
4294 MODE prioritizes some elements over the others. It can be set to
4295 `first-section', `section', `planning', `item', `node-property'
4298 When value is `item', STRUCTURE will be used as the current list
4301 GRANULARITY determines the depth of the recursion. See
4302 `org-element-parse-buffer' for more information.
4304 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4307 Elements are accumulated into ACC."
4310 ;; Visible only: skip invisible parts at the beginning of the
4312 (when (and visible-only
(org-invisible-p2))
4313 (goto-char (min (1+ (org-find-visible)) end
)))
4314 ;; When parsing only headlines, skip any text before first one.
4315 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4316 (org-with-limited-levels (outline-next-heading)))
4318 (while (< (point) end
)
4319 ;; Find current element's type and parse it accordingly to
4321 (let* ((element (org-element--current-element
4322 end granularity mode structure
))
4323 (type (org-element-type element
))
4324 (cbeg (org-element-property :contents-begin element
)))
4325 (goto-char (org-element-property :end element
))
4326 ;; Visible only: skip invisible parts between siblings.
4327 (when (and visible-only
(org-invisible-p2))
4328 (goto-char (min (1+ (org-find-visible)) end
)))
4329 ;; Fill ELEMENT contents by side-effect.
4331 ;; If element has no contents, don't modify it.
4333 ;; Greater element: parse it between `contents-begin' and
4334 ;; `contents-end'. Make sure GRANULARITY allows the
4335 ;; recursion, or ELEMENT is a headline, in which case going
4336 ;; inside is mandatory, in order to get sub-level headings.
4337 ((and (memq type org-element-greater-elements
)
4338 (or (memq granularity
'(element object nil
))
4339 (and (eq granularity
'greater-element
)
4341 (eq type
'headline
)))
4342 (org-element--parse-elements
4343 cbeg
(org-element-property :contents-end element
)
4344 ;; Possibly switch to a special mode.
4345 (org-element--next-mode type t
)
4346 (and (memq type
'(item plain-list
))
4347 (org-element-property :structure element
))
4348 granularity visible-only element
))
4349 ;; ELEMENT has contents. Parse objects inside, if
4350 ;; GRANULARITY allows it.
4351 ((memq granularity
'(object nil
))
4352 (org-element--parse-objects
4353 cbeg
(org-element-property :contents-end element
) element
4354 (org-element-restriction type
))))
4355 (push (org-element-put-property element
:parent acc
) elements
)
4357 (setq mode
(org-element--next-mode type nil
))))
4359 (apply #'org-element-set-contents acc
(nreverse elements
)))))
4361 (defun org-element--object-lex (restriction)
4362 "Return next object in current buffer or nil.
4363 RESTRICTION is a list of object types, as symbols, that should be
4364 looked after. This function assumes that the buffer is narrowed
4365 to an appropriate container (e.g., a paragraph)."
4366 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4367 (let* ((start (point))
4370 (cond ((not org-target-link-regexp
) nil
)
4371 ((not (memq 'link restriction
)) nil
)
4373 (unless (bolp) (forward-char -
1))
4374 (not (re-search-forward org-target-link-regexp nil t
)))
4376 ;; Since we moved backward, we do not want to
4377 ;; match again an hypothetical 1-character long
4378 ;; radio link before us. Realizing that this can
4379 ;; only happen if such a radio link starts at
4380 ;; beginning of line, we prevent this here.
4381 ((and (= start
(1+ (line-beginning-position)))
4382 (= start
(match-end 1)))
4383 (and (re-search-forward org-target-link-regexp nil t
)
4384 (match-beginning 1)))
4385 (t (match-beginning 1)))))
4388 (while (and (not found
)
4389 (re-search-forward org-element--object-regexp limit
'move
))
4390 (goto-char (match-beginning 0))
4391 (let ((result (match-string 0)))
4394 ((string-prefix-p "call_" result t
)
4395 (and (memq 'inline-babel-call restriction
)
4396 (org-element-inline-babel-call-parser)))
4397 ((string-prefix-p "src_" result t
)
4398 (and (memq 'inline-src-block restriction
)
4399 (org-element-inline-src-block-parser)))
4402 (?^
(and (memq 'superscript restriction
)
4403 (org-element-superscript-parser)))
4404 (?_
(or (and (memq 'subscript restriction
)
4405 (org-element-subscript-parser))
4406 (and (memq 'underline restriction
)
4407 (org-element-underline-parser))))
4408 (?
* (and (memq 'bold restriction
)
4409 (org-element-bold-parser)))
4410 (?
/ (and (memq 'italic restriction
)
4411 (org-element-italic-parser)))
4412 (?~
(and (memq 'code restriction
)
4413 (org-element-code-parser)))
4414 (?
= (and (memq 'verbatim restriction
)
4415 (org-element-verbatim-parser)))
4416 (?
+ (and (memq 'strike-through restriction
)
4417 (org-element-strike-through-parser)))
4418 (?
@ (and (memq 'export-snippet restriction
)
4419 (org-element-export-snippet-parser)))
4420 (?
{ (and (memq 'macro restriction
)
4421 (org-element-macro-parser)))
4422 (?$
(and (memq 'latex-fragment restriction
)
4423 (org-element-latex-fragment-parser)))
4425 (if (eq (aref result
1) ?
<)
4426 (or (and (memq 'radio-target restriction
)
4427 (org-element-radio-target-parser))
4428 (and (memq 'target restriction
)
4429 (org-element-target-parser)))
4430 (or (and (memq 'timestamp restriction
)
4431 (org-element-timestamp-parser))
4432 (and (or (memq 'link restriction
)
4433 (memq 'simple-link restriction
))
4434 (org-element-link-parser)))))
4436 (if (eq (aref result
1) ?
\\)
4437 (and (memq 'line-break restriction
)
4438 (org-element-line-break-parser))
4439 (or (and (memq 'entity restriction
)
4440 (org-element-entity-parser))
4441 (and (memq 'latex-fragment restriction
)
4442 (org-element-latex-fragment-parser)))))
4444 (if (eq (aref result
1) ?\
[)
4445 (and (memq 'link restriction
)
4446 (org-element-link-parser))
4447 (or (and (memq 'footnote-reference restriction
)
4448 (org-element-footnote-reference-parser))
4449 (and (memq 'timestamp restriction
)
4450 (org-element-timestamp-parser))
4451 (and (memq 'statistics-cookie restriction
)
4452 (org-element-statistics-cookie-parser)))))
4453 ;; This is probably a plain link.
4454 (_ (and (or (memq 'link restriction
)
4455 (memq 'simple-link restriction
))
4456 (org-element-link-parser)))))))
4457 (or (eobp) (forward-char))))
4459 (limit (org-element-link-parser)) ;radio link
4462 (defun org-element--parse-objects (beg end acc restriction
&optional parent
)
4463 "Parse objects between BEG and END and return recursive structure.
4465 Objects are accumulated in ACC. RESTRICTION is a list of object
4466 successors which are allowed in the current object.
4468 ACC becomes the parent for all parsed objects. However, if ACC
4469 is nil (i.e., a secondary string is being parsed) and optional
4470 argument PARENT is non-nil, use it as the parent for all objects.
4471 Eventually, if both ACC and PARENT are nil, the common parent is
4472 the list of objects itself."
4475 (narrow-to-region beg end
)
4476 (goto-char (point-min))
4477 (let (next-object contents
)
4478 (while (and (not (eobp))
4479 (setq next-object
(org-element--object-lex restriction
)))
4480 ;; Text before any object.
4481 (let ((obj-beg (org-element-property :begin next-object
)))
4482 (unless (= (point) obj-beg
)
4483 (let ((text (buffer-substring-no-properties (point) obj-beg
)))
4484 (push (if acc
(org-element-put-property text
:parent acc
) text
)
4487 (let ((obj-end (org-element-property :end next-object
))
4488 (cont-beg (org-element-property :contents-begin next-object
)))
4489 (when acc
(org-element-put-property next-object
:parent acc
))
4491 ;; Fill contents of NEXT-OBJECT if possible.
4492 (org-element--parse-objects
4494 (org-element-property :contents-end next-object
)
4496 (org-element-restriction next-object
))
4499 (goto-char obj-end
)))
4500 ;; Text after last object.
4502 (let ((text (buffer-substring-no-properties (point) end
)))
4503 (push (if acc
(org-element-put-property text
:parent acc
) text
)
4505 ;; Result. Set appropriate parent.
4506 (if acc
(apply #'org-element-set-contents acc
(nreverse contents
))
4507 (let* ((contents (nreverse contents
))
4508 (parent (or parent contents
)))
4509 (dolist (datum contents contents
)
4510 (org-element-put-property datum
:parent parent
))))))))
4514 ;;; Towards A Bijective Process
4516 ;; The parse tree obtained with `org-element-parse-buffer' is really
4517 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4518 ;; interpreted and expanded into a string with canonical Org syntax.
4519 ;; Hence `org-element-interpret-data'.
4521 ;; The function relies internally on
4522 ;; `org-element--interpret-affiliated-keywords'.
4525 (defun org-element-interpret-data (data)
4526 "Interpret DATA as Org syntax.
4527 DATA is a parse tree, an element, an object or a secondary string
4528 to interpret. Return Org syntax as a string."
4530 (lambda (data parent
)
4531 (let* ((type (org-element-type data
))
4532 ;; Find interpreter for current object or
4533 ;; element. If it doesn't exist (e.g. this is
4534 ;; a pseudo object or element), return contents,
4538 (format "org-element-%s-interpreter" type
))))
4539 (if (fboundp fun
) fun
(lambda (_ contents
) contents
))))
4542 ;; Secondary string.
4544 (mapconcat (lambda (obj) (funcall fun obj parent
))
4547 ;; Full Org document.
4548 ((eq type
'org-data
)
4549 (mapconcat (lambda (obj) (funcall fun obj parent
))
4550 (org-element-contents data
)
4552 ;; Plain text: return it.
4553 ((stringp data
) data
)
4554 ;; Element or object without contents.
4555 ((not (org-element-contents data
))
4556 (funcall interpret data nil
))
4557 ;; Element or object with contents.
4562 ;; Recursively interpret contents.
4564 (lambda (datum) (funcall fun datum data
))
4565 (org-element-contents
4566 (if (not (memq type
'(paragraph verse-block
)))
4568 ;; Fix indentation of elements containing
4569 ;; objects. We ignore `table-row'
4570 ;; elements as they are one line long
4572 (org-element-normalize-contents
4574 ;; When normalizing first paragraph of
4575 ;; an item or a footnote-definition,
4576 ;; ignore first line's indentation.
4577 (and (eq type
'paragraph
)
4578 (memq (org-element-type parent
)
4579 '(footnote-definition item
))
4581 (car (org-element-contents parent
)))))))
4583 (if (memq type
'(org-data plain-text nil
)) results
4584 ;; Build white spaces. If no `:post-blank' property
4585 ;; is specified, assume its value is 0.
4586 (let ((blank (or (org-element-property :post-blank data
) 0)))
4587 (if (eq (org-element-class data parent
) 'object
)
4588 (concat results
(make-string blank ?\s
))
4589 (concat (org-element--interpret-affiliated-keywords data
)
4590 (org-element-normalize-string results
)
4591 (make-string blank ?
\n)))))))))
4592 (funcall fun data nil
)))
4594 (defun org-element--interpret-affiliated-keywords (element)
4595 "Return ELEMENT's affiliated keywords as Org syntax.
4596 If there is no affiliated keyword, return the empty string."
4597 (let ((keyword-to-org
4601 (when (member key org-element-dual-keywords
)
4602 (setq dual
(cdr value
) value
(car value
)))
4605 (format "[%s]" (org-element-interpret-data dual
)))
4607 (if (member key org-element-parsed-keywords
)
4608 (org-element-interpret-data value
)
4613 (let ((value (org-element-property prop element
))
4614 (keyword (upcase (substring (symbol-name prop
) 1))))
4616 (if (or (member keyword org-element-multiple-keywords
)
4617 ;; All attribute keywords can have multiple lines.
4618 (string-match "^ATTR_" keyword
))
4619 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4622 (funcall keyword-to-org keyword value
)))))
4623 ;; List all ELEMENT's properties matching an attribute line or an
4624 ;; affiliated keyword, but ignore translated keywords since they
4625 ;; cannot belong to the property list.
4626 (cl-loop for prop in
(nth 1 element
) by
'cddr
4627 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4628 (or (string-match "^ATTR_" keyword
)
4630 (member keyword org-element-affiliated-keywords
)
4632 org-element-keyword-translation-alist
)))))
4636 ;; Because interpretation of the parse tree must return the same
4637 ;; number of blank lines between elements and the same number of white
4638 ;; space after objects, some special care must be given to white
4641 ;; The first function, `org-element-normalize-string', ensures any
4642 ;; string different from the empty string will end with a single
4643 ;; newline character.
4645 ;; The second function, `org-element-normalize-contents', removes
4646 ;; global indentation from the contents of the current element.
4648 (defun org-element-normalize-string (s)
4649 "Ensure string S ends with a single newline character.
4651 If S isn't a string return it unchanged. If S is the empty
4652 string, return it. Otherwise, return a new string with a single
4653 newline character at its end."
4655 ((not (stringp s
)) s
)
4657 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4658 (replace-match "\n" nil nil s
)))))
4660 (defun org-element-normalize-contents (element &optional ignore-first
)
4661 "Normalize plain text in ELEMENT's contents.
4663 ELEMENT must only contain plain text and objects.
4665 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4666 indentation to compute maximal common indentation.
4668 Return the normalized element that is element with global
4669 indentation removed from its contents."
4670 (letrec ((find-min-ind
4671 ;; Return minimal common indentation within BLOB. This is
4672 ;; done by walking recursively BLOB and updating MIN-IND
4673 ;; along the way. FIRST-FLAG is non-nil when the next
4674 ;; object is expected to be a string that doesn't start
4675 ;; with a newline character. It happens for strings at
4676 ;; the beginnings of the contents or right after a line
4678 (lambda (blob first-flag min-ind
)
4679 (dolist (datum (org-element-contents blob
) min-ind
)
4681 (setq first-flag nil
)
4683 ;; Objects cannot start with spaces: in this
4684 ;; case, indentation is 0.
4685 ((not (stringp datum
)) (throw :zero
0))
4687 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum
))
4689 ((equal (match-string 2 datum
) "\n")
4691 (match-beginning 1) (match-end 1) 'org-ind
'empty datum
))
4693 (let ((i (string-width (match-string 1 datum
))))
4695 (match-beginning 1) (match-end 1) 'org-ind i datum
)
4696 (setq min-ind
(min i min-ind
))))))
4700 (while (string-match
4701 "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s
)
4702 (setq s
(match-end 1))
4704 ((equal (match-string 1 datum
) "")
4705 (unless (member (match-string 2 datum
) '("" "\n"))
4707 ((equal (match-string 2 datum
) "\n")
4708 (put-text-property (match-beginning 1) (match-end 1)
4709 'org-ind
'empty datum
))
4711 (let ((i (string-width (match-string 1 datum
))))
4712 (put-text-property (match-beginning 1) (match-end 1)
4714 (setq min-ind
(min i min-ind
))))))))
4715 ((eq (org-element-type datum
) 'line-break
)
4716 (setq first-flag t
))
4717 ((memq (org-element-type datum
) org-element-recursive-objects
)
4719 (funcall find-min-ind datum first-flag min-ind
)))))))
4722 (funcall find-min-ind
4723 element
(not ignore-first
) most-positive-fixnum
))))
4724 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4725 ;; Build ELEMENT back, replacing each string with the same
4726 ;; string minus common indentation.
4729 ;; Return DATUM with all its strings indentation
4730 ;; shortened from MIN-IND white spaces.
4739 (let ((s (point-min)))
4740 (while (setq s
(text-property-not-all
4741 s
(point-max) 'org-ind nil
))
4743 (let ((i (get-text-property s
'org-ind
)))
4744 (delete-region s
(progn
4745 (skip-chars-forward " \t")
4747 (when (integerp i
) (indent-to (- i min-ind
))))))
4749 ((memq (org-element-type object
)
4750 org-element-recursive-objects
)
4751 (funcall build object
))
4753 (org-element-contents datum
)))
4755 (funcall build element
)))))
4761 ;; Implement a caching mechanism for `org-element-at-point' and
4762 ;; `org-element-context', which see.
4764 ;; A single public function is provided: `org-element-cache-reset'.
4766 ;; Cache is enabled by default, but can be disabled globally with
4767 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4768 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4769 ;; can be tweaked to control caching behaviour.
4771 ;; Internally, parsed elements are stored in an AVL tree,
4772 ;; `org-element--cache'. This tree is updated lazily: whenever
4773 ;; a change happens to the buffer, a synchronization request is
4774 ;; registered in `org-element--cache-sync-requests' (see
4775 ;; `org-element--cache-submit-request'). During idle time, requests
4776 ;; are processed by `org-element--cache-sync'. Synchronization also
4777 ;; happens when an element is required from the cache. In this case,
4778 ;; the process stops as soon as the needed element is up-to-date.
4780 ;; A synchronization request can only apply on a synchronized part of
4781 ;; the cache. Therefore, the cache is updated at least to the
4782 ;; location where the new request applies. Thus, requests are ordered
4783 ;; from left to right and all elements starting before the first
4784 ;; request are correct. This property is used by functions like
4785 ;; `org-element--cache-find' to retrieve elements in the part of the
4786 ;; cache that can be trusted.
4788 ;; A request applies to every element, starting from its original
4789 ;; location (or key, see below). When a request is processed, it
4790 ;; moves forward and may collide the next one. In this case, both
4791 ;; requests are merged into a new one that starts from that element.
4792 ;; As a consequence, the whole synchronization complexity does not
4793 ;; depend on the number of pending requests, but on the number of
4794 ;; elements the very first request will be applied on.
4796 ;; Elements cannot be accessed through their beginning position, which
4797 ;; may or may not be up-to-date. Instead, each element in the tree is
4798 ;; associated to a key, obtained with `org-element--cache-key'. This
4799 ;; mechanism is robust enough to preserve total order among elements
4800 ;; even when the tree is only partially synchronized.
4802 ;; Objects contained in an element are stored in a hash table,
4803 ;; `org-element--cache-objects'.
4806 (defvar org-element-use-cache nil
4807 "Non-nil when Org parser should cache its results.
4809 WARNING: for the time being, using cache sometimes triggers
4810 freezes. Therefore, it is disabled by default. Activate it if
4811 you want to help debugging the issue.")
4813 (defvar org-element-cache-sync-idle-time
0.6
4814 "Length, in seconds, of idle time before syncing cache.")
4816 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4817 "Maximum duration, as a time value, for a cache synchronization.
4818 If the synchronization is not over after this delay, the process
4819 pauses and resumes after `org-element-cache-sync-break'
4822 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4823 "Duration, as a time value, of the pause between synchronizations.
4824 See `org-element-cache-sync-duration' for more information.")
4829 (defvar org-element--cache nil
4830 "AVL tree used to cache elements.
4831 Each node of the tree contains an element. Comparison is done
4832 with `org-element--cache-compare'. This cache is used in
4833 `org-element-at-point'.")
4835 (defvar org-element--cache-objects nil
4836 "Hash table used as to cache objects.
4837 Key is an element, as returned by `org-element-at-point', and
4838 value is an alist where each association is:
4840 (PARENT COMPLETEP . OBJECTS)
4842 where PARENT is an element or object, COMPLETEP is a boolean,
4843 non-nil when all direct children of parent are already cached and
4844 OBJECTS is a list of such children, as objects, from farthest to
4847 In the following example, \\alpha, bold object and \\beta are
4848 contained within a paragraph
4852 If the paragraph is completely parsed, OBJECTS-DATA will be
4854 ((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4855 (BOLD-OBJECT t ENTITY-OBJECT))
4857 whereas in a partially parsed paragraph, it could be
4859 ((PARAGRAPH nil ENTITY-OBJECT))
4861 This cache is used in `org-element-context'.")
4863 (defvar org-element--cache-sync-requests nil
4864 "List of pending synchronization requests.
4866 A request is a vector with the following pattern:
4868 \[NEXT BEG END OFFSET PARENT PHASE]
4870 Processing a synchronization request consists of three phases:
4872 0. Delete modified elements,
4873 1. Fill missing area in cache,
4874 2. Shift positions and re-parent elements after the changes.
4876 During phase 0, NEXT is the key of the first element to be
4877 removed, BEG and END is buffer position delimiting the
4878 modifications. Elements starting between them (inclusive) are
4879 removed. So are elements whose parent is removed. PARENT, when
4880 non-nil, is the parent of the first element to be removed.
4882 During phase 1, NEXT is the key of the next known element in
4883 cache and BEG its beginning position. Parse buffer between that
4884 element and the one before it in order to determine the parent of
4885 the next element. Set PARENT to the element containing NEXT.
4887 During phase 2, NEXT is the key of the next element to shift in
4888 the parse tree. All elements starting from this one have their
4889 properties relatives to buffer positions shifted by integer
4890 OFFSET and, if they belong to element PARENT, are adopted by it.
4892 PHASE specifies the phase number, as an integer.")
4894 (defvar org-element--cache-sync-timer nil
4895 "Timer used for cache synchronization.")
4897 (defvar org-element--cache-sync-keys nil
4898 "Hash table used to store keys during synchronization.
4899 See `org-element--cache-key' for more information.")
4901 (defsubst org-element--cache-key
(element)
4902 "Return a unique key for ELEMENT in cache tree.
4904 Keys are used to keep a total order among elements in the cache.
4905 Comparison is done with `org-element--cache-key-less-p'.
4907 When no synchronization is taking place, a key is simply the
4908 beginning position of the element, or that position plus one in
4909 the case of an first item (respectively row) in
4910 a list (respectively a table).
4912 During a synchronization, the key is the one the element had when
4913 the cache was synchronized for the last time. Elements added to
4914 cache during the synchronization get a new key generated with
4915 `org-element--cache-generate-key'.
4917 Such keys are stored in `org-element--cache-sync-keys'. The hash
4918 table is cleared once the synchronization is complete."
4919 (or (gethash element org-element--cache-sync-keys
)
4920 (let* ((begin (org-element-property :begin element
))
4921 ;; Increase beginning position of items (respectively
4922 ;; table rows) by one, so the first item can get
4923 ;; a different key from its parent list (respectively
4925 (key (if (memq (org-element-type element
) '(item table-row
))
4928 (if org-element--cache-sync-requests
4929 (puthash element key org-element--cache-sync-keys
)
4932 (defun org-element--cache-generate-key (lower upper
)
4933 "Generate a key between LOWER and UPPER.
4935 LOWER and UPPER are integers or lists, possibly empty.
4937 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4938 a unique key, as an integer or a list of integers, according to
4939 the following rules:
4941 - LOWER and UPPER are compared level-wise until values differ.
4943 - If, at a given level, LOWER and UPPER differ from more than
4944 2, the new key shares all the levels above with LOWER and
4945 gets a new level. Its value is the mean between LOWER and
4948 (1 2) + (1 4) --> (1 3)
4950 - If LOWER has no value to compare with, it is assumed that its
4951 value is `most-negative-fixnum'. E.g.,
4959 where m is `most-negative-fixnum'. Likewise, if UPPER is
4960 short of levels, the current value is `most-positive-fixnum'.
4962 - If they differ from only one, the new key inherits from
4963 current LOWER level and fork it at the next level. E.g.,
4971 where M is `most-positive-fixnum'.
4973 - If the key is only one level long, it is returned as an
4978 When they are not equals, the function assumes that LOWER is
4979 lesser than UPPER, per `org-element--cache-key-less-p'."
4980 (if (equal lower upper
) lower
4981 (let ((lower (if (integerp lower
) (list lower
) lower
))
4982 (upper (if (integerp upper
) (list upper
) upper
))
4986 (let ((min (or (car lower
) most-negative-fixnum
))
4987 (max (cond (skip-upper most-positive-fixnum
)
4989 (t most-positive-fixnum
))))
4990 (if (< (1+ min
) max
)
4991 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4992 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4993 (when (and (< min max
) (not skip-upper
))
4994 ;; When at a given level, LOWER and UPPER differ from
4995 ;; 1, ignore UPPER altogether. Instead create a key
4996 ;; between LOWER and the greatest key with the same
4997 ;; prefix as LOWER so far.
4998 (setq skip-upper t
))
5000 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
5002 (defsubst org-element--cache-key-less-p
(a b
)
5003 "Non-nil if key A is less than key B.
5004 A and B are either integers or lists of integers, as returned by
5005 `org-element--cache-key'."
5006 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
5007 (if (integerp b
) (< (car a
) b
)
5010 (cond ((car-less-than-car a b
) (throw 'exit t
))
5011 ((car-less-than-car b a
) (throw 'exit nil
))
5012 (t (setq a
(cdr a
) b
(cdr b
)))))
5013 ;; If A is empty, either keys are equal (B is also empty) and
5014 ;; we return nil, or A is lesser than B (B is longer) and we
5015 ;; return a non-nil value.
5017 ;; If A is not empty, B is necessarily empty and A is greater
5018 ;; than B (A is longer). Therefore, return nil.
5019 (and (null a
) b
)))))
5021 (defun org-element--cache-compare (a b
)
5022 "Non-nil when element A is located before element B."
5023 (org-element--cache-key-less-p (org-element--cache-key a
)
5024 (org-element--cache-key b
)))
5026 (defsubst org-element--cache-root
()
5027 "Return root value in cache.
5028 This function assumes `org-element--cache' is a valid AVL tree."
5029 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
5034 (defsubst org-element--cache-active-p
()
5035 "Non-nil when cache is active in current buffer."
5036 (and org-element-use-cache
5038 (derived-mode-p 'org-mode
)))
5040 (defun org-element--cache-find (pos &optional side
)
5041 "Find element in cache starting at POS or before.
5043 POS refers to a buffer position.
5045 When optional argument SIDE is non-nil, the function checks for
5046 elements starting at or past POS instead. If SIDE is `both', the
5047 function returns a cons cell where car is the first element
5048 starting at or before POS and cdr the first element starting
5051 The function can only find elements in the synchronized part of
5053 (let ((limit (and org-element--cache-sync-requests
5054 (aref (car org-element--cache-sync-requests
) 0)))
5055 (node (org-element--cache-root))
5058 (let* ((element (avl-tree--node-data node
))
5059 (begin (org-element-property :begin element
)))
5062 (not (org-element--cache-key-less-p
5063 (org-element--cache-key element
) limit
)))
5064 (setq node
(avl-tree--node-left node
)))
5067 node
(avl-tree--node-left node
)))
5070 node
(avl-tree--node-right node
)))
5071 ;; We found an element in cache starting at POS. If `side'
5072 ;; is `both' we also want the next one in order to generate
5073 ;; a key in-between.
5075 ;; If the element is the first row or item in a table or
5076 ;; a plain list, we always return the table or the plain
5079 ;; In any other case, we return the element found.
5081 (setq lower element
)
5082 (setq node
(avl-tree--node-right node
)))
5083 ((and (memq (org-element-type element
) '(item table-row
))
5084 (let ((parent (org-element-property :parent element
)))
5085 (and (= (org-element-property :begin element
)
5086 (org-element-property :contents-begin parent
))
5095 (`both
(cons lower upper
))
5099 (defun org-element--cache-put (element &optional data
)
5100 "Store ELEMENT in current buffer's cache, if allowed.
5101 When optional argument DATA is non-nil, assume is it object data
5102 relative to ELEMENT and store it in the objects cache."
5103 (cond ((not (org-element--cache-active-p)) nil
)
5105 (when org-element--cache-sync-requests
5106 ;; During synchronization, first build an appropriate key
5107 ;; for the new element so `avl-tree-enter' can insert it at
5108 ;; the right spot in the cache.
5109 (let ((keys (org-element--cache-find
5110 (org-element-property :begin element
) 'both
)))
5112 (org-element--cache-generate-key
5113 (and (car keys
) (org-element--cache-key (car keys
)))
5114 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
5115 (org-element--cache-sync-requests
5116 (aref (car org-element--cache-sync-requests
) 0))))
5117 org-element--cache-sync-keys
)))
5118 (avl-tree-enter org-element--cache element
))
5119 ;; Headlines are not stored in cache, so objects in titles are
5120 ;; not stored either.
5121 ((eq (org-element-type element
) 'headline
) nil
)
5122 (t (puthash element data org-element--cache-objects
))))
5124 (defsubst org-element--cache-remove
(element)
5125 "Remove ELEMENT from cache.
5126 Assume ELEMENT belongs to cache and that a cache is active."
5127 (avl-tree-delete org-element--cache element
)
5128 (remhash element org-element--cache-objects
))
5131 ;;;; Synchronization
5133 (defsubst org-element--cache-set-timer
(buffer)
5134 "Set idle timer for cache synchronization in BUFFER."
5135 (when org-element--cache-sync-timer
5136 (cancel-timer org-element--cache-sync-timer
))
5137 (setq org-element--cache-sync-timer
5138 (run-with-idle-timer
5139 (let ((idle (current-idle-time)))
5140 (if idle
(time-add idle org-element-cache-sync-break
)
5141 org-element-cache-sync-idle-time
))
5143 #'org-element--cache-sync
5146 (defsubst org-element--cache-interrupt-p
(time-limit)
5147 "Non-nil when synchronization process should be interrupted.
5148 TIME-LIMIT is a time value or nil."
5150 (or (input-pending-p)
5151 (time-less-p time-limit
(current-time)))))
5153 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
5154 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5156 Properties containing buffer positions are `:begin', `:end',
5157 `:contents-begin', `:contents-end' and `:structure'. When
5158 optional argument PROPS is a list of keywords, only shift
5159 properties provided in that list.
5161 Properties are modified by side-effect."
5162 (let ((properties (nth 1 element
)))
5163 ;; Shift `:structure' property for the first plain list only: it
5164 ;; is the only one that really matters and it prevents from
5165 ;; shifting it more than once.
5166 (when (and (or (not props
) (memq :structure props
))
5167 (eq (org-element-type element
) 'plain-list
)
5168 (not (eq (org-element-type (plist-get properties
:parent
))
5170 (dolist (item (plist-get properties
:structure
))
5171 (cl-incf (car item
) offset
)
5172 (cl-incf (nth 6 item
) offset
)))
5173 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
5174 (let ((value (and (or (not props
) (memq key props
))
5175 (plist-get properties key
))))
5176 (and value
(plist-put properties key
(+ offset value
)))))))
5178 (defun org-element--cache-sync (buffer &optional threshold future-change
)
5179 "Synchronize cache with recent modification in BUFFER.
5181 When optional argument THRESHOLD is non-nil, do the
5182 synchronization for all elements starting before or at threshold,
5183 then exit. Otherwise, synchronize cache for as long as
5184 `org-element-cache-sync-duration' or until Emacs leaves idle
5187 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5188 not registered yet in the cache are going to happen. It is used
5189 in `org-element--cache-submit-request', where cache is partially
5190 updated before current modification are actually submitted."
5191 (when (buffer-live-p buffer
)
5192 (with-current-buffer buffer
5193 (let ((inhibit-quit t
) request next
)
5194 (when org-element--cache-sync-timer
5195 (cancel-timer org-element--cache-sync-timer
))
5197 (while org-element--cache-sync-requests
5198 (setq request
(car org-element--cache-sync-requests
)
5199 next
(nth 1 org-element--cache-sync-requests
))
5200 (org-element--cache-process-request
5202 (and next
(aref next
0))
5204 (and (not threshold
)
5205 (time-add (current-time)
5206 org-element-cache-sync-duration
))
5208 ;; Request processed. Merge current and next offsets and
5209 ;; transfer ending position.
5211 (cl-incf (aref next
3) (aref request
3))
5212 (aset next
2 (aref request
2)))
5213 (setq org-element--cache-sync-requests
5214 (cdr org-element--cache-sync-requests
))))
5215 ;; If more requests are awaiting, set idle timer accordingly.
5216 ;; Otherwise, reset keys.
5217 (if org-element--cache-sync-requests
5218 (org-element--cache-set-timer buffer
)
5219 (clrhash org-element--cache-sync-keys
))))))
5221 (defun org-element--cache-process-request
5222 (request next threshold time-limit future-change
)
5223 "Process synchronization REQUEST for all entries before NEXT.
5225 REQUEST is a vector, built by `org-element--cache-submit-request'.
5227 NEXT is a cache key, as returned by `org-element--cache-key'.
5229 When non-nil, THRESHOLD is a buffer position. Synchronization
5230 stops as soon as a shifted element begins after it.
5232 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5233 after this time or when Emacs exits idle state.
5235 When non-nil, FUTURE-CHANGE is a buffer position where changes
5236 not registered yet in the cache are going to happen. See
5237 `org-element--cache-submit-request' for more information.
5239 Throw `interrupt' if the process stops before completing the
5242 (when (= (aref request
5) 0)
5245 ;; Delete all elements starting after BEG, but not after buffer
5246 ;; position END or past element with key NEXT. Also delete
5247 ;; elements contained within a previously removed element
5248 ;; (stored in `last-container').
5250 ;; At each iteration, we start again at tree root since
5251 ;; a deletion modifies structure of the balanced tree.
5254 (when (org-element--cache-interrupt-p time-limit
)
5255 (throw 'interrupt nil
))
5256 ;; Find first element in cache with key BEG or after it.
5257 (let ((beg (aref request
0))
5258 (end (aref request
2))
5259 (node (org-element--cache-root))
5260 data data-key last-container
)
5262 (let* ((element (avl-tree--node-data node
))
5263 (key (org-element--cache-key element
)))
5265 ((org-element--cache-key-less-p key beg
)
5266 (setq node
(avl-tree--node-right node
)))
5267 ((org-element--cache-key-less-p beg key
)
5270 node
(avl-tree--node-left node
)))
5271 (t (setq data element
5275 (let ((pos (org-element-property :begin data
)))
5276 (if (if (or (not next
)
5277 (org-element--cache-key-less-p data-key next
))
5281 (while (and up
(not (eq up last-container
)))
5282 (setq up
(org-element-property :parent up
)))
5284 (progn (when (and (not last-container
)
5285 (> (org-element-property :end data
)
5287 (setq last-container data
))
5288 (org-element--cache-remove data
))
5289 (aset request
0 data-key
)
5290 (aset request
1 pos
)
5292 (throw 'end-phase nil
)))
5293 ;; No element starting after modifications left in
5294 ;; cache: further processing is futile.
5295 (throw 'quit t
))))))
5296 (when (= (aref request
5) 1)
5299 ;; Phase 0 left a hole in the cache. Some elements after it
5300 ;; could have parents within. For example, in the following
5310 ;; if we remove a blank line between "item" and "Paragraph1",
5311 ;; everything down to "Paragraph2" is removed from cache. But
5312 ;; the paragraph now belongs to the list, and its `:parent'
5313 ;; property no longer is accurate.
5315 ;; Therefore we need to parse again elements in the hole, or at
5316 ;; least in its last section, so that we can re-parent
5317 ;; subsequent elements, during phase 2.
5319 ;; Note that we only need to get the parent from the first
5320 ;; element in cache after the hole.
5322 ;; When next key is lesser or equal to the current one, delegate
5323 ;; phase 1 processing to next request in order to preserve key
5324 ;; order among requests.
5325 (let ((key (aref request
0)))
5326 (when (and next
(not (org-element--cache-key-less-p key next
)))
5327 (let ((next-request (nth 1 org-element--cache-sync-requests
)))
5328 (aset next-request
0 key
)
5329 (aset next-request
1 (aref request
1))
5330 (aset next-request
5 1))
5332 ;; Next element will start at its beginning position plus
5333 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5334 ;; contains the real beginning position of the first element to
5335 ;; shift and re-parent.
5336 (let ((limit (+ (aref request
1) (aref request
3))))
5337 (cond ((and threshold
(> limit threshold
)) (throw 'interrupt nil
))
5338 ((and future-change
(>= limit future-change
))
5339 ;; Changes are going to happen around this element and
5340 ;; they will trigger another phase 1 request. Skip the
5344 (let ((parent (org-element--parse-to limit t time-limit
)))
5345 (aset request
4 parent
)
5346 (aset request
5 2))))))
5349 ;; Shift all elements starting from key START, but before NEXT, by
5350 ;; OFFSET, and re-parent them when appropriate.
5352 ;; Elements are modified by side-effect so the tree structure
5355 ;; Once THRESHOLD, if any, is reached, or once there is an input
5356 ;; pending, exit. Before leaving, the current synchronization
5357 ;; request is updated.
5358 (let ((start (aref request
0))
5359 (offset (aref request
3))
5360 (parent (aref request
4))
5361 (node (org-element--cache-root))
5365 ;; No re-parenting nor shifting planned: request is over.
5366 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5368 (let* ((data (avl-tree--node-data node
))
5369 (key (org-element--cache-key data
)))
5370 (if (and leftp
(avl-tree--node-left node
)
5371 (not (org-element--cache-key-less-p key start
)))
5372 (progn (push node stack
)
5373 (setq node
(avl-tree--node-left node
)))
5374 (unless (org-element--cache-key-less-p key start
)
5375 ;; We reached NEXT. Request is complete.
5376 (when (equal key next
) (throw 'quit t
))
5377 ;; Handle interruption request. Update current request.
5378 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5379 (aset request
0 key
)
5380 (aset request
4 parent
)
5381 (throw 'interrupt nil
))
5383 (unless (zerop offset
)
5384 (org-element--cache-shift-positions data offset
)
5385 ;; Shift associated objects data, if any.
5386 (dolist (object-data (gethash data org-element--cache-objects
))
5387 (dolist (object (cddr object-data
))
5388 (org-element--cache-shift-positions object offset
))))
5389 (let ((begin (org-element-property :begin data
)))
5390 ;; Update PARENT and re-parent DATA, only when
5391 ;; necessary. Propagate new structures for lists.
5393 (<= (org-element-property :end parent
) begin
))
5394 (setq parent
(org-element-property :parent parent
)))
5395 (cond ((and (not parent
) (zerop offset
)) (throw 'quit nil
))
5397 (let ((p (org-element-property :parent data
)))
5399 (< (org-element-property :begin p
)
5400 (org-element-property :begin parent
)))))
5401 (org-element-put-property data
:parent parent
)
5402 (let ((s (org-element-property :structure parent
)))
5403 (when (and s
(org-element-property :structure data
))
5404 (org-element-put-property data
:structure s
)))))
5405 ;; Cache is up-to-date past THRESHOLD. Request
5407 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5408 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5409 (avl-tree--node-right node
)
5411 ;; We reached end of tree: synchronization complete.
5414 (defun org-element--parse-to (pos &optional syncp time-limit
)
5415 "Parse elements in current section, down to POS.
5417 Start parsing from the closest between the last known element in
5418 cache or headline above. Return the smallest element containing
5421 When optional argument SYNCP is non-nil, return the parent of the
5422 element containing POS instead. In that case, it is also
5423 possible to provide TIME-LIMIT, which is a time value specifying
5424 when the parsing should stop. The function throws `interrupt' if
5425 the process stopped before finding the expected result."
5427 (org-with-wide-buffer
5429 (let* ((cached (and (org-element--cache-active-p)
5430 (org-element--cache-find pos nil
)))
5431 (begin (org-element-property :begin cached
))
5434 ;; Nothing in cache before point: start parsing from first
5435 ;; element following headline above, or first element in
5438 (when (org-with-limited-levels (outline-previous-heading))
5439 (setq mode
'planning
)
5441 (skip-chars-forward " \r\t\n")
5442 (beginning-of-line))
5443 ;; Cache returned exact match: return it.
5445 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5446 ;; There's a headline between cached value and POS: cached
5447 ;; value is invalid. Start parsing from first element
5448 ;; following the headline.
5449 ((re-search-backward
5450 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5452 (skip-chars-forward " \r\t\n")
5454 (setq mode
'planning
))
5455 ;; Check if CACHED or any of its ancestors contain point.
5457 ;; If there is such an element, we inspect it in order to know
5458 ;; if we return it or if we need to parse its contents.
5459 ;; Otherwise, we just start parsing from current location,
5460 ;; which is right after the top-most element containing
5463 ;; As a special case, if POS is at the end of the buffer, we
5464 ;; want to return the innermost element ending there.
5466 ;; Also, if we find an ancestor and discover that we need to
5467 ;; parse its contents, make sure we don't start from
5468 ;; `:contents-begin', as we would otherwise go past CACHED
5469 ;; again. Instead, in that situation, we will resume parsing
5470 ;; from NEXT, which is located after CACHED or its higher
5471 ;; ancestor not containing point.
5474 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5475 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5476 (while (let ((end (org-element-property :end up
)))
5479 (setq up
(org-element-property :parent up
)))))
5481 ((eobp) (setq element up
))
5482 (t (setq element up next
(point)))))))
5483 ;; Parse successively each element until we reach POS.
5484 (let ((end (or (org-element-property :end element
)
5486 (org-with-limited-levels (outline-next-heading))
5491 (cond ((= (point) pos
) (throw 'exit parent
))
5492 ((org-element--cache-interrupt-p time-limit
)
5493 (throw 'interrupt nil
))))
5495 (setq element
(org-element--current-element
5497 (org-element-property :structure parent
)))
5498 (org-element-put-property element
:parent parent
)
5499 (org-element--cache-put element
))
5500 (let ((elem-end (org-element-property :end element
))
5501 (type (org-element-type element
)))
5503 ;; Skip any element ending before point. Also skip
5504 ;; element ending at point (unless it is also the end of
5505 ;; buffer) since we're sure that another element begins
5507 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5508 (goto-char elem-end
)
5509 (setq mode
(org-element--next-mode type nil
)))
5510 ;; A non-greater element contains point: return it.
5511 ((not (memq type org-element-greater-elements
))
5512 (throw 'exit element
))
5513 ;; Otherwise, we have to decide if ELEMENT really
5514 ;; contains POS. In that case we start parsing from
5515 ;; contents' beginning.
5517 ;; If POS is at contents' beginning but it is also at
5518 ;; the beginning of the first item in a list or a table.
5519 ;; In that case, we need to create an anchor for that
5520 ;; list or table, so return it.
5522 ;; Also, if POS is at the end of the buffer, no element
5523 ;; can start after it, but more than one may end there.
5524 ;; Arbitrarily, we choose to return the innermost of
5526 ((let ((cbeg (org-element-property :contents-begin element
))
5527 (cend (org-element-property :contents-end element
)))
5532 (not (memq type
'(plain-list table
)))))
5534 (and (= cend pos
) (= (point-max) pos
)))))
5535 (goto-char (or next cbeg
))
5537 mode
(org-element--next-mode type t
)
5540 ;; Otherwise, return ELEMENT as it is the smallest
5541 ;; element containing POS.
5542 (t (throw 'exit element
))))
5543 (setq element nil
)))))))
5546 ;;;; Staging Buffer Changes
5548 (defconst org-element--cache-sensitive-re
5550 org-outline-regexp-bol
"\\|"
5551 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5553 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5554 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5555 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5557 "Regexp matching a sensitive line, structure wise.
5558 A sensitive line is a headline, inlinetask, block, drawer, or
5559 latex-environment boundary. When such a line is modified,
5560 structure changes in the document may propagate in the whole
5561 section, possibly making cache invalid.")
5563 (defvar org-element--cache-change-warning nil
5564 "Non-nil when a sensitive line is about to be changed.
5565 It is a symbol among nil, t and `headline'.")
5567 (defun org-element--cache-before-change (beg end
)
5568 "Request extension of area going to be modified if needed.
5569 BEG and END are the beginning and end of the range of changed
5570 text. See `before-change-functions' for more information."
5571 (when (org-element--cache-active-p)
5572 (org-with-wide-buffer
5575 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5576 (setq org-element--cache-change-warning
5578 (if (and (org-with-limited-levels (org-at-heading-p))
5579 (= (line-end-position) bottom
))
5581 (let ((case-fold-search t
))
5583 org-element--cache-sensitive-re bottom t
)))))))))
5585 (defun org-element--cache-after-change (beg end pre
)
5586 "Update buffer modifications for current buffer.
5587 BEG and END are the beginning and end of the range of changed
5588 text, and the length in bytes of the pre-change text replaced by
5589 that range. See `after-change-functions' for more information."
5590 (when (org-element--cache-active-p)
5591 (org-with-wide-buffer
5596 (bottom (save-excursion (goto-char end
) (line-end-position))))
5597 ;; Determine if modified area needs to be extended, according
5598 ;; to both previous and current state. We make a special
5599 ;; case for headline editing: if a headline is modified but
5600 ;; not removed, do not extend.
5601 (when (pcase org-element--cache-change-warning
5604 (not (and (org-with-limited-levels (org-at-heading-p))
5605 (= (line-end-position) bottom
))))
5607 (let ((case-fold-search t
))
5609 org-element--cache-sensitive-re bottom t
))))
5610 ;; Effectively extend modified area.
5611 (org-with-limited-levels
5612 (setq top
(progn (goto-char top
)
5613 (when (outline-previous-heading) (forward-line))
5615 (setq bottom
(progn (goto-char bottom
)
5616 (if (outline-next-heading) (1- (point))
5618 ;; Store synchronization request.
5619 (let ((offset (- end beg pre
)))
5620 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5621 ;; Activate a timer to process the request during idle time.
5622 (org-element--cache-set-timer (current-buffer))))
5624 (defun org-element--cache-for-removal (beg end offset
)
5625 "Return first element to remove from cache.
5627 BEG and END are buffer positions delimiting buffer modifications.
5628 OFFSET is the size of the changes.
5630 Returned element is usually the first element in cache containing
5631 any position between BEG and END. As an exception, greater
5632 elements around the changes that are robust to contents
5633 modifications are preserved and updated according to the
5635 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5636 (before (car elements
))
5637 (after (cdr elements
)))
5638 (if (not before
) after
5642 (if (let ((type (org-element-type up
)))
5643 (and (or (memq type
'(center-block dynamic-block quote-block
5645 ;; Drawers named "PROPERTIES" are probably
5646 ;; a properties drawer being edited. Force
5647 ;; parsing to check if editing is over.
5648 (and (eq type
'drawer
)
5650 (org-element-property :drawer-name up
)
5652 (let ((cbeg (org-element-property :contents-begin up
)))
5655 (> (org-element-property :contents-end up
) end
)))))
5656 ;; UP is a robust greater element containing changes.
5657 ;; We only need to extend its ending boundaries.
5658 (org-element--cache-shift-positions
5659 up offset
'(:contents-end
:end
))
5661 (when robust-flag
(setq robust-flag nil
)))
5662 (setq up
(org-element-property :parent up
)))
5663 ;; We're at top level element containing ELEMENT: if it's
5664 ;; altered by buffer modifications, it is first element in
5665 ;; cache to be removed. Otherwise, that first element is the
5668 ;; As a special case, do not remove BEFORE if it is a robust
5669 ;; container for current changes.
5670 (if (or (< (org-element-property :end before
) beg
) robust-flag
) after
5673 (defun org-element--cache-submit-request (beg end offset
)
5674 "Submit a new cache synchronization request for current buffer.
5675 BEG and END are buffer positions delimiting the minimal area
5676 where cache data should be removed. OFFSET is the size of the
5677 change, as an integer."
5678 (let ((next (car org-element--cache-sync-requests
))
5679 delete-to delete-from
)
5681 (zerop (aref next
5))
5682 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5683 (<= (setq delete-from
(aref next
1)) end
))
5684 ;; Current changes can be merged with first sync request: we
5685 ;; can save a partial cache synchronization.
5687 (cl-incf (aref next
3) offset
)
5688 ;; If last change happened within area to be removed, extend
5689 ;; boundaries of robust parents, if any. Otherwise, find
5690 ;; first element to remove and update request accordingly.
5691 (if (> beg delete-from
)
5692 (let ((up (aref next
4)))
5694 (org-element--cache-shift-positions
5695 up offset
'(:contents-end
:end
))
5696 (setq up
(org-element-property :parent up
))))
5697 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5699 (aset next
0 (org-element--cache-key first
))
5700 (aset next
1 (org-element-property :begin first
))
5701 (aset next
4 (org-element-property :parent first
))))))
5702 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5703 ;; if any, is no longer a 0-phase request, thus ensuring that
5704 ;; phases are properly ordered. We need to provide OFFSET as
5705 ;; optional parameter since current modifications are not known
5706 ;; yet to the otherwise correct part of the cache (i.e, before
5707 ;; the first request).
5708 (when next
(org-element--cache-sync (current-buffer) end beg
))
5709 (let ((first (org-element--cache-for-removal beg end offset
)))
5711 (push (let ((beg (org-element-property :begin first
))
5712 (key (org-element--cache-key first
)))
5714 ;; When changes happen before the first known
5715 ;; element, re-parent and shift the rest of the
5717 ((> beg end
) (vector key beg nil offset nil
1))
5718 ;; Otherwise, we find the first non robust
5719 ;; element containing END. All elements between
5720 ;; FIRST and this one are to be removed.
5721 ((let ((first-end (org-element-property :end first
)))
5722 (and (> first-end end
)
5723 (vector key beg first-end offset first
0))))
5725 (let* ((element (org-element--cache-find end
))
5726 (end (org-element-property :end element
))
5728 (while (and (setq up
(org-element-property :parent up
))
5729 (>= (org-element-property :begin up
) beg
))
5730 (setq end
(org-element-property :end up
)
5732 (vector key beg end offset element
0)))))
5733 org-element--cache-sync-requests
)
5734 ;; No element to remove. No need to re-parent either.
5735 ;; Simply shift additional elements, if any, by OFFSET.
5736 (when org-element--cache-sync-requests
5737 (cl-incf (aref (car org-element--cache-sync-requests
) 3)
5741 ;;;; Public Functions
5744 (defun org-element-cache-reset (&optional all
)
5745 "Reset cache in current buffer.
5746 When optional argument ALL is non-nil, reset cache in all Org
5749 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5750 (with-current-buffer buffer
5751 (when (and org-element-use-cache
(derived-mode-p 'org-mode
))
5752 (setq-local org-element--cache
5753 (avl-tree-create #'org-element--cache-compare
))
5754 (setq-local org-element--cache-objects
(make-hash-table :test
#'eq
))
5755 (setq-local org-element--cache-sync-keys
5756 (make-hash-table :weakness
'key
:test
#'eq
))
5757 (setq-local org-element--cache-change-warning nil
)
5758 (setq-local org-element--cache-sync-requests nil
)
5759 (setq-local org-element--cache-sync-timer nil
)
5760 (add-hook 'before-change-functions
5761 #'org-element--cache-before-change nil t
)
5762 (add-hook 'after-change-functions
5763 #'org-element--cache-after-change nil t
)))))
5766 (defun org-element-cache-refresh (pos)
5767 "Refresh cache at position POS."
5768 (when (org-element--cache-active-p)
5769 (org-element--cache-sync (current-buffer) pos
)
5770 (org-element--cache-submit-request pos pos
0)
5771 (org-element--cache-set-timer (current-buffer))))
5777 ;; The first move is to implement a way to obtain the smallest element
5778 ;; containing point. This is the job of `org-element-at-point'. It
5779 ;; basically jumps back to the beginning of section containing point
5780 ;; and proceed, one element after the other, with
5781 ;; `org-element--current-element' until the container is found. Note:
5782 ;; When using `org-element-at-point', secondary values are never
5783 ;; parsed since the function focuses on elements, not on objects.
5785 ;; At a deeper level, `org-element-context' lists all elements and
5786 ;; objects containing point.
5788 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5789 ;; internally by navigation and manipulation tools.
5793 (defun org-element-at-point ()
5794 "Determine closest element around point.
5796 Return value is a list like (TYPE PROPS) where TYPE is the type
5797 of the element and PROPS a plist of properties associated to the
5800 Possible types are defined in `org-element-all-elements'.
5801 Properties depend on element or object type, but always include
5802 `:begin', `:end', `:parent' and `:post-blank' properties.
5804 As a special case, if point is at the very beginning of the first
5805 item in a list or sub-list, returned element will be that list
5806 instead of the item. Likewise, if point is at the beginning of
5807 the first row of a table, returned element will be the table
5808 instead of the first row.
5810 When point is at the end of the buffer, return the innermost
5811 element ending there."
5812 (org-with-wide-buffer
5813 (let ((origin (point)))
5815 (skip-chars-backward " \r\t\n")
5817 ;; Within blank lines at the beginning of buffer, return nil.
5819 ;; Within blank lines right after a headline, return that
5821 ((org-with-limited-levels (org-at-heading-p))
5823 (org-element-headline-parser (point-max) t
))
5824 ;; Otherwise parse until we find element containing ORIGIN.
5826 (when (org-element--cache-active-p)
5827 (if (not org-element--cache
) (org-element-cache-reset)
5828 (org-element--cache-sync (current-buffer) origin
)))
5829 (org-element--parse-to origin
))))))
5832 (defun org-element-context (&optional element
)
5833 "Return smallest element or object around point.
5835 Return value is a list like (TYPE PROPS) where TYPE is the type
5836 of the element or object and PROPS a plist of properties
5839 Possible types are defined in `org-element-all-elements' and
5840 `org-element-all-objects'. Properties depend on element or
5841 object type, but always include `:begin', `:end', `:parent' and
5844 As a special case, if point is right after an object and not at
5845 the beginning of any other object, return that object.
5847 Optional argument ELEMENT, when non-nil, is the closest element
5848 containing point, as returned by `org-element-at-point'.
5849 Providing it allows for quicker computation."
5850 (catch 'objects-forbidden
5851 (org-with-wide-buffer
5852 (let* ((pos (point))
5853 (element (or element
(org-element-at-point)))
5854 (type (org-element-type element
))
5855 (post (org-element-property :post-affiliated element
)))
5856 ;; If point is inside an element containing objects or
5857 ;; a secondary string, narrow buffer to the container and
5858 ;; proceed with parsing. Otherwise, return ELEMENT.
5860 ;; At a parsed affiliated keyword, check if we're inside main
5862 ((and post
(< pos post
))
5864 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5866 ((not (member-ignore-case (match-string 1)
5867 org-element-parsed-keywords
))
5868 (throw 'objects-forbidden element
))
5869 ((< (match-end 0) pos
)
5870 (narrow-to-region (match-end 0) (line-end-position)))
5871 ((and (match-beginning 2)
5872 (>= pos
(match-beginning 2))
5873 (< pos
(match-end 2)))
5874 (narrow-to-region (match-beginning 2) (match-end 2)))
5875 (t (throw 'objects-forbidden element
)))
5876 ;; Also change type to retrieve correct restrictions.
5877 (setq type
'keyword
))
5878 ;; At an item, objects can only be located within tag, if any.
5880 (let ((tag (org-element-property :tag element
)))
5881 (if (or (not tag
) (/= (line-beginning-position) post
))
5882 (throw 'objects-forbidden element
)
5884 (search-forward tag
(line-end-position))
5885 (goto-char (match-beginning 0))
5886 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5887 (narrow-to-region (point) (match-end 0))
5888 (throw 'objects-forbidden element
)))))
5889 ;; At an headline or inlinetask, objects are in title.
5890 ((memq type
'(headline inlinetask
))
5891 (let ((case-fold-search nil
))
5892 (goto-char (org-element-property :begin element
))
5893 (looking-at org-complex-heading-regexp
)
5894 (let ((end (match-end 4)))
5895 (if (not end
) (throw 'objects-forbidden element
)
5896 (goto-char (match-beginning 4))
5897 (when (looking-at org-comment-string
)
5898 (goto-char (match-end 0)))
5899 (if (>= (point) end
) (throw 'objects-forbidden element
)
5900 (narrow-to-region (point) end
))))))
5901 ;; At a paragraph, a table-row or a verse block, objects are
5902 ;; located within their contents.
5903 ((memq type
'(paragraph table-row verse-block
))
5904 (let ((cbeg (org-element-property :contents-begin element
))
5905 (cend (org-element-property :contents-end element
)))
5906 ;; CBEG is nil for table rules.
5907 (if (and cbeg cend
(>= pos cbeg
)
5908 (or (< pos cend
) (and (= pos cend
) (eobp))))
5909 (narrow-to-region cbeg cend
)
5910 (throw 'objects-forbidden element
))))
5911 ;; At a planning line, if point is at a timestamp, return it,
5912 ;; otherwise, return element.
5913 ((eq type
'planning
)
5914 (dolist (p '(:closed
:deadline
:scheduled
))
5915 (let ((timestamp (org-element-property p element
)))
5916 (when (and timestamp
5917 (<= (org-element-property :begin timestamp
) pos
)
5918 (> (org-element-property :end timestamp
) pos
))
5919 (throw 'objects-forbidden timestamp
))))
5920 ;; All other locations cannot contain objects: bail out.
5921 (throw 'objects-forbidden element
))
5922 (t (throw 'objects-forbidden element
)))
5923 (goto-char (point-min))
5924 (let ((restriction (org-element-restriction type
))
5926 (cache (cond ((not (org-element--cache-active-p)) nil
)
5927 (org-element--cache-objects
5928 (gethash element org-element--cache-objects
))
5929 (t (org-element-cache-reset) nil
)))
5930 next object-data last
)
5934 ;; When entering PARENT for the first time, get list
5935 ;; of objects within known so far. Store it in
5938 (let ((data (assq parent cache
)))
5939 (if data
(setq object-data data
)
5940 (push (setq object-data
(list parent nil
)) cache
))))
5941 ;; Find NEXT object for analysis.
5943 ;; If NEXT is non-nil, we already exhausted the
5944 ;; cache so we can parse buffer to find the object
5946 (if next
(setq next
(org-element--object-lex restriction
))
5947 ;; Otherwise, check if cache can help us.
5948 (let ((objects (cddr object-data
))
5949 (completep (nth 1 object-data
)))
5951 ((and (not objects
) completep
) (throw 'exit parent
))
5953 (setq next
(org-element--object-lex restriction
)))
5956 (org-element-property :end
(car objects
))))
5957 (if (>= cache-limit pos
)
5958 ;; Cache contains the information needed.
5959 (dolist (object objects
(throw 'exit parent
))
5960 (when (<= (org-element-property :begin object
)
5962 (if (>= (org-element-property :end object
)
5964 (throw 'found
(setq next object
))
5965 (throw 'exit parent
))))
5966 (goto-char cache-limit
)
5968 (org-element--object-lex restriction
))))))))
5969 ;; If we have a new object to analyze, store it in
5970 ;; cache. Otherwise record that there is nothing
5971 ;; more to parse in this element at this depth.
5973 (progn (org-element-put-property next
:parent parent
)
5974 (push next
(cddr object-data
)))
5975 (setcar (cdr object-data
) t
)))
5976 ;; Process NEXT, if any, in order to know if we need
5977 ;; to skip it, return it or move into it.
5978 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5979 (throw 'exit
(or last parent
))
5980 (let ((end (org-element-property :end next
))
5981 (cbeg (org-element-property :contents-begin next
))
5982 (cend (org-element-property :contents-end next
)))
5984 ;; Skip objects ending before point. Also skip
5985 ;; objects ending at point unless it is also the
5986 ;; end of buffer, since we want to return the
5987 ;; innermost object.
5988 ((and (<= end pos
) (/= (point-max) end
))
5990 ;; For convenience, when object ends at POS,
5991 ;; without any space, store it in LAST, as we
5992 ;; will return it if no object starts here.
5993 (when (and (= end pos
)
5994 (not (memq (char-before) '(?\s ?
\t))))
5996 ;; If POS is within a container object, move
5997 ;; into that object.
6001 ;; At contents' end, if there is no
6002 ;; space before point, also move into
6003 ;; object, for consistency with
6004 ;; convenience feature above.
6006 (or (= (point-max) pos
)
6007 (not (memq (char-before pos
)
6010 (narrow-to-region (point) cend
)
6012 restriction
(org-element-restriction next
)
6015 ;; Otherwise, return NEXT.
6016 (t (throw 'exit next
)))))))
6017 ;; Store results in cache, if applicable.
6018 (org-element--cache-put element cache
)))))))
6020 (defun org-element-lineage (blob &optional types with-self
)
6021 "List all ancestors of a given element or object.
6023 BLOB is an object or element.
6025 When optional argument TYPES is a list of symbols, return the
6026 first element or object in the lineage whose type belongs to that
6029 When optional argument WITH-SELF is non-nil, lineage includes
6030 BLOB itself as the first element, and TYPES, if provided, also
6033 When BLOB is obtained through `org-element-context' or
6034 `org-element-at-point', only ancestors from its section can be
6035 found. There is no such limitation when BLOB belongs to a full
6037 (let ((up (if with-self blob
(org-element-property :parent blob
)))
6039 (while (and up
(not (memq (org-element-type up
) types
)))
6040 (unless types
(push up ancestors
))
6041 (setq up
(org-element-property :parent up
)))
6042 (if types up
(nreverse ancestors
))))
6044 (defun org-element-nested-p (elem-A elem-B
)
6045 "Non-nil when elements ELEM-A and ELEM-B are nested."
6046 (let ((beg-A (org-element-property :begin elem-A
))
6047 (beg-B (org-element-property :begin elem-B
))
6048 (end-A (org-element-property :end elem-A
))
6049 (end-B (org-element-property :end elem-B
)))
6050 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
6051 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
6053 (defun org-element-swap-A-B (elem-A elem-B
)
6054 "Swap elements ELEM-A and ELEM-B.
6055 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
6057 (goto-char (org-element-property :begin elem-A
))
6058 ;; There are two special cases when an element doesn't start at bol:
6059 ;; the first paragraph in an item or in a footnote definition.
6060 (let ((specialp (not (bolp))))
6061 ;; Only a paragraph without any affiliated keyword can be moved at
6062 ;; ELEM-A position in such a situation. Note that the case of
6063 ;; a footnote definition is impossible: it cannot contain two
6064 ;; paragraphs in a row because it cannot contain a blank line.
6066 (or (not (eq (org-element-type elem-B
) 'paragraph
))
6067 (/= (org-element-property :begin elem-B
)
6068 (org-element-property :contents-begin elem-B
))))
6069 (error "Cannot swap elements"))
6070 ;; In a special situation, ELEM-A will have no indentation. We'll
6071 ;; give it ELEM-B's (which will in, in turn, have no indentation).
6072 (let* ((ind-B (when specialp
6073 (goto-char (org-element-property :begin elem-B
))
6074 (org-get-indentation)))
6075 (beg-A (org-element-property :begin elem-A
))
6076 (end-A (save-excursion
6077 (goto-char (org-element-property :end elem-A
))
6078 (skip-chars-backward " \r\t\n")
6080 (beg-B (org-element-property :begin elem-B
))
6081 (end-B (save-excursion
6082 (goto-char (org-element-property :end elem-B
))
6083 (skip-chars-backward " \r\t\n")
6085 ;; Store inner overlays responsible for visibility status.
6086 ;; We also need to store their boundaries as they will be
6087 ;; removed from buffer.
6092 (and (>= (overlay-start o
) beg-A
)
6093 (<= (overlay-end o
) end-A
)
6094 (list o
(overlay-start o
) (overlay-end o
))))
6095 (overlays-in beg-A end-A
)))
6098 (and (>= (overlay-start o
) beg-B
)
6099 (<= (overlay-end o
) end-B
)
6100 (list o
(overlay-start o
) (overlay-end o
))))
6101 (overlays-in beg-B end-B
)))))
6103 (body-A (buffer-substring beg-A end-A
))
6104 (body-B (delete-and-extract-region beg-B end-B
)))
6107 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
6108 (indent-to-column ind-B
))
6110 ;; Restore ex ELEM-A overlays.
6111 (let ((offset (- beg-B beg-A
)))
6112 (dolist (o (car overlays
))
6113 (move-overlay (car o
) (+ (nth 1 o
) offset
) (+ (nth 2 o
) offset
)))
6115 (delete-region beg-A end-A
)
6117 ;; Restore ex ELEM-B overlays.
6118 (dolist (o (cdr overlays
))
6119 (move-overlay (car o
) (- (nth 1 o
) offset
) (- (nth 2 o
) offset
))))
6120 (goto-char (org-element-property :end elem-B
)))))
6123 (provide 'org-element
)
6126 ;; generated-autoload-file: "org-loaddefs.el"
6129 ;;; org-element.el ends here