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 in a link description. Also ignore
356 ;; radio-targets and line breaks.
357 (link bold code entity export-snippet inline-babel-call inline-src-block
358 italic latex-fragment macro statistics-cookie strike-through
359 subscript superscript underline verbatim
)
360 (paragraph ,@standard-set
)
361 ;; Remove any variable object from radio target as it would
362 ;; prevent it from being properly recognized.
363 (radio-target bold code entity italic latex-fragment strike-through
364 subscript superscript underline superscript
)
365 (strike-through ,@standard-set
)
366 (subscript ,@standard-set
)
367 (superscript ,@standard-set
)
368 ;; Ignore inline babel call and inline src block as formulas are
369 ;; possible. Also ignore line breaks and statistics cookies.
370 (table-cell bold code entity export-snippet footnote-reference italic
371 latex-fragment link macro radio-target strike-through
372 subscript superscript target timestamp underline verbatim
)
373 (table-row table-cell
)
374 (underline ,@standard-set
)
375 (verse-block ,@standard-set
)))
376 "Alist of objects restrictions.
378 key is an element or object type containing objects and value is
379 a list of types that can be contained within an element or object
382 For example, in a `radio-target' object, one can only find
383 entities, latex-fragments, subscript, superscript and text
386 This alist also applies to secondary string. For example, an
387 `headline' type element doesn't directly contain objects, but
388 still has an entry since one of its properties (`:title') does.")
390 (defconst org-element-secondary-value-alist
394 "Alist between element types and locations of secondary values.")
396 (defconst org-element--pair-round-table
397 (let ((table (make-syntax-table)))
398 (modify-syntax-entry ?\
( "()" table
)
399 (modify-syntax-entry ?\
) ")(" table
)
400 (dolist (char '(?\
{ ?\
} ?\
[ ?\
] ?\
< ?\
>) table
)
401 (modify-syntax-entry char
" " table
)))
402 "Table used internally to pair only round brackets.
403 Other brackets are treated as spaces.")
405 (defconst org-element--pair-square-table
406 (let ((table (make-syntax-table)))
407 (modify-syntax-entry ?\
[ "(]" table
)
408 (modify-syntax-entry ?\
] ")[" table
)
409 (dolist (char '(?\
{ ?\
} ?\
( ?\
) ?\
< ?\
>) table
)
410 (modify-syntax-entry char
" " table
)))
411 "Table used internally to pair only square brackets.
412 Other brackets are treated as spaces.")
414 (defconst org-element--pair-curly-table
415 (let ((table (make-syntax-table)))
416 (modify-syntax-entry ?\
{ "(}" table
)
417 (modify-syntax-entry ?\
} "){" table
)
418 (dolist (char '(?\
[ ?\
] ?\
( ?\
) ?\
< ?\
>) table
)
419 (modify-syntax-entry char
" " table
)))
420 "Table used internally to pair only curly brackets.
421 Other brackets are treated as spaces.")
423 (defun org-element--parse-paired-brackets (char)
424 "Parse paired brackets at point.
425 CHAR is the opening bracket to consider, as a character. Return
426 contents between brackets, as a string, or nil. Also move point
428 (when (eq char
(char-after))
429 (let ((syntax-table (pcase char
430 (?\
{ org-element--pair-curly-table
)
431 (?\
[ org-element--pair-square-table
)
432 (?\
( org-element--pair-round-table
)
436 (with-syntax-table syntax-table
437 (let ((end (ignore-errors (scan-lists pos
1 0))))
440 (buffer-substring-no-properties (1+ pos
) (1- end
)))))))))
443 ;;; Accessors and Setters
445 ;; Provide four accessors: `org-element-type', `org-element-property'
446 ;; `org-element-contents' and `org-element-restriction'.
448 ;; Setter functions allow modification of elements by side effect.
449 ;; There is `org-element-put-property', `org-element-set-contents'.
450 ;; These low-level functions are useful to build a parse tree.
452 ;; `org-element-adopt-element', `org-element-set-element',
453 ;; `org-element-extract-element' and `org-element-insert-before' are
454 ;; high-level functions useful to modify a parse tree.
456 ;; `org-element-secondary-p' is a predicate used to know if a given
457 ;; object belongs to a secondary string. `org-element-class' tells if
458 ;; some parsed data is an element or an object, handling pseudo
459 ;; elements and objects. `org-element-copy' returns an element or
460 ;; object, stripping its parent property in the process.
462 (defsubst org-element-type
(element)
463 "Return type of ELEMENT.
465 The function returns the type of the element or object provided.
466 It can also return the following special value:
467 `plain-text' for a string
468 `org-data' for a complete document
469 nil in any other case."
471 ((not (consp element
)) (and (stringp element
) 'plain-text
))
472 ((symbolp (car element
)) (car element
))))
474 (defsubst org-element-property
(property element
)
475 "Extract the value from the PROPERTY of an ELEMENT."
476 (if (stringp element
) (get-text-property 0 property element
)
477 (plist-get (nth 1 element
) property
)))
479 (defsubst org-element-contents
(element)
480 "Extract contents from an ELEMENT."
481 (cond ((not (consp element
)) nil
)
482 ((symbolp (car element
)) (nthcdr 2 element
))
485 (defsubst org-element-restriction
(element)
486 "Return restriction associated to ELEMENT.
487 ELEMENT can be an element, an object or a symbol representing an
488 element or object type."
489 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
490 org-element-object-restrictions
)))
492 (defsubst org-element-put-property
(element property value
)
493 "In ELEMENT set PROPERTY to VALUE.
494 Return modified element."
495 (if (stringp element
) (org-add-props element nil property value
)
496 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
499 (defsubst org-element-set-contents
(element &rest contents
)
500 "Set ELEMENT's contents to CONTENTS.
502 (cond ((null element
) contents
)
503 ((not (symbolp (car element
))) contents
)
504 ((cdr element
) (setcdr (cdr element
) contents
) element
)
505 (t (nconc element contents
))))
507 (defun org-element-secondary-p (object)
508 "Non-nil when OBJECT directly belongs to a secondary string.
509 Return value is the property name, as a keyword, or nil."
510 (let* ((parent (org-element-property :parent object
))
511 (properties (cdr (assq (org-element-type parent
)
512 org-element-secondary-value-alist
))))
514 (dolist (p properties
)
515 (and (memq object
(org-element-property p parent
))
518 (defsubst org-element-class
(datum &optional parent
)
519 "Return class for ELEMENT, as a symbol.
520 Class is either `element' or `object'. Optional argument PARENT
521 is the element or object containing DATUM. It defaults to the
522 value of DATUM `:parent' property."
523 (let ((type (org-element-type datum
))
524 (parent (or parent
(org-element-property :parent datum
))))
527 ((memq type org-element-all-objects
) 'object
)
528 ((memq type org-element-all-elements
) 'element
)
530 ((eq type
'org-data
) 'element
)
531 ((eq type
'plain-text
) 'object
)
533 ;; Pseudo object or elements. Make a guess about its class.
534 ;; Basically a pseudo object is contained within another object,
535 ;; a secondary string or a container element.
536 ((not parent
) 'element
)
538 (let ((parent-type (org-element-type parent
)))
539 (cond ((not parent-type
) 'object
)
540 ((memq parent-type org-element-object-containers
) 'object
)
541 ((org-element-secondary-p datum
) 'object
)
544 (defsubst org-element-adopt-elements
(parent &rest children
)
545 "Append elements to the contents of another element.
547 PARENT is an element or object. CHILDREN can be elements,
548 objects, or a strings.
550 The function takes care of setting `:parent' property for CHILD.
551 Return parent element."
552 (if (not children
) parent
553 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
554 ;; string: parent is the list itself.
555 (dolist (child children
)
556 (org-element-put-property child
:parent
(or parent children
)))
557 ;; Add CHILDREN at the end of PARENT contents.
559 (apply #'org-element-set-contents
561 (nconc (org-element-contents parent
) children
)))
562 ;; Return modified PARENT element.
563 (or parent children
)))
565 (defun org-element-extract-element (element)
566 "Extract ELEMENT from parse tree.
567 Remove element from the parse tree by side-effect, and return it
568 with its `:parent' property stripped out."
569 (let ((parent (org-element-property :parent element
))
570 (secondary (org-element-secondary-p element
)))
572 (org-element-put-property
574 (delq element
(org-element-property secondary parent
)))
575 (apply #'org-element-set-contents
577 (delq element
(org-element-contents parent
))))
578 ;; Return ELEMENT with its :parent removed.
579 (org-element-put-property element
:parent nil
)))
581 (defun org-element-insert-before (element location
)
582 "Insert ELEMENT before LOCATION in parse tree.
583 LOCATION is an element, object or string within the parse tree.
584 Parse tree is modified by side effect."
585 (let* ((parent (org-element-property :parent location
))
586 (property (org-element-secondary-p location
))
587 (siblings (if property
(org-element-property property parent
)
588 (org-element-contents parent
)))
589 ;; Special case: LOCATION is the first element of an
590 ;; independent secondary string (e.g. :title property). Add
592 (specialp (and (not property
)
594 (eq (car parent
) location
))))
595 ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
597 ((or (null siblings
) (eq (car siblings
) location
))
598 (push element siblings
))
599 ((null location
) (nconc siblings
(list element
)))
601 (let ((index (cl-position location siblings
)))
602 (unless index
(error "No location found to insert element"))
603 (push element
(cdr (nthcdr (1- index
) siblings
))))))
604 ;; Store SIBLINGS at appropriate place in parse tree.
606 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
607 (property (org-element-put-property parent property siblings
))
608 (t (apply #'org-element-set-contents parent siblings
)))
609 ;; Set appropriate :parent property.
610 (org-element-put-property element
:parent parent
)))
612 (defun org-element-set-element (old new
)
613 "Replace element or object OLD with element or object NEW.
614 The function takes care of setting `:parent' property for NEW."
615 ;; Ensure OLD and NEW have the same parent.
616 (org-element-put-property new
:parent
(org-element-property :parent old
))
617 (if (or (memq (org-element-type old
) '(plain-text nil
))
618 (memq (org-element-type new
) '(plain-text nil
)))
619 ;; We cannot replace OLD with NEW since one of them is not an
620 ;; object or element. We take the long path.
621 (progn (org-element-insert-before new old
)
622 (org-element-extract-element old
))
623 ;; Since OLD is going to be changed into NEW by side-effect, first
624 ;; make sure that every element or object within NEW has OLD as
626 (dolist (blob (org-element-contents new
))
627 (org-element-put-property blob
:parent old
))
628 ;; Transfer contents.
629 (apply #'org-element-set-contents old
(org-element-contents new
))
630 ;; Overwrite OLD's properties with NEW's.
631 (setcar (cdr old
) (nth 1 new
))
633 (setcar old
(car new
))))
635 (defun org-element-create (type &optional props
&rest children
)
636 "Create a new element of type TYPE.
637 Optional argument PROPS, when non-nil, is a plist defining the
638 properties of the element. CHILDREN can be elements, objects or
640 (apply #'org-element-adopt-elements
(list type props
) children
))
642 (defun org-element-copy (datum)
643 "Return a copy of DATUM.
644 DATUM is an element, object, string or nil. `:parent' property
645 is cleared and contents are removed in the process."
647 (let ((type (org-element-type datum
)))
649 (`org-data
(list 'org-data nil
))
650 (`plain-text
(substring-no-properties datum
))
651 (`nil
(copy-sequence datum
))
653 (list type
(plist-put (copy-sequence (nth 1 datum
)) :parent nil
)))))))
659 ;; For each greater element type, we define a parser and an
662 ;; A parser returns the element or object as the list described above.
663 ;; Most of them accepts no argument. Though, exceptions exist. Hence
664 ;; every element containing a secondary string (see
665 ;; `org-element-secondary-value-alist') will accept an optional
666 ;; argument to toggle parsing of these secondary strings. Moreover,
667 ;; `item' parser requires current list's structure as its first
670 ;; An interpreter accepts two arguments: the list representation of
671 ;; the element or object, and its contents. The latter may be nil,
672 ;; depending on the element or object considered. It returns the
673 ;; appropriate Org syntax, as a string.
675 ;; Parsing functions must follow the naming convention:
676 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
677 ;; defined in `org-element-greater-elements'.
679 ;; Similarly, interpreting functions must follow the naming
680 ;; convention: org-element-TYPE-interpreter.
682 ;; With the exception of `headline' and `item' types, greater elements
683 ;; cannot contain other greater elements of their own type.
685 ;; Beside implementing a parser and an interpreter, adding a new
686 ;; greater element requires tweaking `org-element--current-element'.
687 ;; Moreover, the newly defined type must be added to both
688 ;; `org-element-all-elements' and `org-element-greater-elements'.
693 (defun org-element-center-block-parser (limit affiliated
)
694 "Parse a center block.
696 LIMIT bounds the search. AFFILIATED is a list of which CAR is
697 the buffer position at the beginning of the first affiliated
698 keyword and CDR is a plist of affiliated keywords along with
701 Return a list whose CAR is `center-block' and CDR is a plist
702 containing `:begin', `:end', `:contents-begin', `:contents-end',
703 `:post-blank' and `:post-affiliated' keywords.
705 Assume point is at the beginning of the block."
706 (let ((case-fold-search t
))
707 (if (not (save-excursion
708 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
709 ;; Incomplete block: parse it as a paragraph.
710 (org-element-paragraph-parser limit affiliated
)
711 (let ((block-end-line (match-beginning 0)))
712 (let* ((begin (car affiliated
))
713 (post-affiliated (point))
714 ;; Empty blocks have no contents.
715 (contents-begin (progn (forward-line)
716 (and (< (point) block-end-line
)
718 (contents-end (and contents-begin block-end-line
))
719 (pos-before-blank (progn (goto-char block-end-line
)
723 (skip-chars-forward " \r\t\n" limit
)
724 (if (eobp) (point) (line-beginning-position)))))
729 :contents-begin contents-begin
730 :contents-end contents-end
731 :post-blank
(count-lines pos-before-blank end
)
732 :post-affiliated post-affiliated
)
733 (cdr affiliated
))))))))
735 (defun org-element-center-block-interpreter (_ contents
)
736 "Interpret a center-block element as Org syntax.
737 CONTENTS is the contents of the element."
738 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
743 (defun org-element-drawer-parser (limit affiliated
)
746 LIMIT bounds the search. AFFILIATED is a list of which CAR is
747 the buffer position at the beginning of the first affiliated
748 keyword and CDR is a plist of affiliated keywords along with
751 Return a list whose CAR is `drawer' and CDR is a plist containing
752 `:drawer-name', `:begin', `:end', `:contents-begin',
753 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
755 Assume point is at beginning of drawer."
756 (let ((case-fold-search t
))
757 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
758 ;; Incomplete drawer: parse it as a paragraph.
759 (org-element-paragraph-parser limit affiliated
)
761 (let* ((drawer-end-line (match-beginning 0))
762 (name (progn (looking-at org-drawer-regexp
)
763 (match-string-no-properties 1)))
764 (begin (car affiliated
))
765 (post-affiliated (point))
766 ;; Empty drawers have no contents.
767 (contents-begin (progn (forward-line)
768 (and (< (point) drawer-end-line
)
770 (contents-end (and contents-begin drawer-end-line
))
771 (pos-before-blank (progn (goto-char drawer-end-line
)
774 (end (progn (skip-chars-forward " \r\t\n" limit
)
775 (if (eobp) (point) (line-beginning-position)))))
781 :contents-begin contents-begin
782 :contents-end contents-end
783 :post-blank
(count-lines pos-before-blank end
)
784 :post-affiliated post-affiliated
)
785 (cdr affiliated
))))))))
787 (defun org-element-drawer-interpreter (drawer contents
)
788 "Interpret DRAWER element as Org syntax.
789 CONTENTS is the contents of the element."
790 (format ":%s:\n%s:END:"
791 (org-element-property :drawer-name drawer
)
797 (defun org-element-dynamic-block-parser (limit affiliated
)
798 "Parse a dynamic block.
800 LIMIT bounds the search. AFFILIATED is a list of which CAR is
801 the buffer position at the beginning of the first affiliated
802 keyword and CDR is a plist of affiliated keywords along with
805 Return a list whose CAR is `dynamic-block' and CDR is a plist
806 containing `:block-name', `:begin', `:end', `:contents-begin',
807 `:contents-end', `:arguments', `:post-blank' and
808 `:post-affiliated' keywords.
810 Assume point is at beginning of dynamic block."
811 (let ((case-fold-search t
))
812 (if (not (save-excursion
813 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
814 ;; Incomplete block: parse it as a paragraph.
815 (org-element-paragraph-parser limit affiliated
)
816 (let ((block-end-line (match-beginning 0)))
818 (let* ((name (progn (looking-at org-dblock-start-re
)
819 (match-string-no-properties 1)))
820 (arguments (match-string-no-properties 3))
821 (begin (car affiliated
))
822 (post-affiliated (point))
823 ;; Empty blocks have no contents.
824 (contents-begin (progn (forward-line)
825 (and (< (point) block-end-line
)
827 (contents-end (and contents-begin block-end-line
))
828 (pos-before-blank (progn (goto-char block-end-line
)
831 (end (progn (skip-chars-forward " \r\t\n" limit
)
832 (if (eobp) (point) (line-beginning-position)))))
839 :contents-begin contents-begin
840 :contents-end contents-end
841 :post-blank
(count-lines pos-before-blank end
)
842 :post-affiliated post-affiliated
)
843 (cdr affiliated
)))))))))
845 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
846 "Interpret DYNAMIC-BLOCK element as Org syntax.
847 CONTENTS is the contents of the element."
848 (format "#+BEGIN: %s%s\n%s#+END:"
849 (org-element-property :block-name dynamic-block
)
850 (let ((args (org-element-property :arguments dynamic-block
)))
851 (and args
(concat " " args
)))
855 ;;;; Footnote Definition
857 (defconst org-element--footnote-separator
858 (concat org-outline-regexp-bol
"\\|"
859 org-footnote-definition-re
"\\|"
860 "^\\([ \t]*\n\\)\\{2,\\}")
861 "Regexp used as a footnote definition separator.")
863 (defun org-element-footnote-definition-parser (limit affiliated
)
864 "Parse a footnote definition.
866 LIMIT bounds the search. AFFILIATED is a list of which CAR is
867 the buffer position at the beginning of the first affiliated
868 keyword and CDR is a plist of affiliated keywords along with
871 Return a list whose CAR is `footnote-definition' and CDR is
872 a plist containing `:label', `:begin' `:end', `:contents-begin',
873 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
875 Assume point is at the beginning of the footnote definition."
877 (let* ((label (progn (looking-at org-footnote-definition-re
)
878 (match-string-no-properties 1)))
879 (begin (car affiliated
))
880 (post-affiliated (point))
886 (re-search-forward org-element--footnote-separator limit t
))
888 ((eq (char-after (match-beginning 0)) ?\
[)
889 ;; At a new footnote definition, make sure we end
890 ;; before any affiliated keyword above.
892 (while (and (> (point) post-affiliated
)
893 (looking-at-p org-element--affiliated-re
))
895 (line-beginning-position 2))
896 (t (match-beginning 0)))))
900 (skip-chars-forward " \r\t\n" ending
)
901 (cond ((= (point) ending
) nil
)
902 ((= (line-beginning-position) post-affiliated
) (point))
903 (t (line-beginning-position)))))
904 (contents-end (and contents-begin ending
))
905 (end (progn (goto-char ending
)
906 (skip-chars-forward " \r\t\n" limit
)
907 (if (eobp) (point) (line-beginning-position)))))
908 (list 'footnote-definition
913 :contents-begin contents-begin
914 :contents-end contents-end
915 :post-blank
(count-lines ending end
)
916 :post-affiliated post-affiliated
)
917 (cdr affiliated
))))))
919 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
920 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
921 CONTENTS is the contents of the footnote-definition."
922 (concat (format "[fn:%s]" (org-element-property :label footnote-definition
))
929 (defun org-element--get-node-properties ()
930 "Return node properties associated to headline at point.
931 Upcase property names. It avoids confusion between properties
932 obtained through property drawer and default properties from the
933 parser (e.g. `:end' and :END:). Return value is a plist."
936 (when (looking-at-p org-planning-line-re
) (forward-line))
937 (when (looking-at org-property-drawer-re
)
939 (let ((end (match-end 0)) properties
)
940 (while (< (line-end-position) end
)
941 (looking-at org-property-re
)
942 (push (match-string-no-properties 3) properties
)
943 (push (intern (concat ":" (upcase (match-string 2)))) properties
)
947 (defun org-element--get-time-properties ()
948 "Return time properties associated to headline at point.
949 Return value is a plist."
951 (when (progn (forward-line) (looking-at org-planning-line-re
))
952 (let ((end (line-end-position)) plist
)
953 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
954 (goto-char (match-end 1))
955 (skip-chars-forward " \t")
956 (let ((keyword (match-string 1))
957 (time (org-element-timestamp-parser)))
958 (cond ((equal keyword org-scheduled-string
)
959 (setq plist
(plist-put plist
:scheduled time
)))
960 ((equal keyword org-deadline-string
)
961 (setq plist
(plist-put plist
:deadline time
)))
962 (t (setq plist
(plist-put plist
:closed time
))))))
965 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
968 Return a list whose CAR is `headline' and CDR is a plist
969 containing `:raw-value', `:title', `:begin', `:end',
970 `:pre-blank', `:contents-begin' and `:contents-end', `:level',
971 `:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
972 `:deadline', `:closed', `:archivedp', `:commentedp'
973 `:footnote-section-p', `:post-blank' and `:post-affiliated'
976 The plist also contains any property set in the property drawer,
977 with its name in upper cases and colons added at the
978 beginning (e.g., `:CUSTOM_ID').
980 LIMIT is a buffer position bounding the search.
982 When RAW-SECONDARY-P is non-nil, headline's title will not be
983 parsed as a secondary string, but as a plain string instead.
985 Assume point is at beginning of the headline."
987 (let* ((begin (point))
988 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
989 (skip-chars-forward " \t")))
990 (todo (and org-todo-regexp
991 (let (case-fold-search) (looking-at org-todo-regexp
))
992 (progn (goto-char (match-end 0))
993 (skip-chars-forward " \t")
996 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
997 (priority (and (looking-at "\\[#.\\][ \t]*")
998 (progn (goto-char (match-end 0))
999 (aref (match-string 0) 2))))
1001 (and (let (case-fold-search) (looking-at org-comment-string
))
1002 (goto-char (match-end 0))))
1003 (title-start (point))
1004 (tags (when (re-search-forward
1005 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
1008 (goto-char (match-beginning 0))
1009 (org-split-string (match-string 1) ":")))
1011 (raw-value (org-trim
1012 (buffer-substring-no-properties title-start title-end
)))
1013 (archivedp (member org-archive-tag tags
))
1014 (footnote-section-p (and org-footnote-section
1015 (string= org-footnote-section raw-value
)))
1016 (standard-props (org-element--get-node-properties))
1017 (time-props (org-element--get-time-properties))
1018 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
1019 (contents-begin (save-excursion
1021 (skip-chars-forward " \r\t\n" end
)
1022 (and (/= (point) end
) (line-beginning-position))))
1023 (contents-end (and contents-begin
1024 (progn (goto-char end
)
1025 (skip-chars-backward " \r\t\n")
1026 (line-beginning-position 2)))))
1030 (list :raw-value raw-value
1034 (if (not contents-begin
) 0
1035 (1- (count-lines begin contents-begin
)))
1036 :contents-begin contents-begin
1037 :contents-end contents-end
1042 :todo-type todo-type
1045 (count-lines contents-end end
)
1046 (1- (count-lines begin end
)))
1047 :footnote-section-p footnote-section-p
1048 :archivedp archivedp
1049 :commentedp commentedp
1050 :post-affiliated begin
)
1053 (org-element-put-property
1055 (if raw-secondary-p raw-value
1056 (org-element--parse-objects
1057 (progn (goto-char title-start
)
1058 (skip-chars-forward " \t")
1060 (progn (goto-char title-end
)
1061 (skip-chars-backward " \t")
1064 (org-element-restriction 'headline
)
1067 (defun org-element-headline-interpreter (headline contents
)
1068 "Interpret HEADLINE element as Org syntax.
1069 CONTENTS is the contents of the element."
1070 (let* ((level (org-element-property :level headline
))
1071 (todo (org-element-property :todo-keyword headline
))
1072 (priority (org-element-property :priority headline
))
1073 (title (org-element-interpret-data
1074 (org-element-property :title headline
)))
1075 (tags (let ((tag-list (org-element-property :tags headline
)))
1077 (format ":%s:" (mapconcat #'identity tag-list
":")))))
1078 (commentedp (org-element-property :commentedp headline
))
1079 (pre-blank (or (org-element-property :pre-blank headline
) 0))
1081 (concat (make-string (if org-odd-levels-only
(1- (* level
2)) level
)
1083 (and todo
(concat " " todo
))
1084 (and commentedp
(concat " " org-comment-string
))
1085 (and priority
(format " [#%c]" priority
))
1087 (if (and org-footnote-section
1088 (org-element-property :footnote-section-p headline
))
1089 org-footnote-section
1096 ((zerop org-tags-column
) (format " %s" tags
))
1097 ((< org-tags-column
0)
1100 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
1105 (make-string (max (- org-tags-column
(length heading
)) 1) ?\s
)
1107 (make-string (1+ pre-blank
) ?
\n)
1113 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
1114 "Parse an inline task.
1116 Return a list whose CAR is `inlinetask' and CDR is a plist
1117 containing `:title', `:begin', `:end', `:pre-blank',
1118 `:contents-begin' and `:contents-end', `:level', `:priority',
1119 `:raw-value', `:tags', `:todo-keyword', `:todo-type',
1120 `:scheduled', `:deadline', `:closed', `:post-blank' and
1121 `:post-affiliated' keywords.
1123 The plist also contains any property set in the property drawer,
1124 with its name in upper cases and colons added at the
1125 beginning (e.g., `:CUSTOM_ID').
1127 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
1128 title will not be parsed as a secondary string, but as a plain
1131 Assume point is at beginning of the inline task."
1133 (let* ((begin (point))
1134 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1135 (skip-chars-forward " \t")))
1136 (todo (and org-todo-regexp
1137 (let (case-fold-search) (looking-at org-todo-regexp
))
1138 (progn (goto-char (match-end 0))
1139 (skip-chars-forward " \t")
1141 (todo-type (and todo
1142 (if (member todo org-done-keywords
) 'done
'todo
)))
1143 (priority (and (looking-at "\\[#.\\][ \t]*")
1144 (progn (goto-char (match-end 0))
1145 (aref (match-string 0) 2))))
1146 (title-start (point))
1147 (tags (when (re-search-forward
1148 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
1151 (goto-char (match-beginning 0))
1152 (org-split-string (match-string 1) ":")))
1154 (raw-value (org-trim
1155 (buffer-substring-no-properties title-start title-end
)))
1156 (task-end (save-excursion
1158 (and (re-search-forward org-outline-regexp-bol limit t
)
1159 (looking-at-p "[ \t]*END[ \t]*$")
1160 (line-beginning-position))))
1161 (standard-props (and task-end
(org-element--get-node-properties)))
1162 (time-props (and task-end
(org-element--get-time-properties)))
1163 (contents-begin (and task-end
1164 (< (point) task-end
)
1167 (skip-chars-forward " \t\n")
1168 (line-beginning-position))))
1169 (contents-end (and contents-begin task-end
))
1170 (end (progn (when task-end
(goto-char task-end
))
1172 (skip-chars-forward " \r\t\n" limit
)
1173 (if (eobp) (point) (line-beginning-position))))
1177 (list :raw-value raw-value
1181 (if (not contents-begin
) 0
1182 (1- (count-lines begin contents-begin
)))
1183 :contents-begin contents-begin
1184 :contents-end contents-end
1189 :todo-type todo-type
1190 :post-blank
(1- (count-lines (or task-end begin
) end
))
1191 :post-affiliated begin
)
1194 (org-element-put-property
1196 (if raw-secondary-p raw-value
1197 (org-element--parse-objects
1198 (progn (goto-char title-start
)
1199 (skip-chars-forward " \t")
1201 (progn (goto-char title-end
)
1202 (skip-chars-backward " \t")
1205 (org-element-restriction 'inlinetask
)
1208 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1209 "Interpret INLINETASK element as Org syntax.
1210 CONTENTS is the contents of inlinetask."
1211 (let* ((level (org-element-property :level inlinetask
))
1212 (todo (org-element-property :todo-keyword inlinetask
))
1213 (priority (org-element-property :priority inlinetask
))
1214 (title (org-element-interpret-data
1215 (org-element-property :title inlinetask
)))
1216 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1218 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1219 (task (concat (make-string level ?
*)
1220 (and todo
(concat " " todo
))
1221 (and priority
(format " [#%c]" priority
))
1222 (and title
(concat " " title
)))))
1227 ((zerop org-tags-column
) (format " %s" tags
))
1228 ((< org-tags-column
0)
1231 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1236 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1238 ;; Prefer degenerate inlinetasks when there are no
1243 (make-string level ?
*) " END")))))
1248 (defun org-element-item-parser (_ struct
&optional raw-secondary-p
)
1251 STRUCT is the structure of the plain list.
1253 Return a list whose CAR is `item' and CDR is a plist containing
1254 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1255 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1256 `:post-affiliated' keywords.
1258 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1259 any, will not be parsed as a secondary string, but as a plain
1262 Assume point is at the beginning of the item."
1265 (looking-at org-list-full-item-re
)
1266 (let* ((begin (point))
1267 (bullet (match-string-no-properties 1))
1268 (checkbox (let ((box (match-string 3)))
1269 (cond ((equal "[ ]" box
) 'off
)
1270 ((equal "[X]" box
) 'on
)
1271 ((equal "[-]" box
) 'trans
))))
1272 (counter (let ((c (match-string 2)))
1276 ((string-match "[A-Za-z]" c
)
1277 (- (string-to-char (upcase (match-string 0 c
)))
1279 ((string-match "[0-9]+" c
)
1280 (string-to-number (match-string 0 c
)))))))
1281 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1282 (if (bolp) (point) (line-beginning-position 2))))
1285 ;; Ignore tags in un-ordered lists: they are just
1286 ;; a part of item's body.
1287 (if (and (match-beginning 4)
1288 (save-match-data (string-match "[.)]" bullet
)))
1291 (skip-chars-forward " \r\t\n" end
)
1292 (cond ((= (point) end
) nil
)
1293 ;; If first line isn't empty, contents really
1294 ;; start at the text after item's meta-data.
1295 ((= (line-beginning-position) begin
) (point))
1296 (t (line-beginning-position)))))
1297 (contents-end (and contents-begin
1298 (progn (goto-char end
)
1299 (skip-chars-backward " \r\t\n")
1300 (line-beginning-position 2))))
1303 (list :bullet bullet
1306 :contents-begin contents-begin
1307 :contents-end contents-end
1311 :post-blank
(count-lines (or contents-end begin
) end
)
1312 :post-affiliated begin
))))
1313 (org-element-put-property
1315 (let ((raw (org-list-get-tag begin struct
)))
1317 (if raw-secondary-p raw
1318 (org-element--parse-objects
1319 (match-beginning 4) (match-end 4) nil
1320 (org-element-restriction 'item
)
1323 (defun org-element-item-interpreter (item contents
)
1324 "Interpret ITEM element as Org syntax.
1325 CONTENTS is the contents of the element."
1326 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1327 (org-list-bullet-string
1328 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1329 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1331 (checkbox (org-element-property :checkbox item
))
1332 (counter (org-element-property :counter item
))
1333 (tag (let ((tag (org-element-property :tag item
)))
1334 (and tag
(org-element-interpret-data tag
))))
1335 ;; Compute indentation.
1336 (ind (make-string (length bullet
) 32))
1337 (item-starts-with-par-p
1338 (eq (org-element-type (car (org-element-contents item
)))
1343 (and counter
(format "[@%d] " counter
))
1349 (and tag
(format "%s :: " tag
))
1351 (let ((contents (replace-regexp-in-string
1352 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1353 (if item-starts-with-par-p
(org-trim contents
)
1354 (concat "\n" contents
)))))))
1359 (defun org-element--list-struct (limit)
1360 ;; Return structure of list at point. Internal function. See
1361 ;; `org-list-struct' for details.
1362 (let ((case-fold-search t
)
1364 (item-re (org-item-re))
1365 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1371 ;; At limit: end all items.
1374 (let ((end (progn (skip-chars-backward " \r\t\n")
1377 (dolist (item items
(sort (nconc items struct
)
1378 'car-less-than-car
))
1379 (setcar (nthcdr 6 item
) end
)))))
1380 ;; At list end: end all items.
1381 ((looking-at org-list-end-re
)
1382 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1383 'car-less-than-car
))
1384 (setcar (nthcdr 6 item
) (point)))))
1385 ;; At a new item: end previous sibling.
1386 ((looking-at item-re
)
1387 (let ((ind (save-excursion (skip-chars-forward " \t")
1389 (setq top-ind
(min top-ind ind
))
1390 (while (and items
(<= ind
(nth 1 (car items
))))
1391 (let ((item (pop items
)))
1392 (setcar (nthcdr 6 item
) (point))
1393 (push item struct
)))
1394 (push (progn (looking-at org-list-full-item-re
)
1395 (let ((bullet (match-string-no-properties 1)))
1399 (match-string-no-properties 2) ; counter
1400 (match-string-no-properties 3) ; checkbox
1402 (and (save-match-data
1403 (string-match "[-+*]" bullet
))
1404 (match-string-no-properties 4))
1405 ;; Ending position, unknown so far.
1409 ;; Skip empty lines.
1410 ((looking-at "^[ \t]*$") (forward-line))
1411 ;; Skip inline tasks and blank lines along the way.
1412 ((and inlinetask-re
(looking-at inlinetask-re
))
1414 (let ((origin (point)))
1415 (when (re-search-forward inlinetask-re limit t
)
1416 (if (looking-at-p "END[ \t]*$") (forward-line)
1417 (goto-char origin
)))))
1418 ;; At some text line. Check if it ends any previous item.
1420 (let ((ind (save-excursion (skip-chars-forward " \t")
1422 (when (<= ind top-ind
)
1423 (skip-chars-backward " \r\t\n")
1425 (while (<= ind
(nth 1 (car items
)))
1426 (let ((item (pop items
)))
1427 (setcar (nthcdr 6 item
) (line-beginning-position))
1430 (throw 'exit
(sort struct
#'car-less-than-car
))))))
1431 ;; Skip blocks (any type) and drawers contents.
1433 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1435 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1437 ((and (looking-at org-drawer-regexp
)
1438 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1439 (forward-line))))))))
1441 (defun org-element-plain-list-parser (limit affiliated structure
)
1442 "Parse a plain list.
1444 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1445 the buffer position at the beginning of the first affiliated
1446 keyword and CDR is a plist of affiliated keywords along with
1447 their value. STRUCTURE is the structure of the plain list being
1450 Return a list whose CAR is `plain-list' and CDR is a plist
1451 containing `:type', `:begin', `:end', `:contents-begin' and
1452 `:contents-end', `:structure', `:post-blank' and
1453 `:post-affiliated' keywords.
1455 Assume point is at the beginning of the list."
1457 (let* ((struct (or structure
(org-element--list-struct limit
)))
1458 (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1459 ((nth 5 (assq (point) struct
)) 'descriptive
)
1461 (contents-begin (point))
1462 (begin (car affiliated
))
1463 (contents-end (let* ((item (assq contents-begin struct
))
1466 (while (and (setq item
(assq pos struct
))
1467 (= (nth 1 item
) ind
))
1468 (setq pos
(nth 6 item
)))
1470 (end (progn (goto-char contents-end
)
1471 (skip-chars-forward " \r\t\n" limit
)
1472 (if (= (point) limit
) limit
(line-beginning-position)))))
1479 :contents-begin contents-begin
1480 :contents-end contents-end
1482 :post-blank
(count-lines contents-end end
)
1483 :post-affiliated contents-begin
)
1484 (cdr affiliated
))))))
1486 (defun org-element-plain-list-interpreter (_ contents
)
1487 "Interpret plain-list element as Org syntax.
1488 CONTENTS is the contents of the element."
1491 (goto-char (point-min))
1496 ;;;; Property Drawer
1498 (defun org-element-property-drawer-parser (limit)
1499 "Parse a property drawer.
1501 LIMIT bounds the search.
1503 Return a list whose car is `property-drawer' and cdr is a plist
1504 containing `:begin', `:end', `:contents-begin', `:contents-end',
1505 `:post-blank' and `:post-affiliated' keywords.
1507 Assume point is at the beginning of the property drawer."
1509 (let ((case-fold-search t
)
1511 (contents-begin (line-beginning-position 2)))
1512 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)
1513 (let ((contents-end (and (> (match-beginning 0) contents-begin
)
1514 (match-beginning 0)))
1515 (before-blank (progn (forward-line) (point)))
1516 (end (progn (skip-chars-forward " \r\t\n" limit
)
1517 (if (eobp) (point) (line-beginning-position)))))
1518 (list 'property-drawer
1521 :contents-begin
(and contents-end contents-begin
)
1522 :contents-end contents-end
1523 :post-blank
(count-lines before-blank end
)
1524 :post-affiliated begin
))))))
1526 (defun org-element-property-drawer-interpreter (_ contents
)
1527 "Interpret property-drawer element as Org syntax.
1528 CONTENTS is the properties within the drawer."
1529 (format ":PROPERTIES:\n%s:END:" contents
))
1534 (defun org-element-quote-block-parser (limit affiliated
)
1535 "Parse a quote block.
1537 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1538 the buffer position at the beginning of the first affiliated
1539 keyword and CDR is a plist of affiliated keywords along with
1542 Return a list whose CAR is `quote-block' and CDR is a plist
1543 containing `:begin', `:end', `:contents-begin', `:contents-end',
1544 `:post-blank' and `:post-affiliated' keywords.
1546 Assume point is at the beginning of the block."
1547 (let ((case-fold-search t
))
1548 (if (not (save-excursion
1549 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1550 ;; Incomplete block: parse it as a paragraph.
1551 (org-element-paragraph-parser limit affiliated
)
1552 (let ((block-end-line (match-beginning 0)))
1554 (let* ((begin (car affiliated
))
1555 (post-affiliated (point))
1556 ;; Empty blocks have no contents.
1557 (contents-begin (progn (forward-line)
1558 (and (< (point) block-end-line
)
1560 (contents-end (and contents-begin block-end-line
))
1561 (pos-before-blank (progn (goto-char block-end-line
)
1564 (end (progn (skip-chars-forward " \r\t\n" limit
)
1565 (if (eobp) (point) (line-beginning-position)))))
1570 :contents-begin contents-begin
1571 :contents-end contents-end
1572 :post-blank
(count-lines pos-before-blank end
)
1573 :post-affiliated post-affiliated
)
1574 (cdr affiliated
)))))))))
1576 (defun org-element-quote-block-interpreter (_ contents
)
1577 "Interpret quote-block element as Org syntax.
1578 CONTENTS is the contents of the element."
1579 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1584 (defun org-element-section-parser (_)
1587 Return a list whose CAR is `section' and CDR is a plist
1588 containing `:begin', `:end', `:contents-begin', `contents-end',
1589 `:post-blank' and `:post-affiliated' keywords."
1591 ;; Beginning of section is the beginning of the first non-blank
1592 ;; line after previous headline.
1593 (let ((begin (point))
1594 (end (progn (org-with-limited-levels (outline-next-heading))
1596 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1597 (line-beginning-position 2))))
1601 :contents-begin begin
1602 :contents-end pos-before-blank
1603 :post-blank
(count-lines pos-before-blank end
)
1604 :post-affiliated begin
)))))
1606 (defun org-element-section-interpreter (_ contents
)
1607 "Interpret section element as Org syntax.
1608 CONTENTS is the contents of the element."
1614 (defun org-element-special-block-parser (limit affiliated
)
1615 "Parse a special block.
1617 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1618 the buffer position at the beginning of the first affiliated
1619 keyword and CDR is a plist of affiliated keywords along with
1622 Return a list whose CAR is `special-block' and CDR is a plist
1623 containing `:type', `:begin', `:end', `:contents-begin',
1624 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1626 Assume point is at the beginning of the block."
1627 (let* ((case-fold-search t
)
1628 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1629 (match-string-no-properties 1))))
1630 (if (not (save-excursion
1632 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1634 ;; Incomplete block: parse it as a paragraph.
1635 (org-element-paragraph-parser limit affiliated
)
1636 (let ((block-end-line (match-beginning 0)))
1638 (let* ((begin (car affiliated
))
1639 (post-affiliated (point))
1640 ;; Empty blocks have no contents.
1641 (contents-begin (progn (forward-line)
1642 (and (< (point) block-end-line
)
1644 (contents-end (and contents-begin block-end-line
))
1645 (pos-before-blank (progn (goto-char block-end-line
)
1648 (end (progn (skip-chars-forward " \r\t\n" limit
)
1649 (if (eobp) (point) (line-beginning-position)))))
1650 (list 'special-block
1655 :contents-begin contents-begin
1656 :contents-end contents-end
1657 :post-blank
(count-lines pos-before-blank end
)
1658 :post-affiliated post-affiliated
)
1659 (cdr affiliated
)))))))))
1661 (defun org-element-special-block-interpreter (special-block contents
)
1662 "Interpret SPECIAL-BLOCK element as Org syntax.
1663 CONTENTS is the contents of the element."
1664 (let ((block-type (org-element-property :type special-block
)))
1665 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1671 ;; For each element, a parser and an interpreter are also defined.
1672 ;; Both follow the same naming convention used for greater elements.
1674 ;; Also, as for greater elements, adding a new element type is done
1675 ;; through the following steps: implement a parser and an interpreter,
1676 ;; tweak `org-element--current-element' so that it recognizes the new
1677 ;; type and add that new type to `org-element-all-elements'.
1682 (defun org-element-babel-call-parser (limit affiliated
)
1683 "Parse a babel call.
1685 LIMIT bounds the search. AFFILIATED is a list of which car is
1686 the buffer position at the beginning of the first affiliated
1687 keyword and cdr is a plist of affiliated keywords along with
1690 Return a list whose car is `babel-call' and cdr is a plist
1691 containing `:call', `:inside-header', `:arguments',
1692 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1693 `:post-affiliated' as keywords."
1695 (let* ((begin (car affiliated
))
1696 (post-affiliated (point))
1697 (value (progn (search-forward ":" nil t
)
1699 (buffer-substring-no-properties
1700 (point) (line-end-position)))))
1701 (pos-before-blank (progn (forward-line) (point)))
1702 (end (progn (skip-chars-forward " \r\t\n" limit
)
1703 (if (eobp) (point) (line-beginning-position))))
1706 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*\\))[ \t]*\\(.*\\)"
1710 (list :call
(and valid-value
(match-string 1 value
))
1711 :inside-header
(and valid-value
1712 (org-string-nw-p (match-string 2 value
)))
1713 :arguments
(and valid-value
1714 (org-string-nw-p (match-string 3 value
)))
1715 :end-header
(and valid-value
1716 (org-string-nw-p (match-string 4 value
)))
1720 :post-blank
(count-lines pos-before-blank end
)
1721 :post-affiliated post-affiliated
)
1722 (cdr affiliated
))))))
1724 (defun org-element-babel-call-interpreter (babel-call _
)
1725 "Interpret BABEL-CALL element as Org syntax."
1727 (org-element-property :call babel-call
)
1728 (let ((h (org-element-property :inside-header babel-call
)))
1729 (and h
(format "[%s]" h
)))
1730 (concat "(" (org-element-property :arguments babel-call
) ")")
1731 (let ((h (org-element-property :end-header babel-call
)))
1732 (and h
(concat " " h
)))))
1737 (defun org-element-clock-parser (limit)
1740 LIMIT bounds the search.
1742 Return a list whose CAR is `clock' and CDR is a plist containing
1743 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1744 `:post-affiliated' as keywords."
1746 (let* ((case-fold-search nil
)
1748 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1749 (skip-chars-forward " \t")
1750 (org-element-timestamp-parser)))
1751 (duration (and (search-forward " => " (line-end-position) t
)
1752 (progn (skip-chars-forward " \t")
1753 (looking-at "\\(\\S-+\\)[ \t]*$"))
1754 (match-string-no-properties 1)))
1755 (status (if duration
'closed
'running
))
1756 (post-blank (let ((before-blank (progn (forward-line) (point))))
1757 (skip-chars-forward " \r\t\n" limit
)
1758 (skip-chars-backward " \t")
1759 (unless (bolp) (end-of-line))
1760 (count-lines before-blank
(point))))
1763 (list :status status
1768 :post-blank post-blank
1769 :post-affiliated begin
)))))
1771 (defun org-element-clock-interpreter (clock _
)
1772 "Interpret CLOCK element as Org syntax."
1773 (concat org-clock-string
" "
1774 (org-element-timestamp-interpreter
1775 (org-element-property :value clock
) nil
)
1776 (let ((duration (org-element-property :duration clock
)))
1781 (org-split-string duration
":")))))))
1786 (defun org-element-comment-parser (limit affiliated
)
1789 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1790 the buffer position at the beginning of the first affiliated
1791 keyword and CDR is a plist of affiliated keywords along with
1794 Return a list whose CAR is `comment' and CDR is a plist
1795 containing `:begin', `:end', `:value', `:post-blank',
1796 `:post-affiliated' keywords.
1798 Assume point is at comment beginning."
1800 (let* ((begin (car affiliated
))
1801 (post-affiliated (point))
1802 (value (prog2 (looking-at "[ \t]*# ?")
1803 (buffer-substring-no-properties
1804 (match-end 0) (line-end-position))
1807 ;; Get comments ending.
1809 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1810 ;; Accumulate lines without leading hash and first
1815 (buffer-substring-no-properties
1816 (match-end 0) (line-end-position))))
1819 (end (progn (goto-char com-end
)
1820 (skip-chars-forward " \r\t\n" limit
)
1821 (if (eobp) (point) (line-beginning-position)))))
1827 :post-blank
(count-lines com-end end
)
1828 :post-affiliated post-affiliated
)
1829 (cdr affiliated
))))))
1831 (defun org-element-comment-interpreter (comment _
)
1832 "Interpret COMMENT element as Org syntax.
1834 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1839 (defun org-element-comment-block-parser (limit affiliated
)
1840 "Parse an export block.
1842 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1843 the buffer position at the beginning of the first affiliated
1844 keyword and CDR is a plist of affiliated keywords along with
1847 Return a list whose CAR is `comment-block' and CDR is a plist
1848 containing `:begin', `:end', `:value', `:post-blank' and
1849 `:post-affiliated' keywords.
1851 Assume point is at comment block beginning."
1852 (let ((case-fold-search t
))
1853 (if (not (save-excursion
1854 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1855 ;; Incomplete block: parse it as a paragraph.
1856 (org-element-paragraph-parser limit affiliated
)
1857 (let ((contents-end (match-beginning 0)))
1859 (let* ((begin (car affiliated
))
1860 (post-affiliated (point))
1861 (contents-begin (progn (forward-line) (point)))
1862 (pos-before-blank (progn (goto-char contents-end
)
1865 (end (progn (skip-chars-forward " \r\t\n" limit
)
1866 (if (eobp) (point) (line-beginning-position))))
1867 (value (buffer-substring-no-properties
1868 contents-begin contents-end
)))
1869 (list 'comment-block
1874 :post-blank
(count-lines pos-before-blank end
)
1875 :post-affiliated post-affiliated
)
1876 (cdr affiliated
)))))))))
1878 (defun org-element-comment-block-interpreter (comment-block _
)
1879 "Interpret COMMENT-BLOCK element as Org syntax."
1880 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1881 (org-element-normalize-string
1882 (org-remove-indentation
1883 (org-element-property :value comment-block
)))))
1888 (defun org-element-diary-sexp-parser (limit affiliated
)
1889 "Parse a diary sexp.
1891 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1892 the buffer position at the beginning of the first affiliated
1893 keyword and CDR is a plist of affiliated keywords along with
1896 Return a list whose CAR is `diary-sexp' and CDR is a plist
1897 containing `:begin', `:end', `:value', `:post-blank' and
1898 `:post-affiliated' keywords."
1900 (let ((begin (car affiliated
))
1901 (post-affiliated (point))
1902 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1903 (match-string-no-properties 1)))
1904 (pos-before-blank (progn (forward-line) (point)))
1905 (end (progn (skip-chars-forward " \r\t\n" limit
)
1906 (if (eobp) (point) (line-beginning-position)))))
1912 :post-blank
(count-lines pos-before-blank end
)
1913 :post-affiliated post-affiliated
)
1914 (cdr affiliated
))))))
1916 (defun org-element-diary-sexp-interpreter (diary-sexp _
)
1917 "Interpret DIARY-SEXP as Org syntax."
1918 (org-element-property :value diary-sexp
))
1923 (defun org-element-example-block-parser (limit affiliated
)
1924 "Parse an example block.
1926 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1927 the buffer position at the beginning of the first affiliated
1928 keyword and CDR is a plist of affiliated keywords along with
1931 Return a list whose CAR is `example-block' and CDR is a plist
1932 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1933 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1934 `:value', `:post-blank' and `:post-affiliated' keywords."
1935 (let ((case-fold-search t
))
1936 (if (not (save-excursion
1937 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1938 ;; Incomplete block: parse it as a paragraph.
1939 (org-element-paragraph-parser limit affiliated
)
1940 (let ((contents-end (match-beginning 0)))
1944 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1945 (match-string-no-properties 1)))
1946 ;; Switches analysis.
1949 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
1952 (if (equal (match-string 1 switches
) "-")
1955 (if (not (match-end 2)) 0
1956 ;; Subtract 1 to give number of lines before
1958 (1- (string-to-number (match-string 2 switches
)))))))
1960 (and switches
(string-match "-i\\>" switches
)))
1961 ;; Should labels be retained in (or stripped from) example
1965 (not (string-match "-r\\>" switches
))
1966 (and number-lines
(string-match "-k\\>" switches
))))
1967 ;; What should code-references use - labels or
1972 (not (string-match "-k\\>" switches
)))))
1975 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1976 (match-string 1 switches
)))
1977 ;; Standard block parsing.
1978 (begin (car affiliated
))
1979 (post-affiliated (point))
1980 (contents-begin (line-beginning-position 2))
1981 (value (org-unescape-code-in-string
1982 (buffer-substring-no-properties
1983 contents-begin contents-end
)))
1984 (pos-before-blank (progn (goto-char contents-end
)
1987 (end (progn (skip-chars-forward " \r\t\n" limit
)
1988 (if (eobp) (point) (line-beginning-position)))))
1989 (list 'example-block
1995 :number-lines number-lines
1996 :preserve-indent preserve-indent
1997 :retain-labels retain-labels
1998 :use-labels use-labels
1999 :label-fmt label-fmt
2000 :post-blank
(count-lines pos-before-blank end
)
2001 :post-affiliated post-affiliated
)
2002 (cdr affiliated
)))))))))
2004 (defun org-element-example-block-interpreter (example-block _
)
2005 "Interpret EXAMPLE-BLOCK element as Org syntax."
2006 (let ((switches (org-element-property :switches example-block
))
2007 (value (org-element-property :value example-block
)))
2008 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
2009 (org-element-normalize-string
2010 (org-escape-code-in-string
2011 (if (or org-src-preserve-indentation
2012 (org-element-property :preserve-indent example-block
))
2014 (org-remove-indentation value
))))
2020 (defun org-element-export-block-parser (limit affiliated
)
2021 "Parse an export block.
2023 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2024 the buffer position at the beginning of the first affiliated
2025 keyword and CDR is a plist of affiliated keywords along with
2028 Return a list whose CAR is `export-block' and CDR is a plist
2029 containing `:begin', `:end', `:type', `:value', `:post-blank' and
2030 `:post-affiliated' keywords.
2032 Assume point is at export-block beginning."
2033 (let* ((case-fold-search t
))
2034 (if (not (save-excursion
2035 (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t
)))
2036 ;; Incomplete block: parse it as a paragraph.
2037 (org-element-paragraph-parser limit affiliated
)
2039 (let* ((contents-end (match-beginning 0))
2043 "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
2044 (match-string-no-properties 1)))
2045 (begin (car affiliated
))
2046 (post-affiliated (point))
2047 (contents-begin (progn (forward-line) (point)))
2048 (pos-before-blank (progn (goto-char contents-end
)
2051 (end (progn (skip-chars-forward " \r\t\n" limit
)
2052 (if (eobp) (point) (line-beginning-position))))
2053 (value (org-unescape-code-in-string
2054 (buffer-substring-no-properties contents-begin
2058 (list :type
(and backend
(upcase backend
))
2062 :post-blank
(count-lines pos-before-blank end
)
2063 :post-affiliated post-affiliated
)
2064 (cdr affiliated
))))))))
2066 (defun org-element-export-block-interpreter (export-block _
)
2067 "Interpret EXPORT-BLOCK element as Org syntax."
2068 (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT"
2069 (org-element-property :type export-block
)
2070 (org-element-property :value export-block
)))
2075 (defun org-element-fixed-width-parser (limit affiliated
)
2076 "Parse a fixed-width section.
2078 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2079 the buffer position at the beginning of the first affiliated
2080 keyword and CDR is a plist of affiliated keywords along with
2083 Return a list whose CAR is `fixed-width' and CDR is a plist
2084 containing `:begin', `:end', `:value', `:post-blank' and
2085 `:post-affiliated' keywords.
2087 Assume point is at the beginning of the fixed-width area."
2089 (let* ((begin (car affiliated
))
2090 (post-affiliated (point))
2094 (while (and (< (point) limit
)
2095 (looking-at "[ \t]*:\\( \\|$\\)"))
2096 ;; Accumulate text without starting colons.
2099 (buffer-substring-no-properties
2100 (match-end 0) (point-at-eol))
2104 (end (progn (skip-chars-forward " \r\t\n" limit
)
2105 (if (eobp) (point) (line-beginning-position)))))
2111 :post-blank
(count-lines end-area end
)
2112 :post-affiliated post-affiliated
)
2113 (cdr affiliated
))))))
2115 (defun org-element-fixed-width-interpreter (fixed-width _
)
2116 "Interpret FIXED-WIDTH element as Org syntax."
2117 (let ((value (org-element-property :value fixed-width
)))
2119 (replace-regexp-in-string
2121 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
2124 ;;;; Horizontal Rule
2126 (defun org-element-horizontal-rule-parser (limit affiliated
)
2127 "Parse an horizontal rule.
2129 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2130 the buffer position at the beginning of the first affiliated
2131 keyword and CDR is a plist of affiliated keywords along with
2134 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2135 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2138 (let ((begin (car affiliated
))
2139 (post-affiliated (point))
2140 (post-hr (progn (forward-line) (point)))
2141 (end (progn (skip-chars-forward " \r\t\n" limit
)
2142 (if (eobp) (point) (line-beginning-position)))))
2143 (list 'horizontal-rule
2147 :post-blank
(count-lines post-hr end
)
2148 :post-affiliated post-affiliated
)
2149 (cdr affiliated
))))))
2151 (defun org-element-horizontal-rule-interpreter (&rest _
)
2152 "Interpret HORIZONTAL-RULE element as Org syntax."
2158 (defun org-element-keyword-parser (limit affiliated
)
2159 "Parse a keyword at point.
2161 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2162 the buffer position at the beginning of the first affiliated
2163 keyword and CDR is a plist of affiliated keywords along with
2166 Return a list whose CAR is `keyword' and CDR is a plist
2167 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2168 `:post-affiliated' keywords."
2170 ;; An orphaned affiliated keyword is considered as a regular
2171 ;; keyword. In this case AFFILIATED is nil, so we take care of
2172 ;; this corner case.
2173 (let ((begin (or (car affiliated
) (point)))
2174 (post-affiliated (point))
2175 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2176 (upcase (match-string-no-properties 1))))
2177 (value (org-trim (buffer-substring-no-properties
2178 (match-end 0) (point-at-eol))))
2179 (pos-before-blank (progn (forward-line) (point)))
2180 (end (progn (skip-chars-forward " \r\t\n" limit
)
2181 (if (eobp) (point) (line-beginning-position)))))
2188 :post-blank
(count-lines pos-before-blank end
)
2189 :post-affiliated post-affiliated
)
2190 (cdr affiliated
))))))
2192 (defun org-element-keyword-interpreter (keyword _
)
2193 "Interpret KEYWORD element as Org syntax."
2195 (org-element-property :key keyword
)
2196 (org-element-property :value keyword
)))
2199 ;;;; Latex Environment
2201 (defconst org-element--latex-begin-environment
2202 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2203 "Regexp matching the beginning of a LaTeX environment.
2204 The environment is captured by the first group.
2206 See also `org-element--latex-end-environment'.")
2208 (defconst org-element--latex-end-environment
2209 "\\\\end{%s}[ \t]*$"
2210 "Format string matching the ending of a LaTeX environment.
2211 See also `org-element--latex-begin-environment'.")
2213 (defun org-element-latex-environment-parser (limit affiliated
)
2214 "Parse a LaTeX environment.
2216 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2217 the buffer position at the beginning of the first affiliated
2218 keyword and CDR is a plist of affiliated keywords along with
2221 Return a list whose CAR is `latex-environment' and CDR is a plist
2222 containing `:begin', `:end', `:value', `:post-blank' and
2223 `:post-affiliated' keywords.
2225 Assume point is at the beginning of the latex environment."
2227 (let ((case-fold-search t
)
2228 (code-begin (point)))
2229 (looking-at org-element--latex-begin-environment
)
2230 (if (not (re-search-forward (format org-element--latex-end-environment
2231 (regexp-quote (match-string 1)))
2233 ;; Incomplete latex environment: parse it as a paragraph.
2234 (org-element-paragraph-parser limit affiliated
)
2235 (let* ((code-end (progn (forward-line) (point)))
2236 (begin (car affiliated
))
2237 (value (buffer-substring-no-properties code-begin code-end
))
2238 (end (progn (skip-chars-forward " \r\t\n" limit
)
2239 (if (eobp) (point) (line-beginning-position)))))
2240 (list 'latex-environment
2245 :post-blank
(count-lines code-end end
)
2246 :post-affiliated code-begin
)
2247 (cdr affiliated
))))))))
2249 (defun org-element-latex-environment-interpreter (latex-environment _
)
2250 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2251 (org-element-property :value latex-environment
))
2256 (defun org-element-node-property-parser (limit)
2257 "Parse a node-property at point.
2259 LIMIT bounds the search.
2261 Return a list whose CAR is `node-property' and CDR is a plist
2262 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2263 `:post-affiliated' keywords."
2264 (looking-at org-property-re
)
2265 (let ((case-fold-search t
)
2267 (key (match-string-no-properties 2))
2268 (value (match-string-no-properties 3))
2269 (end (save-excursion
2271 (if (re-search-forward org-property-re limit t
)
2272 (line-beginning-position)
2274 (list 'node-property
2280 :post-affiliated begin
))))
2282 (defun org-element-node-property-interpreter (node-property _
)
2283 "Interpret NODE-PROPERTY element as Org syntax."
2284 (format org-property-format
2285 (format ":%s:" (org-element-property :key node-property
))
2286 (or (org-element-property :value node-property
) "")))
2291 (defun org-element-paragraph-parser (limit affiliated
)
2294 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2295 the buffer position at the beginning of the first affiliated
2296 keyword and CDR is a plist of affiliated keywords along with
2299 Return a list whose CAR is `paragraph' and CDR is a plist
2300 containing `:begin', `:end', `:contents-begin' and
2301 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2303 Assume point is at the beginning of the paragraph."
2305 (let* ((begin (car affiliated
))
2306 (contents-begin (point))
2308 (let ((case-fold-search t
))
2310 ;; A matching `org-element-paragraph-separate' is not
2311 ;; necessarily the end of the paragraph. In particular,
2312 ;; drawers, blocks or LaTeX environments opening lines
2313 ;; must be closed. Moreover keywords with a secondary
2314 ;; value must belong to "dual keywords".
2317 ((not (and (re-search-forward
2318 org-element-paragraph-separate limit
'move
)
2319 (progn (beginning-of-line) t
))))
2320 ((looking-at org-drawer-regexp
)
2322 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
2323 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2326 (format "^[ \t]*#\\+END_%s[ \t]*$"
2327 (regexp-quote (match-string 1)))
2329 ((looking-at org-element--latex-begin-environment
)
2332 (format org-element--latex-end-environment
2333 (regexp-quote (match-string 1)))
2335 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2336 (member-ignore-case (match-string 1)
2337 org-element-dual-keywords
))
2338 ;; Everything else is unambiguous.
2341 (if (= (point) limit
) limit
2342 (goto-char (line-beginning-position)))))
2343 (contents-end (save-excursion
2344 (skip-chars-backward " \r\t\n" contents-begin
)
2345 (line-beginning-position 2)))
2346 (end (progn (skip-chars-forward " \r\t\n" limit
)
2347 (if (eobp) (point) (line-beginning-position)))))
2352 :contents-begin contents-begin
2353 :contents-end contents-end
2354 :post-blank
(count-lines before-blank end
)
2355 :post-affiliated contents-begin
)
2356 (cdr affiliated
))))))
2358 (defun org-element-paragraph-interpreter (_ contents
)
2359 "Interpret paragraph element as Org syntax.
2360 CONTENTS is the contents of the element."
2366 (defun org-element-planning-parser (limit)
2369 LIMIT bounds the search.
2371 Return a list whose CAR is `planning' and CDR is a plist
2372 containing `:closed', `:deadline', `:scheduled', `:begin',
2373 `:end', `:post-blank' and `:post-affiliated' keywords."
2375 (let* ((case-fold-search nil
)
2377 (post-blank (let ((before-blank (progn (forward-line) (point))))
2378 (skip-chars-forward " \r\t\n" limit
)
2379 (skip-chars-backward " \t")
2380 (unless (bolp) (end-of-line))
2381 (count-lines before-blank
(point))))
2383 closed deadline scheduled
)
2385 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2386 (goto-char (match-end 1))
2387 (skip-chars-forward " \t" end
)
2388 (let ((keyword (match-string 1))
2389 (time (org-element-timestamp-parser)))
2390 (cond ((equal keyword org-closed-string
) (setq closed time
))
2391 ((equal keyword org-deadline-string
) (setq deadline time
))
2392 (t (setq scheduled time
)))))
2394 (list :closed closed
2396 :scheduled scheduled
2399 :post-blank post-blank
2400 :post-affiliated begin
)))))
2402 (defun org-element-planning-interpreter (planning _
)
2403 "Interpret PLANNING element as Org syntax."
2407 (list (let ((deadline (org-element-property :deadline planning
)))
2409 (concat org-deadline-string
" "
2410 (org-element-timestamp-interpreter deadline nil
))))
2411 (let ((scheduled (org-element-property :scheduled planning
)))
2413 (concat org-scheduled-string
" "
2414 (org-element-timestamp-interpreter scheduled nil
))))
2415 (let ((closed (org-element-property :closed planning
)))
2417 (concat org-closed-string
" "
2418 (org-element-timestamp-interpreter closed nil
))))))
2424 (defun org-element-src-block-parser (limit affiliated
)
2427 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2428 the buffer position at the beginning of the first affiliated
2429 keyword and CDR is a plist of affiliated keywords along with
2432 Return a list whose CAR is `src-block' and CDR is a plist
2433 containing `:language', `:switches', `:parameters', `:begin',
2434 `:end', `:number-lines', `:retain-labels', `:use-labels',
2435 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2436 `:post-affiliated' keywords.
2438 Assume point is at the beginning of the block."
2439 (let ((case-fold-search t
))
2440 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2442 ;; Incomplete block: parse it as a paragraph.
2443 (org-element-paragraph-parser limit affiliated
)
2444 (let ((contents-end (match-beginning 0)))
2446 (let* ((begin (car affiliated
))
2447 (post-affiliated (point))
2448 ;; Get language as a string.
2452 "^[ \t]*#\\+BEGIN_SRC\
2453 \\(?: +\\(\\S-+\\)\\)?\
2454 \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
2456 (match-string-no-properties 1)))
2458 (switches (match-string-no-properties 2))
2460 (parameters (match-string-no-properties 3))
2461 ;; Switches analysis.
2464 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
2467 (if (equal (match-string 1 switches
) "-")
2470 (if (not (match-end 2)) 0
2471 ;; Subtract 1 to give number of lines before
2473 (1- (string-to-number (match-string 2 switches
)))))))
2474 (preserve-indent (and switches
2475 (string-match "-i\\>" switches
)))
2478 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2479 (match-string 1 switches
)))
2480 ;; Should labels be retained in (or stripped from)
2484 (not (string-match "-r\\>" switches
))
2485 (and number-lines
(string-match "-k\\>" switches
))))
2486 ;; What should code-references use - labels or
2491 (not (string-match "-k\\>" switches
)))))
2493 (value (org-unescape-code-in-string
2494 (buffer-substring-no-properties
2495 (line-beginning-position 2) contents-end
)))
2496 (pos-before-blank (progn (goto-char contents-end
)
2499 ;; Get position after ending blank lines.
2500 (end (progn (skip-chars-forward " \r\t\n" limit
)
2501 (if (eobp) (point) (line-beginning-position)))))
2504 (list :language language
2505 :switches
(and (org-string-nw-p switches
)
2506 (org-trim switches
))
2507 :parameters
(and (org-string-nw-p parameters
)
2508 (org-trim parameters
))
2511 :number-lines number-lines
2512 :preserve-indent preserve-indent
2513 :retain-labels retain-labels
2514 :use-labels use-labels
2515 :label-fmt label-fmt
2517 :post-blank
(count-lines pos-before-blank end
)
2518 :post-affiliated post-affiliated
)
2519 (cdr affiliated
)))))))))
2521 (defun org-element-src-block-interpreter (src-block _
)
2522 "Interpret SRC-BLOCK element as Org syntax."
2523 (let ((lang (org-element-property :language src-block
))
2524 (switches (org-element-property :switches src-block
))
2525 (params (org-element-property :parameters src-block
))
2527 (let ((val (org-element-property :value src-block
)))
2529 ((or org-src-preserve-indentation
2530 (org-element-property :preserve-indent src-block
))
2532 ((zerop org-edit-src-content-indentation
)
2533 (org-remove-indentation val
))
2535 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2536 (replace-regexp-in-string
2537 "^" ind
(org-remove-indentation val
))))))))
2538 (concat (format "#+BEGIN_SRC%s\n"
2539 (concat (and lang
(concat " " lang
))
2540 (and switches
(concat " " switches
))
2541 (and params
(concat " " params
))))
2542 (org-element-normalize-string (org-escape-code-in-string value
))
2548 (defun org-element-table-parser (limit affiliated
)
2549 "Parse a table at point.
2551 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2552 the buffer position at the beginning of the first affiliated
2553 keyword and CDR is a plist of affiliated keywords along with
2556 Return a list whose CAR is `table' and CDR is a plist containing
2557 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2558 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2561 Assume point is at the beginning of the table."
2563 (let* ((case-fold-search t
)
2564 (table-begin (point))
2565 (type (if (looking-at "[ \t]*|") 'org
'table.el
))
2566 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2567 (if (eq type
'org
) "" "+")))
2568 (begin (car affiliated
))
2570 (if (re-search-forward end-re limit
'move
)
2571 (goto-char (match-beginning 0))
2574 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2575 (push (match-string-no-properties 1) acc
)
2578 (pos-before-blank (point))
2579 (end (progn (skip-chars-forward " \r\t\n" limit
)
2580 (if (eobp) (point) (line-beginning-position)))))
2587 ;; Only `org' tables have contents. `table.el' tables
2588 ;; use a `:value' property to store raw table as
2590 :contents-begin
(and (eq type
'org
) table-begin
)
2591 :contents-end
(and (eq type
'org
) table-end
)
2592 :value
(and (eq type
'table.el
)
2593 (buffer-substring-no-properties
2594 table-begin table-end
))
2595 :post-blank
(count-lines pos-before-blank end
)
2596 :post-affiliated table-begin
)
2597 (cdr affiliated
))))))
2599 (defun org-element-table-interpreter (table contents
)
2600 "Interpret TABLE element as Org syntax.
2601 CONTENTS is a string, if table's type is `org', or nil."
2602 (if (eq (org-element-property :type table
) 'table.el
)
2603 (org-remove-indentation (org-element-property :value table
))
2604 (concat (with-temp-buffer (insert contents
)
2607 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2608 (reverse (org-element-property :tblfm table
))
2614 (defun org-element-table-row-parser (_)
2615 "Parse table row at point.
2617 Return a list whose CAR is `table-row' and CDR is a plist
2618 containing `:begin', `:end', `:contents-begin', `:contents-end',
2619 `:type', `:post-blank' and `:post-affiliated' keywords."
2621 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2623 ;; A table rule has no contents. In that case, ensure
2624 ;; CONTENTS-BEGIN matches CONTENTS-END.
2625 (contents-begin (and (eq type
'standard
) (search-forward "|")))
2626 (contents-end (and (eq type
'standard
)
2629 (skip-chars-backward " \t")
2631 (end (line-beginning-position 2)))
2636 :contents-begin contents-begin
2637 :contents-end contents-end
2639 :post-affiliated begin
)))))
2641 (defun org-element-table-row-interpreter (table-row contents
)
2642 "Interpret TABLE-ROW element as Org syntax.
2643 CONTENTS is the contents of the table row."
2644 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2645 (concat "|" contents
)))
2650 (defun org-element-verse-block-parser (limit affiliated
)
2651 "Parse a verse block.
2653 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2654 the buffer position at the beginning of the first affiliated
2655 keyword and CDR is a plist of affiliated keywords along with
2658 Return a list whose CAR is `verse-block' and CDR is a plist
2659 containing `:begin', `:end', `:contents-begin', `:contents-end',
2660 `:post-blank' and `:post-affiliated' keywords.
2662 Assume point is at beginning of the block."
2663 (let ((case-fold-search t
))
2664 (if (not (save-excursion
2665 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2666 ;; Incomplete block: parse it as a paragraph.
2667 (org-element-paragraph-parser limit affiliated
)
2668 (let ((contents-end (match-beginning 0)))
2670 (let* ((begin (car affiliated
))
2671 (post-affiliated (point))
2672 (contents-begin (progn (forward-line) (point)))
2673 (pos-before-blank (progn (goto-char contents-end
)
2676 (end (progn (skip-chars-forward " \r\t\n" limit
)
2677 (if (eobp) (point) (line-beginning-position)))))
2682 :contents-begin contents-begin
2683 :contents-end contents-end
2684 :post-blank
(count-lines pos-before-blank end
)
2685 :post-affiliated post-affiliated
)
2686 (cdr affiliated
)))))))))
2688 (defun org-element-verse-block-interpreter (_ contents
)
2689 "Interpret verse-block element as Org syntax.
2690 CONTENTS is verse block contents."
2691 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2697 ;; Unlike to elements, raw text can be found between objects. Hence,
2698 ;; `org-element--object-lex' is provided to find the next object in
2701 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2702 ;; object types they can contain will be specified in
2703 ;; `org-element-object-restrictions'.
2705 ;; Creating a new type of object requires to alter
2706 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2707 ;; new type in `org-element-all-objects', and possibly add
2708 ;; restrictions in `org-element-object-restrictions'.
2712 (defun org-element-bold-parser ()
2713 "Parse bold object at point, if any.
2715 When at a bold object, return a list whose car is `bold' and cdr
2716 is a plist with `:begin', `:end', `:contents-begin' and
2717 `:contents-end' and `:post-blank' keywords. Otherwise, return
2720 Assume point is at the first star marker."
2722 (unless (bolp) (backward-char 1))
2723 (when (looking-at org-emph-re
)
2724 (let ((begin (match-beginning 2))
2725 (contents-begin (match-beginning 4))
2726 (contents-end (match-end 4))
2727 (post-blank (progn (goto-char (match-end 2))
2728 (skip-chars-forward " \t")))
2733 :contents-begin contents-begin
2734 :contents-end contents-end
2735 :post-blank post-blank
))))))
2737 (defun org-element-bold-interpreter (_ contents
)
2738 "Interpret bold object as Org syntax.
2739 CONTENTS is the contents of the object."
2740 (format "*%s*" contents
))
2745 (defun org-element-code-parser ()
2746 "Parse code object at point, if any.
2748 When at a code object, return a list whose car is `code' and cdr
2749 is a plist with `:value', `:begin', `:end' and `:post-blank'
2750 keywords. Otherwise, return nil.
2752 Assume point is at the first tilde marker."
2754 (unless (bolp) (backward-char 1))
2755 (when (looking-at org-verbatim-re
)
2756 (let ((begin (match-beginning 2))
2757 (value (match-string-no-properties 4))
2758 (post-blank (progn (goto-char (match-end 2))
2759 (skip-chars-forward " \t")))
2765 :post-blank post-blank
))))))
2767 (defun org-element-code-interpreter (code _
)
2768 "Interpret CODE object as Org syntax."
2769 (format "~%s~" (org-element-property :value code
)))
2774 (defun org-element-entity-parser ()
2775 "Parse entity at point, if any.
2777 When at an entity, return a list whose car is `entity' and cdr
2778 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2779 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2780 `:post-blank' as keywords. Otherwise, return nil.
2782 Assume point is at the beginning of the entity."
2784 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2786 (let* ((value (or (org-entity-get (match-string 1))
2787 (throw 'no-object nil
)))
2788 (begin (match-beginning 0))
2789 (bracketsp (string= (match-string 2) "{}"))
2790 (post-blank (progn (goto-char (match-end 1))
2791 (when bracketsp
(forward-char 2))
2792 (skip-chars-forward " \t")))
2795 (list :name
(car value
)
2796 :latex
(nth 1 value
)
2797 :latex-math-p
(nth 2 value
)
2799 :ascii
(nth 4 value
)
2800 :latin1
(nth 5 value
)
2801 :utf-8
(nth 6 value
)
2804 :use-brackets-p bracketsp
2805 :post-blank post-blank
)))))))
2807 (defun org-element-entity-interpreter (entity _
)
2808 "Interpret ENTITY object as Org syntax."
2810 (org-element-property :name entity
)
2811 (when (org-element-property :use-brackets-p entity
) "{}")))
2816 (defun org-element-export-snippet-parser ()
2817 "Parse export snippet at point.
2819 When at an export snippet, return a list whose car is
2820 `export-snippet' and cdr a plist with `:begin', `:end',
2821 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2824 Assume point is at the beginning of the snippet."
2827 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2829 (save-match-data (goto-char (match-end 0))
2830 (re-search-forward "@@" nil t
)
2831 (match-beginning 0))))
2832 (let* ((begin (match-beginning 0))
2833 (back-end (match-string-no-properties 1))
2834 (value (buffer-substring-no-properties
2835 (match-end 0) contents-end
))
2836 (post-blank (skip-chars-forward " \t"))
2838 (list 'export-snippet
2839 (list :back-end back-end
2843 :post-blank post-blank
)))))))
2845 (defun org-element-export-snippet-interpreter (export-snippet _
)
2846 "Interpret EXPORT-SNIPPET object as Org syntax."
2848 (org-element-property :back-end export-snippet
)
2849 (org-element-property :value export-snippet
)))
2852 ;;;; Footnote Reference
2854 (defun org-element-footnote-reference-parser ()
2855 "Parse footnote reference at point, if any.
2857 When at a footnote reference, return a list whose car is
2858 `footnote-reference' and cdr a plist with `:label', `:type',
2859 `:begin', `:end', `:content-begin', `:contents-end' and
2860 `:post-blank' as keywords. Otherwise, return nil."
2861 (when (looking-at org-footnote-re
)
2862 (let ((closing (with-syntax-table org-element--pair-square-table
2863 (ignore-errors (scan-lists (point) 1 0)))))
2866 (let* ((begin (point))
2867 (label (match-string-no-properties 1))
2868 (inner-begin (match-end 0))
2869 (inner-end (1- closing
))
2870 (type (if (match-end 2) 'inline
'standard
))
2871 (post-blank (progn (goto-char closing
)
2872 (skip-chars-forward " \t")))
2874 (list 'footnote-reference
2879 :contents-begin
(and (eq type
'inline
) inner-begin
)
2880 :contents-end
(and (eq type
'inline
) inner-end
)
2881 :post-blank post-blank
))))))))
2883 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2884 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2885 CONTENTS is its definition, when inline, or nil."
2887 (or (org-element-property :label footnote-reference
) "")
2888 (if contents
(concat ":" contents
) "")))
2891 ;;;; Inline Babel Call
2893 (defun org-element-inline-babel-call-parser ()
2894 "Parse inline babel call at point, if any.
2896 When at an inline babel call, return a list whose car is
2897 `inline-babel-call' and cdr a plist with `:call',
2898 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2899 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2901 Assume point is at the beginning of the babel call."
2904 (when (let ((case-fold-search nil
))
2905 (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
2906 (goto-char (match-end 1))
2907 (let* ((begin (match-beginning 0))
2908 (call (match-string-no-properties 1))
2910 (let ((p (org-element--parse-paired-brackets ?\
[)))
2911 (and (org-string-nw-p p
)
2912 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2913 (arguments (org-string-nw-p
2914 (or (org-element--parse-paired-brackets ?\
()
2915 ;; Parenthesis are mandatory.
2916 (throw :no-object nil
))))
2918 (let ((p (org-element--parse-paired-brackets ?\
[)))
2919 (and (org-string-nw-p p
)
2920 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2921 (value (buffer-substring-no-properties begin
(point)))
2922 (post-blank (skip-chars-forward " \t"))
2924 (list 'inline-babel-call
2926 :inside-header inside-header
2927 :arguments arguments
2928 :end-header end-header
2932 :post-blank post-blank
)))))))
2934 (defun org-element-inline-babel-call-interpreter (inline-babel-call _
)
2935 "Interpret INLINE-BABEL-CALL object as Org syntax."
2937 (org-element-property :call inline-babel-call
)
2938 (let ((h (org-element-property :inside-header inline-babel-call
)))
2939 (and h
(format "[%s]" h
)))
2940 "(" (org-element-property :arguments inline-babel-call
) ")"
2941 (let ((h (org-element-property :end-header inline-babel-call
)))
2942 (and h
(format "[%s]" h
)))))
2945 ;;;; Inline Src Block
2947 (defun org-element-inline-src-block-parser ()
2948 "Parse inline source block at point, if any.
2950 When at an inline source block, return a list whose car is
2951 `inline-src-block' and cdr a plist with `:begin', `:end',
2952 `:language', `:value', `:parameters' and `:post-blank' as
2953 keywords. Otherwise, return nil.
2955 Assume point is at the beginning of the inline src block."
2958 (when (let ((case-fold-search nil
))
2959 (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
2960 (goto-char (match-end 1))
2961 (let ((begin (match-beginning 0))
2962 (language (match-string-no-properties 1))
2964 (let ((p (org-element--parse-paired-brackets ?\
[)))
2965 (and (org-string-nw-p p
)
2966 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p
)))))
2967 (value (or (org-element--parse-paired-brackets ?\
{)
2968 (throw :no-object nil
)))
2969 (post-blank (skip-chars-forward " \t")))
2970 (list 'inline-src-block
2971 (list :language language
2973 :parameters parameters
2976 :post-blank post-blank
)))))))
2978 (defun org-element-inline-src-block-interpreter (inline-src-block _
)
2979 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2980 (let ((language (org-element-property :language inline-src-block
))
2981 (arguments (org-element-property :parameters inline-src-block
))
2982 (body (org-element-property :value inline-src-block
)))
2983 (format "src_%s%s{%s}"
2985 (if arguments
(format "[%s]" arguments
) "")
2990 (defun org-element-italic-parser ()
2991 "Parse italic object at point, if any.
2993 When at an italic object, return a list whose car is `italic' and
2994 cdr is a plist with `:begin', `:end', `:contents-begin' and
2995 `:contents-end' and `:post-blank' keywords. Otherwise, return
2998 Assume point is at the first slash marker."
3000 (unless (bolp) (backward-char 1))
3001 (when (looking-at org-emph-re
)
3002 (let ((begin (match-beginning 2))
3003 (contents-begin (match-beginning 4))
3004 (contents-end (match-end 4))
3005 (post-blank (progn (goto-char (match-end 2))
3006 (skip-chars-forward " \t")))
3011 :contents-begin contents-begin
3012 :contents-end contents-end
3013 :post-blank post-blank
))))))
3015 (defun org-element-italic-interpreter (_ contents
)
3016 "Interpret italic object as Org syntax.
3017 CONTENTS is the contents of the object."
3018 (format "/%s/" contents
))
3023 (defun org-element-latex-fragment-parser ()
3024 "Parse LaTeX fragment at point, if any.
3026 When at a LaTeX fragment, return a list whose car is
3027 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
3028 and `:post-blank' as keywords. Otherwise, return nil.
3030 Assume point is at the beginning of the LaTeX fragment."
3033 (let* ((begin (point))
3035 (if (eq (char-after) ?$
)
3036 (if (eq (char-after (1+ (point))) ?$
)
3037 (search-forward "$$" nil t
2)
3038 (and (not (eq (char-before) ?$
))
3039 (search-forward "$" nil t
2)
3040 (not (memq (char-before (match-beginning 0))
3041 '(?\s ?
\t ?
\n ?
, ?.
)))
3042 (looking-at "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|$\\)")
3044 (pcase (char-after (1+ (point)))
3045 (?\
( (search-forward "\\)" nil t
))
3046 (?\
[ (search-forward "\\]" nil t
))
3049 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
3050 \\|\\({[^{}\n]*}\\)\\)*")
3052 (post-blank (if (not after-fragment
) (throw 'no-object nil
)
3053 (goto-char after-fragment
)
3054 (skip-chars-forward " \t")))
3056 (list 'latex-fragment
3057 (list :value
(buffer-substring-no-properties begin after-fragment
)
3060 :post-blank post-blank
))))))
3062 (defun org-element-latex-fragment-interpreter (latex-fragment _
)
3063 "Interpret LATEX-FRAGMENT object as Org syntax."
3064 (org-element-property :value latex-fragment
))
3068 (defun org-element-line-break-parser ()
3069 "Parse line break at point, if any.
3071 When at a line break, return a list whose car is `line-break',
3072 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3073 Otherwise, return nil.
3075 Assume point is at the beginning of the line break."
3076 (when (and (looking-at-p "\\\\\\\\[ \t]*$")
3077 (not (eq (char-before) ?
\\)))
3079 (list :begin
(point)
3080 :end
(line-beginning-position 2)
3083 (defun org-element-line-break-interpreter (&rest _
)
3084 "Interpret LINE-BREAK object as Org syntax."
3090 (defun org-element-link-parser ()
3091 "Parse link at point, if any.
3093 When at a link, return a list whose car is `link' and cdr a plist
3094 with `:type', `:path', `:format', `:raw-link', `:application',
3095 `:search-option', `:begin', `:end', `:contents-begin',
3096 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3099 Assume point is at the beginning of the link."
3101 (let ((begin (point))
3102 end contents-begin contents-end link-end post-blank path type format
3103 raw-link search-option application
)
3105 ;; Type 1: Text targeted from a radio target.
3106 ((and org-target-link-regexp
3107 (save-excursion (or (bolp) (backward-char))
3108 (looking-at org-target-link-regexp
)))
3110 (setq format
'plain
)
3111 (setq link-end
(match-end 1))
3112 (setq path
(match-string-no-properties 1))
3113 (setq contents-begin
(match-beginning 1))
3114 (setq contents-end
(match-end 1)))
3115 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3116 ((looking-at org-bracket-link-regexp
)
3117 (setq format
'bracket
)
3118 (setq contents-begin
(match-beginning 3))
3119 (setq contents-end
(match-end 3))
3120 (setq link-end
(match-end 0))
3121 ;; RAW-LINK is the original link. Expand any
3122 ;; abbreviation in it.
3124 ;; Also treat any newline character and associated
3125 ;; indentation as a single space character. This is not
3126 ;; compatible with RFC 3986, which requires to ignore
3127 ;; them altogether. However, doing so would require
3128 ;; users to encode spaces on the fly when writing links
3129 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3130 ;; [[shell:ls *.org]], which defeats Org's focus on
3132 (setq raw-link
(org-link-expand-abbrev
3133 (replace-regexp-in-string
3134 "[ \t]*\n[ \t]*" " "
3135 (match-string-no-properties 1))))
3136 ;; Determine TYPE of link and set PATH accordingly. According
3137 ;; to RFC 3986, remove whitespaces from URI in external links.
3138 ;; In internal ones, treat indentation as a single space.
3141 ((or (file-name-absolute-p raw-link
)
3142 (string-match "\\`\\.\\.?/" raw-link
))
3144 (setq path raw-link
))
3145 ;; Explicit type (http, irc, bbdb...).
3146 ((string-match org-link-types-re raw-link
)
3147 (setq type
(match-string 1 raw-link
))
3148 (setq path
(substring raw-link
(match-end 0))))
3149 ;; Code-ref type: PATH is the name of the reference.
3150 ((and (string-match-p "\\`(" raw-link
)
3151 (string-match-p ")\\'" raw-link
))
3152 (setq type
"coderef")
3153 (setq path
(substring raw-link
1 -
1)))
3154 ;; Custom-id type: PATH is the name of the custom id.
3155 ((= (string-to-char raw-link
) ?
#)
3156 (setq type
"custom-id")
3157 (setq path
(substring raw-link
1)))
3158 ;; Fuzzy type: Internal link either matches a target, an
3159 ;; headline name or nothing. PATH is the target or
3163 (setq path raw-link
))))
3164 ;; Type 3: Plain link, e.g., http://orgmode.org
3165 ((looking-at org-plain-link-re
)
3166 (setq format
'plain
)
3167 (setq raw-link
(match-string-no-properties 0))
3168 (setq type
(match-string-no-properties 1))
3169 (setq link-end
(match-end 0))
3170 (setq path
(match-string-no-properties 2)))
3171 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3172 ;; bracket links, follow RFC 3986 and remove any extra
3173 ;; whitespace in URI.
3174 ((looking-at org-angle-link-re
)
3175 (setq format
'angle
)
3176 (setq type
(match-string-no-properties 1))
3177 (setq link-end
(match-end 0))
3179 (buffer-substring-no-properties
3180 (match-beginning 1) (match-end 2)))
3181 (setq path
(replace-regexp-in-string
3182 "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
3183 (t (throw 'no-object nil
)))
3184 ;; In any case, deduce end point after trailing white space from
3185 ;; LINK-END variable.
3188 (progn (goto-char link-end
) (skip-chars-forward " \t")))
3190 ;; Special "file" type link processing. Extract opening
3191 ;; application and search option, if any. Also normalize URI.
3192 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type
)
3193 (setq application
(match-string 1 type
) type
"file")
3194 (when (string-match "::\\(.*\\)\\'" path
)
3195 (setq search-option
(match-string 1 path
))
3196 (setq path
(replace-match "" nil nil path
)))
3197 (setq path
(replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path
)))
3198 ;; Translate link, if `org-link-translation-function' is set.
3199 (let ((trans (and (functionp org-link-translation-function
)
3200 (funcall org-link-translation-function type path
))))
3202 (setq type
(car trans
))
3203 (setq path
(cdr trans
))))
3208 :raw-link
(or raw-link path
)
3209 :application application
3210 :search-option search-option
3213 :contents-begin contents-begin
3214 :contents-end contents-end
3215 :post-blank post-blank
)))))
3217 (defun org-element-link-interpreter (link contents
)
3218 "Interpret LINK object as Org syntax.
3219 CONTENTS is the contents of the object, or nil."
3220 (let ((type (org-element-property :type link
))
3221 (path (org-element-property :path link
)))
3222 (if (string= type
"radio") path
3223 (let ((fmt (pcase (org-element-property :format link
)
3224 ;; Links with contents and internal links have to
3225 ;; use bracket syntax. Ignore `:format' in these
3226 ;; cases. This is also the default syntax when the
3227 ;; property is not defined, e.g., when the object
3228 ;; was crafted by the user.
3230 (format "[[%%s][%s]]"
3231 ;; Since this is going to be used as
3232 ;; a format string, escape percent signs
3234 (replace-regexp-in-string "%" "%%" contents
)))
3237 (guard (member type
'("coderef" "custom-id" "fuzzy"))))
3239 ;; Otherwise, just obey to `:format'.
3242 (f (error "Wrong `:format' value: %s" f
)))))
3245 ("coderef" (format "(%s)" path
))
3246 ("custom-id" (concat "#" path
))
3248 (let ((app (org-element-property :application link
))
3249 (opt (org-element-property :search-option link
)))
3250 (concat type
(and app
(concat "+" app
)) ":"
3252 (and opt
(concat "::" opt
)))))
3254 (_ (concat type
":" path
))))))))
3259 (defun org-element-macro-parser ()
3260 "Parse macro at point, if any.
3262 When at a macro, return a list whose car is `macro' and cdr
3263 a plist with `:key', `:args', `:begin', `:end', `:value' and
3264 `:post-blank' as keywords. Otherwise, return nil.
3266 Assume point is at the macro."
3268 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3269 (let ((begin (point))
3270 (key (downcase (match-string-no-properties 1)))
3271 (value (match-string-no-properties 0))
3272 (post-blank (progn (goto-char (match-end 0))
3273 (skip-chars-forward " \t")))
3275 (args (let ((args (match-string-no-properties 3)))
3276 (and args
(org-macro-extract-arguments args
)))))
3283 :post-blank post-blank
))))))
3285 (defun org-element-macro-interpreter (macro _
)
3286 "Interpret MACRO object as Org syntax."
3287 (org-element-property :value macro
))
3292 (defun org-element-radio-target-parser ()
3293 "Parse radio target at point, if any.
3295 When at a radio target, return a list whose car is `radio-target'
3296 and cdr a plist with `:begin', `:end', `:contents-begin',
3297 `:contents-end', `:value' and `:post-blank' as keywords.
3298 Otherwise, return nil.
3300 Assume point is at the radio target."
3302 (when (looking-at org-radio-target-regexp
)
3303 (let ((begin (point))
3304 (contents-begin (match-beginning 1))
3305 (contents-end (match-end 1))
3306 (value (match-string-no-properties 1))
3307 (post-blank (progn (goto-char (match-end 0))
3308 (skip-chars-forward " \t")))
3313 :contents-begin contents-begin
3314 :contents-end contents-end
3315 :post-blank post-blank
3318 (defun org-element-radio-target-interpreter (_ contents
)
3319 "Interpret target object as Org syntax.
3320 CONTENTS is the contents of the object."
3321 (concat "<<<" contents
">>>"))
3324 ;;;; Statistics Cookie
3326 (defun org-element-statistics-cookie-parser ()
3327 "Parse statistics cookie at point, if any.
3329 When at a statistics cookie, return a list whose car is
3330 `statistics-cookie', and cdr a plist with `:begin', `:end',
3331 `:value' and `:post-blank' keywords. Otherwise, return nil.
3333 Assume point is at the beginning of the statistics-cookie."
3335 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3336 (let* ((begin (point))
3337 (value (buffer-substring-no-properties
3338 (match-beginning 0) (match-end 0)))
3339 (post-blank (progn (goto-char (match-end 0))
3340 (skip-chars-forward " \t")))
3342 (list 'statistics-cookie
3346 :post-blank post-blank
))))))
3348 (defun org-element-statistics-cookie-interpreter (statistics-cookie _
)
3349 "Interpret STATISTICS-COOKIE object as Org syntax."
3350 (org-element-property :value statistics-cookie
))
3355 (defun org-element-strike-through-parser ()
3356 "Parse strike-through object at point, if any.
3358 When at a strike-through object, return a list whose car is
3359 `strike-through' and cdr is a plist with `:begin', `:end',
3360 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3361 Otherwise, return nil.
3363 Assume point is at the first plus sign marker."
3365 (unless (bolp) (backward-char 1))
3366 (when (looking-at org-emph-re
)
3367 (let ((begin (match-beginning 2))
3368 (contents-begin (match-beginning 4))
3369 (contents-end (match-end 4))
3370 (post-blank (progn (goto-char (match-end 2))
3371 (skip-chars-forward " \t")))
3373 (list 'strike-through
3376 :contents-begin contents-begin
3377 :contents-end contents-end
3378 :post-blank post-blank
))))))
3380 (defun org-element-strike-through-interpreter (_ contents
)
3381 "Interpret strike-through object as Org syntax.
3382 CONTENTS is the contents of the object."
3383 (format "+%s+" contents
))
3388 (defun org-element-subscript-parser ()
3389 "Parse subscript at point, if any.
3391 When at a subscript object, return a list whose car is
3392 `subscript' and cdr a plist with `:begin', `:end',
3393 `:contents-begin', `:contents-end', `:use-brackets-p' and
3394 `:post-blank' as keywords. Otherwise, return nil.
3396 Assume point is at the underscore."
3398 (unless (bolp) (backward-char))
3399 (when (looking-at org-match-substring-regexp
)
3400 (let ((bracketsp (match-beginning 4))
3401 (begin (match-beginning 2))
3402 (contents-begin (or (match-beginning 4)
3403 (match-beginning 3)))
3404 (contents-end (or (match-end 4) (match-end 3)))
3405 (post-blank (progn (goto-char (match-end 0))
3406 (skip-chars-forward " \t")))
3411 :use-brackets-p bracketsp
3412 :contents-begin contents-begin
3413 :contents-end contents-end
3414 :post-blank post-blank
))))))
3416 (defun org-element-subscript-interpreter (subscript contents
)
3417 "Interpret SUBSCRIPT object as Org syntax.
3418 CONTENTS is the contents of the object."
3420 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3426 (defun org-element-superscript-parser ()
3427 "Parse superscript at point, if any.
3429 When at a superscript object, return a list whose car is
3430 `superscript' and cdr a plist with `:begin', `:end',
3431 `:contents-begin', `:contents-end', `:use-brackets-p' and
3432 `:post-blank' as keywords. Otherwise, return nil.
3434 Assume point is at the caret."
3436 (unless (bolp) (backward-char))
3437 (when (looking-at org-match-substring-regexp
)
3438 (let ((bracketsp (match-beginning 4))
3439 (begin (match-beginning 2))
3440 (contents-begin (or (match-beginning 4)
3441 (match-beginning 3)))
3442 (contents-end (or (match-end 4) (match-end 3)))
3443 (post-blank (progn (goto-char (match-end 0))
3444 (skip-chars-forward " \t")))
3449 :use-brackets-p bracketsp
3450 :contents-begin contents-begin
3451 :contents-end contents-end
3452 :post-blank post-blank
))))))
3454 (defun org-element-superscript-interpreter (superscript contents
)
3455 "Interpret SUPERSCRIPT object as Org syntax.
3456 CONTENTS is the contents of the object."
3458 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3464 (defun org-element-table-cell-parser ()
3465 "Parse table cell at point.
3466 Return a list whose car is `table-cell' and cdr is a plist
3467 containing `:begin', `:end', `:contents-begin', `:contents-end'
3468 and `:post-blank' keywords."
3469 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3470 (let* ((begin (match-beginning 0))
3472 (contents-begin (match-beginning 1))
3473 (contents-end (match-end 1)))
3477 :contents-begin contents-begin
3478 :contents-end contents-end
3481 (defun org-element-table-cell-interpreter (_ contents
)
3482 "Interpret table-cell element as Org syntax.
3483 CONTENTS is the contents of the cell, or nil."
3484 (concat " " contents
" |"))
3489 (defun org-element-target-parser ()
3490 "Parse target at point, if any.
3492 When at a target, return a list whose car is `target' and cdr
3493 a plist with `:begin', `:end', `:value' and `:post-blank' as
3494 keywords. Otherwise, return nil.
3496 Assume point is at the target."
3498 (when (looking-at org-target-regexp
)
3499 (let ((begin (point))
3500 (value (match-string-no-properties 1))
3501 (post-blank (progn (goto-char (match-end 0))
3502 (skip-chars-forward " \t")))
3508 :post-blank post-blank
))))))
3510 (defun org-element-target-interpreter (target _
)
3511 "Interpret TARGET object as Org syntax."
3512 (format "<<%s>>" (org-element-property :value target
)))
3517 (defconst org-element--timestamp-regexp
3518 (concat org-ts-regexp-both
3520 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3522 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3523 "Regexp matching any timestamp type object.")
3525 (defun org-element-timestamp-parser ()
3526 "Parse time stamp at point, if any.
3528 When at a time stamp, return a list whose car is `timestamp', and
3529 cdr a plist with `:type', `:raw-value', `:year-start',
3530 `:month-start', `:day-start', `:hour-start', `:minute-start',
3531 `:year-end', `:month-end', `:day-end', `:hour-end',
3532 `:minute-end', `:repeater-type', `:repeater-value',
3533 `:repeater-unit', `:warning-type', `:warning-value',
3534 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3535 Otherwise, return nil.
3537 Assume point is at the beginning of the timestamp."
3538 (when (looking-at-p org-element--timestamp-regexp
)
3540 (let* ((begin (point))
3541 (activep (eq (char-after) ?
<))
3544 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3545 (match-string-no-properties 0)))
3546 (date-start (match-string-no-properties 1))
3547 (date-end (match-string 3))
3548 (diaryp (match-beginning 2))
3549 (post-blank (progn (goto-char (match-end 0))
3550 (skip-chars-forward " \t")))
3555 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3557 (cons (string-to-number (match-string 2 date-start
))
3558 (string-to-number (match-string 3 date-start
)))))
3559 (type (cond (diaryp 'diary
)
3560 ((and activep
(or date-end time-range
)) 'active-range
)
3562 ((or date-end time-range
) 'inactive-range
)
3566 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3570 (let ((type (match-string 1 raw-value
)))
3571 (cond ((equal "++" type
) 'catch-up
)
3572 ((equal ".+" type
) 'restart
)
3574 :repeater-value
(string-to-number (match-string 2 raw-value
))
3576 (pcase (string-to-char (match-string 3 raw-value
))
3577 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (_ 'year
)))))
3580 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3582 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3583 :warning-value
(string-to-number (match-string 2 raw-value
))
3585 (pcase (string-to-char (match-string 3 raw-value
))
3586 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (_ 'year
)))))
3587 year-start month-start day-start hour-start minute-start year-end
3588 month-end day-end hour-end minute-end
)
3589 ;; Parse date-start.
3591 (let ((date (org-parse-time-string date-start t
)))
3592 (setq year-start
(nth 5 date
)
3593 month-start
(nth 4 date
)
3594 day-start
(nth 3 date
)
3595 hour-start
(nth 2 date
)
3596 minute-start
(nth 1 date
))))
3597 ;; Compute date-end. It can be provided directly in time-stamp,
3598 ;; or extracted from time range. Otherwise, it defaults to the
3599 ;; same values as date-start.
3601 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3602 (setq year-end
(or (nth 5 date
) year-start
)
3603 month-end
(or (nth 4 date
) month-start
)
3604 day-end
(or (nth 3 date
) day-start
)
3605 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3606 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3608 (nconc (list :type type
3609 :raw-value raw-value
3610 :year-start year-start
3611 :month-start month-start
3612 :day-start day-start
3613 :hour-start hour-start
3614 :minute-start minute-start
3616 :month-end month-end
3619 :minute-end minute-end
3622 :post-blank post-blank
)
3626 (defun org-element-timestamp-interpreter (timestamp _
)
3627 "Interpret TIMESTAMP object as Org syntax."
3628 (let* ((repeat-string
3630 (pcase (org-element-property :repeater-type timestamp
)
3631 (`cumulate
"+") (`catch-up
"++") (`restart
".+"))
3632 (let ((val (org-element-property :repeater-value timestamp
)))
3633 (and val
(number-to-string val
)))
3634 (pcase (org-element-property :repeater-unit timestamp
)
3635 (`hour
"h") (`day
"d") (`week
"w") (`month
"m") (`year
"y"))))
3638 (pcase (org-element-property :warning-type timestamp
)
3639 (`first
"--") (`all
"-"))
3640 (let ((val (org-element-property :warning-value timestamp
)))
3641 (and val
(number-to-string val
)))
3642 (pcase (org-element-property :warning-unit timestamp
)
3643 (`hour
"h") (`day
"d") (`week
"w") (`month
"m") (`year
"y"))))
3645 ;; Build an Org timestamp string from TIME. ACTIVEP is
3646 ;; non-nil when time stamp is active. If WITH-TIME-P is
3647 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3648 ;; specify a time range in the timestamp. REPEAT-STRING is
3649 ;; the repeater string, if any.
3650 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3651 (let ((ts (format-time-string
3652 (funcall (if with-time-p
#'cdr
#'car
)
3653 org-time-stamp-formats
)
3655 (when (and hour-end minute-end
)
3656 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3659 (format "\\&-%02d:%02d" hour-end minute-end
)
3661 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3662 (dolist (s (list repeat-string warning-string
))
3663 (when (org-string-nw-p s
)
3664 (setq ts
(concat (substring ts
0 -
1)
3667 (substring ts -
1)))))
3670 (type (org-element-property :type timestamp
)))
3672 ((or `active
`inactive
)
3673 (let* ((minute-start (org-element-property :minute-start timestamp
))
3674 (minute-end (org-element-property :minute-end timestamp
))
3675 (hour-start (org-element-property :hour-start timestamp
))
3676 (hour-end (org-element-property :hour-end timestamp
))
3677 (time-range-p (and hour-start hour-end minute-start minute-end
3678 (or (/= hour-start hour-end
)
3679 (/= minute-start minute-end
)))))
3685 (org-element-property :day-start timestamp
)
3686 (org-element-property :month-start timestamp
)
3687 (org-element-property :year-start timestamp
))
3689 (and hour-start minute-start
)
3690 (and time-range-p hour-end
)
3691 (and time-range-p minute-end
))))
3692 ((or `active-range
`inactive-range
)
3693 (let ((minute-start (org-element-property :minute-start timestamp
))
3694 (minute-end (org-element-property :minute-end timestamp
))
3695 (hour-start (org-element-property :hour-start timestamp
))
3696 (hour-end (org-element-property :hour-end timestamp
)))
3699 build-ts-string
(encode-time
3703 (org-element-property :day-start timestamp
)
3704 (org-element-property :month-start timestamp
)
3705 (org-element-property :year-start timestamp
))
3706 (eq type
'active-range
)
3707 (and hour-start minute-start
))
3709 (funcall build-ts-string
3713 (org-element-property :day-end timestamp
)
3714 (org-element-property :month-end timestamp
)
3715 (org-element-property :year-end timestamp
))
3716 (eq type
'active-range
)
3717 (and hour-end minute-end
)))))
3718 (_ (org-element-property :raw-value timestamp
)))))
3723 (defun org-element-underline-parser ()
3724 "Parse underline object at point, if any.
3726 When at an underline object, return a list whose car is
3727 `underline' and cdr is a plist with `:begin', `:end',
3728 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3729 Otherwise, return nil.
3731 Assume point is at the first underscore marker."
3733 (unless (bolp) (backward-char 1))
3734 (when (looking-at org-emph-re
)
3735 (let ((begin (match-beginning 2))
3736 (contents-begin (match-beginning 4))
3737 (contents-end (match-end 4))
3738 (post-blank (progn (goto-char (match-end 2))
3739 (skip-chars-forward " \t")))
3744 :contents-begin contents-begin
3745 :contents-end contents-end
3746 :post-blank post-blank
))))))
3748 (defun org-element-underline-interpreter (_ contents
)
3749 "Interpret underline object as Org syntax.
3750 CONTENTS is the contents of the object."
3751 (format "_%s_" contents
))
3756 (defun org-element-verbatim-parser ()
3757 "Parse verbatim object at point, if any.
3759 When at a verbatim object, return a list whose car is `verbatim'
3760 and cdr is a plist with `:value', `:begin', `:end' and
3761 `:post-blank' keywords. Otherwise, return nil.
3763 Assume point is at the first equal sign marker."
3765 (unless (bolp) (backward-char 1))
3766 (when (looking-at org-verbatim-re
)
3767 (let ((begin (match-beginning 2))
3768 (value (match-string-no-properties 4))
3769 (post-blank (progn (goto-char (match-end 2))
3770 (skip-chars-forward " \t")))
3776 :post-blank post-blank
))))))
3778 (defun org-element-verbatim-interpreter (verbatim _
)
3779 "Interpret VERBATIM object as Org syntax."
3780 (format "=%s=" (org-element-property :value verbatim
)))
3784 ;;; Parsing Element Starting At Point
3786 ;; `org-element--current-element' is the core function of this section.
3787 ;; It returns the Lisp representation of the element starting at
3790 ;; `org-element--current-element' makes use of special modes. They
3791 ;; are activated for fixed element chaining (e.g., `plain-list' >
3792 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3793 ;; `section'). Special modes are: `first-section', `item',
3794 ;; `node-property', `section' and `table-row'.
3796 (defun org-element--current-element (limit &optional granularity mode structure
)
3797 "Parse the element starting at point.
3799 Return value is a list like (TYPE PROPS) where TYPE is the type
3800 of the element and PROPS a plist of properties associated to the
3803 Possible types are defined in `org-element-all-elements'.
3805 LIMIT bounds the search.
3807 Optional argument GRANULARITY determines the depth of the
3808 recursion. Allowed values are `headline', `greater-element',
3809 `element', `object' or nil. When it is broader than `object' (or
3810 nil), secondary values will not be parsed, since they only
3813 Optional argument MODE, when non-nil, can be either
3814 `first-section', `section', `planning', `item', `node-property'
3817 If STRUCTURE isn't provided but MODE is set to `item', it will be
3820 This function assumes point is always at the beginning of the
3821 element it has to parse."
3823 (let ((case-fold-search t
)
3824 ;; Determine if parsing depth allows for secondary strings
3825 ;; parsing. It only applies to elements referenced in
3826 ;; `org-element-secondary-value-alist'.
3827 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3831 (org-element-item-parser limit structure raw-secondary-p
))
3833 ((eq mode
'table-row
) (org-element-table-row-parser limit
))
3835 ((eq mode
'node-property
) (org-element-node-property-parser limit
))
3837 ((org-with-limited-levels (org-at-heading-p))
3838 (org-element-headline-parser limit raw-secondary-p
))
3839 ;; Sections (must be checked after headline).
3840 ((eq mode
'section
) (org-element-section-parser limit
))
3841 ((eq mode
'first-section
)
3842 (org-element-section-parser
3843 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3846 ((and (eq mode
'planning
)
3847 (eq ?
* (char-after (line-beginning-position 0)))
3848 (looking-at org-planning-line-re
))
3849 (org-element-planning-parser limit
))
3851 ((and (memq mode
'(planning property-drawer
))
3852 (eq ?
* (char-after (line-beginning-position
3853 (if (eq mode
'planning
) 0 -
1))))
3854 (looking-at org-property-drawer-re
))
3855 (org-element-property-drawer-parser limit
))
3856 ;; When not at bol, point is at the beginning of an item or
3857 ;; a footnote definition: next item is always a paragraph.
3858 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3860 ((looking-at org-clock-line-re
) (org-element-clock-parser limit
))
3863 (org-element-inlinetask-parser limit raw-secondary-p
))
3864 ;; From there, elements can have affiliated keywords.
3865 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3867 ;; Jumping over affiliated keywords put point off-limits.
3868 ;; Parse them as regular keywords.
3869 ((and (cdr affiliated
) (>= (point) limit
))
3870 (goto-char (car affiliated
))
3871 (org-element-keyword-parser limit nil
))
3872 ;; LaTeX Environment.
3873 ((looking-at org-element--latex-begin-environment
)
3874 (org-element-latex-environment-parser limit affiliated
))
3875 ;; Drawer and Property Drawer.
3876 ((looking-at org-drawer-regexp
)
3877 (org-element-drawer-parser limit affiliated
))
3879 ((looking-at "[ \t]*:\\( \\|$\\)")
3880 (org-element-fixed-width-parser limit affiliated
))
3881 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3883 ((looking-at "[ \t]*#")
3884 (goto-char (match-end 0))
3886 ((looking-at "\\(?: \\|$\\)")
3888 (org-element-comment-parser limit affiliated
))
3889 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3891 (funcall (pcase (upcase (match-string 1))
3892 ("CENTER" #'org-element-center-block-parser
)
3893 ("COMMENT" #'org-element-comment-block-parser
)
3894 ("EXAMPLE" #'org-element-example-block-parser
)
3895 ("EXPORT" #'org-element-export-block-parser
)
3896 ("QUOTE" #'org-element-quote-block-parser
)
3897 ("SRC" #'org-element-src-block-parser
)
3898 ("VERSE" #'org-element-verse-block-parser
)
3899 (_ #'org-element-special-block-parser
))
3902 ((looking-at "\\+CALL:")
3904 (org-element-babel-call-parser limit affiliated
))
3905 ((looking-at "\\+BEGIN:? ")
3907 (org-element-dynamic-block-parser limit affiliated
))
3908 ((looking-at "\\+\\S-+:")
3910 (org-element-keyword-parser limit affiliated
))
3913 (org-element-paragraph-parser limit affiliated
))))
3914 ;; Footnote Definition.
3915 ((looking-at org-footnote-definition-re
)
3916 (org-element-footnote-definition-parser limit affiliated
))
3918 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3919 (org-element-horizontal-rule-parser limit affiliated
))
3922 (org-element-diary-sexp-parser limit affiliated
))
3924 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3925 (org-element-table-parser limit affiliated
))
3927 ((looking-at (org-item-re))
3928 (org-element-plain-list-parser
3930 (or structure
(org-element--list-struct limit
))))
3931 ;; Default element: Paragraph.
3932 (t (org-element-paragraph-parser limit affiliated
)))))))))
3935 ;; Most elements can have affiliated keywords. When looking for an
3936 ;; element beginning, we want to move before them, as they belong to
3937 ;; that element, and, in the meantime, collect information they give
3938 ;; into appropriate properties. Hence the following function.
3940 (defun org-element--collect-affiliated-keywords (limit)
3941 "Collect affiliated keywords from point down to LIMIT.
3943 Return a list whose CAR is the position at the first of them and
3944 CDR a plist of keywords and values and move point to the
3945 beginning of the first line after them.
3947 As a special case, if element doesn't start at the beginning of
3948 the line (e.g., a paragraph starting an item), CAR is current
3949 position of point and CDR is nil."
3950 (if (not (bolp)) (list (point))
3951 (let ((case-fold-search t
)
3953 ;; RESTRICT is the list of objects allowed in parsed
3955 (restrict (org-element-restriction 'keyword
))
3957 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3958 (let* ((raw-kwd (upcase (match-string 1)))
3959 ;; Apply translation to RAW-KWD. From there, KWD is
3960 ;; the official keyword.
3961 (kwd (or (cdr (assoc raw-kwd
3962 org-element-keyword-translation-alist
))
3964 ;; Find main value for any keyword.
3968 (buffer-substring-no-properties
3969 (match-end 0) (line-end-position)))))
3970 ;; PARSEDP is non-nil when keyword should have its
3972 (parsedp (member kwd org-element-parsed-keywords
))
3973 ;; If KWD is a dual keyword, find its secondary
3974 ;; value. Maybe parse it.
3975 (dualp (member kwd org-element-dual-keywords
))
3978 (let ((sec (match-string-no-properties 2)))
3979 (if (or (not sec
) (not parsedp
)) sec
3981 (org-element--parse-objects
3982 (match-beginning 2) (match-end 2) nil restrict
))))))
3983 ;; Attribute a property name to KWD.
3984 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3985 ;; Now set final shape for VALUE.
3988 (org-element--parse-objects
3990 (progn (end-of-line) (skip-chars-backward " \t") (point))
3993 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3994 (when (or (member kwd org-element-multiple-keywords
)
3995 ;; Attributes can always appear on multiple lines.
3996 (string-match "^ATTR_" kwd
))
3997 (setq value
(cons value
(plist-get output kwd-sym
))))
3998 ;; Eventually store the new value in OUTPUT.
3999 (setq output
(plist-put output kwd-sym value
))
4000 ;; Move to next keyword.
4002 ;; If affiliated keywords are orphaned: move back to first one.
4003 ;; They will be parsed as a paragraph.
4004 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
4006 (cons origin output
))))
4012 ;; The two major functions here are `org-element-parse-buffer', which
4013 ;; parses Org syntax inside the current buffer, taking into account
4014 ;; region, narrowing, or even visibility if specified, and
4015 ;; `org-element-parse-secondary-string', which parses objects within
4018 ;; The (almost) almighty `org-element-map' allows applying a function
4019 ;; on elements or objects matching some type, and accumulating the
4020 ;; resulting values. In an export situation, it also skips unneeded
4021 ;; parts of the parse tree.
4023 (defun org-element-parse-buffer (&optional granularity visible-only
)
4024 "Recursively parse the buffer and return structure.
4025 If narrowing is in effect, only parse the visible part of the
4028 Optional argument GRANULARITY determines the depth of the
4029 recursion. It can be set to the following symbols:
4031 `headline' Only parse headlines.
4032 `greater-element' Don't recurse into greater elements excepted
4033 headlines and sections. Thus, elements
4034 parsed are the top-level ones.
4035 `element' Parse everything but objects and plain text.
4036 `object' Parse the complete buffer (default).
4038 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4041 An element or an objects is represented as a list with the
4042 pattern (TYPE PROPERTIES CONTENTS), where :
4044 TYPE is a symbol describing the element or object. See
4045 `org-element-all-elements' and `org-element-all-objects' for an
4046 exhaustive list of such symbols. One can retrieve it with
4047 `org-element-type' function.
4049 PROPERTIES is the list of attributes attached to the element or
4050 object, as a plist. Although most of them are specific to the
4051 element or object type, all types share `:begin', `:end',
4052 `:post-blank' and `:parent' properties, which respectively
4053 refer to buffer position where the element or object starts,
4054 ends, the number of white spaces or blank lines after it, and
4055 the element or object containing it. Properties values can be
4056 obtained by using `org-element-property' function.
4058 CONTENTS is a list of elements, objects or raw strings
4059 contained in the current element or object, when applicable.
4060 One can access them with `org-element-contents' function.
4062 The Org buffer has `org-data' as type and nil as properties.
4063 `org-element-map' function can be used to find specific elements
4064 or objects within the parse tree.
4066 This function assumes that current major mode is `org-mode'."
4068 (goto-char (point-min))
4069 (org-skip-whitespace)
4070 (org-element--parse-elements
4071 (point-at-bol) (point-max)
4072 ;; Start in `first-section' mode so text before the first
4073 ;; headline belongs to a section.
4074 'first-section nil granularity visible-only
(list 'org-data nil
))))
4076 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
4077 "Recursively parse objects in STRING and return structure.
4079 RESTRICTION is a symbol limiting the object types that will be
4082 Optional argument PARENT, when non-nil, is the element or object
4083 containing the secondary string. It is used to set correctly
4084 `:parent' property within the string.
4086 If STRING is the empty string or nil, return nil."
4089 ((equal string
"") nil
)
4090 (t (let ((local-variables (buffer-local-variables)))
4092 (dolist (v local-variables
)
4094 (if (symbolp v
) (makunbound v
)
4095 (set (make-local-variable (car v
)) (cdr v
)))))
4097 (restore-buffer-modified-p nil
)
4098 (org-element--parse-objects
4099 (point-min) (point-max) nil restriction parent
))))))
4101 (defun org-element-map
4102 (data types fun
&optional info first-match no-recursion with-affiliated
)
4103 "Map a function on selected elements or objects.
4105 DATA is a parse tree, an element, an object, a string, or a list
4106 of such constructs. TYPES is a symbol or list of symbols of
4107 elements or objects types (see `org-element-all-elements' and
4108 `org-element-all-objects' for a complete list of types). FUN is
4109 the function called on the matching element or object. It has to
4110 accept one argument: the element or object itself.
4112 When optional argument INFO is non-nil, it should be a plist
4113 holding export options. In that case, parts of the parse tree
4114 not exportable according to that property list will be skipped.
4116 When optional argument FIRST-MATCH is non-nil, stop at the first
4117 match for which FUN doesn't return nil, and return that value.
4119 Optional argument NO-RECURSION is a symbol or a list of symbols
4120 representing elements or objects types. `org-element-map' won't
4121 enter any recursive element or object whose type belongs to that
4122 list. Though, FUN can still be applied on them.
4124 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4125 apply to matching objects within parsed affiliated keywords (see
4126 `org-element-parsed-keywords').
4128 Nil values returned from FUN do not appear in the results.
4134 Assuming TREE is a variable containing an Org buffer parse tree,
4135 the following example will return a flat list of all `src-block'
4136 and `example-block' elements in it:
4138 (org-element-map tree \\='(example-block src-block) #\\='identity)
4140 The following snippet will find the first headline with a level
4141 of 1 and a \"phone\" tag, and will return its beginning position:
4143 (org-element-map tree \\='headline
4145 (and (= (org-element-property :level hl) 1)
4146 (member \"phone\" (org-element-property :tags hl))
4147 (org-element-property :begin hl)))
4150 The next example will return a flat list of all `plain-list' type
4151 elements in TREE that are not a sub-list themselves:
4153 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4155 Eventually, this example will return a flat list of all `bold'
4156 type objects containing a `latex-snippet' type object, even
4157 looking into captions:
4159 (org-element-map tree \\='bold
4161 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4163 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4164 (let* ((types (if (listp types
) types
(list types
)))
4165 (no-recursion (if (listp no-recursion
) no-recursion
4166 (list no-recursion
)))
4167 ;; Recursion depth is determined by --CATEGORY.
4170 (let ((category 'greater-elements
)
4171 (all-objects (cons 'plain-text org-element-all-objects
)))
4172 (dolist (type types category
)
4173 (cond ((memq type all-objects
)
4174 ;; If one object is found, the function has
4175 ;; to recurse into every object.
4176 (throw :--found
'objects
))
4177 ((not (memq type org-element-greater-elements
))
4178 ;; If one regular element is found, the
4179 ;; function has to recurse, at least, into
4180 ;; every element it encounters.
4181 (and (not (eq category
'elements
))
4182 (setq category
'elements
))))))))
4184 (letrec ((--walk-tree
4186 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4187 ;; holding contextual information.
4188 (let ((--type (org-element-type --data
)))
4191 ;; Ignored element in an export context.
4192 ((and info
(memq --data
(plist-get info
:ignore-list
))))
4193 ;; List of elements or objects.
4194 ((not --type
) (mapc --walk-tree --data
))
4195 ;; Unconditionally enter parse trees.
4196 ((eq --type
'org-data
)
4197 (mapc --walk-tree
(org-element-contents --data
)))
4199 ;; Check if TYPE is matching among TYPES. If so,
4200 ;; apply FUN to --DATA and accumulate return value
4201 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4202 (when (memq --type types
)
4203 (let ((result (funcall fun --data
)))
4204 (cond ((not result
))
4205 (first-match (throw :--map-first-match result
))
4206 (t (push result --acc
)))))
4207 ;; If --DATA has a secondary string that can contain
4208 ;; objects with their type among TYPES, look inside.
4209 (when (and (eq --category
'objects
) (not (stringp --data
)))
4210 (dolist (p (cdr (assq --type
4211 org-element-secondary-value-alist
)))
4212 (funcall --walk-tree
(org-element-property p --data
))))
4213 ;; If --DATA has any parsed affiliated keywords and
4214 ;; WITH-AFFILIATED is non-nil, look for objects in
4216 (when (and with-affiliated
4217 (eq --category
'objects
)
4218 (eq (org-element-class --data
) 'element
))
4219 (dolist (kwd-pair org-element--parsed-properties-alist
)
4220 (let ((kwd (car kwd-pair
))
4221 (value (org-element-property (cdr kwd-pair
) --data
)))
4222 ;; Pay attention to the type of parsed
4223 ;; keyword. In particular, preserve order for
4224 ;; multiple keywords.
4227 ((member kwd org-element-dual-keywords
)
4228 (if (member kwd org-element-multiple-keywords
)
4229 (dolist (line (reverse value
))
4230 (funcall --walk-tree
(cdr line
))
4231 (funcall --walk-tree
(car line
)))
4232 (funcall --walk-tree
(cdr value
))
4233 (funcall --walk-tree
(car value
))))
4234 ((member kwd org-element-multiple-keywords
)
4235 (mapc --walk-tree
(reverse value
)))
4236 (t (funcall --walk-tree value
))))))
4237 ;; Determine if a recursion into --DATA is possible.
4239 ;; --TYPE is explicitly removed from recursion.
4240 ((memq --type no-recursion
))
4241 ;; --DATA has no contents.
4242 ((not (org-element-contents --data
)))
4243 ;; Looking for greater elements but --DATA is
4244 ;; simply an element or an object.
4245 ((and (eq --category
'greater-elements
)
4246 (not (memq --type org-element-greater-elements
))))
4247 ;; Looking for elements but --DATA is an object.
4248 ((and (eq --category
'elements
)
4249 (eq (org-element-class --data
) 'object
)))
4250 ;; In any other case, map contents.
4251 (t (mapc --walk-tree
(org-element-contents --data
))))))))))
4252 (catch :--map-first-match
4253 (funcall --walk-tree data
)
4254 ;; Return value in a proper order.
4255 (nreverse --acc
)))))
4256 (put 'org-element-map
'lisp-indent-function
2)
4258 ;; The following functions are internal parts of the parser.
4260 ;; The first one, `org-element--parse-elements' acts at the element's
4263 ;; The second one, `org-element--parse-objects' applies on all objects
4264 ;; of a paragraph or a secondary string. It calls
4265 ;; `org-element--object-lex' to find the next object in the current
4268 (defsubst org-element--next-mode
(type parentp
)
4269 "Return next special mode according to TYPE, or nil.
4270 TYPE is a symbol representing the type of an element or object
4271 containing next element if PARENTP is non-nil, or before it
4272 otherwise. Modes can be either `first-section', `item',
4273 `node-property', `planning', `property-drawer', `section',
4274 `table-row' or nil."
4277 (`headline
'section
)
4278 (`inlinetask
'planning
)
4280 (`property-drawer
'node-property
)
4281 (`section
'planning
)
4282 (`table
'table-row
))
4285 (`node-property
'node-property
)
4286 (`planning
'property-drawer
)
4287 (`table-row
'table-row
))))
4289 (defun org-element--parse-elements
4290 (beg end mode structure granularity visible-only acc
)
4291 "Parse elements between BEG and END positions.
4293 MODE prioritizes some elements over the others. It can be set to
4294 `first-section', `section', `planning', `item', `node-property'
4297 When value is `item', STRUCTURE will be used as the current list
4300 GRANULARITY determines the depth of the recursion. See
4301 `org-element-parse-buffer' for more information.
4303 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4306 Elements are accumulated into ACC."
4309 ;; Visible only: skip invisible parts at the beginning of the
4311 (when (and visible-only
(org-invisible-p2))
4312 (goto-char (min (1+ (org-find-visible)) end
)))
4313 ;; When parsing only headlines, skip any text before first one.
4314 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4315 (org-with-limited-levels (outline-next-heading)))
4317 (while (< (point) end
)
4318 ;; Find current element's type and parse it accordingly to
4320 (let* ((element (org-element--current-element
4321 end granularity mode structure
))
4322 (type (org-element-type element
))
4323 (cbeg (org-element-property :contents-begin element
)))
4324 (goto-char (org-element-property :end element
))
4325 ;; Visible only: skip invisible parts between siblings.
4326 (when (and visible-only
(org-invisible-p2))
4327 (goto-char (min (1+ (org-find-visible)) end
)))
4328 ;; Fill ELEMENT contents by side-effect.
4330 ;; If element has no contents, don't modify it.
4332 ;; Greater element: parse it between `contents-begin' and
4333 ;; `contents-end'. Make sure GRANULARITY allows the
4334 ;; recursion, or ELEMENT is a headline, in which case going
4335 ;; inside is mandatory, in order to get sub-level headings.
4336 ((and (memq type org-element-greater-elements
)
4337 (or (memq granularity
'(element object nil
))
4338 (and (eq granularity
'greater-element
)
4340 (eq type
'headline
)))
4341 (org-element--parse-elements
4342 cbeg
(org-element-property :contents-end element
)
4343 ;; Possibly switch to a special mode.
4344 (org-element--next-mode type t
)
4345 (and (memq type
'(item plain-list
))
4346 (org-element-property :structure element
))
4347 granularity visible-only element
))
4348 ;; ELEMENT has contents. Parse objects inside, if
4349 ;; GRANULARITY allows it.
4350 ((memq granularity
'(object nil
))
4351 (org-element--parse-objects
4352 cbeg
(org-element-property :contents-end element
) element
4353 (org-element-restriction type
))))
4354 (push (org-element-put-property element
:parent acc
) elements
)
4356 (setq mode
(org-element--next-mode type nil
))))
4358 (apply #'org-element-set-contents acc
(nreverse elements
)))))
4360 (defun org-element--object-lex (restriction)
4361 "Return next object in current buffer or nil.
4362 RESTRICTION is a list of object types, as symbols, that should be
4363 looked after. This function assumes that the buffer is narrowed
4364 to an appropriate container (e.g., a paragraph)."
4365 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4366 (let* ((start (point))
4369 (cond ((not org-target-link-regexp
) nil
)
4370 ((not (memq 'link restriction
)) nil
)
4372 (unless (bolp) (forward-char -
1))
4373 (not (re-search-forward org-target-link-regexp nil t
)))
4375 ;; Since we moved backward, we do not want to
4376 ;; match again an hypothetical 1-character long
4377 ;; radio link before us. Realizing that this can
4378 ;; only happen if such a radio link starts at
4379 ;; beginning of line, we prevent this here.
4380 ((and (= start
(1+ (line-beginning-position)))
4381 (= start
(match-end 1)))
4382 (and (re-search-forward org-target-link-regexp nil t
)
4383 (match-beginning 1)))
4384 (t (match-beginning 1)))))
4387 (while (and (not found
)
4388 (re-search-forward org-element--object-regexp limit
'move
))
4389 (goto-char (match-beginning 0))
4390 (let ((result (match-string 0)))
4393 ((string-prefix-p "call_" result t
)
4394 (and (memq 'inline-babel-call restriction
)
4395 (org-element-inline-babel-call-parser)))
4396 ((string-prefix-p "src_" result t
)
4397 (and (memq 'inline-src-block restriction
)
4398 (org-element-inline-src-block-parser)))
4401 (?^
(and (memq 'superscript restriction
)
4402 (org-element-superscript-parser)))
4403 (?_
(or (and (memq 'subscript restriction
)
4404 (org-element-subscript-parser))
4405 (and (memq 'underline restriction
)
4406 (org-element-underline-parser))))
4407 (?
* (and (memq 'bold restriction
)
4408 (org-element-bold-parser)))
4409 (?
/ (and (memq 'italic restriction
)
4410 (org-element-italic-parser)))
4411 (?~
(and (memq 'code restriction
)
4412 (org-element-code-parser)))
4413 (?
= (and (memq 'verbatim restriction
)
4414 (org-element-verbatim-parser)))
4415 (?
+ (and (memq 'strike-through restriction
)
4416 (org-element-strike-through-parser)))
4417 (?
@ (and (memq 'export-snippet restriction
)
4418 (org-element-export-snippet-parser)))
4419 (?
{ (and (memq 'macro restriction
)
4420 (org-element-macro-parser)))
4421 (?$
(and (memq 'latex-fragment restriction
)
4422 (org-element-latex-fragment-parser)))
4424 (if (eq (aref result
1) ?
<)
4425 (or (and (memq 'radio-target restriction
)
4426 (org-element-radio-target-parser))
4427 (and (memq 'target restriction
)
4428 (org-element-target-parser)))
4429 (or (and (memq 'timestamp restriction
)
4430 (org-element-timestamp-parser))
4431 (and (memq 'link restriction
)
4432 (org-element-link-parser)))))
4434 (if (eq (aref result
1) ?
\\)
4435 (and (memq 'line-break restriction
)
4436 (org-element-line-break-parser))
4437 (or (and (memq 'entity restriction
)
4438 (org-element-entity-parser))
4439 (and (memq 'latex-fragment restriction
)
4440 (org-element-latex-fragment-parser)))))
4442 (if (eq (aref result
1) ?\
[)
4443 (and (memq 'link restriction
)
4444 (org-element-link-parser))
4445 (or (and (memq 'footnote-reference restriction
)
4446 (org-element-footnote-reference-parser))
4447 (and (memq 'timestamp restriction
)
4448 (org-element-timestamp-parser))
4449 (and (memq 'statistics-cookie restriction
)
4450 (org-element-statistics-cookie-parser)))))
4451 ;; This is probably a plain link.
4452 (_ (and (memq 'link restriction
)
4453 (org-element-link-parser)))))))
4454 (or (eobp) (forward-char))))
4456 (limit (org-element-link-parser)) ;radio link
4459 (defun org-element--parse-objects (beg end acc restriction
&optional parent
)
4460 "Parse objects between BEG and END and return recursive structure.
4462 Objects are accumulated in ACC. RESTRICTION is a list of object
4463 successors which are allowed in the current object.
4465 ACC becomes the parent for all parsed objects. However, if ACC
4466 is nil (i.e., a secondary string is being parsed) and optional
4467 argument PARENT is non-nil, use it as the parent for all objects.
4468 Eventually, if both ACC and PARENT are nil, the common parent is
4469 the list of objects itself."
4472 (narrow-to-region beg end
)
4473 (goto-char (point-min))
4474 (let (next-object contents
)
4475 (while (and (not (eobp))
4476 (setq next-object
(org-element--object-lex restriction
)))
4477 ;; Text before any object.
4478 (let ((obj-beg (org-element-property :begin next-object
)))
4479 (unless (= (point) obj-beg
)
4480 (let ((text (buffer-substring-no-properties (point) obj-beg
)))
4481 (push (if acc
(org-element-put-property text
:parent acc
) text
)
4484 (let ((obj-end (org-element-property :end next-object
))
4485 (cont-beg (org-element-property :contents-begin next-object
)))
4486 (when acc
(org-element-put-property next-object
:parent acc
))
4488 ;; Fill contents of NEXT-OBJECT if possible.
4489 (org-element--parse-objects
4491 (org-element-property :contents-end next-object
)
4493 (org-element-restriction next-object
))
4496 (goto-char obj-end
)))
4497 ;; Text after last object.
4499 (let ((text (buffer-substring-no-properties (point) end
)))
4500 (push (if acc
(org-element-put-property text
:parent acc
) text
)
4502 ;; Result. Set appropriate parent.
4503 (if acc
(apply #'org-element-set-contents acc
(nreverse contents
))
4504 (let* ((contents (nreverse contents
))
4505 (parent (or parent contents
)))
4506 (dolist (datum contents contents
)
4507 (org-element-put-property datum
:parent parent
))))))))
4511 ;;; Towards A Bijective Process
4513 ;; The parse tree obtained with `org-element-parse-buffer' is really
4514 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4515 ;; interpreted and expanded into a string with canonical Org syntax.
4516 ;; Hence `org-element-interpret-data'.
4518 ;; The function relies internally on
4519 ;; `org-element--interpret-affiliated-keywords'.
4522 (defun org-element-interpret-data (data)
4523 "Interpret DATA as Org syntax.
4524 DATA is a parse tree, an element, an object or a secondary string
4525 to interpret. Return Org syntax as a string."
4527 (lambda (data parent
)
4528 (let* ((type (org-element-type data
))
4529 ;; Find interpreter for current object or
4530 ;; element. If it doesn't exist (e.g. this is
4531 ;; a pseudo object or element), return contents,
4535 (format "org-element-%s-interpreter" type
))))
4536 (if (fboundp fun
) fun
(lambda (_ contents
) contents
))))
4539 ;; Secondary string.
4541 (mapconcat (lambda (obj) (funcall fun obj parent
))
4544 ;; Full Org document.
4545 ((eq type
'org-data
)
4546 (mapconcat (lambda (obj) (funcall fun obj parent
))
4547 (org-element-contents data
)
4549 ;; Plain text: return it.
4550 ((stringp data
) data
)
4551 ;; Element or object without contents.
4552 ((not (org-element-contents data
))
4553 (funcall interpret data nil
))
4554 ;; Element or object with contents.
4559 ;; Recursively interpret contents.
4561 (lambda (datum) (funcall fun datum data
))
4562 (org-element-contents
4563 (if (not (memq type
'(paragraph verse-block
)))
4565 ;; Fix indentation of elements containing
4566 ;; objects. We ignore `table-row'
4567 ;; elements as they are one line long
4569 (org-element-normalize-contents
4571 ;; When normalizing first paragraph of
4572 ;; an item or a footnote-definition,
4573 ;; ignore first line's indentation.
4574 (and (eq type
'paragraph
)
4575 (memq (org-element-type parent
)
4576 '(footnote-definition item
))
4578 (car (org-element-contents parent
)))))))
4580 (if (memq type
'(org-data plain-text nil
)) results
4581 ;; Build white spaces. If no `:post-blank' property
4582 ;; is specified, assume its value is 0.
4583 (let ((blank (or (org-element-property :post-blank data
) 0)))
4584 (if (eq (org-element-class data parent
) 'object
)
4585 (concat results
(make-string blank ?\s
))
4586 (concat (org-element--interpret-affiliated-keywords data
)
4587 (org-element-normalize-string results
)
4588 (make-string blank ?
\n)))))))))
4589 (funcall fun data nil
)))
4591 (defun org-element--interpret-affiliated-keywords (element)
4592 "Return ELEMENT's affiliated keywords as Org syntax.
4593 If there is no affiliated keyword, return the empty string."
4594 (let ((keyword-to-org
4598 (when (member key org-element-dual-keywords
)
4599 (setq dual
(cdr value
) value
(car value
)))
4602 (format "[%s]" (org-element-interpret-data dual
)))
4604 (if (member key org-element-parsed-keywords
)
4605 (org-element-interpret-data value
)
4610 (let ((value (org-element-property prop element
))
4611 (keyword (upcase (substring (symbol-name prop
) 1))))
4613 (if (or (member keyword org-element-multiple-keywords
)
4614 ;; All attribute keywords can have multiple lines.
4615 (string-match "^ATTR_" keyword
))
4616 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4619 (funcall keyword-to-org keyword value
)))))
4620 ;; List all ELEMENT's properties matching an attribute line or an
4621 ;; affiliated keyword, but ignore translated keywords since they
4622 ;; cannot belong to the property list.
4623 (cl-loop for prop in
(nth 1 element
) by
'cddr
4624 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4625 (or (string-match "^ATTR_" keyword
)
4627 (member keyword org-element-affiliated-keywords
)
4629 org-element-keyword-translation-alist
)))))
4633 ;; Because interpretation of the parse tree must return the same
4634 ;; number of blank lines between elements and the same number of white
4635 ;; space after objects, some special care must be given to white
4638 ;; The first function, `org-element-normalize-string', ensures any
4639 ;; string different from the empty string will end with a single
4640 ;; newline character.
4642 ;; The second function, `org-element-normalize-contents', removes
4643 ;; global indentation from the contents of the current element.
4645 (defun org-element-normalize-string (s)
4646 "Ensure string S ends with a single newline character.
4648 If S isn't a string return it unchanged. If S is the empty
4649 string, return it. Otherwise, return a new string with a single
4650 newline character at its end."
4652 ((not (stringp s
)) s
)
4654 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4655 (replace-match "\n" nil nil s
)))))
4657 (defun org-element-normalize-contents (element &optional ignore-first
)
4658 "Normalize plain text in ELEMENT's contents.
4660 ELEMENT must only contain plain text and objects.
4662 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4663 indentation to compute maximal common indentation.
4665 Return the normalized element that is element with global
4666 indentation removed from its contents."
4667 (letrec ((find-min-ind
4668 ;; Return minimal common indentation within BLOB. This is
4669 ;; done by walking recursively BLOB and updating MIN-IND
4670 ;; along the way. FIRST-FLAG is non-nil when the next
4671 ;; object is expected to be a string that doesn't start
4672 ;; with a newline character. It happens for strings at
4673 ;; the beginnings of the contents or right after a line
4675 (lambda (blob first-flag min-ind
)
4676 (dolist (datum (org-element-contents blob
) min-ind
)
4678 (setq first-flag nil
)
4680 ;; Objects cannot start with spaces: in this
4681 ;; case, indentation is 0.
4682 ((not (stringp datum
)) (throw :zero
0))
4684 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum
))
4686 ((equal (match-string 2 datum
) "\n")
4688 (match-beginning 1) (match-end 1) 'org-ind
'empty datum
))
4690 (let ((i (string-width (match-string 1 datum
))))
4692 (match-beginning 1) (match-end 1) 'org-ind i datum
)
4693 (setq min-ind
(min i min-ind
))))))
4697 (while (string-match
4698 "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s
)
4699 (setq s
(match-end 1))
4701 ((equal (match-string 1 datum
) "")
4702 (unless (member (match-string 2 datum
) '("" "\n"))
4704 ((equal (match-string 2 datum
) "\n")
4705 (put-text-property (match-beginning 1) (match-end 1)
4706 'org-ind
'empty datum
))
4708 (let ((i (string-width (match-string 1 datum
))))
4709 (put-text-property (match-beginning 1) (match-end 1)
4711 (setq min-ind
(min i min-ind
))))))))
4712 ((eq (org-element-type datum
) 'line-break
)
4713 (setq first-flag t
))
4714 ((memq (org-element-type datum
) org-element-recursive-objects
)
4716 (funcall find-min-ind datum first-flag min-ind
)))))))
4719 (funcall find-min-ind
4720 element
(not ignore-first
) most-positive-fixnum
))))
4721 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4722 ;; Build ELEMENT back, replacing each string with the same
4723 ;; string minus common indentation.
4726 ;; Return DATUM with all its strings indentation
4727 ;; shortened from MIN-IND white spaces.
4736 (let ((s (point-min)))
4737 (while (setq s
(text-property-not-all
4738 s
(point-max) 'org-ind nil
))
4740 (let ((i (get-text-property s
'org-ind
)))
4741 (delete-region s
(progn
4742 (skip-chars-forward " \t")
4744 (when (integerp i
) (indent-to (- i min-ind
))))))
4746 ((memq (org-element-type object
)
4747 org-element-recursive-objects
)
4748 (funcall build object
))
4750 (org-element-contents datum
)))
4752 (funcall build element
)))))
4758 ;; Implement a caching mechanism for `org-element-at-point' and
4759 ;; `org-element-context', which see.
4761 ;; A single public function is provided: `org-element-cache-reset'.
4763 ;; Cache is enabled by default, but can be disabled globally with
4764 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4765 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4766 ;; can be tweaked to control caching behaviour.
4768 ;; Internally, parsed elements are stored in an AVL tree,
4769 ;; `org-element--cache'. This tree is updated lazily: whenever
4770 ;; a change happens to the buffer, a synchronization request is
4771 ;; registered in `org-element--cache-sync-requests' (see
4772 ;; `org-element--cache-submit-request'). During idle time, requests
4773 ;; are processed by `org-element--cache-sync'. Synchronization also
4774 ;; happens when an element is required from the cache. In this case,
4775 ;; the process stops as soon as the needed element is up-to-date.
4777 ;; A synchronization request can only apply on a synchronized part of
4778 ;; the cache. Therefore, the cache is updated at least to the
4779 ;; location where the new request applies. Thus, requests are ordered
4780 ;; from left to right and all elements starting before the first
4781 ;; request are correct. This property is used by functions like
4782 ;; `org-element--cache-find' to retrieve elements in the part of the
4783 ;; cache that can be trusted.
4785 ;; A request applies to every element, starting from its original
4786 ;; location (or key, see below). When a request is processed, it
4787 ;; moves forward and may collide the next one. In this case, both
4788 ;; requests are merged into a new one that starts from that element.
4789 ;; As a consequence, the whole synchronization complexity does not
4790 ;; depend on the number of pending requests, but on the number of
4791 ;; elements the very first request will be applied on.
4793 ;; Elements cannot be accessed through their beginning position, which
4794 ;; may or may not be up-to-date. Instead, each element in the tree is
4795 ;; associated to a key, obtained with `org-element--cache-key'. This
4796 ;; mechanism is robust enough to preserve total order among elements
4797 ;; even when the tree is only partially synchronized.
4800 (defvar org-element-use-cache nil
4801 "Non-nil when Org parser should cache its results.
4803 WARNING: for the time being, using cache sometimes triggers
4804 freezes. Therefore, it is disabled by default. Activate it if
4805 you want to help debugging the issue.")
4807 (defvar org-element-cache-sync-idle-time
0.6
4808 "Length, in seconds, of idle time before syncing cache.")
4810 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4811 "Maximum duration, as a time value, for a cache synchronization.
4812 If the synchronization is not over after this delay, the process
4813 pauses and resumes after `org-element-cache-sync-break'
4816 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4817 "Duration, as a time value, of the pause between synchronizations.
4818 See `org-element-cache-sync-duration' for more information.")
4823 (defvar org-element--cache nil
4824 "AVL tree used to cache elements.
4825 Each node of the tree contains an element. Comparison is done
4826 with `org-element--cache-compare'. This cache is used in
4827 `org-element-at-point'.")
4829 (defvar org-element--cache-sync-requests nil
4830 "List of pending synchronization requests.
4832 A request is a vector with the following pattern:
4834 \[NEXT BEG END OFFSET PARENT PHASE]
4836 Processing a synchronization request consists of three phases:
4838 0. Delete modified elements,
4839 1. Fill missing area in cache,
4840 2. Shift positions and re-parent elements after the changes.
4842 During phase 0, NEXT is the key of the first element to be
4843 removed, BEG and END is buffer position delimiting the
4844 modifications. Elements starting between them (inclusive) are
4845 removed. So are elements whose parent is removed. PARENT, when
4846 non-nil, is the parent of the first element to be removed.
4848 During phase 1, NEXT is the key of the next known element in
4849 cache and BEG its beginning position. Parse buffer between that
4850 element and the one before it in order to determine the parent of
4851 the next element. Set PARENT to the element containing NEXT.
4853 During phase 2, NEXT is the key of the next element to shift in
4854 the parse tree. All elements starting from this one have their
4855 properties relatives to buffer positions shifted by integer
4856 OFFSET and, if they belong to element PARENT, are adopted by it.
4858 PHASE specifies the phase number, as an integer.")
4860 (defvar org-element--cache-sync-timer nil
4861 "Timer used for cache synchronization.")
4863 (defvar org-element--cache-sync-keys nil
4864 "Hash table used to store keys during synchronization.
4865 See `org-element--cache-key' for more information.")
4867 (defsubst org-element--cache-key
(element)
4868 "Return a unique key for ELEMENT in cache tree.
4870 Keys are used to keep a total order among elements in the cache.
4871 Comparison is done with `org-element--cache-key-less-p'.
4873 When no synchronization is taking place, a key is simply the
4874 beginning position of the element, or that position plus one in
4875 the case of an first item (respectively row) in
4876 a list (respectively a table).
4878 During a synchronization, the key is the one the element had when
4879 the cache was synchronized for the last time. Elements added to
4880 cache during the synchronization get a new key generated with
4881 `org-element--cache-generate-key'.
4883 Such keys are stored in `org-element--cache-sync-keys'. The hash
4884 table is cleared once the synchronization is complete."
4885 (or (gethash element org-element--cache-sync-keys
)
4886 (let* ((begin (org-element-property :begin element
))
4887 ;; Increase beginning position of items (respectively
4888 ;; table rows) by one, so the first item can get
4889 ;; a different key from its parent list (respectively
4891 (key (if (memq (org-element-type element
) '(item table-row
))
4894 (if org-element--cache-sync-requests
4895 (puthash element key org-element--cache-sync-keys
)
4898 (defun org-element--cache-generate-key (lower upper
)
4899 "Generate a key between LOWER and UPPER.
4901 LOWER and UPPER are integers or lists, possibly empty.
4903 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4904 a unique key, as an integer or a list of integers, according to
4905 the following rules:
4907 - LOWER and UPPER are compared level-wise until values differ.
4909 - If, at a given level, LOWER and UPPER differ from more than
4910 2, the new key shares all the levels above with LOWER and
4911 gets a new level. Its value is the mean between LOWER and
4914 (1 2) + (1 4) --> (1 3)
4916 - If LOWER has no value to compare with, it is assumed that its
4917 value is `most-negative-fixnum'. E.g.,
4925 where m is `most-negative-fixnum'. Likewise, if UPPER is
4926 short of levels, the current value is `most-positive-fixnum'.
4928 - If they differ from only one, the new key inherits from
4929 current LOWER level and fork it at the next level. E.g.,
4937 where M is `most-positive-fixnum'.
4939 - If the key is only one level long, it is returned as an
4944 When they are not equals, the function assumes that LOWER is
4945 lesser than UPPER, per `org-element--cache-key-less-p'."
4946 (if (equal lower upper
) lower
4947 (let ((lower (if (integerp lower
) (list lower
) lower
))
4948 (upper (if (integerp upper
) (list upper
) upper
))
4952 (let ((min (or (car lower
) most-negative-fixnum
))
4953 (max (cond (skip-upper most-positive-fixnum
)
4955 (t most-positive-fixnum
))))
4956 (if (< (1+ min
) max
)
4957 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4958 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4959 (when (and (< min max
) (not skip-upper
))
4960 ;; When at a given level, LOWER and UPPER differ from
4961 ;; 1, ignore UPPER altogether. Instead create a key
4962 ;; between LOWER and the greatest key with the same
4963 ;; prefix as LOWER so far.
4964 (setq skip-upper t
))
4966 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
4968 (defsubst org-element--cache-key-less-p
(a b
)
4969 "Non-nil if key A is less than key B.
4970 A and B are either integers or lists of integers, as returned by
4971 `org-element--cache-key'."
4972 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4973 (if (integerp b
) (< (car a
) b
)
4976 (cond ((car-less-than-car a b
) (throw 'exit t
))
4977 ((car-less-than-car b a
) (throw 'exit nil
))
4978 (t (setq a
(cdr a
) b
(cdr b
)))))
4979 ;; If A is empty, either keys are equal (B is also empty) and
4980 ;; we return nil, or A is lesser than B (B is longer) and we
4981 ;; return a non-nil value.
4983 ;; If A is not empty, B is necessarily empty and A is greater
4984 ;; than B (A is longer). Therefore, return nil.
4985 (and (null a
) b
)))))
4987 (defun org-element--cache-compare (a b
)
4988 "Non-nil when element A is located before element B."
4989 (org-element--cache-key-less-p (org-element--cache-key a
)
4990 (org-element--cache-key b
)))
4992 (defsubst org-element--cache-root
()
4993 "Return root value in cache.
4994 This function assumes `org-element--cache' is a valid AVL tree."
4995 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
5000 (defsubst org-element--cache-active-p
()
5001 "Non-nil when cache is active in current buffer."
5002 (and org-element-use-cache
5004 (derived-mode-p 'org-mode
)))
5006 (defun org-element--cache-find (pos &optional side
)
5007 "Find element in cache starting at POS or before.
5009 POS refers to a buffer position.
5011 When optional argument SIDE is non-nil, the function checks for
5012 elements starting at or past POS instead. If SIDE is `both', the
5013 function returns a cons cell where car is the first element
5014 starting at or before POS and cdr the first element starting
5017 The function can only find elements in the synchronized part of
5019 (let ((limit (and org-element--cache-sync-requests
5020 (aref (car org-element--cache-sync-requests
) 0)))
5021 (node (org-element--cache-root))
5024 (let* ((element (avl-tree--node-data node
))
5025 (begin (org-element-property :begin element
)))
5028 (not (org-element--cache-key-less-p
5029 (org-element--cache-key element
) limit
)))
5030 (setq node
(avl-tree--node-left node
)))
5033 node
(avl-tree--node-left node
)))
5036 node
(avl-tree--node-right node
)))
5037 ;; We found an element in cache starting at POS. If `side'
5038 ;; is `both' we also want the next one in order to generate
5039 ;; a key in-between.
5041 ;; If the element is the first row or item in a table or
5042 ;; a plain list, we always return the table or the plain
5045 ;; In any other case, we return the element found.
5047 (setq lower element
)
5048 (setq node
(avl-tree--node-right node
)))
5049 ((and (memq (org-element-type element
) '(item table-row
))
5050 (let ((parent (org-element-property :parent element
)))
5051 (and (= (org-element-property :begin element
)
5052 (org-element-property :contents-begin parent
))
5061 (`both
(cons lower upper
))
5065 (defun org-element--cache-put (element)
5066 "Store ELEMENT in current buffer's cache, if allowed."
5067 (when (org-element--cache-active-p)
5068 (when org-element--cache-sync-requests
5069 ;; During synchronization, first build an appropriate key for
5070 ;; the new element so `avl-tree-enter' can insert it at the
5071 ;; right spot in the cache.
5072 (let ((keys (org-element--cache-find
5073 (org-element-property :begin element
) 'both
)))
5075 (org-element--cache-generate-key
5076 (and (car keys
) (org-element--cache-key (car keys
)))
5077 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
5078 (org-element--cache-sync-requests
5079 (aref (car org-element--cache-sync-requests
) 0))))
5080 org-element--cache-sync-keys
)))
5081 (avl-tree-enter org-element--cache element
)))
5083 (defsubst org-element--cache-remove
(element)
5084 "Remove ELEMENT from cache.
5085 Assume ELEMENT belongs to cache and that a cache is active."
5086 (avl-tree-delete org-element--cache element
))
5089 ;;;; Synchronization
5091 (defsubst org-element--cache-set-timer
(buffer)
5092 "Set idle timer for cache synchronization in BUFFER."
5093 (when org-element--cache-sync-timer
5094 (cancel-timer org-element--cache-sync-timer
))
5095 (setq org-element--cache-sync-timer
5096 (run-with-idle-timer
5097 (let ((idle (current-idle-time)))
5098 (if idle
(time-add idle org-element-cache-sync-break
)
5099 org-element-cache-sync-idle-time
))
5101 #'org-element--cache-sync
5104 (defsubst org-element--cache-interrupt-p
(time-limit)
5105 "Non-nil when synchronization process should be interrupted.
5106 TIME-LIMIT is a time value or nil."
5108 (or (input-pending-p)
5109 (time-less-p time-limit
(current-time)))))
5111 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
5112 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5114 Properties containing buffer positions are `:begin', `:end',
5115 `:contents-begin', `:contents-end' and `:structure'. When
5116 optional argument PROPS is a list of keywords, only shift
5117 properties provided in that list.
5119 Properties are modified by side-effect."
5120 (let ((properties (nth 1 element
)))
5121 ;; Shift `:structure' property for the first plain list only: it
5122 ;; is the only one that really matters and it prevents from
5123 ;; shifting it more than once.
5124 (when (and (or (not props
) (memq :structure props
))
5125 (eq (org-element-type element
) 'plain-list
)
5126 (not (eq (org-element-type (plist-get properties
:parent
))
5128 (dolist (item (plist-get properties
:structure
))
5129 (cl-incf (car item
) offset
)
5130 (cl-incf (nth 6 item
) offset
)))
5131 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
5132 (let ((value (and (or (not props
) (memq key props
))
5133 (plist-get properties key
))))
5134 (and value
(plist-put properties key
(+ offset value
)))))))
5136 (defun org-element--cache-sync (buffer &optional threshold future-change
)
5137 "Synchronize cache with recent modification in BUFFER.
5139 When optional argument THRESHOLD is non-nil, do the
5140 synchronization for all elements starting before or at threshold,
5141 then exit. Otherwise, synchronize cache for as long as
5142 `org-element-cache-sync-duration' or until Emacs leaves idle
5145 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5146 not registered yet in the cache are going to happen. It is used
5147 in `org-element--cache-submit-request', where cache is partially
5148 updated before current modification are actually submitted."
5149 (when (buffer-live-p buffer
)
5150 (with-current-buffer buffer
5151 (let ((inhibit-quit t
) request next
)
5152 (when org-element--cache-sync-timer
5153 (cancel-timer org-element--cache-sync-timer
))
5155 (while org-element--cache-sync-requests
5156 (setq request
(car org-element--cache-sync-requests
)
5157 next
(nth 1 org-element--cache-sync-requests
))
5158 (org-element--cache-process-request
5160 (and next
(aref next
0))
5162 (and (not threshold
)
5163 (time-add (current-time)
5164 org-element-cache-sync-duration
))
5166 ;; Request processed. Merge current and next offsets and
5167 ;; transfer ending position.
5169 (cl-incf (aref next
3) (aref request
3))
5170 (aset next
2 (aref request
2)))
5171 (setq org-element--cache-sync-requests
5172 (cdr org-element--cache-sync-requests
))))
5173 ;; If more requests are awaiting, set idle timer accordingly.
5174 ;; Otherwise, reset keys.
5175 (if org-element--cache-sync-requests
5176 (org-element--cache-set-timer buffer
)
5177 (clrhash org-element--cache-sync-keys
))))))
5179 (defun org-element--cache-process-request
5180 (request next threshold time-limit future-change
)
5181 "Process synchronization REQUEST for all entries before NEXT.
5183 REQUEST is a vector, built by `org-element--cache-submit-request'.
5185 NEXT is a cache key, as returned by `org-element--cache-key'.
5187 When non-nil, THRESHOLD is a buffer position. Synchronization
5188 stops as soon as a shifted element begins after it.
5190 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5191 after this time or when Emacs exits idle state.
5193 When non-nil, FUTURE-CHANGE is a buffer position where changes
5194 not registered yet in the cache are going to happen. See
5195 `org-element--cache-submit-request' for more information.
5197 Throw `interrupt' if the process stops before completing the
5200 (when (= (aref request
5) 0)
5203 ;; Delete all elements starting after BEG, but not after buffer
5204 ;; position END or past element with key NEXT. Also delete
5205 ;; elements contained within a previously removed element
5206 ;; (stored in `last-container').
5208 ;; At each iteration, we start again at tree root since
5209 ;; a deletion modifies structure of the balanced tree.
5212 (when (org-element--cache-interrupt-p time-limit
)
5213 (throw 'interrupt nil
))
5214 ;; Find first element in cache with key BEG or after it.
5215 (let ((beg (aref request
0))
5216 (end (aref request
2))
5217 (node (org-element--cache-root))
5218 data data-key last-container
)
5220 (let* ((element (avl-tree--node-data node
))
5221 (key (org-element--cache-key element
)))
5223 ((org-element--cache-key-less-p key beg
)
5224 (setq node
(avl-tree--node-right node
)))
5225 ((org-element--cache-key-less-p beg key
)
5228 node
(avl-tree--node-left node
)))
5229 (t (setq data element
5233 (let ((pos (org-element-property :begin data
)))
5234 (if (if (or (not next
)
5235 (org-element--cache-key-less-p data-key next
))
5239 (while (and up
(not (eq up last-container
)))
5240 (setq up
(org-element-property :parent up
)))
5242 (progn (when (and (not last-container
)
5243 (> (org-element-property :end data
)
5245 (setq last-container data
))
5246 (org-element--cache-remove data
))
5247 (aset request
0 data-key
)
5248 (aset request
1 pos
)
5250 (throw 'end-phase nil
)))
5251 ;; No element starting after modifications left in
5252 ;; cache: further processing is futile.
5253 (throw 'quit t
))))))
5254 (when (= (aref request
5) 1)
5257 ;; Phase 0 left a hole in the cache. Some elements after it
5258 ;; could have parents within. For example, in the following
5268 ;; if we remove a blank line between "item" and "Paragraph1",
5269 ;; everything down to "Paragraph2" is removed from cache. But
5270 ;; the paragraph now belongs to the list, and its `:parent'
5271 ;; property no longer is accurate.
5273 ;; Therefore we need to parse again elements in the hole, or at
5274 ;; least in its last section, so that we can re-parent
5275 ;; subsequent elements, during phase 2.
5277 ;; Note that we only need to get the parent from the first
5278 ;; element in cache after the hole.
5280 ;; When next key is lesser or equal to the current one, delegate
5281 ;; phase 1 processing to next request in order to preserve key
5282 ;; order among requests.
5283 (let ((key (aref request
0)))
5284 (when (and next
(not (org-element--cache-key-less-p key next
)))
5285 (let ((next-request (nth 1 org-element--cache-sync-requests
)))
5286 (aset next-request
0 key
)
5287 (aset next-request
1 (aref request
1))
5288 (aset next-request
5 1))
5290 ;; Next element will start at its beginning position plus
5291 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5292 ;; contains the real beginning position of the first element to
5293 ;; shift and re-parent.
5294 (let ((limit (+ (aref request
1) (aref request
3))))
5295 (cond ((and threshold
(> limit threshold
)) (throw 'interrupt nil
))
5296 ((and future-change
(>= limit future-change
))
5297 ;; Changes are going to happen around this element and
5298 ;; they will trigger another phase 1 request. Skip the
5302 (let ((parent (org-element--parse-to limit t time-limit
)))
5303 (aset request
4 parent
)
5304 (aset request
5 2))))))
5307 ;; Shift all elements starting from key START, but before NEXT, by
5308 ;; OFFSET, and re-parent them when appropriate.
5310 ;; Elements are modified by side-effect so the tree structure
5313 ;; Once THRESHOLD, if any, is reached, or once there is an input
5314 ;; pending, exit. Before leaving, the current synchronization
5315 ;; request is updated.
5316 (let ((start (aref request
0))
5317 (offset (aref request
3))
5318 (parent (aref request
4))
5319 (node (org-element--cache-root))
5323 ;; No re-parenting nor shifting planned: request is over.
5324 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5326 (let* ((data (avl-tree--node-data node
))
5327 (key (org-element--cache-key data
)))
5328 (if (and leftp
(avl-tree--node-left node
)
5329 (not (org-element--cache-key-less-p key start
)))
5330 (progn (push node stack
)
5331 (setq node
(avl-tree--node-left node
)))
5332 (unless (org-element--cache-key-less-p key start
)
5333 ;; We reached NEXT. Request is complete.
5334 (when (equal key next
) (throw 'quit t
))
5335 ;; Handle interruption request. Update current request.
5336 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5337 (aset request
0 key
)
5338 (aset request
4 parent
)
5339 (throw 'interrupt nil
))
5341 (unless (zerop offset
)
5342 (org-element--cache-shift-positions data offset
))
5343 (let ((begin (org-element-property :begin data
)))
5344 ;; Update PARENT and re-parent DATA, only when
5345 ;; necessary. Propagate new structures for lists.
5347 (<= (org-element-property :end parent
) begin
))
5348 (setq parent
(org-element-property :parent parent
)))
5349 (cond ((and (not parent
) (zerop offset
)) (throw 'quit nil
))
5351 (let ((p (org-element-property :parent data
)))
5353 (< (org-element-property :begin p
)
5354 (org-element-property :begin parent
)))))
5355 (org-element-put-property data
:parent parent
)
5356 (let ((s (org-element-property :structure parent
)))
5357 (when (and s
(org-element-property :structure data
))
5358 (org-element-put-property data
:structure s
)))))
5359 ;; Cache is up-to-date past THRESHOLD. Request
5361 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5362 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5363 (avl-tree--node-right node
)
5365 ;; We reached end of tree: synchronization complete.
5368 (defun org-element--parse-to (pos &optional syncp time-limit
)
5369 "Parse elements in current section, down to POS.
5371 Start parsing from the closest between the last known element in
5372 cache or headline above. Return the smallest element containing
5375 When optional argument SYNCP is non-nil, return the parent of the
5376 element containing POS instead. In that case, it is also
5377 possible to provide TIME-LIMIT, which is a time value specifying
5378 when the parsing should stop. The function throws `interrupt' if
5379 the process stopped before finding the expected result."
5381 (org-with-wide-buffer
5383 (let* ((cached (and (org-element--cache-active-p)
5384 (org-element--cache-find pos nil
)))
5385 (begin (org-element-property :begin cached
))
5388 ;; Nothing in cache before point: start parsing from first
5389 ;; element following headline above, or first element in
5392 (when (org-with-limited-levels (outline-previous-heading))
5393 (setq mode
'planning
)
5395 (skip-chars-forward " \r\t\n")
5396 (beginning-of-line))
5397 ;; Cache returned exact match: return it.
5399 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5400 ;; There's a headline between cached value and POS: cached
5401 ;; value is invalid. Start parsing from first element
5402 ;; following the headline.
5403 ((re-search-backward
5404 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5406 (skip-chars-forward " \r\t\n")
5408 (setq mode
'planning
))
5409 ;; Check if CACHED or any of its ancestors contain point.
5411 ;; If there is such an element, we inspect it in order to know
5412 ;; if we return it or if we need to parse its contents.
5413 ;; Otherwise, we just start parsing from current location,
5414 ;; which is right after the top-most element containing
5417 ;; As a special case, if POS is at the end of the buffer, we
5418 ;; want to return the innermost element ending there.
5420 ;; Also, if we find an ancestor and discover that we need to
5421 ;; parse its contents, make sure we don't start from
5422 ;; `:contents-begin', as we would otherwise go past CACHED
5423 ;; again. Instead, in that situation, we will resume parsing
5424 ;; from NEXT, which is located after CACHED or its higher
5425 ;; ancestor not containing point.
5428 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5429 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5430 (while (let ((end (org-element-property :end up
)))
5433 (setq up
(org-element-property :parent up
)))))
5435 ((eobp) (setq element up
))
5436 (t (setq element up next
(point)))))))
5437 ;; Parse successively each element until we reach POS.
5438 (let ((end (or (org-element-property :end element
)
5440 (org-with-limited-levels (outline-next-heading))
5445 (cond ((= (point) pos
) (throw 'exit parent
))
5446 ((org-element--cache-interrupt-p time-limit
)
5447 (throw 'interrupt nil
))))
5449 (setq element
(org-element--current-element
5451 (org-element-property :structure parent
)))
5452 (org-element-put-property element
:parent parent
)
5453 (org-element--cache-put element
))
5454 (let ((elem-end (org-element-property :end element
))
5455 (type (org-element-type element
)))
5457 ;; Skip any element ending before point. Also skip
5458 ;; element ending at point (unless it is also the end of
5459 ;; buffer) since we're sure that another element begins
5461 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5462 (goto-char elem-end
)
5463 (setq mode
(org-element--next-mode type nil
)))
5464 ;; A non-greater element contains point: return it.
5465 ((not (memq type org-element-greater-elements
))
5466 (throw 'exit element
))
5467 ;; Otherwise, we have to decide if ELEMENT really
5468 ;; contains POS. In that case we start parsing from
5469 ;; contents' beginning.
5471 ;; If POS is at contents' beginning but it is also at
5472 ;; the beginning of the first item in a list or a table.
5473 ;; In that case, we need to create an anchor for that
5474 ;; list or table, so return it.
5476 ;; Also, if POS is at the end of the buffer, no element
5477 ;; can start after it, but more than one may end there.
5478 ;; Arbitrarily, we choose to return the innermost of
5480 ((let ((cbeg (org-element-property :contents-begin element
))
5481 (cend (org-element-property :contents-end element
)))
5486 (not (memq type
'(plain-list table
)))))
5488 (and (= cend pos
) (= (point-max) pos
)))))
5489 (goto-char (or next cbeg
))
5491 mode
(org-element--next-mode type t
)
5494 ;; Otherwise, return ELEMENT as it is the smallest
5495 ;; element containing POS.
5496 (t (throw 'exit element
))))
5497 (setq element nil
)))))))
5500 ;;;; Staging Buffer Changes
5502 (defconst org-element--cache-sensitive-re
5504 org-outline-regexp-bol
"\\|"
5505 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5507 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5508 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5509 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5511 "Regexp matching a sensitive line, structure wise.
5512 A sensitive line is a headline, inlinetask, block, drawer, or
5513 latex-environment boundary. When such a line is modified,
5514 structure changes in the document may propagate in the whole
5515 section, possibly making cache invalid.")
5517 (defvar org-element--cache-change-warning nil
5518 "Non-nil when a sensitive line is about to be changed.
5519 It is a symbol among nil, t and `headline'.")
5521 (defun org-element--cache-before-change (beg end
)
5522 "Request extension of area going to be modified if needed.
5523 BEG and END are the beginning and end of the range of changed
5524 text. See `before-change-functions' for more information."
5525 (when (org-element--cache-active-p)
5526 (org-with-wide-buffer
5529 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5530 (setq org-element--cache-change-warning
5532 (if (and (org-with-limited-levels (org-at-heading-p))
5533 (= (line-end-position) bottom
))
5535 (let ((case-fold-search t
))
5537 org-element--cache-sensitive-re bottom t
)))))))))
5539 (defun org-element--cache-after-change (beg end pre
)
5540 "Update buffer modifications for current buffer.
5541 BEG and END are the beginning and end of the range of changed
5542 text, and the length in bytes of the pre-change text replaced by
5543 that range. See `after-change-functions' for more information."
5544 (when (org-element--cache-active-p)
5545 (org-with-wide-buffer
5550 (bottom (save-excursion (goto-char end
) (line-end-position))))
5551 ;; Determine if modified area needs to be extended, according
5552 ;; to both previous and current state. We make a special
5553 ;; case for headline editing: if a headline is modified but
5554 ;; not removed, do not extend.
5555 (when (pcase org-element--cache-change-warning
5558 (not (and (org-with-limited-levels (org-at-heading-p))
5559 (= (line-end-position) bottom
))))
5561 (let ((case-fold-search t
))
5563 org-element--cache-sensitive-re bottom t
))))
5564 ;; Effectively extend modified area.
5565 (org-with-limited-levels
5566 (setq top
(progn (goto-char top
)
5567 (when (outline-previous-heading) (forward-line))
5569 (setq bottom
(progn (goto-char bottom
)
5570 (if (outline-next-heading) (1- (point))
5572 ;; Store synchronization request.
5573 (let ((offset (- end beg pre
)))
5574 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5575 ;; Activate a timer to process the request during idle time.
5576 (org-element--cache-set-timer (current-buffer))))
5578 (defun org-element--cache-for-removal (beg end offset
)
5579 "Return first element to remove from cache.
5581 BEG and END are buffer positions delimiting buffer modifications.
5582 OFFSET is the size of the changes.
5584 Returned element is usually the first element in cache containing
5585 any position between BEG and END. As an exception, greater
5586 elements around the changes that are robust to contents
5587 modifications are preserved and updated according to the
5589 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5590 (before (car elements
))
5591 (after (cdr elements
)))
5592 (if (not before
) after
5596 (if (let ((type (org-element-type up
)))
5597 (and (or (memq type
'(center-block dynamic-block quote-block
5599 ;; Drawers named "PROPERTIES" are probably
5600 ;; a properties drawer being edited. Force
5601 ;; parsing to check if editing is over.
5602 (and (eq type
'drawer
)
5604 (org-element-property :drawer-name up
)
5606 (let ((cbeg (org-element-property :contents-begin up
)))
5609 (> (org-element-property :contents-end up
) end
)))))
5610 ;; UP is a robust greater element containing changes.
5611 ;; We only need to extend its ending boundaries.
5612 (org-element--cache-shift-positions
5613 up offset
'(:contents-end
:end
))
5615 (when robust-flag
(setq robust-flag nil
)))
5616 (setq up
(org-element-property :parent up
)))
5617 ;; We're at top level element containing ELEMENT: if it's
5618 ;; altered by buffer modifications, it is first element in
5619 ;; cache to be removed. Otherwise, that first element is the
5622 ;; As a special case, do not remove BEFORE if it is a robust
5623 ;; container for current changes.
5624 (if (or (< (org-element-property :end before
) beg
) robust-flag
) after
5627 (defun org-element--cache-submit-request (beg end offset
)
5628 "Submit a new cache synchronization request for current buffer.
5629 BEG and END are buffer positions delimiting the minimal area
5630 where cache data should be removed. OFFSET is the size of the
5631 change, as an integer."
5632 (let ((next (car org-element--cache-sync-requests
))
5633 delete-to delete-from
)
5635 (zerop (aref next
5))
5636 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5637 (<= (setq delete-from
(aref next
1)) end
))
5638 ;; Current changes can be merged with first sync request: we
5639 ;; can save a partial cache synchronization.
5641 (cl-incf (aref next
3) offset
)
5642 ;; If last change happened within area to be removed, extend
5643 ;; boundaries of robust parents, if any. Otherwise, find
5644 ;; first element to remove and update request accordingly.
5645 (if (> beg delete-from
)
5646 (let ((up (aref next
4)))
5648 (org-element--cache-shift-positions
5649 up offset
'(:contents-end
:end
))
5650 (setq up
(org-element-property :parent up
))))
5651 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5653 (aset next
0 (org-element--cache-key first
))
5654 (aset next
1 (org-element-property :begin first
))
5655 (aset next
4 (org-element-property :parent first
))))))
5656 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5657 ;; if any, is no longer a 0-phase request, thus ensuring that
5658 ;; phases are properly ordered. We need to provide OFFSET as
5659 ;; optional parameter since current modifications are not known
5660 ;; yet to the otherwise correct part of the cache (i.e, before
5661 ;; the first request).
5662 (when next
(org-element--cache-sync (current-buffer) end beg
))
5663 (let ((first (org-element--cache-for-removal beg end offset
)))
5665 (push (let ((beg (org-element-property :begin first
))
5666 (key (org-element--cache-key first
)))
5668 ;; When changes happen before the first known
5669 ;; element, re-parent and shift the rest of the
5671 ((> beg end
) (vector key beg nil offset nil
1))
5672 ;; Otherwise, we find the first non robust
5673 ;; element containing END. All elements between
5674 ;; FIRST and this one are to be removed.
5675 ((let ((first-end (org-element-property :end first
)))
5676 (and (> first-end end
)
5677 (vector key beg first-end offset first
0))))
5679 (let* ((element (org-element--cache-find end
))
5680 (end (org-element-property :end element
))
5682 (while (and (setq up
(org-element-property :parent up
))
5683 (>= (org-element-property :begin up
) beg
))
5684 (setq end
(org-element-property :end up
)
5686 (vector key beg end offset element
0)))))
5687 org-element--cache-sync-requests
)
5688 ;; No element to remove. No need to re-parent either.
5689 ;; Simply shift additional elements, if any, by OFFSET.
5690 (when org-element--cache-sync-requests
5691 (cl-incf (aref (car org-element--cache-sync-requests
) 3)
5695 ;;;; Public Functions
5698 (defun org-element-cache-reset (&optional all
)
5699 "Reset cache in current buffer.
5700 When optional argument ALL is non-nil, reset cache in all Org
5703 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5704 (with-current-buffer buffer
5705 (when (and org-element-use-cache
(derived-mode-p 'org-mode
))
5706 (setq-local org-element--cache
5707 (avl-tree-create #'org-element--cache-compare
))
5708 (setq-local org-element--cache-sync-keys
5709 (make-hash-table :weakness
'key
:test
#'eq
))
5710 (setq-local org-element--cache-change-warning nil
)
5711 (setq-local org-element--cache-sync-requests nil
)
5712 (setq-local org-element--cache-sync-timer nil
)
5713 (add-hook 'before-change-functions
5714 #'org-element--cache-before-change nil t
)
5715 (add-hook 'after-change-functions
5716 #'org-element--cache-after-change nil t
)))))
5719 (defun org-element-cache-refresh (pos)
5720 "Refresh cache at position POS."
5721 (when (org-element--cache-active-p)
5722 (org-element--cache-sync (current-buffer) pos
)
5723 (org-element--cache-submit-request pos pos
0)
5724 (org-element--cache-set-timer (current-buffer))))
5730 ;; The first move is to implement a way to obtain the smallest element
5731 ;; containing point. This is the job of `org-element-at-point'. It
5732 ;; basically jumps back to the beginning of section containing point
5733 ;; and proceed, one element after the other, with
5734 ;; `org-element--current-element' until the container is found. Note:
5735 ;; When using `org-element-at-point', secondary values are never
5736 ;; parsed since the function focuses on elements, not on objects.
5738 ;; At a deeper level, `org-element-context' lists all elements and
5739 ;; objects containing point.
5741 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5742 ;; internally by navigation and manipulation tools.
5746 (defun org-element-at-point ()
5747 "Determine closest element around point.
5749 Return value is a list like (TYPE PROPS) where TYPE is the type
5750 of the element and PROPS a plist of properties associated to the
5753 Possible types are defined in `org-element-all-elements'.
5754 Properties depend on element or object type, but always include
5755 `:begin', `:end', `:parent' and `:post-blank' properties.
5757 As a special case, if point is at the very beginning of the first
5758 item in a list or sub-list, returned element will be that list
5759 instead of the item. Likewise, if point is at the beginning of
5760 the first row of a table, returned element will be the table
5761 instead of the first row.
5763 When point is at the end of the buffer, return the innermost
5764 element ending there."
5765 (org-with-wide-buffer
5766 (let ((origin (point)))
5768 (skip-chars-backward " \r\t\n")
5770 ;; Within blank lines at the beginning of buffer, return nil.
5772 ;; Within blank lines right after a headline, return that
5774 ((org-with-limited-levels (org-at-heading-p))
5776 (org-element-headline-parser (point-max) t
))
5777 ;; Otherwise parse until we find element containing ORIGIN.
5779 (when (org-element--cache-active-p)
5780 (if (not org-element--cache
) (org-element-cache-reset)
5781 (org-element--cache-sync (current-buffer) origin
)))
5782 (org-element--parse-to origin
))))))
5785 (defun org-element-context (&optional element
)
5786 "Return smallest element or object around point.
5788 Return value is a list like (TYPE PROPS) where TYPE is the type
5789 of the element or object and PROPS a plist of properties
5792 Possible types are defined in `org-element-all-elements' and
5793 `org-element-all-objects'. Properties depend on element or
5794 object type, but always include `:begin', `:end', `:parent' and
5797 As a special case, if point is right after an object and not at
5798 the beginning of any other object, return that object.
5800 Optional argument ELEMENT, when non-nil, is the closest element
5801 containing point, as returned by `org-element-at-point'.
5802 Providing it allows for quicker computation."
5803 (catch 'objects-forbidden
5804 (org-with-wide-buffer
5805 (let* ((pos (point))
5806 (element (or element
(org-element-at-point)))
5807 (type (org-element-type element
))
5808 (post (org-element-property :post-affiliated element
)))
5809 ;; If point is inside an element containing objects or
5810 ;; a secondary string, narrow buffer to the container and
5811 ;; proceed with parsing. Otherwise, return ELEMENT.
5813 ;; At a parsed affiliated keyword, check if we're inside main
5815 ((and post
(< pos post
))
5817 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5819 ((not (member-ignore-case (match-string 1)
5820 org-element-parsed-keywords
))
5821 (throw 'objects-forbidden element
))
5822 ((< (match-end 0) pos
)
5823 (narrow-to-region (match-end 0) (line-end-position)))
5824 ((and (match-beginning 2)
5825 (>= pos
(match-beginning 2))
5826 (< pos
(match-end 2)))
5827 (narrow-to-region (match-beginning 2) (match-end 2)))
5828 (t (throw 'objects-forbidden element
)))
5829 ;; Also change type to retrieve correct restrictions.
5830 (setq type
'keyword
))
5831 ;; At an item, objects can only be located within tag, if any.
5833 (let ((tag (org-element-property :tag element
)))
5834 (if (or (not tag
) (/= (line-beginning-position) post
))
5835 (throw 'objects-forbidden element
)
5837 (search-forward tag
(line-end-position))
5838 (goto-char (match-beginning 0))
5839 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5840 (narrow-to-region (point) (match-end 0))
5841 (throw 'objects-forbidden element
)))))
5842 ;; At an headline or inlinetask, objects are in title.
5843 ((memq type
'(headline inlinetask
))
5844 (let ((case-fold-search nil
))
5845 (goto-char (org-element-property :begin element
))
5846 (looking-at org-complex-heading-regexp
)
5847 (let ((end (match-end 4)))
5848 (if (not end
) (throw 'objects-forbidden element
)
5849 (goto-char (match-beginning 4))
5850 (when (looking-at org-comment-string
)
5851 (goto-char (match-end 0)))
5852 (if (>= (point) end
) (throw 'objects-forbidden element
)
5853 (narrow-to-region (point) end
))))))
5854 ;; At a paragraph, a table-row or a verse block, objects are
5855 ;; located within their contents.
5856 ((memq type
'(paragraph table-row verse-block
))
5857 (let ((cbeg (org-element-property :contents-begin element
))
5858 (cend (org-element-property :contents-end element
)))
5859 ;; CBEG is nil for table rules.
5860 (if (and cbeg cend
(>= pos cbeg
)
5861 (or (< pos cend
) (and (= pos cend
) (eobp))))
5862 (narrow-to-region cbeg cend
)
5863 (throw 'objects-forbidden element
))))
5864 ;; At a planning line, if point is at a timestamp, return it,
5865 ;; otherwise, return element.
5866 ((eq type
'planning
)
5867 (dolist (p '(:closed
:deadline
:scheduled
))
5868 (let ((timestamp (org-element-property p element
)))
5869 (when (and timestamp
5870 (<= (org-element-property :begin timestamp
) pos
)
5871 (> (org-element-property :end timestamp
) pos
))
5872 (throw 'objects-forbidden timestamp
))))
5873 ;; All other locations cannot contain objects: bail out.
5874 (throw 'objects-forbidden element
))
5875 (t (throw 'objects-forbidden element
)))
5876 (goto-char (point-min))
5877 (let ((restriction (org-element-restriction type
))
5882 (let ((next (org-element--object-lex restriction
)))
5883 (when next
(org-element-put-property next
:parent parent
))
5884 ;; Process NEXT, if any, in order to know if we need to
5885 ;; skip it, return it or move into it.
5886 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5887 (throw 'exit
(or last parent
))
5888 (let ((end (org-element-property :end next
))
5889 (cbeg (org-element-property :contents-begin next
))
5890 (cend (org-element-property :contents-end next
)))
5892 ;; Skip objects ending before point. Also skip
5893 ;; objects ending at point unless it is also the
5894 ;; end of buffer, since we want to return the
5895 ;; innermost object.
5896 ((and (<= end pos
) (/= (point-max) end
))
5898 ;; For convenience, when object ends at POS,
5899 ;; without any space, store it in LAST, as we
5900 ;; will return it if no object starts here.
5901 (when (and (= end pos
)
5902 (not (memq (char-before) '(?\s ?
\t))))
5904 ;; If POS is within a container object, move into
5909 ;; At contents' end, if there is no
5910 ;; space before point, also move into
5911 ;; object, for consistency with
5912 ;; convenience feature above.
5914 (or (= (point-max) pos
)
5915 (not (memq (char-before pos
)
5918 (narrow-to-region (point) cend
)
5920 (setq restriction
(org-element-restriction next
)))
5921 ;; Otherwise, return NEXT.
5922 (t (throw 'exit next
)))))))))))))
5924 (defun org-element-lineage (blob &optional types with-self
)
5925 "List all ancestors of a given element or object.
5927 BLOB is an object or element.
5929 When optional argument TYPES is a list of symbols, return the
5930 first element or object in the lineage whose type belongs to that
5933 When optional argument WITH-SELF is non-nil, lineage includes
5934 BLOB itself as the first element, and TYPES, if provided, also
5937 When BLOB is obtained through `org-element-context' or
5938 `org-element-at-point', only ancestors from its section can be
5939 found. There is no such limitation when BLOB belongs to a full
5941 (let ((up (if with-self blob
(org-element-property :parent blob
)))
5943 (while (and up
(not (memq (org-element-type up
) types
)))
5944 (unless types
(push up ancestors
))
5945 (setq up
(org-element-property :parent up
)))
5946 (if types up
(nreverse ancestors
))))
5948 (defun org-element-nested-p (elem-A elem-B
)
5949 "Non-nil when elements ELEM-A and ELEM-B are nested."
5950 (let ((beg-A (org-element-property :begin elem-A
))
5951 (beg-B (org-element-property :begin elem-B
))
5952 (end-A (org-element-property :end elem-A
))
5953 (end-B (org-element-property :end elem-B
)))
5954 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5955 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5957 (defun org-element-swap-A-B (elem-A elem-B
)
5958 "Swap elements ELEM-A and ELEM-B.
5959 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5961 (goto-char (org-element-property :begin elem-A
))
5962 ;; There are two special cases when an element doesn't start at bol:
5963 ;; the first paragraph in an item or in a footnote definition.
5964 (let ((specialp (not (bolp))))
5965 ;; Only a paragraph without any affiliated keyword can be moved at
5966 ;; ELEM-A position in such a situation. Note that the case of
5967 ;; a footnote definition is impossible: it cannot contain two
5968 ;; paragraphs in a row because it cannot contain a blank line.
5970 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5971 (/= (org-element-property :begin elem-B
)
5972 (org-element-property :contents-begin elem-B
))))
5973 (error "Cannot swap elements"))
5974 ;; In a special situation, ELEM-A will have no indentation. We'll
5975 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5976 (let* ((ind-B (when specialp
5977 (goto-char (org-element-property :begin elem-B
))
5978 (org-get-indentation)))
5979 (beg-A (org-element-property :begin elem-A
))
5980 (end-A (save-excursion
5981 (goto-char (org-element-property :end elem-A
))
5982 (skip-chars-backward " \r\t\n")
5984 (beg-B (org-element-property :begin elem-B
))
5985 (end-B (save-excursion
5986 (goto-char (org-element-property :end elem-B
))
5987 (skip-chars-backward " \r\t\n")
5989 ;; Store inner overlays responsible for visibility status.
5990 ;; We also need to store their boundaries as they will be
5991 ;; removed from buffer.
5996 (and (>= (overlay-start o
) beg-A
)
5997 (<= (overlay-end o
) end-A
)
5998 (list o
(overlay-start o
) (overlay-end o
))))
5999 (overlays-in beg-A end-A
)))
6002 (and (>= (overlay-start o
) beg-B
)
6003 (<= (overlay-end o
) end-B
)
6004 (list o
(overlay-start o
) (overlay-end o
))))
6005 (overlays-in beg-B end-B
)))))
6007 (body-A (buffer-substring beg-A end-A
))
6008 (body-B (delete-and-extract-region beg-B end-B
)))
6011 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
6012 (indent-to-column ind-B
))
6014 ;; Restore ex ELEM-A overlays.
6015 (let ((offset (- beg-B beg-A
)))
6016 (dolist (o (car overlays
))
6017 (move-overlay (car o
) (+ (nth 1 o
) offset
) (+ (nth 2 o
) offset
)))
6019 (delete-region beg-A end-A
)
6021 ;; Restore ex ELEM-B overlays.
6022 (dolist (o (cdr overlays
))
6023 (move-overlay (car o
) (- (nth 1 o
) offset
) (- (nth 2 o
) offset
))))
6024 (goto-char (org-element-property :end elem-B
)))))
6027 (provide 'org-element
)
6030 ;; generated-autoload-file: "org-loaddefs.el"
6033 ;;; org-element.el ends here