org-attach: Fix git annex test directories
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob6eabf7661b60f5464b342468eb2b806c35c4a680
1 ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2016 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/>.
23 ;;; Commentary:
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
89 ;; list.
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
114 ;; these functions.
117 ;;; Code:
119 (require 'org)
120 (require 'avl-tree)
121 (require 'cl-lib)
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
132 ;; to current setup.
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
150 (concat "^\\(?:"
151 ;; Headlines, inlinetasks.
152 org-outline-regexp "\\|"
153 ;; Footnote definitions.
154 "\\[fn:[-_[:word:]]+\\]" "\\|"
155 ;; Diary sexps.
156 "%%(" "\\|"
157 "[ \t]*\\(?:"
158 ;; Empty lines.
159 "$" "\\|"
160 ;; Tables (any type).
161 "|" "\\|"
162 "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
163 ;; Comments, keyword-like or block-like constructs.
164 ;; Blocks and keywords with dual values need to be
165 ;; double-checked.
166 "#\\(?: \\|$\\|\\+\\(?:"
167 "BEGIN_\\S-+" "\\|"
168 "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
169 "\\|"
170 ;; Drawers (any type) and fixed-width areas. Drawers
171 ;; need to be double-checked.
172 ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
173 ;; Horizontal rules.
174 "-\\{5,\\}[ \t]*$" "\\|"
175 ;; LaTeX environments.
176 "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
177 ;; Clock lines.
178 (regexp-quote org-clock-string) "\\|"
179 ;; Lists.
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]\\|$\\)"))
185 "\\)\\)")
186 org-element--object-regexp
187 (mapconcat #'identity
188 (let ((link-types (regexp-opt org-link-types)))
189 (list
190 ;; Sub/superscript.
191 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
192 ;; Bold, code, italic, strike-through, underline
193 ;; and verbatim.
194 (concat "[*~=+_/]"
195 (format "[^%s]"
196 (nth 2 org-emphasis-regexp-components)))
197 ;; Plain links.
198 (concat "\\<" link-types ":")
199 ;; Objects starting with "[": regular link,
200 ;; footnote reference, statistics cookie,
201 ;; timestamp (inactive).
202 (concat "\\[\\(?:"
203 "fn:" "\\|"
204 "\\[" "\\|"
205 "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" "\\|"
206 "[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
207 "\\)")
208 ;; Objects starting with "@": export snippets.
209 "@@"
210 ;; Objects starting with "{": macro.
211 "{{{"
212 ;; Objects starting with "<" : timestamp
213 ;; (active, diary), target, radio target and
214 ;; angular links.
215 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
216 ;; Objects starting with "$": latex fragment.
217 "\\$"
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\\)_"))
224 "\\|")))
226 (org-element--set-regexps)
228 ;;;###autoload
229 (defun org-element-update-syntax ()
230 "Update parser internals."
231 (interactive)
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
247 special-block table)
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
297 strings and objects.
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
307 see.")
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]*"
323 (concat
324 ;; Dual affiliated keywords.
325 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
326 (regexp-opt org-element-dual-keywords))
327 "\\|"
328 ;; Regular affiliated keywords.
329 (format "\\(?1:%s\\)"
330 (regexp-opt
331 (cl-remove-if
332 (lambda (k) (member k org-element-dual-keywords))
333 org-element-affiliated-keywords)))
334 "\\|"
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
341 match group 2.
343 Don't modify it, set `org-element-affiliated-keywords' instead.")
345 (defconst org-element-object-restrictions
346 (let* ((standard-set (remq 'table-cell org-element-all-objects))
347 (standard-set-no-line-break (remq 'line-break standard-set)))
348 `((bold ,@standard-set)
349 (footnote-reference ,@standard-set)
350 (headline ,@standard-set-no-line-break)
351 (inlinetask ,@standard-set-no-line-break)
352 (italic ,@standard-set)
353 (item ,@standard-set-no-line-break)
354 (keyword ,@(remq 'footnote-reference standard-set))
355 ;; Ignore all links excepted plain links in a link description.
356 ;; Also ignore radio-targets and line breaks.
357 (link bold code entity export-snippet inline-babel-call inline-src-block
358 italic latex-fragment macro plain-link statistics-cookie
359 strike-through 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
380 of such type.
382 For example, in a `radio-target' object, one can only find
383 entities, latex-fragments, subscript, superscript and text
384 markup.
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
391 '((headline :title)
392 (inlinetask :title)
393 (item :tag))
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.")
425 ;;; Accessors and Setters
427 ;; Provide four accessors: `org-element-type', `org-element-property'
428 ;; `org-element-contents' and `org-element-restriction'.
430 ;; Setter functions allow modification of elements by side effect.
431 ;; There is `org-element-put-property', `org-element-set-contents'.
432 ;; These low-level functions are useful to build a parse tree.
434 ;; `org-element-adopt-element', `org-element-set-element',
435 ;; `org-element-extract-element' and `org-element-insert-before' are
436 ;; high-level functions useful to modify a parse tree.
438 ;; `org-element-secondary-p' is a predicate used to know if a given
439 ;; object belongs to a secondary string. `org-element-copy' returns
440 ;; an element or object, stripping its parent property in the process.
442 (defsubst org-element-type (element)
443 "Return type of ELEMENT.
445 The function returns the type of the element or object provided.
446 It can also return the following special value:
447 `plain-text' for a string
448 `org-data' for a complete document
449 nil in any other case."
450 (cond
451 ((not (consp element)) (and (stringp element) 'plain-text))
452 ((symbolp (car element)) (car element))))
454 (defsubst org-element-property (property element)
455 "Extract the value from the PROPERTY of an ELEMENT."
456 (if (stringp element) (get-text-property 0 property element)
457 (plist-get (nth 1 element) property)))
459 (defsubst org-element-contents (element)
460 "Extract contents from an ELEMENT."
461 (cond ((not (consp element)) nil)
462 ((symbolp (car element)) (nthcdr 2 element))
463 (t element)))
465 (defsubst org-element-restriction (element)
466 "Return restriction associated to ELEMENT.
467 ELEMENT can be an element, an object or a symbol representing an
468 element or object type."
469 (cdr (assq (if (symbolp element) element (org-element-type element))
470 org-element-object-restrictions)))
472 (defsubst org-element-put-property (element property value)
473 "In ELEMENT set PROPERTY to VALUE.
474 Return modified element."
475 (if (stringp element) (org-add-props element nil property value)
476 (setcar (cdr element) (plist-put (nth 1 element) property value))
477 element))
479 (defsubst org-element-set-contents (element &rest contents)
480 "Set ELEMENT's contents to CONTENTS.
481 Return ELEMENT."
482 (cond ((null element) contents)
483 ((not (symbolp (car element))) contents)
484 ((cdr element) (setcdr (cdr element) contents) element)
485 (t (nconc element contents))))
487 (defun org-element-secondary-p (object)
488 "Non-nil when OBJECT directly belongs to a secondary string.
489 Return value is the property name, as a keyword, or nil."
490 (let* ((parent (org-element-property :parent object))
491 (properties (cdr (assq (org-element-type parent)
492 org-element-secondary-value-alist))))
493 (catch 'exit
494 (dolist (p properties)
495 (and (memq object (org-element-property p parent))
496 (throw 'exit p))))))
498 (defsubst org-element-adopt-elements (parent &rest children)
499 "Append elements to the contents of another element.
501 PARENT is an element or object. CHILDREN can be elements,
502 objects, or a strings.
504 The function takes care of setting `:parent' property for CHILD.
505 Return parent element."
506 (if (not children) parent
507 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
508 ;; string: parent is the list itself.
509 (dolist (child children)
510 (org-element-put-property child :parent (or parent children)))
511 ;; Add CHILDREN at the end of PARENT contents.
512 (when parent
513 (apply #'org-element-set-contents
514 parent
515 (nconc (org-element-contents parent) children)))
516 ;; Return modified PARENT element.
517 (or parent children)))
519 (defun org-element-extract-element (element)
520 "Extract ELEMENT from parse tree.
521 Remove element from the parse tree by side-effect, and return it
522 with its `:parent' property stripped out."
523 (let ((parent (org-element-property :parent element))
524 (secondary (org-element-secondary-p element)))
525 (if secondary
526 (org-element-put-property
527 parent secondary
528 (delq element (org-element-property secondary parent)))
529 (apply #'org-element-set-contents
530 parent
531 (delq element (org-element-contents parent))))
532 ;; Return ELEMENT with its :parent removed.
533 (org-element-put-property element :parent nil)))
535 (defun org-element-insert-before (element location)
536 "Insert ELEMENT before LOCATION in parse tree.
537 LOCATION is an element, object or string within the parse tree.
538 Parse tree is modified by side effect."
539 (let* ((parent (org-element-property :parent location))
540 (property (org-element-secondary-p location))
541 (siblings (if property (org-element-property property parent)
542 (org-element-contents parent)))
543 ;; Special case: LOCATION is the first element of an
544 ;; independent secondary string (e.g. :title property). Add
545 ;; ELEMENT in-place.
546 (specialp (and (not property)
547 (eq siblings parent)
548 (eq (car parent) location))))
549 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
550 (cond (specialp)
551 ((or (null siblings) (eq (car siblings) location))
552 (push element siblings))
553 ((null location) (nconc siblings (list element)))
554 (t (let ((previous (cadr (memq location (reverse siblings)))))
555 (if (not previous)
556 (error "No location found to insert element")
557 (let ((next (memq previous siblings)))
558 (setcdr next (cons element (cdr next))))))))
559 ;; Store SIBLINGS at appropriate place in parse tree.
560 (cond
561 (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
562 (property (org-element-put-property parent property siblings))
563 (t (apply #'org-element-set-contents parent siblings)))
564 ;; Set appropriate :parent property.
565 (org-element-put-property element :parent parent)))
567 (defun org-element-set-element (old new)
568 "Replace element or object OLD with element or object NEW.
569 The function takes care of setting `:parent' property for NEW."
570 ;; Ensure OLD and NEW have the same parent.
571 (org-element-put-property new :parent (org-element-property :parent old))
572 (if (or (memq (org-element-type old) '(plain-text nil))
573 (memq (org-element-type new) '(plain-text nil)))
574 ;; We cannot replace OLD with NEW since one of them is not an
575 ;; object or element. We take the long path.
576 (progn (org-element-insert-before new old)
577 (org-element-extract-element old))
578 ;; Since OLD is going to be changed into NEW by side-effect, first
579 ;; make sure that every element or object within NEW has OLD as
580 ;; parent.
581 (dolist (blob (org-element-contents new))
582 (org-element-put-property blob :parent old))
583 ;; Transfer contents.
584 (apply #'org-element-set-contents old (org-element-contents new))
585 ;; Overwrite OLD's properties with NEW's.
586 (setcar (cdr old) (nth 1 new))
587 ;; Transfer type.
588 (setcar old (car new))))
590 (defun org-element-create (type &optional props &rest children)
591 "Create a new element of type TYPE.
592 Optional argument PROPS, when non-nil, is a plist defining the
593 properties of the element. CHILDREN can be elements, objects or
594 strings."
595 (apply #'org-element-adopt-elements (list type props) children))
597 (defun org-element-copy (datum)
598 "Return a copy of DATUM.
599 DATUM is an element, object, string or nil. `:parent' property
600 is cleared and contents are removed in the process."
601 (when datum
602 (let ((type (org-element-type datum)))
603 (pcase type
604 (`org-data (list 'org-data nil))
605 (`plain-text (substring-no-properties datum))
606 (`nil (copy-sequence datum))
608 (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
612 ;;; Greater elements
614 ;; For each greater element type, we define a parser and an
615 ;; interpreter.
617 ;; A parser returns the element or object as the list described above.
618 ;; Most of them accepts no argument. Though, exceptions exist. Hence
619 ;; every element containing a secondary string (see
620 ;; `org-element-secondary-value-alist') will accept an optional
621 ;; argument to toggle parsing of these secondary strings. Moreover,
622 ;; `item' parser requires current list's structure as its first
623 ;; element.
625 ;; An interpreter accepts two arguments: the list representation of
626 ;; the element or object, and its contents. The latter may be nil,
627 ;; depending on the element or object considered. It returns the
628 ;; appropriate Org syntax, as a string.
630 ;; Parsing functions must follow the naming convention:
631 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
632 ;; defined in `org-element-greater-elements'.
634 ;; Similarly, interpreting functions must follow the naming
635 ;; convention: org-element-TYPE-interpreter.
637 ;; With the exception of `headline' and `item' types, greater elements
638 ;; cannot contain other greater elements of their own type.
640 ;; Beside implementing a parser and an interpreter, adding a new
641 ;; greater element requires tweaking `org-element--current-element'.
642 ;; Moreover, the newly defined type must be added to both
643 ;; `org-element-all-elements' and `org-element-greater-elements'.
646 ;;;; Center Block
648 (defun org-element-center-block-parser (limit affiliated)
649 "Parse a center block.
651 LIMIT bounds the search. AFFILIATED is a list of which CAR is
652 the buffer position at the beginning of the first affiliated
653 keyword and CDR is a plist of affiliated keywords along with
654 their value.
656 Return a list whose CAR is `center-block' and CDR is a plist
657 containing `:begin', `:end', `:contents-begin', `:contents-end',
658 `:post-blank' and `:post-affiliated' keywords.
660 Assume point is at the beginning of the block."
661 (let ((case-fold-search t))
662 (if (not (save-excursion
663 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
664 ;; Incomplete block: parse it as a paragraph.
665 (org-element-paragraph-parser limit affiliated)
666 (let ((block-end-line (match-beginning 0)))
667 (let* ((begin (car affiliated))
668 (post-affiliated (point))
669 ;; Empty blocks have no contents.
670 (contents-begin (progn (forward-line)
671 (and (< (point) block-end-line)
672 (point))))
673 (contents-end (and contents-begin block-end-line))
674 (pos-before-blank (progn (goto-char block-end-line)
675 (forward-line)
676 (point)))
677 (end (save-excursion
678 (skip-chars-forward " \r\t\n" limit)
679 (if (eobp) (point) (line-beginning-position)))))
680 (list 'center-block
681 (nconc
682 (list :begin begin
683 :end end
684 :contents-begin contents-begin
685 :contents-end contents-end
686 :post-blank (count-lines pos-before-blank end)
687 :post-affiliated post-affiliated)
688 (cdr affiliated))))))))
690 (defun org-element-center-block-interpreter (_ contents)
691 "Interpret a center-block element as Org syntax.
692 CONTENTS is the contents of the element."
693 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
696 ;;;; Drawer
698 (defun org-element-drawer-parser (limit affiliated)
699 "Parse a drawer.
701 LIMIT bounds the search. AFFILIATED is a list of which CAR is
702 the buffer position at the beginning of the first affiliated
703 keyword and CDR is a plist of affiliated keywords along with
704 their value.
706 Return a list whose CAR is `drawer' and CDR is a plist containing
707 `:drawer-name', `:begin', `:end', `:contents-begin',
708 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
710 Assume point is at beginning of drawer."
711 (let ((case-fold-search t))
712 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
713 ;; Incomplete drawer: parse it as a paragraph.
714 (org-element-paragraph-parser limit affiliated)
715 (save-excursion
716 (let* ((drawer-end-line (match-beginning 0))
717 (name (progn (looking-at org-drawer-regexp)
718 (org-match-string-no-properties 1)))
719 (begin (car affiliated))
720 (post-affiliated (point))
721 ;; Empty drawers have no contents.
722 (contents-begin (progn (forward-line)
723 (and (< (point) drawer-end-line)
724 (point))))
725 (contents-end (and contents-begin drawer-end-line))
726 (pos-before-blank (progn (goto-char drawer-end-line)
727 (forward-line)
728 (point)))
729 (end (progn (skip-chars-forward " \r\t\n" limit)
730 (if (eobp) (point) (line-beginning-position)))))
731 (list 'drawer
732 (nconc
733 (list :begin begin
734 :end end
735 :drawer-name name
736 :contents-begin contents-begin
737 :contents-end contents-end
738 :post-blank (count-lines pos-before-blank end)
739 :post-affiliated post-affiliated)
740 (cdr affiliated))))))))
742 (defun org-element-drawer-interpreter (drawer contents)
743 "Interpret DRAWER element as Org syntax.
744 CONTENTS is the contents of the element."
745 (format ":%s:\n%s:END:"
746 (org-element-property :drawer-name drawer)
747 contents))
750 ;;;; Dynamic Block
752 (defun org-element-dynamic-block-parser (limit affiliated)
753 "Parse a dynamic block.
755 LIMIT bounds the search. AFFILIATED is a list of which CAR is
756 the buffer position at the beginning of the first affiliated
757 keyword and CDR is a plist of affiliated keywords along with
758 their value.
760 Return a list whose CAR is `dynamic-block' and CDR is a plist
761 containing `:block-name', `:begin', `:end', `:contents-begin',
762 `:contents-end', `:arguments', `:post-blank' and
763 `:post-affiliated' keywords.
765 Assume point is at beginning of dynamic block."
766 (let ((case-fold-search t))
767 (if (not (save-excursion
768 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
769 ;; Incomplete block: parse it as a paragraph.
770 (org-element-paragraph-parser limit affiliated)
771 (let ((block-end-line (match-beginning 0)))
772 (save-excursion
773 (let* ((name (progn (looking-at org-dblock-start-re)
774 (org-match-string-no-properties 1)))
775 (arguments (org-match-string-no-properties 3))
776 (begin (car affiliated))
777 (post-affiliated (point))
778 ;; Empty blocks have no contents.
779 (contents-begin (progn (forward-line)
780 (and (< (point) block-end-line)
781 (point))))
782 (contents-end (and contents-begin block-end-line))
783 (pos-before-blank (progn (goto-char block-end-line)
784 (forward-line)
785 (point)))
786 (end (progn (skip-chars-forward " \r\t\n" limit)
787 (if (eobp) (point) (line-beginning-position)))))
788 (list 'dynamic-block
789 (nconc
790 (list :begin begin
791 :end end
792 :block-name name
793 :arguments arguments
794 :contents-begin contents-begin
795 :contents-end contents-end
796 :post-blank (count-lines pos-before-blank end)
797 :post-affiliated post-affiliated)
798 (cdr affiliated)))))))))
800 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
801 "Interpret DYNAMIC-BLOCK element as Org syntax.
802 CONTENTS is the contents of the element."
803 (format "#+BEGIN: %s%s\n%s#+END:"
804 (org-element-property :block-name dynamic-block)
805 (let ((args (org-element-property :arguments dynamic-block)))
806 (and args (concat " " args)))
807 contents))
810 ;;;; Footnote Definition
812 (defconst org-element--footnote-separator
813 (concat org-outline-regexp-bol "\\|"
814 org-footnote-definition-re "\\|"
815 "^\\([ \t]*\n\\)\\{2,\\}")
816 "Regexp used as a footnote definition separator.")
818 (defun org-element-footnote-definition-parser (limit affiliated)
819 "Parse a footnote definition.
821 LIMIT bounds the search. AFFILIATED is a list of which CAR is
822 the buffer position at the beginning of the first affiliated
823 keyword and CDR is a plist of affiliated keywords along with
824 their value.
826 Return a list whose CAR is `footnote-definition' and CDR is
827 a plist containing `:label', `:begin' `:end', `:contents-begin',
828 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
830 Assume point is at the beginning of the footnote definition."
831 (save-excursion
832 (let* ((label (progn (looking-at org-footnote-definition-re)
833 (org-match-string-no-properties 1)))
834 (begin (car affiliated))
835 (post-affiliated (point))
836 (ending
837 (save-excursion
838 (end-of-line)
839 (cond
840 ((not
841 (re-search-forward org-element--footnote-separator limit t))
842 limit)
843 ((eq (char-after (match-beginning 0)) ?\[)
844 ;; At a new footnote definition, make sure we end
845 ;; before any affiliated keyword above.
846 (forward-line -1)
847 (while (and (> (point) post-affiliated)
848 (org-looking-at-p org-element--affiliated-re))
849 (forward-line -1))
850 (line-beginning-position 2))
851 (t (match-beginning 0)))))
852 (contents-begin
853 (progn
854 (search-forward "]")
855 (skip-chars-forward " \r\t\n" ending)
856 (cond ((= (point) ending) nil)
857 ((= (line-beginning-position) post-affiliated) (point))
858 (t (line-beginning-position)))))
859 (contents-end (and contents-begin ending))
860 (end (progn (goto-char ending)
861 (skip-chars-forward " \r\t\n" limit)
862 (if (eobp) (point) (line-beginning-position)))))
863 (list 'footnote-definition
864 (nconc
865 (list :label label
866 :begin begin
867 :end end
868 :contents-begin contents-begin
869 :contents-end contents-end
870 :post-blank (count-lines ending end)
871 :post-affiliated post-affiliated)
872 (cdr affiliated))))))
874 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
875 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
876 CONTENTS is the contents of the footnote-definition."
877 (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
879 contents))
882 ;;;; Headline
884 (defun org-element--get-node-properties ()
885 "Return node properties associated to headline at point.
886 Upcase property names. It avoids confusion between properties
887 obtained through property drawer and default properties from the
888 parser (e.g. `:end' and :END:). Return value is a plist."
889 (save-excursion
890 (forward-line)
891 (when (org-looking-at-p org-planning-line-re) (forward-line))
892 (when (looking-at org-property-drawer-re)
893 (forward-line)
894 (let ((end (match-end 0)) properties)
895 (while (< (line-end-position) end)
896 (looking-at org-property-re)
897 (push (org-match-string-no-properties 3) properties)
898 (push (intern (concat ":" (upcase (match-string 2)))) properties)
899 (forward-line))
900 properties))))
902 (defun org-element--get-time-properties ()
903 "Return time properties associated to headline at point.
904 Return value is a plist."
905 (save-excursion
906 (when (progn (forward-line) (looking-at org-planning-line-re))
907 (let ((end (line-end-position)) plist)
908 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
909 (goto-char (match-end 1))
910 (skip-chars-forward " \t")
911 (let ((keyword (match-string 1))
912 (time (org-element-timestamp-parser)))
913 (cond ((equal keyword org-scheduled-string)
914 (setq plist (plist-put plist :scheduled time)))
915 ((equal keyword org-deadline-string)
916 (setq plist (plist-put plist :deadline time)))
917 (t (setq plist (plist-put plist :closed time))))))
918 plist))))
920 (defun org-element-headline-parser (limit &optional raw-secondary-p)
921 "Parse a headline.
923 Return a list whose CAR is `headline' and CDR is a plist
924 containing `:raw-value', `:title', `:begin', `:end',
925 `:pre-blank', `:contents-begin' and `:contents-end', `:level',
926 `:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
927 `:deadline', `:closed', `:archivedp', `:commentedp'
928 `:footnote-section-p', `:post-blank' and `:post-affiliated'
929 keywords.
931 The plist also contains any property set in the property drawer,
932 with its name in upper cases and colons added at the
933 beginning (e.g., `:CUSTOM_ID').
935 LIMIT is a buffer position bounding the search.
937 When RAW-SECONDARY-P is non-nil, headline's title will not be
938 parsed as a secondary string, but as a plain string instead.
940 Assume point is at beginning of the headline."
941 (save-excursion
942 (let* ((begin (point))
943 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
944 (skip-chars-forward " \t")))
945 (todo (and org-todo-regexp
946 (let (case-fold-search) (looking-at org-todo-regexp))
947 (progn (goto-char (match-end 0))
948 (skip-chars-forward " \t")
949 (match-string 0))))
950 (todo-type
951 (and todo (if (member todo org-done-keywords) 'done 'todo)))
952 (priority (and (looking-at "\\[#.\\][ \t]*")
953 (progn (goto-char (match-end 0))
954 (aref (match-string 0) 2))))
955 (commentedp
956 (and (let (case-fold-search) (looking-at org-comment-string))
957 (goto-char (match-end 0))))
958 (title-start (point))
959 (tags (when (re-search-forward
960 (org-re "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
961 (line-end-position)
962 'move)
963 (goto-char (match-beginning 0))
964 (org-split-string (match-string 1) ":")))
965 (title-end (point))
966 (raw-value (org-trim
967 (buffer-substring-no-properties title-start title-end)))
968 (archivedp (member org-archive-tag tags))
969 (footnote-section-p (and org-footnote-section
970 (string= org-footnote-section raw-value)))
971 (standard-props (org-element--get-node-properties))
972 (time-props (org-element--get-time-properties))
973 (end (min (save-excursion (org-end-of-subtree t t)) limit))
974 (pos-after-head (progn (forward-line) (point)))
975 (contents-begin (save-excursion
976 (skip-chars-forward " \r\t\n" end)
977 (and (/= (point) end) (line-beginning-position))))
978 (contents-end (and contents-begin
979 (progn (goto-char end)
980 (skip-chars-backward " \r\t\n")
981 (forward-line)
982 (point)))))
983 (let ((headline
984 (list 'headline
985 (nconc
986 (list :raw-value raw-value
987 :begin begin
988 :end end
989 :pre-blank
990 (if (not contents-begin) 0
991 (count-lines pos-after-head contents-begin))
992 :contents-begin contents-begin
993 :contents-end contents-end
994 :level level
995 :priority priority
996 :tags tags
997 :todo-keyword todo
998 :todo-type todo-type
999 :post-blank (count-lines
1000 (or contents-end pos-after-head)
1001 end)
1002 :footnote-section-p footnote-section-p
1003 :archivedp archivedp
1004 :commentedp commentedp
1005 :post-affiliated begin)
1006 time-props
1007 standard-props))))
1008 (org-element-put-property
1009 headline :title
1010 (if raw-secondary-p raw-value
1011 (org-element--parse-objects
1012 (progn (goto-char title-start)
1013 (skip-chars-forward " \t")
1014 (point))
1015 (progn (goto-char title-end)
1016 (skip-chars-backward " \t")
1017 (point))
1019 (org-element-restriction 'headline)
1020 headline)))))))
1022 (defun org-element-headline-interpreter (headline contents)
1023 "Interpret HEADLINE element as Org syntax.
1024 CONTENTS is the contents of the element."
1025 (let* ((level (org-element-property :level headline))
1026 (todo (org-element-property :todo-keyword headline))
1027 (priority (org-element-property :priority headline))
1028 (title (org-element-interpret-data
1029 (org-element-property :title headline)))
1030 (tags (let ((tag-list (org-element-property :tags headline)))
1031 (and tag-list
1032 (format ":%s:" (mapconcat #'identity tag-list ":")))))
1033 (commentedp (org-element-property :commentedp headline))
1034 (pre-blank (or (org-element-property :pre-blank headline) 0))
1035 (heading
1036 (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
1038 (and todo (concat " " todo))
1039 (and commentedp (concat " " org-comment-string))
1040 (and priority (format " [#%c]" priority))
1042 (if (and org-footnote-section
1043 (org-element-property :footnote-section-p headline))
1044 org-footnote-section
1045 title))))
1046 (concat
1047 heading
1048 ;; Align tags.
1049 (when tags
1050 (cond
1051 ((zerop org-tags-column) (format " %s" tags))
1052 ((< org-tags-column 0)
1053 (concat
1054 (make-string
1055 (max (- (+ org-tags-column (length heading) (length tags))) 1)
1056 ?\s)
1057 tags))
1059 (concat
1060 (make-string (max (- org-tags-column (length heading)) 1) ?\s)
1061 tags))))
1062 (make-string (1+ pre-blank) ?\n)
1063 contents)))
1066 ;;;; Inlinetask
1068 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
1069 "Parse an inline task.
1071 Return a list whose CAR is `inlinetask' and CDR is a plist
1072 containing `:title', `:begin', `:end', `:contents-begin' and
1073 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
1074 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
1075 `:closed', `:post-blank' and `:post-affiliated' keywords.
1077 The plist also contains any property set in the property drawer,
1078 with its name in upper cases and colons added at the
1079 beginning (e.g., `:CUSTOM_ID').
1081 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
1082 title will not be parsed as a secondary string, but as a plain
1083 string instead.
1085 Assume point is at beginning of the inline task."
1086 (save-excursion
1087 (let* ((begin (point))
1088 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1089 (skip-chars-forward " \t")))
1090 (todo (and org-todo-regexp
1091 (let (case-fold-search) (looking-at org-todo-regexp))
1092 (progn (goto-char (match-end 0))
1093 (skip-chars-forward " \t")
1094 (match-string 0))))
1095 (todo-type (and todo
1096 (if (member todo org-done-keywords) 'done 'todo)))
1097 (priority (and (looking-at "\\[#.\\][ \t]*")
1098 (progn (goto-char (match-end 0))
1099 (aref (match-string 0) 2))))
1100 (title-start (point))
1101 (tags (when (re-search-forward
1102 (org-re "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
1103 (line-end-position)
1104 'move)
1105 (goto-char (match-beginning 0))
1106 (org-split-string (match-string 1) ":")))
1107 (title-end (point))
1108 (raw-value (org-trim
1109 (buffer-substring-no-properties title-start title-end)))
1110 (task-end (save-excursion
1111 (end-of-line)
1112 (and (re-search-forward org-outline-regexp-bol limit t)
1113 (org-looking-at-p "END[ \t]*$")
1114 (line-beginning-position))))
1115 (standard-props (and task-end (org-element--get-node-properties)))
1116 (time-props (and task-end (org-element--get-time-properties)))
1117 (contents-begin (progn (forward-line)
1118 (and task-end (< (point) task-end) (point))))
1119 (contents-end (and contents-begin task-end))
1120 (before-blank (if (not task-end) (point)
1121 (goto-char task-end)
1122 (forward-line)
1123 (point)))
1124 (end (progn (skip-chars-forward " \r\t\n" limit)
1125 (if (eobp) (point) (line-beginning-position))))
1126 (inlinetask
1127 (list 'inlinetask
1128 (nconc
1129 (list :raw-value raw-value
1130 :begin begin
1131 :end end
1132 :contents-begin contents-begin
1133 :contents-end contents-end
1134 :level level
1135 :priority priority
1136 :tags tags
1137 :todo-keyword todo
1138 :todo-type todo-type
1139 :post-blank (count-lines before-blank end)
1140 :post-affiliated begin)
1141 time-props
1142 standard-props))))
1143 (org-element-put-property
1144 inlinetask :title
1145 (if raw-secondary-p raw-value
1146 (org-element--parse-objects
1147 (progn (goto-char title-start)
1148 (skip-chars-forward " \t")
1149 (point))
1150 (progn (goto-char title-end)
1151 (skip-chars-backward " \t")
1152 (point))
1154 (org-element-restriction 'inlinetask)
1155 inlinetask))))))
1157 (defun org-element-inlinetask-interpreter (inlinetask contents)
1158 "Interpret INLINETASK element as Org syntax.
1159 CONTENTS is the contents of inlinetask."
1160 (let* ((level (org-element-property :level inlinetask))
1161 (todo (org-element-property :todo-keyword inlinetask))
1162 (priority (org-element-property :priority inlinetask))
1163 (title (org-element-interpret-data
1164 (org-element-property :title inlinetask)))
1165 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1166 (and tag-list
1167 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1168 (task (concat (make-string level ?*)
1169 (and todo (concat " " todo))
1170 (and priority (format " [#%c]" priority))
1171 (and title (concat " " title)))))
1172 (concat task
1173 ;; Align tags.
1174 (when tags
1175 (cond
1176 ((zerop org-tags-column) (format " %s" tags))
1177 ((< org-tags-column 0)
1178 (concat
1179 (make-string
1180 (max (- (+ org-tags-column (length task) (length tags))) 1)
1182 tags))
1184 (concat
1185 (make-string (max (- org-tags-column (length task)) 1) ? )
1186 tags))))
1187 ;; Prefer degenerate inlinetasks when there are no
1188 ;; contents.
1189 (when contents
1190 (concat "\n"
1191 contents
1192 (make-string level ?*) " END")))))
1195 ;;;; Item
1197 (defun org-element-item-parser (_ struct &optional raw-secondary-p)
1198 "Parse an item.
1200 STRUCT is the structure of the plain list.
1202 Return a list whose CAR is `item' and CDR is a plist containing
1203 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1204 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1205 `:post-affiliated' keywords.
1207 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1208 any, will not be parsed as a secondary string, but as a plain
1209 string instead.
1211 Assume point is at the beginning of the item."
1212 (save-excursion
1213 (beginning-of-line)
1214 (looking-at org-list-full-item-re)
1215 (let* ((begin (point))
1216 (bullet (org-match-string-no-properties 1))
1217 (checkbox (let ((box (match-string 3)))
1218 (cond ((equal "[ ]" box) 'off)
1219 ((equal "[X]" box) 'on)
1220 ((equal "[-]" box) 'trans))))
1221 (counter (let ((c (match-string 2)))
1222 (save-match-data
1223 (cond
1224 ((not c) nil)
1225 ((string-match "[A-Za-z]" c)
1226 (- (string-to-char (upcase (match-string 0 c)))
1227 64))
1228 ((string-match "[0-9]+" c)
1229 (string-to-number (match-string 0 c)))))))
1230 (end (progn (goto-char (nth 6 (assq (point) struct)))
1231 (if (bolp) (point) (line-beginning-position 2))))
1232 (contents-begin
1233 (progn (goto-char
1234 ;; Ignore tags in un-ordered lists: they are just
1235 ;; a part of item's body.
1236 (if (and (match-beginning 4)
1237 (save-match-data (string-match "[.)]" bullet)))
1238 (match-beginning 4)
1239 (match-end 0)))
1240 (skip-chars-forward " \r\t\n" end)
1241 (cond ((= (point) end) nil)
1242 ;; If first line isn't empty, contents really
1243 ;; start at the text after item's meta-data.
1244 ((= (line-beginning-position) begin) (point))
1245 (t (line-beginning-position)))))
1246 (contents-end (and contents-begin
1247 (progn (goto-char end)
1248 (skip-chars-backward " \r\t\n")
1249 (line-beginning-position 2))))
1250 (item
1251 (list 'item
1252 (list :bullet bullet
1253 :begin begin
1254 :end end
1255 :contents-begin contents-begin
1256 :contents-end contents-end
1257 :checkbox checkbox
1258 :counter counter
1259 :structure struct
1260 :post-blank (count-lines (or contents-end begin) end)
1261 :post-affiliated begin))))
1262 (org-element-put-property
1263 item :tag
1264 (let ((raw (org-list-get-tag begin struct)))
1265 (when raw
1266 (if raw-secondary-p raw
1267 (org-element--parse-objects
1268 (match-beginning 4) (match-end 4) nil
1269 (org-element-restriction 'item)
1270 item))))))))
1272 (defun org-element-item-interpreter (item contents)
1273 "Interpret ITEM element as Org syntax.
1274 CONTENTS is the contents of the element."
1275 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1276 (org-list-bullet-string
1277 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1278 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1279 (t "1.")))))
1280 (checkbox (org-element-property :checkbox item))
1281 (counter (org-element-property :counter item))
1282 (tag (let ((tag (org-element-property :tag item)))
1283 (and tag (org-element-interpret-data tag))))
1284 ;; Compute indentation.
1285 (ind (make-string (length bullet) 32))
1286 (item-starts-with-par-p
1287 (eq (org-element-type (car (org-element-contents item)))
1288 'paragraph)))
1289 ;; Indent contents.
1290 (concat
1291 bullet
1292 (and counter (format "[@%d] " counter))
1293 (pcase checkbox
1294 (`on "[X] ")
1295 (`off "[ ] ")
1296 (`trans "[-] ")
1297 (_ nil))
1298 (and tag (format "%s :: " tag))
1299 (when contents
1300 (let ((contents (replace-regexp-in-string
1301 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1302 (if item-starts-with-par-p (org-trim contents)
1303 (concat "\n" contents)))))))
1306 ;;;; Plain List
1308 (defun org-element--list-struct (limit)
1309 ;; Return structure of list at point. Internal function. See
1310 ;; `org-list-struct' for details.
1311 (let ((case-fold-search t)
1312 (top-ind limit)
1313 (item-re (org-item-re))
1314 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1315 items struct)
1316 (save-excursion
1317 (catch 'exit
1318 (while t
1319 (cond
1320 ;; At limit: end all items.
1321 ((>= (point) limit)
1322 (throw 'exit
1323 (let ((end (progn (skip-chars-backward " \r\t\n")
1324 (forward-line)
1325 (point))))
1326 (dolist (item items (sort (nconc items struct)
1327 'car-less-than-car))
1328 (setcar (nthcdr 6 item) end)))))
1329 ;; At list end: end all items.
1330 ((looking-at org-list-end-re)
1331 (throw 'exit (dolist (item items (sort (nconc items struct)
1332 'car-less-than-car))
1333 (setcar (nthcdr 6 item) (point)))))
1334 ;; At a new item: end previous sibling.
1335 ((looking-at item-re)
1336 (let ((ind (save-excursion (skip-chars-forward " \t")
1337 (current-column))))
1338 (setq top-ind (min top-ind ind))
1339 (while (and items (<= ind (nth 1 (car items))))
1340 (let ((item (pop items)))
1341 (setcar (nthcdr 6 item) (point))
1342 (push item struct)))
1343 (push (progn (looking-at org-list-full-item-re)
1344 (let ((bullet (match-string-no-properties 1)))
1345 (list (point)
1347 bullet
1348 (match-string-no-properties 2) ; counter
1349 (match-string-no-properties 3) ; checkbox
1350 ;; Description tag.
1351 (and (save-match-data
1352 (string-match "[-+*]" bullet))
1353 (match-string-no-properties 4))
1354 ;; Ending position, unknown so far.
1355 nil)))
1356 items))
1357 (forward-line 1))
1358 ;; Skip empty lines.
1359 ((looking-at "^[ \t]*$") (forward-line))
1360 ;; Skip inline tasks and blank lines along the way.
1361 ((and inlinetask-re (looking-at inlinetask-re))
1362 (forward-line)
1363 (let ((origin (point)))
1364 (when (re-search-forward inlinetask-re limit t)
1365 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1366 (goto-char origin)))))
1367 ;; At some text line. Check if it ends any previous item.
1369 (let ((ind (save-excursion (skip-chars-forward " \t")
1370 (current-column))))
1371 (when (<= ind top-ind)
1372 (skip-chars-backward " \r\t\n")
1373 (forward-line))
1374 (while (<= ind (nth 1 (car items)))
1375 (let ((item (pop items)))
1376 (setcar (nthcdr 6 item) (line-beginning-position))
1377 (push item struct)
1378 (unless items
1379 (throw 'exit (sort struct #'car-less-than-car))))))
1380 ;; Skip blocks (any type) and drawers contents.
1381 (cond
1382 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1383 (re-search-forward
1384 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1385 limit t)))
1386 ((and (looking-at org-drawer-regexp)
1387 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1388 (forward-line))))))))
1390 (defun org-element-plain-list-parser (limit affiliated structure)
1391 "Parse a plain list.
1393 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1394 the buffer position at the beginning of the first affiliated
1395 keyword and CDR is a plist of affiliated keywords along with
1396 their value. STRUCTURE is the structure of the plain list being
1397 parsed.
1399 Return a list whose CAR is `plain-list' and CDR is a plist
1400 containing `:type', `:begin', `:end', `:contents-begin' and
1401 `:contents-end', `:structure', `:post-blank' and
1402 `:post-affiliated' keywords.
1404 Assume point is at the beginning of the list."
1405 (save-excursion
1406 (let* ((struct (or structure (org-element--list-struct limit)))
1407 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1408 ((nth 5 (assq (point) struct)) 'descriptive)
1409 (t 'unordered)))
1410 (contents-begin (point))
1411 (begin (car affiliated))
1412 (contents-end (let* ((item (assq contents-begin struct))
1413 (ind (nth 1 item))
1414 (pos (nth 6 item)))
1415 (while (and (setq item (assq pos struct))
1416 (= (nth 1 item) ind))
1417 (setq pos (nth 6 item)))
1418 pos))
1419 (end (progn (goto-char contents-end)
1420 (skip-chars-forward " \r\t\n" limit)
1421 (if (= (point) limit) limit (line-beginning-position)))))
1422 ;; Return value.
1423 (list 'plain-list
1424 (nconc
1425 (list :type type
1426 :begin begin
1427 :end end
1428 :contents-begin contents-begin
1429 :contents-end contents-end
1430 :structure struct
1431 :post-blank (count-lines contents-end end)
1432 :post-affiliated contents-begin)
1433 (cdr affiliated))))))
1435 (defun org-element-plain-list-interpreter (_ contents)
1436 "Interpret plain-list element as Org syntax.
1437 CONTENTS is the contents of the element."
1438 (with-temp-buffer
1439 (insert contents)
1440 (goto-char (point-min))
1441 (org-list-repair)
1442 (buffer-string)))
1445 ;;;; Property Drawer
1447 (defun org-element-property-drawer-parser (limit)
1448 "Parse a property drawer.
1450 LIMIT bounds the search.
1452 Return a list whose car is `property-drawer' and cdr is a plist
1453 containing `:begin', `:end', `:contents-begin', `:contents-end',
1454 `:post-blank' and `:post-affiliated' keywords.
1456 Assume point is at the beginning of the property drawer."
1457 (save-excursion
1458 (let ((case-fold-search t)
1459 (begin (point))
1460 (contents-begin (line-beginning-position 2)))
1461 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1462 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1463 (match-beginning 0)))
1464 (before-blank (progn (forward-line) (point)))
1465 (end (progn (skip-chars-forward " \r\t\n" limit)
1466 (if (eobp) (point) (line-beginning-position)))))
1467 (list 'property-drawer
1468 (list :begin begin
1469 :end end
1470 :contents-begin (and contents-end contents-begin)
1471 :contents-end contents-end
1472 :post-blank (count-lines before-blank end)
1473 :post-affiliated begin))))))
1475 (defun org-element-property-drawer-interpreter (_ contents)
1476 "Interpret property-drawer element as Org syntax.
1477 CONTENTS is the properties within the drawer."
1478 (format ":PROPERTIES:\n%s:END:" contents))
1481 ;;;; Quote Block
1483 (defun org-element-quote-block-parser (limit affiliated)
1484 "Parse a quote block.
1486 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1487 the buffer position at the beginning of the first affiliated
1488 keyword and CDR is a plist of affiliated keywords along with
1489 their value.
1491 Return a list whose CAR is `quote-block' and CDR is a plist
1492 containing `:begin', `:end', `:contents-begin', `:contents-end',
1493 `:post-blank' and `:post-affiliated' keywords.
1495 Assume point is at the beginning of the block."
1496 (let ((case-fold-search t))
1497 (if (not (save-excursion
1498 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1499 ;; Incomplete block: parse it as a paragraph.
1500 (org-element-paragraph-parser limit affiliated)
1501 (let ((block-end-line (match-beginning 0)))
1502 (save-excursion
1503 (let* ((begin (car affiliated))
1504 (post-affiliated (point))
1505 ;; Empty blocks have no contents.
1506 (contents-begin (progn (forward-line)
1507 (and (< (point) block-end-line)
1508 (point))))
1509 (contents-end (and contents-begin block-end-line))
1510 (pos-before-blank (progn (goto-char block-end-line)
1511 (forward-line)
1512 (point)))
1513 (end (progn (skip-chars-forward " \r\t\n" limit)
1514 (if (eobp) (point) (line-beginning-position)))))
1515 (list 'quote-block
1516 (nconc
1517 (list :begin begin
1518 :end end
1519 :contents-begin contents-begin
1520 :contents-end contents-end
1521 :post-blank (count-lines pos-before-blank end)
1522 :post-affiliated post-affiliated)
1523 (cdr affiliated)))))))))
1525 (defun org-element-quote-block-interpreter (_ contents)
1526 "Interpret quote-block element as Org syntax.
1527 CONTENTS is the contents of the element."
1528 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1531 ;;;; Section
1533 (defun org-element-section-parser (_)
1534 "Parse a section.
1536 Return a list whose CAR is `section' and CDR is a plist
1537 containing `:begin', `:end', `:contents-begin', `contents-end',
1538 `:post-blank' and `:post-affiliated' keywords."
1539 (save-excursion
1540 ;; Beginning of section is the beginning of the first non-blank
1541 ;; line after previous headline.
1542 (let ((begin (point))
1543 (end (progn (org-with-limited-levels (outline-next-heading))
1544 (point)))
1545 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1546 (line-beginning-position 2))))
1547 (list 'section
1548 (list :begin begin
1549 :end end
1550 :contents-begin begin
1551 :contents-end pos-before-blank
1552 :post-blank (count-lines pos-before-blank end)
1553 :post-affiliated begin)))))
1555 (defun org-element-section-interpreter (_ contents)
1556 "Interpret section element as Org syntax.
1557 CONTENTS is the contents of the element."
1558 contents)
1561 ;;;; Special Block
1563 (defun org-element-special-block-parser (limit affiliated)
1564 "Parse a special block.
1566 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1567 the buffer position at the beginning of the first affiliated
1568 keyword and CDR is a plist of affiliated keywords along with
1569 their value.
1571 Return a list whose CAR is `special-block' and CDR is a plist
1572 containing `:type', `:begin', `:end', `:contents-begin',
1573 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1575 Assume point is at the beginning of the block."
1576 (let* ((case-fold-search t)
1577 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1578 (match-string-no-properties 1))))
1579 (if (not (save-excursion
1580 (re-search-forward
1581 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1582 limit t)))
1583 ;; Incomplete block: parse it as a paragraph.
1584 (org-element-paragraph-parser limit affiliated)
1585 (let ((block-end-line (match-beginning 0)))
1586 (save-excursion
1587 (let* ((begin (car affiliated))
1588 (post-affiliated (point))
1589 ;; Empty blocks have no contents.
1590 (contents-begin (progn (forward-line)
1591 (and (< (point) block-end-line)
1592 (point))))
1593 (contents-end (and contents-begin block-end-line))
1594 (pos-before-blank (progn (goto-char block-end-line)
1595 (forward-line)
1596 (point)))
1597 (end (progn (skip-chars-forward " \r\t\n" limit)
1598 (if (eobp) (point) (line-beginning-position)))))
1599 (list 'special-block
1600 (nconc
1601 (list :type type
1602 :begin begin
1603 :end end
1604 :contents-begin contents-begin
1605 :contents-end contents-end
1606 :post-blank (count-lines pos-before-blank end)
1607 :post-affiliated post-affiliated)
1608 (cdr affiliated)))))))))
1610 (defun org-element-special-block-interpreter (special-block contents)
1611 "Interpret SPECIAL-BLOCK element as Org syntax.
1612 CONTENTS is the contents of the element."
1613 (let ((block-type (org-element-property :type special-block)))
1614 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1618 ;;; Elements
1620 ;; For each element, a parser and an interpreter are also defined.
1621 ;; Both follow the same naming convention used for greater elements.
1623 ;; Also, as for greater elements, adding a new element type is done
1624 ;; through the following steps: implement a parser and an interpreter,
1625 ;; tweak `org-element--current-element' so that it recognizes the new
1626 ;; type and add that new type to `org-element-all-elements'.
1629 ;;;; Babel Call
1631 (defun org-element-babel-call-parser (limit affiliated)
1632 "Parse a babel call.
1634 LIMIT bounds the search. AFFILIATED is a list of which car is
1635 the buffer position at the beginning of the first affiliated
1636 keyword and cdr is a plist of affiliated keywords along with
1637 their value.
1639 Return a list whose car is `babel-call' and cdr is a plist
1640 containing `:call', `:inside-header', `:arguments',
1641 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1642 `:post-affiliated' as keywords."
1643 (save-excursion
1644 (let* ((begin (car affiliated))
1645 (post-affiliated (point))
1646 (value (progn (search-forward ":" nil t)
1647 (org-trim
1648 (buffer-substring-no-properties
1649 (point) (line-end-position)))))
1650 (pos-before-blank (progn (forward-line) (point)))
1651 (end (progn (skip-chars-forward " \r\t\n" limit)
1652 (if (eobp) (point) (line-beginning-position))))
1653 (valid-value
1654 (string-match
1655 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*\\))[ \t]*\\(.*\\)"
1656 value)))
1657 (list 'babel-call
1658 (nconc
1659 (list :call (and valid-value (match-string 1 value))
1660 :inside-header (and valid-value
1661 (org-string-nw-p (match-string 2 value)))
1662 :arguments (and valid-value
1663 (org-string-nw-p (match-string 3 value)))
1664 :end-header (and valid-value
1665 (org-string-nw-p (match-string 4 value)))
1666 :begin begin
1667 :end end
1668 :value value
1669 :post-blank (count-lines pos-before-blank end)
1670 :post-affiliated post-affiliated)
1671 (cdr affiliated))))))
1673 (defun org-element-babel-call-interpreter (babel-call _)
1674 "Interpret BABEL-CALL element as Org syntax."
1675 (concat "#+CALL: "
1676 (org-element-property :call babel-call)
1677 (let ((h (org-element-property :inside-header babel-call)))
1678 (and h (format "[%s]" h)))
1679 (concat "(" (org-element-property :arguments babel-call) ")")
1680 (let ((h (org-element-property :end-header babel-call)))
1681 (and h (concat " " h)))))
1684 ;;;; Clock
1686 (defun org-element-clock-parser (limit)
1687 "Parse a clock.
1689 LIMIT bounds the search.
1691 Return a list whose CAR is `clock' and CDR is a plist containing
1692 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1693 `:post-affiliated' as keywords."
1694 (save-excursion
1695 (let* ((case-fold-search nil)
1696 (begin (point))
1697 (value (progn (search-forward org-clock-string (line-end-position) t)
1698 (skip-chars-forward " \t")
1699 (org-element-timestamp-parser)))
1700 (duration (and (search-forward " => " (line-end-position) t)
1701 (progn (skip-chars-forward " \t")
1702 (looking-at "\\(\\S-+\\)[ \t]*$"))
1703 (org-match-string-no-properties 1)))
1704 (status (if duration 'closed 'running))
1705 (post-blank (let ((before-blank (progn (forward-line) (point))))
1706 (skip-chars-forward " \r\t\n" limit)
1707 (skip-chars-backward " \t")
1708 (unless (bolp) (end-of-line))
1709 (count-lines before-blank (point))))
1710 (end (point)))
1711 (list 'clock
1712 (list :status status
1713 :value value
1714 :duration duration
1715 :begin begin
1716 :end end
1717 :post-blank post-blank
1718 :post-affiliated begin)))))
1720 (defun org-element-clock-interpreter (clock _)
1721 "Interpret CLOCK element as Org syntax."
1722 (concat org-clock-string " "
1723 (org-element-timestamp-interpreter
1724 (org-element-property :value clock) nil)
1725 (let ((duration (org-element-property :duration clock)))
1726 (and duration
1727 (concat " => "
1728 (apply 'format
1729 "%2s:%02s"
1730 (org-split-string duration ":")))))))
1733 ;;;; Comment
1735 (defun org-element-comment-parser (limit affiliated)
1736 "Parse a comment.
1738 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1739 the buffer position at the beginning of the first affiliated
1740 keyword and CDR is a plist of affiliated keywords along with
1741 their value.
1743 Return a list whose CAR is `comment' and CDR is a plist
1744 containing `:begin', `:end', `:value', `:post-blank',
1745 `:post-affiliated' keywords.
1747 Assume point is at comment beginning."
1748 (save-excursion
1749 (let* ((begin (car affiliated))
1750 (post-affiliated (point))
1751 (value (prog2 (looking-at "[ \t]*# ?")
1752 (buffer-substring-no-properties
1753 (match-end 0) (line-end-position))
1754 (forward-line)))
1755 (com-end
1756 ;; Get comments ending.
1757 (progn
1758 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1759 ;; Accumulate lines without leading hash and first
1760 ;; whitespace.
1761 (setq value
1762 (concat value
1763 "\n"
1764 (buffer-substring-no-properties
1765 (match-end 0) (line-end-position))))
1766 (forward-line))
1767 (point)))
1768 (end (progn (goto-char com-end)
1769 (skip-chars-forward " \r\t\n" limit)
1770 (if (eobp) (point) (line-beginning-position)))))
1771 (list 'comment
1772 (nconc
1773 (list :begin begin
1774 :end end
1775 :value value
1776 :post-blank (count-lines com-end end)
1777 :post-affiliated post-affiliated)
1778 (cdr affiliated))))))
1780 (defun org-element-comment-interpreter (comment _)
1781 "Interpret COMMENT element as Org syntax.
1782 CONTENTS is nil."
1783 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1786 ;;;; Comment Block
1788 (defun org-element-comment-block-parser (limit affiliated)
1789 "Parse an export block.
1791 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1792 the buffer position at the beginning of the first affiliated
1793 keyword and CDR is a plist of affiliated keywords along with
1794 their value.
1796 Return a list whose CAR is `comment-block' and CDR is a plist
1797 containing `:begin', `:end', `:value', `:post-blank' and
1798 `:post-affiliated' keywords.
1800 Assume point is at comment block beginning."
1801 (let ((case-fold-search t))
1802 (if (not (save-excursion
1803 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1804 ;; Incomplete block: parse it as a paragraph.
1805 (org-element-paragraph-parser limit affiliated)
1806 (let ((contents-end (match-beginning 0)))
1807 (save-excursion
1808 (let* ((begin (car affiliated))
1809 (post-affiliated (point))
1810 (contents-begin (progn (forward-line) (point)))
1811 (pos-before-blank (progn (goto-char contents-end)
1812 (forward-line)
1813 (point)))
1814 (end (progn (skip-chars-forward " \r\t\n" limit)
1815 (if (eobp) (point) (line-beginning-position))))
1816 (value (buffer-substring-no-properties
1817 contents-begin contents-end)))
1818 (list 'comment-block
1819 (nconc
1820 (list :begin begin
1821 :end end
1822 :value value
1823 :post-blank (count-lines pos-before-blank end)
1824 :post-affiliated post-affiliated)
1825 (cdr affiliated)))))))))
1827 (defun org-element-comment-block-interpreter (comment-block _)
1828 "Interpret COMMENT-BLOCK element as Org syntax."
1829 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1830 (org-element-normalize-string
1831 (org-remove-indentation
1832 (org-element-property :value comment-block)))))
1835 ;;;; Diary Sexp
1837 (defun org-element-diary-sexp-parser (limit affiliated)
1838 "Parse a diary sexp.
1840 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1841 the buffer position at the beginning of the first affiliated
1842 keyword and CDR is a plist of affiliated keywords along with
1843 their value.
1845 Return a list whose CAR is `diary-sexp' and CDR is a plist
1846 containing `:begin', `:end', `:value', `:post-blank' and
1847 `:post-affiliated' keywords."
1848 (save-excursion
1849 (let ((begin (car affiliated))
1850 (post-affiliated (point))
1851 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1852 (org-match-string-no-properties 1)))
1853 (pos-before-blank (progn (forward-line) (point)))
1854 (end (progn (skip-chars-forward " \r\t\n" limit)
1855 (if (eobp) (point) (line-beginning-position)))))
1856 (list 'diary-sexp
1857 (nconc
1858 (list :value value
1859 :begin begin
1860 :end end
1861 :post-blank (count-lines pos-before-blank end)
1862 :post-affiliated post-affiliated)
1863 (cdr affiliated))))))
1865 (defun org-element-diary-sexp-interpreter (diary-sexp _)
1866 "Interpret DIARY-SEXP as Org syntax."
1867 (org-element-property :value diary-sexp))
1870 ;;;; Example Block
1872 (defun org-element-example-block-parser (limit affiliated)
1873 "Parse an example block.
1875 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1876 the buffer position at the beginning of the first affiliated
1877 keyword and CDR is a plist of affiliated keywords along with
1878 their value.
1880 Return a list whose CAR is `example-block' and CDR is a plist
1881 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1882 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1883 `:value', `:post-blank' and `:post-affiliated' keywords."
1884 (let ((case-fold-search t))
1885 (if (not (save-excursion
1886 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1887 ;; Incomplete block: parse it as a paragraph.
1888 (org-element-paragraph-parser limit affiliated)
1889 (let ((contents-end (match-beginning 0)))
1890 (save-excursion
1891 (let* ((switches
1892 (progn
1893 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1894 (org-match-string-no-properties 1)))
1895 ;; Switches analysis
1896 (number-lines
1897 (cond ((not switches) nil)
1898 ((string-match "-n\\>" switches) 'new)
1899 ((string-match "+n\\>" switches) 'continued)))
1900 (preserve-indent
1901 (and switches (string-match "-i\\>" switches)))
1902 ;; Should labels be retained in (or stripped from) example
1903 ;; blocks?
1904 (retain-labels
1905 (or (not switches)
1906 (not (string-match "-r\\>" switches))
1907 (and number-lines (string-match "-k\\>" switches))))
1908 ;; What should code-references use - labels or
1909 ;; line-numbers?
1910 (use-labels
1911 (or (not switches)
1912 (and retain-labels
1913 (not (string-match "-k\\>" switches)))))
1914 (label-fmt
1915 (and switches
1916 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1917 (match-string 1 switches)))
1918 ;; Standard block parsing.
1919 (begin (car affiliated))
1920 (post-affiliated (point))
1921 (contents-begin (line-beginning-position 2))
1922 (value (org-unescape-code-in-string
1923 (buffer-substring-no-properties
1924 contents-begin contents-end)))
1925 (pos-before-blank (progn (goto-char contents-end)
1926 (forward-line)
1927 (point)))
1928 (end (progn (skip-chars-forward " \r\t\n" limit)
1929 (if (eobp) (point) (line-beginning-position)))))
1930 (list 'example-block
1931 (nconc
1932 (list :begin begin
1933 :end end
1934 :value value
1935 :switches switches
1936 :number-lines number-lines
1937 :preserve-indent preserve-indent
1938 :retain-labels retain-labels
1939 :use-labels use-labels
1940 :label-fmt label-fmt
1941 :post-blank (count-lines pos-before-blank end)
1942 :post-affiliated post-affiliated)
1943 (cdr affiliated)))))))))
1945 (defun org-element-example-block-interpreter (example-block _)
1946 "Interpret EXAMPLE-BLOCK element as Org syntax."
1947 (let ((switches (org-element-property :switches example-block))
1948 (value (org-element-property :value example-block)))
1949 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1950 (org-element-normalize-string
1951 (org-escape-code-in-string
1952 (if (or org-src-preserve-indentation
1953 (org-element-property :preserve-indent example-block))
1954 value
1955 (org-remove-indentation value))))
1956 "#+END_EXAMPLE")))
1959 ;;;; Export Block
1961 (defun org-element-export-block-parser (limit affiliated)
1962 "Parse an export block.
1964 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1965 the buffer position at the beginning of the first affiliated
1966 keyword and CDR is a plist of affiliated keywords along with
1967 their value.
1969 Return a list whose CAR is `export-block' and CDR is a plist
1970 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1971 `:post-affiliated' keywords.
1973 Assume point is at export-block beginning."
1974 (let* ((case-fold-search t))
1975 (if (not (save-excursion
1976 (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
1977 ;; Incomplete block: parse it as a paragraph.
1978 (org-element-paragraph-parser limit affiliated)
1979 (save-excursion
1980 (let* ((contents-end (match-beginning 0))
1981 (backend
1982 (progn
1983 (looking-at
1984 "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
1985 (match-string-no-properties 1)))
1986 (begin (car affiliated))
1987 (post-affiliated (point))
1988 (contents-begin (progn (forward-line) (point)))
1989 (pos-before-blank (progn (goto-char contents-end)
1990 (forward-line)
1991 (point)))
1992 (end (progn (skip-chars-forward " \r\t\n" limit)
1993 (if (eobp) (point) (line-beginning-position))))
1994 (value (buffer-substring-no-properties contents-begin
1995 contents-end)))
1996 (list 'export-block
1997 (nconc
1998 (list :type (and backend (upcase backend))
1999 :begin begin
2000 :end end
2001 :value value
2002 :post-blank (count-lines pos-before-blank end)
2003 :post-affiliated post-affiliated)
2004 (cdr affiliated))))))))
2006 (defun org-element-export-block-interpreter (export-block _)
2007 "Interpret EXPORT-BLOCK element as Org syntax."
2008 (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT"
2009 (org-element-property :type export-block)
2010 (org-element-property :value export-block)))
2013 ;;;; Fixed-width
2015 (defun org-element-fixed-width-parser (limit affiliated)
2016 "Parse a fixed-width section.
2018 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2019 the buffer position at the beginning of the first affiliated
2020 keyword and CDR is a plist of affiliated keywords along with
2021 their value.
2023 Return a list whose CAR is `fixed-width' and CDR is a plist
2024 containing `:begin', `:end', `:value', `:post-blank' and
2025 `:post-affiliated' keywords.
2027 Assume point is at the beginning of the fixed-width area."
2028 (save-excursion
2029 (let* ((begin (car affiliated))
2030 (post-affiliated (point))
2031 value
2032 (end-area
2033 (progn
2034 (while (and (< (point) limit)
2035 (looking-at "[ \t]*:\\( \\|$\\)"))
2036 ;; Accumulate text without starting colons.
2037 (setq value
2038 (concat value
2039 (buffer-substring-no-properties
2040 (match-end 0) (point-at-eol))
2041 "\n"))
2042 (forward-line))
2043 (point)))
2044 (end (progn (skip-chars-forward " \r\t\n" limit)
2045 (if (eobp) (point) (line-beginning-position)))))
2046 (list 'fixed-width
2047 (nconc
2048 (list :begin begin
2049 :end end
2050 :value value
2051 :post-blank (count-lines end-area end)
2052 :post-affiliated post-affiliated)
2053 (cdr affiliated))))))
2055 (defun org-element-fixed-width-interpreter (fixed-width _)
2056 "Interpret FIXED-WIDTH element as Org syntax."
2057 (let ((value (org-element-property :value fixed-width)))
2058 (and value
2059 (replace-regexp-in-string
2060 "^" ": "
2061 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2064 ;;;; Horizontal Rule
2066 (defun org-element-horizontal-rule-parser (limit affiliated)
2067 "Parse an horizontal rule.
2069 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2070 the buffer position at the beginning of the first affiliated
2071 keyword and CDR is a plist of affiliated keywords along with
2072 their value.
2074 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2075 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2076 keywords."
2077 (save-excursion
2078 (let ((begin (car affiliated))
2079 (post-affiliated (point))
2080 (post-hr (progn (forward-line) (point)))
2081 (end (progn (skip-chars-forward " \r\t\n" limit)
2082 (if (eobp) (point) (line-beginning-position)))))
2083 (list 'horizontal-rule
2084 (nconc
2085 (list :begin begin
2086 :end end
2087 :post-blank (count-lines post-hr end)
2088 :post-affiliated post-affiliated)
2089 (cdr affiliated))))))
2091 (defun org-element-horizontal-rule-interpreter (&rest _)
2092 "Interpret HORIZONTAL-RULE element as Org syntax."
2093 "-----")
2096 ;;;; Keyword
2098 (defun org-element-keyword-parser (limit affiliated)
2099 "Parse a keyword at point.
2101 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2102 the buffer position at the beginning of the first affiliated
2103 keyword and CDR is a plist of affiliated keywords along with
2104 their value.
2106 Return a list whose CAR is `keyword' and CDR is a plist
2107 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2108 `:post-affiliated' keywords."
2109 (save-excursion
2110 ;; An orphaned affiliated keyword is considered as a regular
2111 ;; keyword. In this case AFFILIATED is nil, so we take care of
2112 ;; this corner case.
2113 (let ((begin (or (car affiliated) (point)))
2114 (post-affiliated (point))
2115 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2116 (upcase (org-match-string-no-properties 1))))
2117 (value (org-trim (buffer-substring-no-properties
2118 (match-end 0) (point-at-eol))))
2119 (pos-before-blank (progn (forward-line) (point)))
2120 (end (progn (skip-chars-forward " \r\t\n" limit)
2121 (if (eobp) (point) (line-beginning-position)))))
2122 (list 'keyword
2123 (nconc
2124 (list :key key
2125 :value value
2126 :begin begin
2127 :end end
2128 :post-blank (count-lines pos-before-blank end)
2129 :post-affiliated post-affiliated)
2130 (cdr affiliated))))))
2132 (defun org-element-keyword-interpreter (keyword _)
2133 "Interpret KEYWORD element as Org syntax."
2134 (format "#+%s: %s"
2135 (org-element-property :key keyword)
2136 (org-element-property :value keyword)))
2139 ;;;; Latex Environment
2141 (defconst org-element--latex-begin-environment
2142 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2143 "Regexp matching the beginning of a LaTeX environment.
2144 The environment is captured by the first group.
2146 See also `org-element--latex-end-environment'.")
2148 (defconst org-element--latex-end-environment
2149 "\\\\end{%s}[ \t]*$"
2150 "Format string matching the ending of a LaTeX environment.
2151 See also `org-element--latex-begin-environment'.")
2153 (defun org-element-latex-environment-parser (limit affiliated)
2154 "Parse a LaTeX environment.
2156 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2157 the buffer position at the beginning of the first affiliated
2158 keyword and CDR is a plist of affiliated keywords along with
2159 their value.
2161 Return a list whose CAR is `latex-environment' and CDR is a plist
2162 containing `:begin', `:end', `:value', `:post-blank' and
2163 `:post-affiliated' keywords.
2165 Assume point is at the beginning of the latex environment."
2166 (save-excursion
2167 (let ((case-fold-search t)
2168 (code-begin (point)))
2169 (looking-at org-element--latex-begin-environment)
2170 (if (not (re-search-forward (format org-element--latex-end-environment
2171 (regexp-quote (match-string 1)))
2172 limit t))
2173 ;; Incomplete latex environment: parse it as a paragraph.
2174 (org-element-paragraph-parser limit affiliated)
2175 (let* ((code-end (progn (forward-line) (point)))
2176 (begin (car affiliated))
2177 (value (buffer-substring-no-properties code-begin code-end))
2178 (end (progn (skip-chars-forward " \r\t\n" limit)
2179 (if (eobp) (point) (line-beginning-position)))))
2180 (list 'latex-environment
2181 (nconc
2182 (list :begin begin
2183 :end end
2184 :value value
2185 :post-blank (count-lines code-end end)
2186 :post-affiliated code-begin)
2187 (cdr affiliated))))))))
2189 (defun org-element-latex-environment-interpreter (latex-environment _)
2190 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2191 (org-element-property :value latex-environment))
2194 ;;;; Node Property
2196 (defun org-element-node-property-parser (limit)
2197 "Parse a node-property at point.
2199 LIMIT bounds the search.
2201 Return a list whose CAR is `node-property' and CDR is a plist
2202 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2203 `:post-affiliated' keywords."
2204 (looking-at org-property-re)
2205 (let ((case-fold-search t)
2206 (begin (point))
2207 (key (org-match-string-no-properties 2))
2208 (value (org-match-string-no-properties 3))
2209 (end (save-excursion
2210 (end-of-line)
2211 (if (re-search-forward org-property-re limit t)
2212 (line-beginning-position)
2213 limit))))
2214 (list 'node-property
2215 (list :key key
2216 :value value
2217 :begin begin
2218 :end end
2219 :post-blank 0
2220 :post-affiliated begin))))
2222 (defun org-element-node-property-interpreter (node-property _)
2223 "Interpret NODE-PROPERTY element as Org syntax."
2224 (format org-property-format
2225 (format ":%s:" (org-element-property :key node-property))
2226 (or (org-element-property :value node-property) "")))
2229 ;;;; Paragraph
2231 (defun org-element-paragraph-parser (limit affiliated)
2232 "Parse a paragraph.
2234 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2235 the buffer position at the beginning of the first affiliated
2236 keyword and CDR is a plist of affiliated keywords along with
2237 their value.
2239 Return a list whose CAR is `paragraph' and CDR is a plist
2240 containing `:begin', `:end', `:contents-begin' and
2241 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2243 Assume point is at the beginning of the paragraph."
2244 (save-excursion
2245 (let* ((begin (car affiliated))
2246 (contents-begin (point))
2247 (before-blank
2248 (let ((case-fold-search t))
2249 (end-of-line)
2250 ;; A matching `org-element-paragraph-separate' is not
2251 ;; necessarily the end of the paragraph. In particular,
2252 ;; drawers, blocks or LaTeX environments opening lines
2253 ;; must be closed. Moreover keywords with a secondary
2254 ;; value must belong to "dual keywords".
2255 (while (not
2256 (cond
2257 ((not (and (re-search-forward
2258 org-element-paragraph-separate limit 'move)
2259 (progn (beginning-of-line) t))))
2260 ((looking-at org-drawer-regexp)
2261 (save-excursion
2262 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2263 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2264 (save-excursion
2265 (re-search-forward
2266 (format "^[ \t]*#\\+END_%s[ \t]*$"
2267 (regexp-quote (match-string 1)))
2268 limit t)))
2269 ((looking-at org-element--latex-begin-environment)
2270 (save-excursion
2271 (re-search-forward
2272 (format org-element--latex-end-environment
2273 (regexp-quote (match-string 1)))
2274 limit t)))
2275 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2276 (member-ignore-case (match-string 1)
2277 org-element-dual-keywords))
2278 ;; Everything else is unambiguous.
2279 (t)))
2280 (end-of-line))
2281 (if (= (point) limit) limit
2282 (goto-char (line-beginning-position)))))
2283 (contents-end (save-excursion
2284 (skip-chars-backward " \r\t\n" contents-begin)
2285 (line-beginning-position 2)))
2286 (end (progn (skip-chars-forward " \r\t\n" limit)
2287 (if (eobp) (point) (line-beginning-position)))))
2288 (list 'paragraph
2289 (nconc
2290 (list :begin begin
2291 :end end
2292 :contents-begin contents-begin
2293 :contents-end contents-end
2294 :post-blank (count-lines before-blank end)
2295 :post-affiliated contents-begin)
2296 (cdr affiliated))))))
2298 (defun org-element-paragraph-interpreter (_ contents)
2299 "Interpret paragraph element as Org syntax.
2300 CONTENTS is the contents of the element."
2301 contents)
2304 ;;;; Planning
2306 (defun org-element-planning-parser (limit)
2307 "Parse a planning.
2309 LIMIT bounds the search.
2311 Return a list whose CAR is `planning' and CDR is a plist
2312 containing `:closed', `:deadline', `:scheduled', `:begin',
2313 `:end', `:post-blank' and `:post-affiliated' keywords."
2314 (save-excursion
2315 (let* ((case-fold-search nil)
2316 (begin (point))
2317 (post-blank (let ((before-blank (progn (forward-line) (point))))
2318 (skip-chars-forward " \r\t\n" limit)
2319 (skip-chars-backward " \t")
2320 (unless (bolp) (end-of-line))
2321 (count-lines before-blank (point))))
2322 (end (point))
2323 closed deadline scheduled)
2324 (goto-char begin)
2325 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2326 (goto-char (match-end 1))
2327 (skip-chars-forward " \t" end)
2328 (let ((keyword (match-string 1))
2329 (time (org-element-timestamp-parser)))
2330 (cond ((equal keyword org-closed-string) (setq closed time))
2331 ((equal keyword org-deadline-string) (setq deadline time))
2332 (t (setq scheduled time)))))
2333 (list 'planning
2334 (list :closed closed
2335 :deadline deadline
2336 :scheduled scheduled
2337 :begin begin
2338 :end end
2339 :post-blank post-blank
2340 :post-affiliated begin)))))
2342 (defun org-element-planning-interpreter (planning _)
2343 "Interpret PLANNING element as Org syntax."
2344 (mapconcat
2345 #'identity
2346 (delq nil
2347 (list (let ((deadline (org-element-property :deadline planning)))
2348 (when deadline
2349 (concat org-deadline-string " "
2350 (org-element-timestamp-interpreter deadline nil))))
2351 (let ((scheduled (org-element-property :scheduled planning)))
2352 (when scheduled
2353 (concat org-scheduled-string " "
2354 (org-element-timestamp-interpreter scheduled nil))))
2355 (let ((closed (org-element-property :closed planning)))
2356 (when closed
2357 (concat org-closed-string " "
2358 (org-element-timestamp-interpreter closed nil))))))
2359 " "))
2362 ;;;; Src Block
2364 (defun org-element-src-block-parser (limit affiliated)
2365 "Parse a src block.
2367 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2368 the buffer position at the beginning of the first affiliated
2369 keyword and CDR is a plist of affiliated keywords along with
2370 their value.
2372 Return a list whose CAR is `src-block' and CDR is a plist
2373 containing `:language', `:switches', `:parameters', `:begin',
2374 `:end', `:number-lines', `:retain-labels', `:use-labels',
2375 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2376 `:post-affiliated' keywords.
2378 Assume point is at the beginning of the block."
2379 (let ((case-fold-search t))
2380 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2381 limit t)))
2382 ;; Incomplete block: parse it as a paragraph.
2383 (org-element-paragraph-parser limit affiliated)
2384 (let ((contents-end (match-beginning 0)))
2385 (save-excursion
2386 (let* ((begin (car affiliated))
2387 (post-affiliated (point))
2388 ;; Get language as a string.
2389 (language
2390 (progn
2391 (looking-at
2392 (concat "^[ \t]*#\\+BEGIN_SRC"
2393 "\\(?: +\\(\\S-+\\)\\)?"
2394 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2395 "\\(.*\\)[ \t]*$"))
2396 (org-match-string-no-properties 1)))
2397 ;; Get switches.
2398 (switches (org-match-string-no-properties 2))
2399 ;; Get parameters.
2400 (parameters (org-match-string-no-properties 3))
2401 ;; Switches analysis
2402 (number-lines
2403 (cond ((not switches) nil)
2404 ((string-match "-n\\>" switches) 'new)
2405 ((string-match "+n\\>" switches) 'continued)))
2406 (preserve-indent (and switches
2407 (string-match "-i\\>" switches)))
2408 (label-fmt
2409 (and switches
2410 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2411 (match-string 1 switches)))
2412 ;; Should labels be retained in (or stripped from)
2413 ;; src blocks?
2414 (retain-labels
2415 (or (not switches)
2416 (not (string-match "-r\\>" switches))
2417 (and number-lines (string-match "-k\\>" switches))))
2418 ;; What should code-references use - labels or
2419 ;; line-numbers?
2420 (use-labels
2421 (or (not switches)
2422 (and retain-labels
2423 (not (string-match "-k\\>" switches)))))
2424 ;; Retrieve code.
2425 (value (org-unescape-code-in-string
2426 (buffer-substring-no-properties
2427 (line-beginning-position 2) contents-end)))
2428 (pos-before-blank (progn (goto-char contents-end)
2429 (forward-line)
2430 (point)))
2431 ;; Get position after ending blank lines.
2432 (end (progn (skip-chars-forward " \r\t\n" limit)
2433 (if (eobp) (point) (line-beginning-position)))))
2434 (list 'src-block
2435 (nconc
2436 (list :language language
2437 :switches (and (org-string-nw-p switches)
2438 (org-trim switches))
2439 :parameters (and (org-string-nw-p parameters)
2440 (org-trim parameters))
2441 :begin begin
2442 :end end
2443 :number-lines number-lines
2444 :preserve-indent preserve-indent
2445 :retain-labels retain-labels
2446 :use-labels use-labels
2447 :label-fmt label-fmt
2448 :value value
2449 :post-blank (count-lines pos-before-blank end)
2450 :post-affiliated post-affiliated)
2451 (cdr affiliated)))))))))
2453 (defun org-element-src-block-interpreter (src-block _)
2454 "Interpret SRC-BLOCK element as Org syntax."
2455 (let ((lang (org-element-property :language src-block))
2456 (switches (org-element-property :switches src-block))
2457 (params (org-element-property :parameters src-block))
2458 (value
2459 (let ((val (org-element-property :value src-block)))
2460 (cond
2461 ((or org-src-preserve-indentation
2462 (org-element-property :preserve-indent src-block))
2463 val)
2464 ((zerop org-edit-src-content-indentation)
2465 (org-remove-indentation val))
2467 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2468 (replace-regexp-in-string
2469 "^" ind (org-remove-indentation val))))))))
2470 (concat (format "#+BEGIN_SRC%s\n"
2471 (concat (and lang (concat " " lang))
2472 (and switches (concat " " switches))
2473 (and params (concat " " params))))
2474 (org-element-normalize-string (org-escape-code-in-string value))
2475 "#+END_SRC")))
2478 ;;;; Table
2480 (defun org-element-table-parser (limit affiliated)
2481 "Parse a table at point.
2483 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2484 the buffer position at the beginning of the first affiliated
2485 keyword and CDR is a plist of affiliated keywords along with
2486 their value.
2488 Return a list whose CAR is `table' and CDR is a plist containing
2489 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2490 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2491 keywords.
2493 Assume point is at the beginning of the table."
2494 (save-excursion
2495 (let* ((case-fold-search t)
2496 (table-begin (point))
2497 (type (if (looking-at "[ \t]*|") 'org 'table.el))
2498 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2499 (if (eq type 'org) "" "+")))
2500 (begin (car affiliated))
2501 (table-end
2502 (if (re-search-forward end-re limit 'move)
2503 (goto-char (match-beginning 0))
2504 (point)))
2505 (tblfm (let (acc)
2506 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2507 (push (org-match-string-no-properties 1) acc)
2508 (forward-line))
2509 acc))
2510 (pos-before-blank (point))
2511 (end (progn (skip-chars-forward " \r\t\n" limit)
2512 (if (eobp) (point) (line-beginning-position)))))
2513 (list 'table
2514 (nconc
2515 (list :begin begin
2516 :end end
2517 :type type
2518 :tblfm tblfm
2519 ;; Only `org' tables have contents. `table.el' tables
2520 ;; use a `:value' property to store raw table as
2521 ;; a string.
2522 :contents-begin (and (eq type 'org) table-begin)
2523 :contents-end (and (eq type 'org) table-end)
2524 :value (and (eq type 'table.el)
2525 (buffer-substring-no-properties
2526 table-begin table-end))
2527 :post-blank (count-lines pos-before-blank end)
2528 :post-affiliated table-begin)
2529 (cdr affiliated))))))
2531 (defun org-element-table-interpreter (table contents)
2532 "Interpret TABLE element as Org syntax.
2533 CONTENTS is a string, if table's type is `org', or nil."
2534 (if (eq (org-element-property :type table) 'table.el)
2535 (org-remove-indentation (org-element-property :value table))
2536 (concat (with-temp-buffer (insert contents)
2537 (org-table-align)
2538 (buffer-string))
2539 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2540 (reverse (org-element-property :tblfm table))
2541 "\n"))))
2544 ;;;; Table Row
2546 (defun org-element-table-row-parser (_)
2547 "Parse table row at point.
2549 Return a list whose CAR is `table-row' and CDR is a plist
2550 containing `:begin', `:end', `:contents-begin', `:contents-end',
2551 `:type', `:post-blank' and `:post-affiliated' keywords."
2552 (save-excursion
2553 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2554 (begin (point))
2555 ;; A table rule has no contents. In that case, ensure
2556 ;; CONTENTS-BEGIN matches CONTENTS-END.
2557 (contents-begin (and (eq type 'standard) (search-forward "|")))
2558 (contents-end (and (eq type 'standard)
2559 (progn
2560 (end-of-line)
2561 (skip-chars-backward " \t")
2562 (point))))
2563 (end (line-beginning-position 2)))
2564 (list 'table-row
2565 (list :type type
2566 :begin begin
2567 :end end
2568 :contents-begin contents-begin
2569 :contents-end contents-end
2570 :post-blank 0
2571 :post-affiliated begin)))))
2573 (defun org-element-table-row-interpreter (table-row contents)
2574 "Interpret TABLE-ROW element as Org syntax.
2575 CONTENTS is the contents of the table row."
2576 (if (eq (org-element-property :type table-row) 'rule) "|-"
2577 (concat "| " contents)))
2580 ;;;; Verse Block
2582 (defun org-element-verse-block-parser (limit affiliated)
2583 "Parse a verse block.
2585 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2586 the buffer position at the beginning of the first affiliated
2587 keyword and CDR is a plist of affiliated keywords along with
2588 their value.
2590 Return a list whose CAR is `verse-block' and CDR is a plist
2591 containing `:begin', `:end', `:contents-begin', `:contents-end',
2592 `:post-blank' and `:post-affiliated' keywords.
2594 Assume point is at beginning of the block."
2595 (let ((case-fold-search t))
2596 (if (not (save-excursion
2597 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2598 ;; Incomplete block: parse it as a paragraph.
2599 (org-element-paragraph-parser limit affiliated)
2600 (let ((contents-end (match-beginning 0)))
2601 (save-excursion
2602 (let* ((begin (car affiliated))
2603 (post-affiliated (point))
2604 (contents-begin (progn (forward-line) (point)))
2605 (pos-before-blank (progn (goto-char contents-end)
2606 (forward-line)
2607 (point)))
2608 (end (progn (skip-chars-forward " \r\t\n" limit)
2609 (if (eobp) (point) (line-beginning-position)))))
2610 (list 'verse-block
2611 (nconc
2612 (list :begin begin
2613 :end end
2614 :contents-begin contents-begin
2615 :contents-end contents-end
2616 :post-blank (count-lines pos-before-blank end)
2617 :post-affiliated post-affiliated)
2618 (cdr affiliated)))))))))
2620 (defun org-element-verse-block-interpreter (_ contents)
2621 "Interpret verse-block element as Org syntax.
2622 CONTENTS is verse block contents."
2623 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2627 ;;; Objects
2629 ;; Unlike to elements, raw text can be found between objects. Hence,
2630 ;; `org-element--object-lex' is provided to find the next object in
2631 ;; buffer.
2633 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2634 ;; object types they can contain will be specified in
2635 ;; `org-element-object-restrictions'.
2637 ;; Creating a new type of object requires to alter
2638 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2639 ;; new type in `org-element-all-objects', and possibly add
2640 ;; restrictions in `org-element-object-restrictions'.
2642 ;;;; Bold
2644 (defun org-element-bold-parser ()
2645 "Parse bold object at point, if any.
2647 When at a bold object, return a list whose car is `bold' and cdr
2648 is a plist with `:begin', `:end', `:contents-begin' and
2649 `:contents-end' and `:post-blank' keywords. Otherwise, return
2650 nil.
2652 Assume point is at the first star marker."
2653 (save-excursion
2654 (unless (bolp) (backward-char 1))
2655 (when (looking-at org-emph-re)
2656 (let ((begin (match-beginning 2))
2657 (contents-begin (match-beginning 4))
2658 (contents-end (match-end 4))
2659 (post-blank (progn (goto-char (match-end 2))
2660 (skip-chars-forward " \t")))
2661 (end (point)))
2662 (list 'bold
2663 (list :begin begin
2664 :end end
2665 :contents-begin contents-begin
2666 :contents-end contents-end
2667 :post-blank post-blank))))))
2669 (defun org-element-bold-interpreter (_ contents)
2670 "Interpret bold object as Org syntax.
2671 CONTENTS is the contents of the object."
2672 (format "*%s*" contents))
2675 ;;;; Code
2677 (defun org-element-code-parser ()
2678 "Parse code object at point, if any.
2680 When at a code object, return a list whose car is `code' and cdr
2681 is a plist with `:value', `:begin', `:end' and `:post-blank'
2682 keywords. Otherwise, return nil.
2684 Assume point is at the first tilde marker."
2685 (save-excursion
2686 (unless (bolp) (backward-char 1))
2687 (when (looking-at org-emph-re)
2688 (let ((begin (match-beginning 2))
2689 (value (org-match-string-no-properties 4))
2690 (post-blank (progn (goto-char (match-end 2))
2691 (skip-chars-forward " \t")))
2692 (end (point)))
2693 (list 'code
2694 (list :value value
2695 :begin begin
2696 :end end
2697 :post-blank post-blank))))))
2699 (defun org-element-code-interpreter (code _)
2700 "Interpret CODE object as Org syntax."
2701 (format "~%s~" (org-element-property :value code)))
2704 ;;;; Entity
2706 (defun org-element-entity-parser ()
2707 "Parse entity at point, if any.
2709 When at an entity, return a list whose car is `entity' and cdr
2710 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2711 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2712 `:post-blank' as keywords. Otherwise, return nil.
2714 Assume point is at the beginning of the entity."
2715 (catch 'no-object
2716 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2717 (save-excursion
2718 (let* ((value (or (org-entity-get (match-string 1))
2719 (throw 'no-object nil)))
2720 (begin (match-beginning 0))
2721 (bracketsp (string= (match-string 2) "{}"))
2722 (post-blank (progn (goto-char (match-end 1))
2723 (when bracketsp (forward-char 2))
2724 (skip-chars-forward " \t")))
2725 (end (point)))
2726 (list 'entity
2727 (list :name (car value)
2728 :latex (nth 1 value)
2729 :latex-math-p (nth 2 value)
2730 :html (nth 3 value)
2731 :ascii (nth 4 value)
2732 :latin1 (nth 5 value)
2733 :utf-8 (nth 6 value)
2734 :begin begin
2735 :end end
2736 :use-brackets-p bracketsp
2737 :post-blank post-blank)))))))
2739 (defun org-element-entity-interpreter (entity _)
2740 "Interpret ENTITY object as Org syntax."
2741 (concat "\\"
2742 (org-element-property :name entity)
2743 (when (org-element-property :use-brackets-p entity) "{}")))
2746 ;;;; Export Snippet
2748 (defun org-element-export-snippet-parser ()
2749 "Parse export snippet at point.
2751 When at an export snippet, return a list whose car is
2752 `export-snippet' and cdr a plist with `:begin', `:end',
2753 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2754 return nil.
2756 Assume point is at the beginning of the snippet."
2757 (save-excursion
2758 (let (contents-end)
2759 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2760 (setq contents-end
2761 (save-match-data (goto-char (match-end 0))
2762 (re-search-forward "@@" nil t)
2763 (match-beginning 0))))
2764 (let* ((begin (match-beginning 0))
2765 (back-end (org-match-string-no-properties 1))
2766 (value (buffer-substring-no-properties
2767 (match-end 0) contents-end))
2768 (post-blank (skip-chars-forward " \t"))
2769 (end (point)))
2770 (list 'export-snippet
2771 (list :back-end back-end
2772 :value value
2773 :begin begin
2774 :end end
2775 :post-blank post-blank)))))))
2777 (defun org-element-export-snippet-interpreter (export-snippet _)
2778 "Interpret EXPORT-SNIPPET object as Org syntax."
2779 (format "@@%s:%s@@"
2780 (org-element-property :back-end export-snippet)
2781 (org-element-property :value export-snippet)))
2784 ;;;; Footnote Reference
2786 (defun org-element-footnote-reference-parser ()
2787 "Parse footnote reference at point, if any.
2789 When at a footnote reference, return a list whose car is
2790 `footnote-reference' and cdr a plist with `:label', `:type',
2791 `:begin', `:end', `:content-begin', `:contents-end' and
2792 `:post-blank' as keywords. Otherwise, return nil."
2793 (when (looking-at org-footnote-re)
2794 (let ((closing (with-syntax-table org-element--pair-square-table
2795 (ignore-errors (scan-lists (point) 1 0)))))
2796 (when closing
2797 (save-excursion
2798 (let* ((begin (point))
2799 (label (match-string-no-properties 1))
2800 (inner-begin (match-end 0))
2801 (inner-end (1- closing))
2802 (type (if (match-end 2) 'inline 'standard))
2803 (post-blank (progn (goto-char closing)
2804 (skip-chars-forward " \t")))
2805 (end (point)))
2806 (list 'footnote-reference
2807 (list :label label
2808 :type type
2809 :begin begin
2810 :end end
2811 :contents-begin (and (eq type 'inline) inner-begin)
2812 :contents-end (and (eq type 'inline) inner-end)
2813 :post-blank post-blank))))))))
2815 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2816 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2817 CONTENTS is its definition, when inline, or nil."
2818 (format "[fn:%s%s]"
2819 (or (org-element-property :label footnote-reference) "")
2820 (if contents (concat ":" contents) "")))
2823 ;;;; Inline Babel Call
2825 (defun org-element-inline-babel-call-parser ()
2826 "Parse inline babel call at point, if any.
2828 When at an inline babel call, return a list whose car is
2829 `inline-babel-call' and cdr a plist with `:call',
2830 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2831 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2833 Assume point is at the beginning of the babel call."
2834 (save-excursion
2835 (catch :no-object
2836 (when (let ((case-fold-search nil))
2837 (looking-at
2838 "\\<call_\\([^ \t\n[{]+\\)\\(?:\\[\\([^]]*\\)\\]\\)?("))
2839 (let ((begin (point))
2840 (call (match-string-no-properties 1))
2841 (inside-header
2842 (let ((h (org-string-nw-p (match-string-no-properties 2))))
2843 (and h (org-trim
2844 (replace-regexp-in-string "\n[ \t]*" " " h))))))
2845 (goto-char (1- (match-end 0)))
2846 (let* ((s (point))
2847 (e (with-syntax-table org-element--pair-round-table
2848 (or (ignore-errors (scan-lists s 1 0))
2849 ;; Invalid inline source block.
2850 (throw :no-object nil))))
2851 (arguments
2852 (let ((a (org-string-nw-p
2853 (buffer-substring-no-properties (1+ s) (1- e)))))
2854 (and a (org-trim
2855 (replace-regexp-in-string "\n[ \t]*" " " a)))))
2856 (end-header
2857 (progn
2858 (goto-char e)
2859 (and (looking-at "\\[\\([^]]*\\)\\]")
2860 (prog1 (org-string-nw-p (match-string-no-properties 1))
2861 (goto-char (match-end 0))))))
2862 (value (buffer-substring-no-properties begin (point)))
2863 (post-blank (skip-chars-forward " \t"))
2864 (end (point)))
2865 (list 'inline-babel-call
2866 (list :call call
2867 :inside-header inside-header
2868 :arguments arguments
2869 :end-header end-header
2870 :begin begin
2871 :end end
2872 :value value
2873 :post-blank post-blank))))))))
2875 (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
2876 "Interpret INLINE-BABEL-CALL object as Org syntax."
2877 (concat "call_"
2878 (org-element-property :call inline-babel-call)
2879 (let ((h (org-element-property :inside-header inline-babel-call)))
2880 (and h (format "[%s]" h)))
2881 "(" (org-element-property :arguments inline-babel-call) ")"
2882 (let ((h (org-element-property :end-header inline-babel-call)))
2883 (and h (format "[%s]" h)))))
2886 ;;;; Inline Src Block
2888 (defun org-element-inline-src-block-parser ()
2889 "Parse inline source block at point, if any.
2891 When at an inline source block, return a list whose car is
2892 `inline-src-block' and cdr a plist with `:begin', `:end',
2893 `:language', `:value', `:parameters' and `:post-blank' as
2894 keywords. Otherwise, return nil.
2896 Assume point is at the beginning of the inline src block."
2897 (save-excursion
2898 (catch :no-object
2899 (when (let ((case-fold-search nil))
2900 (looking-at "\\<src_\\([^ \t\n[{]+\\)\
2901 \\(?:\\[[ \t]*\\([^]]*?\\)[ \t]*\\]\\)?{"))
2902 (let ((begin (point))
2903 (language (match-string-no-properties 1))
2904 (parameters
2905 (let ((p (org-string-nw-p (match-string-no-properties 2))))
2906 (and p (org-trim
2907 (replace-regexp-in-string "\n[ \t]*" " " p))))))
2908 (goto-char (1- (match-end 0)))
2909 (let* ((s (point))
2910 (e (with-syntax-table org-element--pair-curly-table
2911 (or (ignore-errors (scan-lists s 1 0))
2912 ;; Invalid inline source block.
2913 (throw :no-object nil))))
2914 (value (buffer-substring-no-properties
2915 (1+ s) (1- e)))
2916 (post-blank (progn (goto-char e)
2917 (skip-chars-forward " \t"))))
2918 (list 'inline-src-block
2919 (list :language language
2920 :value value
2921 :parameters parameters
2922 :begin begin
2923 :end (point)
2924 :post-blank post-blank))))))))
2926 (defun org-element-inline-src-block-interpreter (inline-src-block _)
2927 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2928 (let ((language (org-element-property :language inline-src-block))
2929 (arguments (org-element-property :parameters inline-src-block))
2930 (body (org-element-property :value inline-src-block)))
2931 (format "src_%s%s{%s}"
2932 language
2933 (if arguments (format "[%s]" arguments) "")
2934 body)))
2936 ;;;; Italic
2938 (defun org-element-italic-parser ()
2939 "Parse italic object at point, if any.
2941 When at an italic object, return a list whose car is `italic' and
2942 cdr is a plist with `:begin', `:end', `:contents-begin' and
2943 `:contents-end' and `:post-blank' keywords. Otherwise, return
2944 nil.
2946 Assume point is at the first slash marker."
2947 (save-excursion
2948 (unless (bolp) (backward-char 1))
2949 (when (looking-at org-emph-re)
2950 (let ((begin (match-beginning 2))
2951 (contents-begin (match-beginning 4))
2952 (contents-end (match-end 4))
2953 (post-blank (progn (goto-char (match-end 2))
2954 (skip-chars-forward " \t")))
2955 (end (point)))
2956 (list 'italic
2957 (list :begin begin
2958 :end end
2959 :contents-begin contents-begin
2960 :contents-end contents-end
2961 :post-blank post-blank))))))
2963 (defun org-element-italic-interpreter (_ contents)
2964 "Interpret italic object as Org syntax.
2965 CONTENTS is the contents of the object."
2966 (format "/%s/" contents))
2969 ;;;; Latex Fragment
2971 (defun org-element-latex-fragment-parser ()
2972 "Parse LaTeX fragment at point, if any.
2974 When at a LaTeX fragment, return a list whose car is
2975 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2976 and `:post-blank' as keywords. Otherwise, return nil.
2978 Assume point is at the beginning of the LaTeX fragment."
2979 (catch 'no-object
2980 (save-excursion
2981 (let* ((begin (point))
2982 (after-fragment
2983 (if (eq (char-after) ?$)
2984 (if (eq (char-after (1+ (point))) ?$)
2985 (search-forward "$$" nil t 2)
2986 (and (not (eq (char-before) ?$))
2987 (search-forward "$" nil t 2)
2988 (not (memq (char-before (match-beginning 0))
2989 '(?\s ?\t ?\n ?, ?.)))
2990 (looking-at "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|$\\)")
2991 (point)))
2992 (pcase (char-after (1+ (point)))
2993 (?\( (search-forward "\\)" nil t))
2994 (?\[ (search-forward "\\]" nil t))
2996 ;; Macro.
2997 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
2998 \\|\\({[^{}\n]*}\\)\\)*")
2999 (match-end 0))))))
3000 (post-blank (if (not after-fragment) (throw 'no-object nil)
3001 (goto-char after-fragment)
3002 (skip-chars-forward " \t")))
3003 (end (point)))
3004 (list 'latex-fragment
3005 (list :value (buffer-substring-no-properties begin after-fragment)
3006 :begin begin
3007 :end end
3008 :post-blank post-blank))))))
3010 (defun org-element-latex-fragment-interpreter (latex-fragment _)
3011 "Interpret LATEX-FRAGMENT object as Org syntax."
3012 (org-element-property :value latex-fragment))
3014 ;;;; Line Break
3016 (defun org-element-line-break-parser ()
3017 "Parse line break at point, if any.
3019 When at a line break, return a list whose car is `line-break',
3020 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3021 Otherwise, return nil.
3023 Assume point is at the beginning of the line break."
3024 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
3025 (not (eq (char-before) ?\\)))
3026 (list 'line-break
3027 (list :begin (point)
3028 :end (line-beginning-position 2)
3029 :post-blank 0))))
3031 (defun org-element-line-break-interpreter (&rest _)
3032 "Interpret LINE-BREAK object as Org syntax."
3033 "\\\\\n")
3036 ;;;; Link
3038 (defun org-element-link-parser ()
3039 "Parse link at point, if any.
3041 When at a link, return a list whose car is `link' and cdr a plist
3042 with `:type', `:path', `:raw-link', `:application',
3043 `:search-option', `:begin', `:end', `:contents-begin',
3044 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3045 nil.
3047 Assume point is at the beginning of the link."
3048 (catch 'no-object
3049 (let ((begin (point))
3050 end contents-begin contents-end link-end post-blank path type
3051 raw-link search-option application)
3052 (cond
3053 ;; Type 1: Text targeted from a radio target.
3054 ((and org-target-link-regexp
3055 (save-excursion (or (bolp) (backward-char))
3056 (looking-at org-target-link-regexp)))
3057 (setq type "radio"
3058 link-end (match-end 1)
3059 path (org-match-string-no-properties 1)
3060 contents-begin (match-beginning 1)
3061 contents-end (match-end 1)))
3062 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3063 ((looking-at org-bracket-link-regexp)
3064 (setq contents-begin (match-beginning 3))
3065 (setq contents-end (match-end 3))
3066 (setq link-end (match-end 0))
3067 ;; RAW-LINK is the original link. Expand any
3068 ;; abbreviation in it.
3070 ;; Also treat any newline character and associated
3071 ;; indentation as a single space character. This is not
3072 ;; compatible with RFC 3986, which requires to ignore
3073 ;; them altogether. However, doing so would require
3074 ;; users to encode spaces on the fly when writing links
3075 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3076 ;; [[shell:ls *.org]], which defeats Org's focus on
3077 ;; simplicity.
3078 (setq raw-link (org-link-expand-abbrev
3079 (replace-regexp-in-string
3080 "[ \t]*\n[ \t]*" " "
3081 (org-match-string-no-properties 1))))
3082 ;; Determine TYPE of link and set PATH accordingly. According
3083 ;; to RFC 3986, remove whitespaces from URI in external links.
3084 ;; In internal ones, treat indentation as a single space.
3085 (cond
3086 ;; File type.
3087 ((or (file-name-absolute-p raw-link)
3088 (string-match "\\`\\.\\.?/" raw-link))
3089 (setq type "file")
3090 (setq path raw-link))
3091 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3092 ((string-match org-link-types-re raw-link)
3093 (setq type (match-string 1 raw-link))
3094 (setq path (substring raw-link (match-end 0))))
3095 ;; Id type: PATH is the id.
3096 ((string-match "\\`id:\\([-a-f0-9]+\\)\\'" raw-link)
3097 (setq type "id" path (match-string 1 raw-link)))
3098 ;; Code-ref type: PATH is the name of the reference.
3099 ((and (org-string-match-p "\\`(" raw-link)
3100 (org-string-match-p ")\\'" raw-link))
3101 (setq type "coderef")
3102 (setq path (substring raw-link 1 -1)))
3103 ;; Custom-id type: PATH is the name of the custom id.
3104 ((= (string-to-char raw-link) ?#)
3105 (setq type "custom-id")
3106 (setq path (substring raw-link 1)))
3107 ;; Fuzzy type: Internal link either matches a target, an
3108 ;; headline name or nothing. PATH is the target or
3109 ;; headline's name.
3111 (setq type "fuzzy")
3112 (setq path raw-link))))
3113 ;; Type 3: Plain link, e.g., http://orgmode.org
3114 ((looking-at org-plain-link-re)
3115 (setq raw-link (org-match-string-no-properties 0)
3116 type (org-match-string-no-properties 1)
3117 link-end (match-end 0)
3118 path (org-match-string-no-properties 2)))
3119 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3120 ;; bracket links, follow RFC 3986 and remove any extra
3121 ;; whitespace in URI.
3122 ((looking-at org-angle-link-re)
3123 (setq type (org-match-string-no-properties 1))
3124 (setq link-end (match-end 0))
3125 (setq raw-link
3126 (buffer-substring-no-properties
3127 (match-beginning 1) (match-end 2)))
3128 (setq path (replace-regexp-in-string
3129 "[ \t]*\n[ \t]*" "" (org-match-string-no-properties 2))))
3130 (t (throw 'no-object nil)))
3131 ;; In any case, deduce end point after trailing white space from
3132 ;; LINK-END variable.
3133 (save-excursion
3134 (setq post-blank
3135 (progn (goto-char link-end) (skip-chars-forward " \t")))
3136 (setq end (point)))
3137 ;; Special "file" type link processing. Extract opening
3138 ;; application and search option, if any. Also normalize URI.
3139 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3140 (setq application (match-string 1 type) type "file")
3141 (when (string-match "::\\(.*\\)\\'" path)
3142 (setq search-option (match-string 1 path))
3143 (setq path (replace-match "" nil nil path)))
3144 (setq path (replace-regexp-in-string "\\`///+" "/" path)))
3145 ;; Translate link, if `org-link-translation-function' is set.
3146 (let ((trans (and (functionp org-link-translation-function)
3147 (funcall org-link-translation-function type path))))
3148 (when trans
3149 (setq type (car trans))
3150 (setq path (cdr trans))))
3151 (list 'link
3152 (list :type type
3153 :path path
3154 :raw-link (or raw-link path)
3155 :application application
3156 :search-option search-option
3157 :begin begin
3158 :end end
3159 :contents-begin contents-begin
3160 :contents-end contents-end
3161 :post-blank post-blank)))))
3163 (defun org-element-link-interpreter (link contents)
3164 "Interpret LINK object as Org syntax.
3165 CONTENTS is the contents of the object, or nil."
3166 (let ((type (org-element-property :type link))
3167 (path (org-element-property :path link)))
3168 (if (string= type "radio") path
3169 (format "[[%s]%s]"
3170 (cond ((string= type "coderef") (format "(%s)" path))
3171 ((string= type "custom-id") (concat "#" path))
3172 ((string= type "file")
3173 (let ((app (org-element-property :application link))
3174 (opt (org-element-property :search-option link)))
3175 (concat type (and app (concat "+" app)) ":"
3176 path
3177 (and opt (concat "::" opt)))))
3178 ((string= type "fuzzy") path)
3179 (t (concat type ":" path)))
3180 (if contents (format "[%s]" contents) "")))))
3183 ;;;; Macro
3185 (defun org-element-macro-parser ()
3186 "Parse macro at point, if any.
3188 When at a macro, return a list whose car is `macro' and cdr
3189 a plist with `:key', `:args', `:begin', `:end', `:value' and
3190 `:post-blank' as keywords. Otherwise, return nil.
3192 Assume point is at the macro."
3193 (save-excursion
3194 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3195 (let ((begin (point))
3196 (key (downcase (org-match-string-no-properties 1)))
3197 (value (org-match-string-no-properties 0))
3198 (post-blank (progn (goto-char (match-end 0))
3199 (skip-chars-forward " \t")))
3200 (end (point))
3201 (args (let ((args (org-match-string-no-properties 3)))
3202 (and args (org-macro-extract-arguments args)))))
3203 (list 'macro
3204 (list :key key
3205 :value value
3206 :args args
3207 :begin begin
3208 :end end
3209 :post-blank post-blank))))))
3211 (defun org-element-macro-interpreter (macro _)
3212 "Interpret MACRO object as Org syntax."
3213 (org-element-property :value macro))
3216 ;;;; Radio-target
3218 (defun org-element-radio-target-parser ()
3219 "Parse radio target at point, if any.
3221 When at a radio target, return a list whose car is `radio-target'
3222 and cdr a plist with `:begin', `:end', `:contents-begin',
3223 `:contents-end', `:value' and `:post-blank' as keywords.
3224 Otherwise, return nil.
3226 Assume point is at the radio target."
3227 (save-excursion
3228 (when (looking-at org-radio-target-regexp)
3229 (let ((begin (point))
3230 (contents-begin (match-beginning 1))
3231 (contents-end (match-end 1))
3232 (value (org-match-string-no-properties 1))
3233 (post-blank (progn (goto-char (match-end 0))
3234 (skip-chars-forward " \t")))
3235 (end (point)))
3236 (list 'radio-target
3237 (list :begin begin
3238 :end end
3239 :contents-begin contents-begin
3240 :contents-end contents-end
3241 :post-blank post-blank
3242 :value value))))))
3244 (defun org-element-radio-target-interpreter (_ contents)
3245 "Interpret target object as Org syntax.
3246 CONTENTS is the contents of the object."
3247 (concat "<<<" contents ">>>"))
3250 ;;;; Statistics Cookie
3252 (defun org-element-statistics-cookie-parser ()
3253 "Parse statistics cookie at point, if any.
3255 When at a statistics cookie, return a list whose car is
3256 `statistics-cookie', and cdr a plist with `:begin', `:end',
3257 `:value' and `:post-blank' keywords. Otherwise, return nil.
3259 Assume point is at the beginning of the statistics-cookie."
3260 (save-excursion
3261 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3262 (let* ((begin (point))
3263 (value (buffer-substring-no-properties
3264 (match-beginning 0) (match-end 0)))
3265 (post-blank (progn (goto-char (match-end 0))
3266 (skip-chars-forward " \t")))
3267 (end (point)))
3268 (list 'statistics-cookie
3269 (list :begin begin
3270 :end end
3271 :value value
3272 :post-blank post-blank))))))
3274 (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
3275 "Interpret STATISTICS-COOKIE object as Org syntax."
3276 (org-element-property :value statistics-cookie))
3279 ;;;; Strike-Through
3281 (defun org-element-strike-through-parser ()
3282 "Parse strike-through object at point, if any.
3284 When at a strike-through object, return a list whose car is
3285 `strike-through' and cdr is a plist with `:begin', `:end',
3286 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3287 Otherwise, return nil.
3289 Assume point is at the first plus sign marker."
3290 (save-excursion
3291 (unless (bolp) (backward-char 1))
3292 (when (looking-at org-emph-re)
3293 (let ((begin (match-beginning 2))
3294 (contents-begin (match-beginning 4))
3295 (contents-end (match-end 4))
3296 (post-blank (progn (goto-char (match-end 2))
3297 (skip-chars-forward " \t")))
3298 (end (point)))
3299 (list 'strike-through
3300 (list :begin begin
3301 :end end
3302 :contents-begin contents-begin
3303 :contents-end contents-end
3304 :post-blank post-blank))))))
3306 (defun org-element-strike-through-interpreter (_ contents)
3307 "Interpret strike-through object as Org syntax.
3308 CONTENTS is the contents of the object."
3309 (format "+%s+" contents))
3312 ;;;; Subscript
3314 (defun org-element-subscript-parser ()
3315 "Parse subscript at point, if any.
3317 When at a subscript object, return a list whose car is
3318 `subscript' and cdr a plist with `:begin', `:end',
3319 `:contents-begin', `:contents-end', `:use-brackets-p' and
3320 `:post-blank' as keywords. Otherwise, return nil.
3322 Assume point is at the underscore."
3323 (save-excursion
3324 (unless (bolp) (backward-char))
3325 (when (looking-at org-match-substring-regexp)
3326 (let ((bracketsp (match-beginning 4))
3327 (begin (match-beginning 2))
3328 (contents-begin (or (match-beginning 4)
3329 (match-beginning 3)))
3330 (contents-end (or (match-end 4) (match-end 3)))
3331 (post-blank (progn (goto-char (match-end 0))
3332 (skip-chars-forward " \t")))
3333 (end (point)))
3334 (list 'subscript
3335 (list :begin begin
3336 :end end
3337 :use-brackets-p bracketsp
3338 :contents-begin contents-begin
3339 :contents-end contents-end
3340 :post-blank post-blank))))))
3342 (defun org-element-subscript-interpreter (subscript contents)
3343 "Interpret SUBSCRIPT object as Org syntax.
3344 CONTENTS is the contents of the object."
3345 (format
3346 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3347 contents))
3350 ;;;; Superscript
3352 (defun org-element-superscript-parser ()
3353 "Parse superscript at point, if any.
3355 When at a superscript object, return a list whose car is
3356 `superscript' and cdr a plist with `:begin', `:end',
3357 `:contents-begin', `:contents-end', `:use-brackets-p' and
3358 `:post-blank' as keywords. Otherwise, return nil.
3360 Assume point is at the caret."
3361 (save-excursion
3362 (unless (bolp) (backward-char))
3363 (when (looking-at org-match-substring-regexp)
3364 (let ((bracketsp (match-beginning 4))
3365 (begin (match-beginning 2))
3366 (contents-begin (or (match-beginning 4)
3367 (match-beginning 3)))
3368 (contents-end (or (match-end 4) (match-end 3)))
3369 (post-blank (progn (goto-char (match-end 0))
3370 (skip-chars-forward " \t")))
3371 (end (point)))
3372 (list 'superscript
3373 (list :begin begin
3374 :end end
3375 :use-brackets-p bracketsp
3376 :contents-begin contents-begin
3377 :contents-end contents-end
3378 :post-blank post-blank))))))
3380 (defun org-element-superscript-interpreter (superscript contents)
3381 "Interpret SUPERSCRIPT object as Org syntax.
3382 CONTENTS is the contents of the object."
3383 (format
3384 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3385 contents))
3388 ;;;; Table Cell
3390 (defun org-element-table-cell-parser ()
3391 "Parse table cell at point.
3392 Return a list whose car is `table-cell' and cdr is a plist
3393 containing `:begin', `:end', `:contents-begin', `:contents-end'
3394 and `:post-blank' keywords."
3395 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3396 (let* ((begin (match-beginning 0))
3397 (end (match-end 0))
3398 (contents-begin (match-beginning 1))
3399 (contents-end (match-end 1)))
3400 (list 'table-cell
3401 (list :begin begin
3402 :end end
3403 :contents-begin contents-begin
3404 :contents-end contents-end
3405 :post-blank 0))))
3407 (defun org-element-table-cell-interpreter (_ contents)
3408 "Interpret table-cell element as Org syntax.
3409 CONTENTS is the contents of the cell, or nil."
3410 (concat " " contents " |"))
3413 ;;;; Target
3415 (defun org-element-target-parser ()
3416 "Parse target at point, if any.
3418 When at a target, return a list whose car is `target' and cdr
3419 a plist with `:begin', `:end', `:value' and `:post-blank' as
3420 keywords. Otherwise, return nil.
3422 Assume point is at the target."
3423 (save-excursion
3424 (when (looking-at org-target-regexp)
3425 (let ((begin (point))
3426 (value (org-match-string-no-properties 1))
3427 (post-blank (progn (goto-char (match-end 0))
3428 (skip-chars-forward " \t")))
3429 (end (point)))
3430 (list 'target
3431 (list :begin begin
3432 :end end
3433 :value value
3434 :post-blank post-blank))))))
3436 (defun org-element-target-interpreter (target _)
3437 "Interpret TARGET object as Org syntax."
3438 (format "<<%s>>" (org-element-property :value target)))
3441 ;;;; Timestamp
3443 (defconst org-element--timestamp-regexp
3444 (concat org-ts-regexp-both
3445 "\\|"
3446 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3447 "\\|"
3448 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3449 "Regexp matching any timestamp type object.")
3451 (defun org-element-timestamp-parser ()
3452 "Parse time stamp at point, if any.
3454 When at a time stamp, return a list whose car is `timestamp', and
3455 cdr a plist with `:type', `:raw-value', `:year-start',
3456 `:month-start', `:day-start', `:hour-start', `:minute-start',
3457 `:year-end', `:month-end', `:day-end', `:hour-end',
3458 `:minute-end', `:repeater-type', `:repeater-value',
3459 `:repeater-unit', `:warning-type', `:warning-value',
3460 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3461 Otherwise, return nil.
3463 Assume point is at the beginning of the timestamp."
3464 (when (org-looking-at-p org-element--timestamp-regexp)
3465 (save-excursion
3466 (let* ((begin (point))
3467 (activep (eq (char-after) ?<))
3468 (raw-value
3469 (progn
3470 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3471 (match-string-no-properties 0)))
3472 (date-start (match-string-no-properties 1))
3473 (date-end (match-string 3))
3474 (diaryp (match-beginning 2))
3475 (post-blank (progn (goto-char (match-end 0))
3476 (skip-chars-forward " \t")))
3477 (end (point))
3478 (time-range
3479 (and (not diaryp)
3480 (string-match
3481 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3482 date-start)
3483 (cons (string-to-number (match-string 2 date-start))
3484 (string-to-number (match-string 3 date-start)))))
3485 (type (cond (diaryp 'diary)
3486 ((and activep (or date-end time-range)) 'active-range)
3487 (activep 'active)
3488 ((or date-end time-range) 'inactive-range)
3489 (t 'inactive)))
3490 (repeater-props
3491 (and (not diaryp)
3492 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3493 raw-value)
3494 (list
3495 :repeater-type
3496 (let ((type (match-string 1 raw-value)))
3497 (cond ((equal "++" type) 'catch-up)
3498 ((equal ".+" type) 'restart)
3499 (t 'cumulate)))
3500 :repeater-value (string-to-number (match-string 2 raw-value))
3501 :repeater-unit
3502 (pcase (string-to-char (match-string 3 raw-value))
3503 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3504 (warning-props
3505 (and (not diaryp)
3506 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3507 (list
3508 :warning-type (if (match-string 1 raw-value) 'first 'all)
3509 :warning-value (string-to-number (match-string 2 raw-value))
3510 :warning-unit
3511 (pcase (string-to-char (match-string 3 raw-value))
3512 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3513 year-start month-start day-start hour-start minute-start year-end
3514 month-end day-end hour-end minute-end)
3515 ;; Parse date-start.
3516 (unless diaryp
3517 (let ((date (org-parse-time-string date-start t)))
3518 (setq year-start (nth 5 date)
3519 month-start (nth 4 date)
3520 day-start (nth 3 date)
3521 hour-start (nth 2 date)
3522 minute-start (nth 1 date))))
3523 ;; Compute date-end. It can be provided directly in time-stamp,
3524 ;; or extracted from time range. Otherwise, it defaults to the
3525 ;; same values as date-start.
3526 (unless diaryp
3527 (let ((date (and date-end (org-parse-time-string date-end t))))
3528 (setq year-end (or (nth 5 date) year-start)
3529 month-end (or (nth 4 date) month-start)
3530 day-end (or (nth 3 date) day-start)
3531 hour-end (or (nth 2 date) (car time-range) hour-start)
3532 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3533 (list 'timestamp
3534 (nconc (list :type type
3535 :raw-value raw-value
3536 :year-start year-start
3537 :month-start month-start
3538 :day-start day-start
3539 :hour-start hour-start
3540 :minute-start minute-start
3541 :year-end year-end
3542 :month-end month-end
3543 :day-end day-end
3544 :hour-end hour-end
3545 :minute-end minute-end
3546 :begin begin
3547 :end end
3548 :post-blank post-blank)
3549 repeater-props
3550 warning-props))))))
3552 (defun org-element-timestamp-interpreter (timestamp _)
3553 "Interpret TIMESTAMP object as Org syntax."
3554 (let* ((repeat-string
3555 (concat
3556 (pcase (org-element-property :repeater-type timestamp)
3557 (`cumulate "+") (`catch-up "++") (`restart ".+"))
3558 (let ((val (org-element-property :repeater-value timestamp)))
3559 (and val (number-to-string val)))
3560 (pcase (org-element-property :repeater-unit timestamp)
3561 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3562 (warning-string
3563 (concat
3564 (pcase (org-element-property :warning-type timestamp)
3565 (`first "--") (`all "-"))
3566 (let ((val (org-element-property :warning-value timestamp)))
3567 (and val (number-to-string val)))
3568 (pcase (org-element-property :warning-unit timestamp)
3569 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3570 (build-ts-string
3571 ;; Build an Org timestamp string from TIME. ACTIVEP is
3572 ;; non-nil when time stamp is active. If WITH-TIME-P is
3573 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3574 ;; specify a time range in the timestamp. REPEAT-STRING is
3575 ;; the repeater string, if any.
3576 (lambda (time activep &optional with-time-p hour-end minute-end)
3577 (let ((ts (format-time-string
3578 (funcall (if with-time-p #'cdr #'car)
3579 org-time-stamp-formats)
3580 time)))
3581 (when (and hour-end minute-end)
3582 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3583 (setq ts
3584 (replace-match
3585 (format "\\&-%02d:%02d" hour-end minute-end)
3586 nil nil ts)))
3587 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3588 (dolist (s (list repeat-string warning-string))
3589 (when (org-string-nw-p s)
3590 (setq ts (concat (substring ts 0 -1)
3593 (substring ts -1)))))
3594 ;; Return value.
3595 ts)))
3596 (type (org-element-property :type timestamp)))
3597 (pcase type
3598 ((or `active `inactive)
3599 (let* ((minute-start (org-element-property :minute-start timestamp))
3600 (minute-end (org-element-property :minute-end timestamp))
3601 (hour-start (org-element-property :hour-start timestamp))
3602 (hour-end (org-element-property :hour-end timestamp))
3603 (time-range-p (and hour-start hour-end minute-start minute-end
3604 (or (/= hour-start hour-end)
3605 (/= minute-start minute-end)))))
3606 (funcall
3607 build-ts-string
3608 (encode-time 0
3609 (or minute-start 0)
3610 (or hour-start 0)
3611 (org-element-property :day-start timestamp)
3612 (org-element-property :month-start timestamp)
3613 (org-element-property :year-start timestamp))
3614 (eq type 'active)
3615 (and hour-start minute-start)
3616 (and time-range-p hour-end)
3617 (and time-range-p minute-end))))
3618 ((or `active-range `inactive-range)
3619 (let ((minute-start (org-element-property :minute-start timestamp))
3620 (minute-end (org-element-property :minute-end timestamp))
3621 (hour-start (org-element-property :hour-start timestamp))
3622 (hour-end (org-element-property :hour-end timestamp)))
3623 (concat
3624 (funcall
3625 build-ts-string (encode-time
3627 (or minute-start 0)
3628 (or hour-start 0)
3629 (org-element-property :day-start timestamp)
3630 (org-element-property :month-start timestamp)
3631 (org-element-property :year-start timestamp))
3632 (eq type 'active-range)
3633 (and hour-start minute-start))
3634 "--"
3635 (funcall build-ts-string
3636 (encode-time 0
3637 (or minute-end 0)
3638 (or hour-end 0)
3639 (org-element-property :day-end timestamp)
3640 (org-element-property :month-end timestamp)
3641 (org-element-property :year-end timestamp))
3642 (eq type 'active-range)
3643 (and hour-end minute-end)))))
3644 (_ (org-element-property :raw-value timestamp)))))
3647 ;;;; Underline
3649 (defun org-element-underline-parser ()
3650 "Parse underline object at point, if any.
3652 When at an underline object, return a list whose car is
3653 `underline' and cdr is a plist with `:begin', `:end',
3654 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3655 Otherwise, return nil.
3657 Assume point is at the first underscore marker."
3658 (save-excursion
3659 (unless (bolp) (backward-char 1))
3660 (when (looking-at org-emph-re)
3661 (let ((begin (match-beginning 2))
3662 (contents-begin (match-beginning 4))
3663 (contents-end (match-end 4))
3664 (post-blank (progn (goto-char (match-end 2))
3665 (skip-chars-forward " \t")))
3666 (end (point)))
3667 (list 'underline
3668 (list :begin begin
3669 :end end
3670 :contents-begin contents-begin
3671 :contents-end contents-end
3672 :post-blank post-blank))))))
3674 (defun org-element-underline-interpreter (_ contents)
3675 "Interpret underline object as Org syntax.
3676 CONTENTS is the contents of the object."
3677 (format "_%s_" contents))
3680 ;;;; Verbatim
3682 (defun org-element-verbatim-parser ()
3683 "Parse verbatim object at point, if any.
3685 When at a verbatim object, return a list whose car is `verbatim'
3686 and cdr is a plist with `:value', `:begin', `:end' and
3687 `:post-blank' keywords. Otherwise, return nil.
3689 Assume point is at the first equal sign marker."
3690 (save-excursion
3691 (unless (bolp) (backward-char 1))
3692 (when (looking-at org-emph-re)
3693 (let ((begin (match-beginning 2))
3694 (value (org-match-string-no-properties 4))
3695 (post-blank (progn (goto-char (match-end 2))
3696 (skip-chars-forward " \t")))
3697 (end (point)))
3698 (list 'verbatim
3699 (list :value value
3700 :begin begin
3701 :end end
3702 :post-blank post-blank))))))
3704 (defun org-element-verbatim-interpreter (verbatim _)
3705 "Interpret VERBATIM object as Org syntax."
3706 (format "=%s=" (org-element-property :value verbatim)))
3710 ;;; Parsing Element Starting At Point
3712 ;; `org-element--current-element' is the core function of this section.
3713 ;; It returns the Lisp representation of the element starting at
3714 ;; point.
3716 ;; `org-element--current-element' makes use of special modes. They
3717 ;; are activated for fixed element chaining (e.g., `plain-list' >
3718 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3719 ;; `section'). Special modes are: `first-section', `item',
3720 ;; `node-property', `section' and `table-row'.
3722 (defun org-element--current-element (limit &optional granularity mode structure)
3723 "Parse the element starting at point.
3725 Return value is a list like (TYPE PROPS) where TYPE is the type
3726 of the element and PROPS a plist of properties associated to the
3727 element.
3729 Possible types are defined in `org-element-all-elements'.
3731 LIMIT bounds the search.
3733 Optional argument GRANULARITY determines the depth of the
3734 recursion. Allowed values are `headline', `greater-element',
3735 `element', `object' or nil. When it is broader than `object' (or
3736 nil), secondary values will not be parsed, since they only
3737 contain objects.
3739 Optional argument MODE, when non-nil, can be either
3740 `first-section', `section', `planning', `item', `node-property'
3741 and `table-row'.
3743 If STRUCTURE isn't provided but MODE is set to `item', it will be
3744 computed.
3746 This function assumes point is always at the beginning of the
3747 element it has to parse."
3748 (save-excursion
3749 (let ((case-fold-search t)
3750 ;; Determine if parsing depth allows for secondary strings
3751 ;; parsing. It only applies to elements referenced in
3752 ;; `org-element-secondary-value-alist'.
3753 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3754 (cond
3755 ;; Item.
3756 ((eq mode 'item)
3757 (org-element-item-parser limit structure raw-secondary-p))
3758 ;; Table Row.
3759 ((eq mode 'table-row) (org-element-table-row-parser limit))
3760 ;; Node Property.
3761 ((eq mode 'node-property) (org-element-node-property-parser limit))
3762 ;; Headline.
3763 ((org-with-limited-levels (org-at-heading-p))
3764 (org-element-headline-parser limit raw-secondary-p))
3765 ;; Sections (must be checked after headline).
3766 ((eq mode 'section) (org-element-section-parser limit))
3767 ((eq mode 'first-section)
3768 (org-element-section-parser
3769 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3770 limit)))
3771 ;; Planning.
3772 ((and (eq mode 'planning) (looking-at org-planning-line-re))
3773 (org-element-planning-parser limit))
3774 ;; Property drawer.
3775 ((and (memq mode '(planning property-drawer))
3776 (looking-at org-property-drawer-re))
3777 (org-element-property-drawer-parser limit))
3778 ;; When not at bol, point is at the beginning of an item or
3779 ;; a footnote definition: next item is always a paragraph.
3780 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3781 ;; Clock.
3782 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3783 ;; Inlinetask.
3784 ((org-at-heading-p)
3785 (org-element-inlinetask-parser limit raw-secondary-p))
3786 ;; From there, elements can have affiliated keywords.
3787 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3788 (cond
3789 ;; Jumping over affiliated keywords put point off-limits.
3790 ;; Parse them as regular keywords.
3791 ((and (cdr affiliated) (>= (point) limit))
3792 (goto-char (car affiliated))
3793 (org-element-keyword-parser limit nil))
3794 ;; LaTeX Environment.
3795 ((looking-at org-element--latex-begin-environment)
3796 (org-element-latex-environment-parser limit affiliated))
3797 ;; Drawer and Property Drawer.
3798 ((looking-at org-drawer-regexp)
3799 (org-element-drawer-parser limit affiliated))
3800 ;; Fixed Width
3801 ((looking-at "[ \t]*:\\( \\|$\\)")
3802 (org-element-fixed-width-parser limit affiliated))
3803 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3804 ;; Keywords.
3805 ((looking-at "[ \t]*#")
3806 (goto-char (match-end 0))
3807 (cond
3808 ((looking-at "\\(?: \\|$\\)")
3809 (beginning-of-line)
3810 (org-element-comment-parser limit affiliated))
3811 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3812 (beginning-of-line)
3813 (funcall (pcase (upcase (match-string 1))
3814 ("CENTER" #'org-element-center-block-parser)
3815 ("COMMENT" #'org-element-comment-block-parser)
3816 ("EXAMPLE" #'org-element-example-block-parser)
3817 ("EXPORT" #'org-element-export-block-parser)
3818 ("QUOTE" #'org-element-quote-block-parser)
3819 ("SRC" #'org-element-src-block-parser)
3820 ("VERSE" #'org-element-verse-block-parser)
3821 (_ #'org-element-special-block-parser))
3822 limit
3823 affiliated))
3824 ((looking-at "\\+CALL:")
3825 (beginning-of-line)
3826 (org-element-babel-call-parser limit affiliated))
3827 ((looking-at "\\+BEGIN:? ")
3828 (beginning-of-line)
3829 (org-element-dynamic-block-parser limit affiliated))
3830 ((looking-at "\\+\\S-+:")
3831 (beginning-of-line)
3832 (org-element-keyword-parser limit affiliated))
3834 (beginning-of-line)
3835 (org-element-paragraph-parser limit affiliated))))
3836 ;; Footnote Definition.
3837 ((looking-at org-footnote-definition-re)
3838 (org-element-footnote-definition-parser limit affiliated))
3839 ;; Horizontal Rule.
3840 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3841 (org-element-horizontal-rule-parser limit affiliated))
3842 ;; Diary Sexp.
3843 ((looking-at "%%(")
3844 (org-element-diary-sexp-parser limit affiliated))
3845 ;; Table.
3846 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3847 (org-element-table-parser limit affiliated))
3848 ;; List.
3849 ((looking-at (org-item-re))
3850 (org-element-plain-list-parser
3851 limit affiliated
3852 (or structure (org-element--list-struct limit))))
3853 ;; Default element: Paragraph.
3854 (t (org-element-paragraph-parser limit affiliated)))))))))
3857 ;; Most elements can have affiliated keywords. When looking for an
3858 ;; element beginning, we want to move before them, as they belong to
3859 ;; that element, and, in the meantime, collect information they give
3860 ;; into appropriate properties. Hence the following function.
3862 (defun org-element--collect-affiliated-keywords (limit)
3863 "Collect affiliated keywords from point down to LIMIT.
3865 Return a list whose CAR is the position at the first of them and
3866 CDR a plist of keywords and values and move point to the
3867 beginning of the first line after them.
3869 As a special case, if element doesn't start at the beginning of
3870 the line (e.g., a paragraph starting an item), CAR is current
3871 position of point and CDR is nil."
3872 (if (not (bolp)) (list (point))
3873 (let ((case-fold-search t)
3874 (origin (point))
3875 ;; RESTRICT is the list of objects allowed in parsed
3876 ;; keywords value.
3877 (restrict (org-element-restriction 'keyword))
3878 output)
3879 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3880 (let* ((raw-kwd (upcase (match-string 1)))
3881 ;; Apply translation to RAW-KWD. From there, KWD is
3882 ;; the official keyword.
3883 (kwd (or (cdr (assoc raw-kwd
3884 org-element-keyword-translation-alist))
3885 raw-kwd))
3886 ;; Find main value for any keyword.
3887 (value
3888 (save-match-data
3889 (org-trim
3890 (buffer-substring-no-properties
3891 (match-end 0) (line-end-position)))))
3892 ;; PARSEDP is non-nil when keyword should have its
3893 ;; value parsed.
3894 (parsedp (member kwd org-element-parsed-keywords))
3895 ;; If KWD is a dual keyword, find its secondary
3896 ;; value. Maybe parse it.
3897 (dualp (member kwd org-element-dual-keywords))
3898 (dual-value
3899 (and dualp
3900 (let ((sec (org-match-string-no-properties 2)))
3901 (if (or (not sec) (not parsedp)) sec
3902 (save-match-data
3903 (org-element--parse-objects
3904 (match-beginning 2) (match-end 2) nil restrict))))))
3905 ;; Attribute a property name to KWD.
3906 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3907 ;; Now set final shape for VALUE.
3908 (when parsedp
3909 (setq value
3910 (org-element--parse-objects
3911 (match-end 0)
3912 (progn (end-of-line) (skip-chars-backward " \t") (point))
3913 nil restrict)))
3914 (when dualp
3915 (setq value (and (or value dual-value) (cons value dual-value))))
3916 (when (or (member kwd org-element-multiple-keywords)
3917 ;; Attributes can always appear on multiple lines.
3918 (string-match "^ATTR_" kwd))
3919 (setq value (cons value (plist-get output kwd-sym))))
3920 ;; Eventually store the new value in OUTPUT.
3921 (setq output (plist-put output kwd-sym value))
3922 ;; Move to next keyword.
3923 (forward-line)))
3924 ;; If affiliated keywords are orphaned: move back to first one.
3925 ;; They will be parsed as a paragraph.
3926 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3927 ;; Return value.
3928 (cons origin output))))
3932 ;;; The Org Parser
3934 ;; The two major functions here are `org-element-parse-buffer', which
3935 ;; parses Org syntax inside the current buffer, taking into account
3936 ;; region, narrowing, or even visibility if specified, and
3937 ;; `org-element-parse-secondary-string', which parses objects within
3938 ;; a given string.
3940 ;; The (almost) almighty `org-element-map' allows applying a function
3941 ;; on elements or objects matching some type, and accumulating the
3942 ;; resulting values. In an export situation, it also skips unneeded
3943 ;; parts of the parse tree.
3945 (defun org-element-parse-buffer (&optional granularity visible-only)
3946 "Recursively parse the buffer and return structure.
3947 If narrowing is in effect, only parse the visible part of the
3948 buffer.
3950 Optional argument GRANULARITY determines the depth of the
3951 recursion. It can be set to the following symbols:
3953 `headline' Only parse headlines.
3954 `greater-element' Don't recurse into greater elements excepted
3955 headlines and sections. Thus, elements
3956 parsed are the top-level ones.
3957 `element' Parse everything but objects and plain text.
3958 `object' Parse the complete buffer (default).
3960 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3961 elements.
3963 An element or an objects is represented as a list with the
3964 pattern (TYPE PROPERTIES CONTENTS), where :
3966 TYPE is a symbol describing the element or object. See
3967 `org-element-all-elements' and `org-element-all-objects' for an
3968 exhaustive list of such symbols. One can retrieve it with
3969 `org-element-type' function.
3971 PROPERTIES is the list of attributes attached to the element or
3972 object, as a plist. Although most of them are specific to the
3973 element or object type, all types share `:begin', `:end',
3974 `:post-blank' and `:parent' properties, which respectively
3975 refer to buffer position where the element or object starts,
3976 ends, the number of white spaces or blank lines after it, and
3977 the element or object containing it. Properties values can be
3978 obtained by using `org-element-property' function.
3980 CONTENTS is a list of elements, objects or raw strings
3981 contained in the current element or object, when applicable.
3982 One can access them with `org-element-contents' function.
3984 The Org buffer has `org-data' as type and nil as properties.
3985 `org-element-map' function can be used to find specific elements
3986 or objects within the parse tree.
3988 This function assumes that current major mode is `org-mode'."
3989 (save-excursion
3990 (goto-char (point-min))
3991 (org-skip-whitespace)
3992 (org-element--parse-elements
3993 (point-at-bol) (point-max)
3994 ;; Start in `first-section' mode so text before the first
3995 ;; headline belongs to a section.
3996 'first-section nil granularity visible-only (list 'org-data nil))))
3998 (defun org-element-parse-secondary-string (string restriction &optional parent)
3999 "Recursively parse objects in STRING and return structure.
4001 RESTRICTION is a symbol limiting the object types that will be
4002 looked after.
4004 Optional argument PARENT, when non-nil, is the element or object
4005 containing the secondary string. It is used to set correctly
4006 `:parent' property within the string.
4008 If STRING is the empty string or nil, return nil."
4009 (cond
4010 ((not string) nil)
4011 ((equal string "") nil)
4012 (t (let ((local-variables (buffer-local-variables)))
4013 (with-temp-buffer
4014 (dolist (v local-variables)
4015 (ignore-errors
4016 (if (symbolp v) (makunbound v)
4017 (set (make-local-variable (car v)) (cdr v)))))
4018 (insert string)
4019 (restore-buffer-modified-p nil)
4020 (org-element--parse-objects
4021 (point-min) (point-max) nil restriction parent))))))
4023 (defun org-element-map
4024 (data types fun &optional info first-match no-recursion with-affiliated)
4025 "Map a function on selected elements or objects.
4027 DATA is a parse tree, an element, an object, a string, or a list
4028 of such constructs. TYPES is a symbol or list of symbols of
4029 elements or objects types (see `org-element-all-elements' and
4030 `org-element-all-objects' for a complete list of types). FUN is
4031 the function called on the matching element or object. It has to
4032 accept one argument: the element or object itself.
4034 When optional argument INFO is non-nil, it should be a plist
4035 holding export options. In that case, parts of the parse tree
4036 not exportable according to that property list will be skipped.
4038 When optional argument FIRST-MATCH is non-nil, stop at the first
4039 match for which FUN doesn't return nil, and return that value.
4041 Optional argument NO-RECURSION is a symbol or a list of symbols
4042 representing elements or objects types. `org-element-map' won't
4043 enter any recursive element or object whose type belongs to that
4044 list. Though, FUN can still be applied on them.
4046 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4047 apply to matching objects within parsed affiliated keywords (see
4048 `org-element-parsed-keywords').
4050 Nil values returned from FUN do not appear in the results.
4053 Examples:
4054 ---------
4056 Assuming TREE is a variable containing an Org buffer parse tree,
4057 the following example will return a flat list of all `src-block'
4058 and `example-block' elements in it:
4060 (org-element-map tree \\='(example-block src-block) #\\='identity)
4062 The following snippet will find the first headline with a level
4063 of 1 and a \"phone\" tag, and will return its beginning position:
4065 (org-element-map tree \\='headline
4066 (lambda (hl)
4067 (and (= (org-element-property :level hl) 1)
4068 (member \"phone\" (org-element-property :tags hl))
4069 (org-element-property :begin hl)))
4070 nil t)
4072 The next example will return a flat list of all `plain-list' type
4073 elements in TREE that are not a sub-list themselves:
4075 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4077 Eventually, this example will return a flat list of all `bold'
4078 type objects containing a `latex-snippet' type object, even
4079 looking into captions:
4081 (org-element-map tree \\='bold
4082 (lambda (b)
4083 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4084 nil nil nil t)"
4085 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4086 (let* ((types (if (listp types) types (list types)))
4087 (no-recursion (if (listp no-recursion) no-recursion
4088 (list no-recursion)))
4089 ;; Recursion depth is determined by --CATEGORY.
4090 (--category
4091 (catch :--found
4092 (let ((category 'greater-elements)
4093 (all-objects (cons 'plain-text org-element-all-objects)))
4094 (dolist (type types category)
4095 (cond ((memq type all-objects)
4096 ;; If one object is found, the function has
4097 ;; to recurse into every object.
4098 (throw :--found 'objects))
4099 ((not (memq type org-element-greater-elements))
4100 ;; If one regular element is found, the
4101 ;; function has to recurse, at least, into
4102 ;; every element it encounters.
4103 (and (not (eq category 'elements))
4104 (setq category 'elements))))))))
4105 --acc)
4106 (letrec ((--walk-tree
4107 (lambda (--data)
4108 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4109 ;; holding contextual information.
4110 (let ((--type (org-element-type --data)))
4111 (cond
4112 ((not --data))
4113 ;; Ignored element in an export context.
4114 ((and info (memq --data (plist-get info :ignore-list))))
4115 ;; List of elements or objects.
4116 ((not --type) (mapc --walk-tree --data))
4117 ;; Unconditionally enter parse trees.
4118 ((eq --type 'org-data)
4119 (mapc --walk-tree (org-element-contents --data)))
4121 ;; Check if TYPE is matching among TYPES. If so,
4122 ;; apply FUN to --DATA and accumulate return value
4123 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4124 (when (memq --type types)
4125 (let ((result (funcall fun --data)))
4126 (cond ((not result))
4127 (first-match (throw :--map-first-match result))
4128 (t (push result --acc)))))
4129 ;; If --DATA has a secondary string that can contain
4130 ;; objects with their type among TYPES, look inside.
4131 (when (and (eq --category 'objects) (not (stringp --data)))
4132 (dolist (p (cdr (assq --type
4133 org-element-secondary-value-alist)))
4134 (funcall --walk-tree (org-element-property p --data))))
4135 ;; If --DATA has any parsed affiliated keywords and
4136 ;; WITH-AFFILIATED is non-nil, look for objects in
4137 ;; them.
4138 (when (and with-affiliated
4139 (eq --category 'objects)
4140 (memq --type org-element-all-elements))
4141 (dolist (kwd-pair org-element--parsed-properties-alist)
4142 (let ((kwd (car kwd-pair))
4143 (value (org-element-property (cdr kwd-pair) --data)))
4144 ;; Pay attention to the type of parsed
4145 ;; keyword. In particular, preserve order for
4146 ;; multiple keywords.
4147 (cond
4148 ((not value))
4149 ((member kwd org-element-dual-keywords)
4150 (if (member kwd org-element-multiple-keywords)
4151 (dolist (line (reverse value))
4152 (funcall --walk-tree (cdr line))
4153 (funcall --walk-tree (car line)))
4154 (funcall --walk-tree (cdr value))
4155 (funcall --walk-tree (car value))))
4156 ((member kwd org-element-multiple-keywords)
4157 (mapc --walk-tree (reverse value)))
4158 (t (funcall --walk-tree value))))))
4159 ;; Determine if a recursion into --DATA is possible.
4160 (cond
4161 ;; --TYPE is explicitly removed from recursion.
4162 ((memq --type no-recursion))
4163 ;; --DATA has no contents.
4164 ((not (org-element-contents --data)))
4165 ;; Looking for greater elements but --DATA is
4166 ;; simply an element or an object.
4167 ((and (eq --category 'greater-elements)
4168 (not (memq --type org-element-greater-elements))))
4169 ;; Looking for elements but --DATA is an object.
4170 ((and (eq --category 'elements)
4171 (memq --type org-element-all-objects)))
4172 ;; In any other case, map contents.
4173 (t (mapc --walk-tree (org-element-contents --data))))))))))
4174 (catch :--map-first-match
4175 (funcall --walk-tree data)
4176 ;; Return value in a proper order.
4177 (nreverse --acc)))))
4178 (put 'org-element-map 'lisp-indent-function 2)
4180 ;; The following functions are internal parts of the parser.
4182 ;; The first one, `org-element--parse-elements' acts at the element's
4183 ;; level.
4185 ;; The second one, `org-element--parse-objects' applies on all objects
4186 ;; of a paragraph or a secondary string. It calls
4187 ;; `org-element--object-lex' to find the next object in the current
4188 ;; container.
4190 (defsubst org-element--next-mode (type parentp)
4191 "Return next special mode according to TYPE, or nil.
4192 TYPE is a symbol representing the type of an element or object
4193 containing next element if PARENTP is non-nil, or before it
4194 otherwise. Modes can be either `first-section', `item',
4195 `node-property', `planning', `property-drawer', `section',
4196 `table-row' or nil."
4197 (if parentp
4198 (pcase type
4199 (`headline 'section)
4200 (`inlinetask 'planning)
4201 (`plain-list 'item)
4202 (`property-drawer 'node-property)
4203 (`section 'planning)
4204 (`table 'table-row))
4205 (pcase type
4206 (`item 'item)
4207 (`node-property 'node-property)
4208 (`planning 'property-drawer)
4209 (`table-row 'table-row))))
4211 (defun org-element--parse-elements
4212 (beg end mode structure granularity visible-only acc)
4213 "Parse elements between BEG and END positions.
4215 MODE prioritizes some elements over the others. It can be set to
4216 `first-section', `section', `planning', `item', `node-property'
4217 or `table-row'.
4219 When value is `item', STRUCTURE will be used as the current list
4220 structure.
4222 GRANULARITY determines the depth of the recursion. See
4223 `org-element-parse-buffer' for more information.
4225 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4226 elements.
4228 Elements are accumulated into ACC."
4229 (save-excursion
4230 (goto-char beg)
4231 ;; Visible only: skip invisible parts at the beginning of the
4232 ;; element.
4233 (when (and visible-only (org-invisible-p2))
4234 (goto-char (min (1+ (org-find-visible)) end)))
4235 ;; When parsing only headlines, skip any text before first one.
4236 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4237 (org-with-limited-levels (outline-next-heading)))
4238 (let (elements)
4239 (while (< (point) end)
4240 ;; Find current element's type and parse it accordingly to
4241 ;; its category.
4242 (let* ((element (org-element--current-element
4243 end granularity mode structure))
4244 (type (org-element-type element))
4245 (cbeg (org-element-property :contents-begin element)))
4246 (goto-char (org-element-property :end element))
4247 ;; Visible only: skip invisible parts between siblings.
4248 (when (and visible-only (org-invisible-p2))
4249 (goto-char (min (1+ (org-find-visible)) end)))
4250 ;; Fill ELEMENT contents by side-effect.
4251 (cond
4252 ;; If element has no contents, don't modify it.
4253 ((not cbeg))
4254 ;; Greater element: parse it between `contents-begin' and
4255 ;; `contents-end'. Make sure GRANULARITY allows the
4256 ;; recursion, or ELEMENT is a headline, in which case going
4257 ;; inside is mandatory, in order to get sub-level headings.
4258 ((and (memq type org-element-greater-elements)
4259 (or (memq granularity '(element object nil))
4260 (and (eq granularity 'greater-element)
4261 (eq type 'section))
4262 (eq type 'headline)))
4263 (org-element--parse-elements
4264 cbeg (org-element-property :contents-end element)
4265 ;; Possibly switch to a special mode.
4266 (org-element--next-mode type t)
4267 (and (memq type '(item plain-list))
4268 (org-element-property :structure element))
4269 granularity visible-only element))
4270 ;; ELEMENT has contents. Parse objects inside, if
4271 ;; GRANULARITY allows it.
4272 ((memq granularity '(object nil))
4273 (org-element--parse-objects
4274 cbeg (org-element-property :contents-end element) element
4275 (org-element-restriction type))))
4276 (push (org-element-put-property element :parent acc) elements)
4277 ;; Update mode.
4278 (setq mode (org-element--next-mode type nil))))
4279 ;; Return result.
4280 (apply #'org-element-set-contents acc (nreverse elements)))))
4282 (defun org-element--object-lex (restriction)
4283 "Return next object in current buffer or nil.
4284 RESTRICTION is a list of object types, as symbols, that should be
4285 looked after. This function assumes that the buffer is narrowed
4286 to an appropriate container (e.g., a paragraph)."
4287 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4288 (save-excursion
4289 (let ((limit (and org-target-link-regexp
4290 (save-excursion
4291 (or (bolp) (backward-char))
4292 (re-search-forward org-target-link-regexp nil t))
4293 (match-beginning 1)))
4294 found)
4295 (while (and (not found)
4296 (re-search-forward org-element--object-regexp limit t))
4297 (goto-char (match-beginning 0))
4298 (let ((result (match-string 0)))
4299 (setq found
4300 (cond
4301 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4302 (and (memq 'inline-babel-call restriction)
4303 (org-element-inline-babel-call-parser)))
4304 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4305 (and (memq 'inline-src-block restriction)
4306 (org-element-inline-src-block-parser)))
4308 (pcase (char-after)
4309 (?^ (and (memq 'superscript restriction)
4310 (org-element-superscript-parser)))
4311 (?_ (or (and (memq 'subscript restriction)
4312 (org-element-subscript-parser))
4313 (and (memq 'underline restriction)
4314 (org-element-underline-parser))))
4315 (?* (and (memq 'bold restriction)
4316 (org-element-bold-parser)))
4317 (?/ (and (memq 'italic restriction)
4318 (org-element-italic-parser)))
4319 (?~ (and (memq 'code restriction)
4320 (org-element-code-parser)))
4321 (?= (and (memq 'verbatim restriction)
4322 (org-element-verbatim-parser)))
4323 (?+ (and (memq 'strike-through restriction)
4324 (org-element-strike-through-parser)))
4325 (?@ (and (memq 'export-snippet restriction)
4326 (org-element-export-snippet-parser)))
4327 (?{ (and (memq 'macro restriction)
4328 (org-element-macro-parser)))
4329 (?$ (and (memq 'latex-fragment restriction)
4330 (org-element-latex-fragment-parser)))
4332 (if (eq (aref result 1) ?<)
4333 (or (and (memq 'radio-target restriction)
4334 (org-element-radio-target-parser))
4335 (and (memq 'target restriction)
4336 (org-element-target-parser)))
4337 (or (and (memq 'timestamp restriction)
4338 (org-element-timestamp-parser))
4339 (and (memq 'link restriction)
4340 (org-element-link-parser)))))
4341 (?\\
4342 (if (eq (aref result 1) ?\\)
4343 (and (memq 'line-break restriction)
4344 (org-element-line-break-parser))
4345 (or (and (memq 'entity restriction)
4346 (org-element-entity-parser))
4347 (and (memq 'latex-fragment restriction)
4348 (org-element-latex-fragment-parser)))))
4349 (?\[
4350 (if (eq (aref result 1) ?\[)
4351 (and (memq 'link restriction)
4352 (org-element-link-parser))
4353 (or (and (memq 'footnote-reference restriction)
4354 (org-element-footnote-reference-parser))
4355 (and (memq 'timestamp restriction)
4356 (org-element-timestamp-parser))
4357 (and (memq 'statistics-cookie restriction)
4358 (org-element-statistics-cookie-parser)))))
4359 ;; This is probably a plain link.
4360 (_ (and (or (memq 'link restriction)
4361 (memq 'plain-link restriction))
4362 (org-element-link-parser)))))))
4363 (or (eobp) (forward-char))))
4364 (cond (found)
4365 ;; Radio link.
4366 ((and limit (memq 'link restriction))
4367 (goto-char limit) (org-element-link-parser)))))))
4369 (defun org-element--parse-objects (beg end acc restriction &optional parent)
4370 "Parse objects between BEG and END and return recursive structure.
4372 Objects are accumulated in ACC. RESTRICTION is a list of object
4373 successors which are allowed in the current object.
4375 ACC becomes the parent for all parsed objects. However, if ACC
4376 is nil (i.e., a secondary string is being parsed) and optional
4377 argument PARENT is non-nil, use it as the parent for all objects.
4378 Eventually, if both ACC and PARENT are nil, the common parent is
4379 the list of objects itself."
4380 (save-excursion
4381 (save-restriction
4382 (narrow-to-region beg end)
4383 (goto-char (point-min))
4384 (let (next-object contents)
4385 (while (and (not (eobp))
4386 (setq next-object (org-element--object-lex restriction)))
4387 ;; Text before any object. Untabify it.
4388 (let ((obj-beg (org-element-property :begin next-object)))
4389 (unless (= (point) obj-beg)
4390 (let ((text (buffer-substring-no-properties (point) obj-beg)))
4391 (push (if acc (org-element-put-property text :parent acc) text)
4392 contents))))
4393 ;; Object...
4394 (let ((obj-end (org-element-property :end next-object))
4395 (cont-beg (org-element-property :contents-begin next-object)))
4396 (when acc (org-element-put-property next-object :parent acc))
4397 (push (if cont-beg
4398 ;; Fill contents of NEXT-OBJECT if possible.
4399 (org-element--parse-objects
4400 cont-beg
4401 (org-element-property :contents-end next-object)
4402 next-object
4403 (org-element-restriction next-object))
4404 next-object)
4405 contents)
4406 (goto-char obj-end)))
4407 ;; Text after last object. Untabify it.
4408 (unless (eobp)
4409 (let ((text (buffer-substring-no-properties (point) end)))
4410 (push (if acc (org-element-put-property text :parent acc) text)
4411 contents)))
4412 ;; Result. Set appropriate parent.
4413 (if acc (apply #'org-element-set-contents acc (nreverse contents))
4414 (let* ((contents (nreverse contents))
4415 (parent (or parent contents)))
4416 (dolist (datum contents contents)
4417 (org-element-put-property datum :parent parent))))))))
4421 ;;; Towards A Bijective Process
4423 ;; The parse tree obtained with `org-element-parse-buffer' is really
4424 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4425 ;; interpreted and expanded into a string with canonical Org syntax.
4426 ;; Hence `org-element-interpret-data'.
4428 ;; The function relies internally on
4429 ;; `org-element--interpret-affiliated-keywords'.
4431 ;;;###autoload
4432 (defun org-element-interpret-data (data)
4433 "Interpret DATA as Org syntax.
4434 DATA is a parse tree, an element, an object or a secondary string
4435 to interpret. Return Org syntax as a string."
4436 (letrec ((fun
4437 (lambda (--data parent)
4438 (let* ((type (org-element-type --data))
4439 ;; Find interpreter for current object or
4440 ;; element. If it doesn't exist (e.g. this is
4441 ;; a pseudo object or element), return contents,
4442 ;; if any.
4443 (interpret
4444 (let ((fun (intern
4445 (format "org-element-%s-interpreter" type))))
4446 (if (fboundp fun) fun (lambda (_ contents) contents))))
4447 (results
4448 (cond
4449 ;; Secondary string.
4450 ((not type)
4451 (mapconcat (lambda (obj) (funcall fun obj parent))
4452 --data ""))
4453 ;; Full Org document.
4454 ((eq type 'org-data)
4455 (mapconcat (lambda (obj) (funcall fun obj parent))
4456 (org-element-contents --data) ""))
4457 ;; Plain text: return it.
4458 ((stringp --data) --data)
4459 ;; Element or object without contents.
4460 ((not (org-element-contents --data))
4461 (funcall interpret --data nil))
4462 ;; Element or object with contents.
4464 (funcall
4465 interpret
4466 --data
4467 ;; Recursively interpret contents.
4468 (mapconcat
4469 (lambda (obj) (funcall fun obj --data))
4470 (org-element-contents
4471 (if (not (memq type '(paragraph verse-block)))
4472 --data
4473 ;; Fix indentation of elements containing
4474 ;; objects. We ignore `table-row'
4475 ;; elements as they are one line long
4476 ;; anyway.
4477 (org-element-normalize-contents
4478 --data
4479 ;; When normalizing first paragraph of
4480 ;; an item or a footnote-definition,
4481 ;; ignore first line's indentation.
4482 (and (eq type 'paragraph)
4483 (equal --data
4484 (car (org-element-contents parent)))
4485 (memq (org-element-type parent)
4486 '(footnote-definition item))))))
4487 ""))))))
4488 (if (memq type '(org-data plain-text nil)) results
4489 ;; Build white spaces. If no `:post-blank' property
4490 ;; is specified, assume its value is 0.
4491 (let ((blank (or (org-element-property :post-blank --data) 0)))
4492 (if (or (memq type org-element-all-objects)
4493 (and parent
4494 (let ((type (org-element-type parent)))
4495 (or (not type)
4496 (memq type org-element-object-containers)))))
4497 (concat results (make-string blank ?\s))
4498 (concat
4499 (org-element--interpret-affiliated-keywords --data)
4500 (org-element-normalize-string results)
4501 (make-string blank ?\n)))))))))
4502 (funcall fun data nil)))
4504 (defun org-element--interpret-affiliated-keywords (element)
4505 "Return ELEMENT's affiliated keywords as Org syntax.
4506 If there is no affiliated keyword, return the empty string."
4507 (let ((keyword-to-org
4508 (function
4509 (lambda (key value)
4510 (let (dual)
4511 (when (member key org-element-dual-keywords)
4512 (setq dual (cdr value) value (car value)))
4513 (concat "#+" key
4514 (and dual
4515 (format "[%s]" (org-element-interpret-data dual)))
4516 ": "
4517 (if (member key org-element-parsed-keywords)
4518 (org-element-interpret-data value)
4519 value)
4520 "\n"))))))
4521 (mapconcat
4522 (lambda (prop)
4523 (let ((value (org-element-property prop element))
4524 (keyword (upcase (substring (symbol-name prop) 1))))
4525 (when value
4526 (if (or (member keyword org-element-multiple-keywords)
4527 ;; All attribute keywords can have multiple lines.
4528 (string-match "^ATTR_" keyword))
4529 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4530 (reverse value)
4532 (funcall keyword-to-org keyword value)))))
4533 ;; List all ELEMENT's properties matching an attribute line or an
4534 ;; affiliated keyword, but ignore translated keywords since they
4535 ;; cannot belong to the property list.
4536 (loop for prop in (nth 1 element) by 'cddr
4537 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4538 (or (string-match "^ATTR_" keyword)
4539 (and
4540 (member keyword org-element-affiliated-keywords)
4541 (not (assoc keyword
4542 org-element-keyword-translation-alist)))))
4543 collect prop)
4544 "")))
4546 ;; Because interpretation of the parse tree must return the same
4547 ;; number of blank lines between elements and the same number of white
4548 ;; space after objects, some special care must be given to white
4549 ;; spaces.
4551 ;; The first function, `org-element-normalize-string', ensures any
4552 ;; string different from the empty string will end with a single
4553 ;; newline character.
4555 ;; The second function, `org-element-normalize-contents', removes
4556 ;; global indentation from the contents of the current element.
4558 (defun org-element-normalize-string (s)
4559 "Ensure string S ends with a single newline character.
4561 If S isn't a string return it unchanged. If S is the empty
4562 string, return it. Otherwise, return a new string with a single
4563 newline character at its end."
4564 (cond
4565 ((not (stringp s)) s)
4566 ((string= "" s) "")
4567 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4568 (replace-match "\n" nil nil s)))))
4570 (defun org-element-normalize-contents (element &optional ignore-first)
4571 "Normalize plain text in ELEMENT's contents.
4573 ELEMENT must only contain plain text and objects.
4575 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4576 indentation to compute maximal common indentation.
4578 Return the normalized element that is element with global
4579 indentation removed from its contents."
4580 (letrec ((find-min-ind
4581 ;; Return minimal common indentation within BLOB. This is
4582 ;; done by walking recursively BLOB and updating MIN-IND
4583 ;; along the way. FIRST-FLAG is non-nil when the next
4584 ;; object is expected to be a string that doesn't start
4585 ;; with a newline character. It happens for strings at
4586 ;; the beginnings of the contents or right after a line
4587 ;; break.
4588 (lambda (blob first-flag min-ind)
4589 (catch 'zero
4590 (dolist (datum (org-element-contents blob) min-ind)
4591 (when first-flag
4592 (setq first-flag nil)
4593 (cond
4594 ;; Objects cannot start with spaces: in this
4595 ;; case, indentation is 0.
4596 ((not (stringp datum)) (throw 'zero 0))
4597 ((not (string-match
4598 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
4599 (throw 'zero 0))
4600 ((equal (match-string 2 datum) "\n")
4601 (put-text-property
4602 (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
4604 (let ((i (string-width (match-string 1 datum))))
4605 (put-text-property
4606 (match-beginning 1) (match-end 1) 'org-ind i datum)
4607 (setq min-ind (min i min-ind))))))
4608 (cond
4609 ((stringp datum)
4610 (let ((s 0))
4611 (while (string-match
4612 "\n\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
4613 (setq s (match-end 1))
4614 (if (equal (match-string 2 datum) "\n")
4615 (put-text-property
4616 (match-beginning 1) (match-end 1)
4617 'org-ind 'empty
4618 datum)
4619 (let ((i (string-width (match-string 1 datum))))
4620 (put-text-property
4621 (match-beginning 1) (match-end 1) 'org-ind i datum)
4622 (setq min-ind (min i min-ind)))))))
4623 ((eq (org-element-type datum) 'line-break)
4624 (setq first-flag t))
4625 ((memq (org-element-type datum) org-element-recursive-objects)
4626 (setq min-ind
4627 (funcall find-min-ind datum first-flag min-ind))))))))
4628 (min-ind (funcall find-min-ind
4629 element (not ignore-first) most-positive-fixnum)))
4630 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4631 ;; Build ELEMENT back, replacing each string with the same
4632 ;; string minus common indentation.
4633 (letrec ((build
4634 (lambda (datum)
4635 ;; Return DATUM with all its strings indentation
4636 ;; shortened from MIN-IND white spaces.
4637 (setcdr
4638 (cdr datum)
4639 (mapcar
4640 (lambda (object)
4641 (cond
4642 ((stringp object)
4643 (with-temp-buffer
4644 (insert object)
4645 (let ((s (point-min)))
4646 (while (setq s (text-property-not-all
4647 s (point-max) 'org-ind nil))
4648 (goto-char s)
4649 (let ((i (get-text-property s 'org-ind)))
4650 (delete-region s (progn
4651 (skip-chars-forward " \t")
4652 (point)))
4653 (when (integerp i) (indent-to (- i min-ind))))))
4654 (buffer-string)))
4655 ((memq (org-element-type object)
4656 org-element-recursive-objects)
4657 (funcall build object))
4658 (t object)))
4659 (org-element-contents datum)))
4660 datum)))
4661 (funcall build element)))))
4665 ;;; Cache
4667 ;; Implement a caching mechanism for `org-element-at-point' and
4668 ;; `org-element-context', which see.
4670 ;; A single public function is provided: `org-element-cache-reset'.
4672 ;; Cache is enabled by default, but can be disabled globally with
4673 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4674 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4675 ;; can be tweaked to control caching behaviour.
4677 ;; Internally, parsed elements are stored in an AVL tree,
4678 ;; `org-element--cache'. This tree is updated lazily: whenever
4679 ;; a change happens to the buffer, a synchronization request is
4680 ;; registered in `org-element--cache-sync-requests' (see
4681 ;; `org-element--cache-submit-request'). During idle time, requests
4682 ;; are processed by `org-element--cache-sync'. Synchronization also
4683 ;; happens when an element is required from the cache. In this case,
4684 ;; the process stops as soon as the needed element is up-to-date.
4686 ;; A synchronization request can only apply on a synchronized part of
4687 ;; the cache. Therefore, the cache is updated at least to the
4688 ;; location where the new request applies. Thus, requests are ordered
4689 ;; from left to right and all elements starting before the first
4690 ;; request are correct. This property is used by functions like
4691 ;; `org-element--cache-find' to retrieve elements in the part of the
4692 ;; cache that can be trusted.
4694 ;; A request applies to every element, starting from its original
4695 ;; location (or key, see below). When a request is processed, it
4696 ;; moves forward and may collide the next one. In this case, both
4697 ;; requests are merged into a new one that starts from that element.
4698 ;; As a consequence, the whole synchronization complexity does not
4699 ;; depend on the number of pending requests, but on the number of
4700 ;; elements the very first request will be applied on.
4702 ;; Elements cannot be accessed through their beginning position, which
4703 ;; may or may not be up-to-date. Instead, each element in the tree is
4704 ;; associated to a key, obtained with `org-element--cache-key'. This
4705 ;; mechanism is robust enough to preserve total order among elements
4706 ;; even when the tree is only partially synchronized.
4708 ;; Objects contained in an element are stored in a hash table,
4709 ;; `org-element--cache-objects'.
4712 (defvar org-element-use-cache t
4713 "Non nil when Org parser should cache its results.
4714 This is mostly for debugging purpose.")
4716 (defvar org-element-cache-sync-idle-time 0.6
4717 "Length, in seconds, of idle time before syncing cache.")
4719 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4720 "Maximum duration, as a time value, for a cache synchronization.
4721 If the synchronization is not over after this delay, the process
4722 pauses and resumes after `org-element-cache-sync-break'
4723 seconds.")
4725 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4726 "Duration, as a time value, of the pause between synchronizations.
4727 See `org-element-cache-sync-duration' for more information.")
4730 ;;;; Data Structure
4732 (defvar org-element--cache nil
4733 "AVL tree used to cache elements.
4734 Each node of the tree contains an element. Comparison is done
4735 with `org-element--cache-compare'. This cache is used in
4736 `org-element-at-point'.")
4738 (defvar org-element--cache-objects nil
4739 "Hash table used as to cache objects.
4740 Key is an element, as returned by `org-element-at-point', and
4741 value is an alist where each association is:
4743 \(PARENT COMPLETEP . OBJECTS)
4745 where PARENT is an element or object, COMPLETEP is a boolean,
4746 non-nil when all direct children of parent are already cached and
4747 OBJECTS is a list of such children, as objects, from farthest to
4748 closest.
4750 In the following example, \\alpha, bold object and \\beta are
4751 contained within a paragraph
4753 \\alpha *\\beta*
4755 If the paragraph is completely parsed, OBJECTS-DATA will be
4757 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4758 \(BOLD-OBJECT t ENTITY-OBJECT))
4760 whereas in a partially parsed paragraph, it could be
4762 \((PARAGRAPH nil ENTITY-OBJECT))
4764 This cache is used in `org-element-context'.")
4766 (defvar org-element--cache-sync-requests nil
4767 "List of pending synchronization requests.
4769 A request is a vector with the following pattern:
4771 \[NEXT BEG END OFFSET PARENT PHASE]
4773 Processing a synchronization request consists of three phases:
4775 0. Delete modified elements,
4776 1. Fill missing area in cache,
4777 2. Shift positions and re-parent elements after the changes.
4779 During phase 0, NEXT is the key of the first element to be
4780 removed, BEG and END is buffer position delimiting the
4781 modifications. Elements starting between them (inclusive) are
4782 removed. So are elements whose parent is removed. PARENT, when
4783 non-nil, is the parent of the first element to be removed.
4785 During phase 1, NEXT is the key of the next known element in
4786 cache and BEG its beginning position. Parse buffer between that
4787 element and the one before it in order to determine the parent of
4788 the next element. Set PARENT to the element containing NEXT.
4790 During phase 2, NEXT is the key of the next element to shift in
4791 the parse tree. All elements starting from this one have their
4792 properties relatives to buffer positions shifted by integer
4793 OFFSET and, if they belong to element PARENT, are adopted by it.
4795 PHASE specifies the phase number, as an integer.")
4797 (defvar org-element--cache-sync-timer nil
4798 "Timer used for cache synchronization.")
4800 (defvar org-element--cache-sync-keys nil
4801 "Hash table used to store keys during synchronization.
4802 See `org-element--cache-key' for more information.")
4804 (defsubst org-element--cache-key (element)
4805 "Return a unique key for ELEMENT in cache tree.
4807 Keys are used to keep a total order among elements in the cache.
4808 Comparison is done with `org-element--cache-key-less-p'.
4810 When no synchronization is taking place, a key is simply the
4811 beginning position of the element, or that position plus one in
4812 the case of an first item (respectively row) in
4813 a list (respectively a table).
4815 During a synchronization, the key is the one the element had when
4816 the cache was synchronized for the last time. Elements added to
4817 cache during the synchronization get a new key generated with
4818 `org-element--cache-generate-key'.
4820 Such keys are stored in `org-element--cache-sync-keys'. The hash
4821 table is cleared once the synchronization is complete."
4822 (or (gethash element org-element--cache-sync-keys)
4823 (let* ((begin (org-element-property :begin element))
4824 ;; Increase beginning position of items (respectively
4825 ;; table rows) by one, so the first item can get
4826 ;; a different key from its parent list (respectively
4827 ;; table).
4828 (key (if (memq (org-element-type element) '(item table-row))
4829 (1+ begin)
4830 begin)))
4831 (if org-element--cache-sync-requests
4832 (puthash element key org-element--cache-sync-keys)
4833 key))))
4835 (defun org-element--cache-generate-key (lower upper)
4836 "Generate a key between LOWER and UPPER.
4838 LOWER and UPPER are integers or lists, possibly empty.
4840 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4841 a unique key, as an integer or a list of integers, according to
4842 the following rules:
4844 - LOWER and UPPER are compared level-wise until values differ.
4846 - If, at a given level, LOWER and UPPER differ from more than
4847 2, the new key shares all the levels above with LOWER and
4848 gets a new level. Its value is the mean between LOWER and
4849 UPPER:
4851 \(1 2) + (1 4) --> (1 3)
4853 - If LOWER has no value to compare with, it is assumed that its
4854 value is `most-negative-fixnum'. E.g.,
4856 \(1 1) + (1 1 2)
4858 is equivalent to
4860 \(1 1 m) + (1 1 2)
4862 where m is `most-negative-fixnum'. Likewise, if UPPER is
4863 short of levels, the current value is `most-positive-fixnum'.
4865 - If they differ from only one, the new key inherits from
4866 current LOWER level and fork it at the next level. E.g.,
4868 \(2 1) + (3 3)
4870 is equivalent to
4872 \(2 1) + (2 M)
4874 where M is `most-positive-fixnum'.
4876 - If the key is only one level long, it is returned as an
4877 integer:
4879 \(1 2) + (3 2) --> 2
4881 When they are not equals, the function assumes that LOWER is
4882 lesser than UPPER, per `org-element--cache-key-less-p'."
4883 (if (equal lower upper) lower
4884 (let ((lower (if (integerp lower) (list lower) lower))
4885 (upper (if (integerp upper) (list upper) upper))
4886 skip-upper key)
4887 (catch 'exit
4888 (while t
4889 (let ((min (or (car lower) most-negative-fixnum))
4890 (max (cond (skip-upper most-positive-fixnum)
4891 ((car upper))
4892 (t most-positive-fixnum))))
4893 (if (< (1+ min) max)
4894 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4895 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4896 (when (and (< min max) (not skip-upper))
4897 ;; When at a given level, LOWER and UPPER differ from
4898 ;; 1, ignore UPPER altogether. Instead create a key
4899 ;; between LOWER and the greatest key with the same
4900 ;; prefix as LOWER so far.
4901 (setq skip-upper t))
4902 (push min key)
4903 (setq lower (cdr lower) upper (cdr upper)))))))))
4905 (defsubst org-element--cache-key-less-p (a b)
4906 "Non-nil if key A is less than key B.
4907 A and B are either integers or lists of integers, as returned by
4908 `org-element--cache-key'."
4909 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4910 (if (integerp b) (< (car a) b)
4911 (catch 'exit
4912 (while (and a b)
4913 (cond ((car-less-than-car a b) (throw 'exit t))
4914 ((car-less-than-car b a) (throw 'exit nil))
4915 (t (setq a (cdr a) b (cdr b)))))
4916 ;; If A is empty, either keys are equal (B is also empty) and
4917 ;; we return nil, or A is lesser than B (B is longer) and we
4918 ;; return a non-nil value.
4920 ;; If A is not empty, B is necessarily empty and A is greater
4921 ;; than B (A is longer). Therefore, return nil.
4922 (and (null a) b)))))
4924 (defun org-element--cache-compare (a b)
4925 "Non-nil when element A is located before element B."
4926 (org-element--cache-key-less-p (org-element--cache-key a)
4927 (org-element--cache-key b)))
4929 (defsubst org-element--cache-root ()
4930 "Return root value in cache.
4931 This function assumes `org-element--cache' is a valid AVL tree."
4932 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4935 ;;;; Tools
4937 (defsubst org-element--cache-active-p ()
4938 "Non-nil when cache is active in current buffer."
4939 (and org-element-use-cache
4940 org-element--cache
4941 (derived-mode-p 'org-mode)))
4943 (defun org-element--cache-find (pos &optional side)
4944 "Find element in cache starting at POS or before.
4946 POS refers to a buffer position.
4948 When optional argument SIDE is non-nil, the function checks for
4949 elements starting at or past POS instead. If SIDE is `both', the
4950 function returns a cons cell where car is the first element
4951 starting at or before POS and cdr the first element starting
4952 after POS.
4954 The function can only find elements in the synchronized part of
4955 the cache."
4956 (let ((limit (and org-element--cache-sync-requests
4957 (aref (car org-element--cache-sync-requests) 0)))
4958 (node (org-element--cache-root))
4959 lower upper)
4960 (while node
4961 (let* ((element (avl-tree--node-data node))
4962 (begin (org-element-property :begin element)))
4963 (cond
4964 ((and limit
4965 (not (org-element--cache-key-less-p
4966 (org-element--cache-key element) limit)))
4967 (setq node (avl-tree--node-left node)))
4968 ((> begin pos)
4969 (setq upper element
4970 node (avl-tree--node-left node)))
4971 ((< begin pos)
4972 (setq lower element
4973 node (avl-tree--node-right node)))
4974 ;; We found an element in cache starting at POS. If `side'
4975 ;; is `both' we also want the next one in order to generate
4976 ;; a key in-between.
4978 ;; If the element is the first row or item in a table or
4979 ;; a plain list, we always return the table or the plain
4980 ;; list.
4982 ;; In any other case, we return the element found.
4983 ((eq side 'both)
4984 (setq lower element)
4985 (setq node (avl-tree--node-right node)))
4986 ((and (memq (org-element-type element) '(item table-row))
4987 (let ((parent (org-element-property :parent element)))
4988 (and (= (org-element-property :begin element)
4989 (org-element-property :contents-begin parent))
4990 (setq node nil
4991 lower parent
4992 upper parent)))))
4994 (setq node nil
4995 lower element
4996 upper element)))))
4997 (pcase side
4998 (`both (cons lower upper))
4999 (`nil lower)
5000 (_ upper))))
5002 (defun org-element--cache-put (element &optional data)
5003 "Store ELEMENT in current buffer's cache, if allowed.
5004 When optional argument DATA is non-nil, assume is it object data
5005 relative to ELEMENT and store it in the objects cache."
5006 (cond ((not (org-element--cache-active-p)) nil)
5007 ((not data)
5008 (when org-element--cache-sync-requests
5009 ;; During synchronization, first build an appropriate key
5010 ;; for the new element so `avl-tree-enter' can insert it at
5011 ;; the right spot in the cache.
5012 (let ((keys (org-element--cache-find
5013 (org-element-property :begin element) 'both)))
5014 (puthash element
5015 (org-element--cache-generate-key
5016 (and (car keys) (org-element--cache-key (car keys)))
5017 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5018 (org-element--cache-sync-requests
5019 (aref (car org-element--cache-sync-requests) 0))))
5020 org-element--cache-sync-keys)))
5021 (avl-tree-enter org-element--cache element))
5022 ;; Headlines are not stored in cache, so objects in titles are
5023 ;; not stored either.
5024 ((eq (org-element-type element) 'headline) nil)
5025 (t (puthash element data org-element--cache-objects))))
5027 (defsubst org-element--cache-remove (element)
5028 "Remove ELEMENT from cache.
5029 Assume ELEMENT belongs to cache and that a cache is active."
5030 (avl-tree-delete org-element--cache element)
5031 (remhash element org-element--cache-objects))
5034 ;;;; Synchronization
5036 (defsubst org-element--cache-set-timer (buffer)
5037 "Set idle timer for cache synchronization in BUFFER."
5038 (when org-element--cache-sync-timer
5039 (cancel-timer org-element--cache-sync-timer))
5040 (setq org-element--cache-sync-timer
5041 (run-with-idle-timer
5042 (let ((idle (current-idle-time)))
5043 (if idle (time-add idle org-element-cache-sync-break)
5044 org-element-cache-sync-idle-time))
5046 #'org-element--cache-sync
5047 buffer)))
5049 (defsubst org-element--cache-interrupt-p (time-limit)
5050 "Non-nil when synchronization process should be interrupted.
5051 TIME-LIMIT is a time value or nil."
5052 (and time-limit
5053 (or (input-pending-p)
5054 (time-less-p time-limit (current-time)))))
5056 (defsubst org-element--cache-shift-positions (element offset &optional props)
5057 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5059 Properties containing buffer positions are `:begin', `:end',
5060 `:contents-begin', `:contents-end' and `:structure'. When
5061 optional argument PROPS is a list of keywords, only shift
5062 properties provided in that list.
5064 Properties are modified by side-effect."
5065 (let ((properties (nth 1 element)))
5066 ;; Shift `:structure' property for the first plain list only: it
5067 ;; is the only one that really matters and it prevents from
5068 ;; shifting it more than once.
5069 (when (and (or (not props) (memq :structure props))
5070 (eq (org-element-type element) 'plain-list)
5071 (not (eq (org-element-type (plist-get properties :parent))
5072 'item)))
5073 (dolist (item (plist-get properties :structure))
5074 (incf (car item) offset)
5075 (incf (nth 6 item) offset)))
5076 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5077 (let ((value (and (or (not props) (memq key props))
5078 (plist-get properties key))))
5079 (and value (plist-put properties key (+ offset value)))))))
5081 (defun org-element--cache-sync (buffer &optional threshold future-change)
5082 "Synchronize cache with recent modification in BUFFER.
5084 When optional argument THRESHOLD is non-nil, do the
5085 synchronization for all elements starting before or at threshold,
5086 then exit. Otherwise, synchronize cache for as long as
5087 `org-element-cache-sync-duration' or until Emacs leaves idle
5088 state.
5090 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5091 not registered yet in the cache are going to happen. It is used
5092 in `org-element--cache-submit-request', where cache is partially
5093 updated before current modification are actually submitted."
5094 (when (buffer-live-p buffer)
5095 (with-current-buffer buffer
5096 (let ((inhibit-quit t) request next)
5097 (when org-element--cache-sync-timer
5098 (cancel-timer org-element--cache-sync-timer))
5099 (catch 'interrupt
5100 (while org-element--cache-sync-requests
5101 (setq request (car org-element--cache-sync-requests)
5102 next (nth 1 org-element--cache-sync-requests))
5103 (org-element--cache-process-request
5104 request
5105 (and next (aref next 0))
5106 threshold
5107 (and (not threshold)
5108 (time-add (current-time)
5109 org-element-cache-sync-duration))
5110 future-change)
5111 ;; Request processed. Merge current and next offsets and
5112 ;; transfer ending position.
5113 (when next
5114 (incf (aref next 3) (aref request 3))
5115 (aset next 2 (aref request 2)))
5116 (setq org-element--cache-sync-requests
5117 (cdr org-element--cache-sync-requests))))
5118 ;; If more requests are awaiting, set idle timer accordingly.
5119 ;; Otherwise, reset keys.
5120 (if org-element--cache-sync-requests
5121 (org-element--cache-set-timer buffer)
5122 (clrhash org-element--cache-sync-keys))))))
5124 (defun org-element--cache-process-request
5125 (request next threshold time-limit future-change)
5126 "Process synchronization REQUEST for all entries before NEXT.
5128 REQUEST is a vector, built by `org-element--cache-submit-request'.
5130 NEXT is a cache key, as returned by `org-element--cache-key'.
5132 When non-nil, THRESHOLD is a buffer position. Synchronization
5133 stops as soon as a shifted element begins after it.
5135 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5136 after this time or when Emacs exits idle state.
5138 When non-nil, FUTURE-CHANGE is a buffer position where changes
5139 not registered yet in the cache are going to happen. See
5140 `org-element--cache-submit-request' for more information.
5142 Throw `interrupt' if the process stops before completing the
5143 request."
5144 (catch 'quit
5145 (when (= (aref request 5) 0)
5146 ;; Phase 0.
5148 ;; Delete all elements starting after BEG, but not after buffer
5149 ;; position END or past element with key NEXT. Also delete
5150 ;; elements contained within a previously removed element
5151 ;; (stored in `last-container').
5153 ;; At each iteration, we start again at tree root since
5154 ;; a deletion modifies structure of the balanced tree.
5155 (catch 'end-phase
5156 (while t
5157 (when (org-element--cache-interrupt-p time-limit)
5158 (throw 'interrupt nil))
5159 ;; Find first element in cache with key BEG or after it.
5160 (let ((beg (aref request 0))
5161 (end (aref request 2))
5162 (node (org-element--cache-root))
5163 data data-key last-container)
5164 (while node
5165 (let* ((element (avl-tree--node-data node))
5166 (key (org-element--cache-key element)))
5167 (cond
5168 ((org-element--cache-key-less-p key beg)
5169 (setq node (avl-tree--node-right node)))
5170 ((org-element--cache-key-less-p beg key)
5171 (setq data element
5172 data-key key
5173 node (avl-tree--node-left node)))
5174 (t (setq data element
5175 data-key key
5176 node nil)))))
5177 (if data
5178 (let ((pos (org-element-property :begin data)))
5179 (if (if (or (not next)
5180 (org-element--cache-key-less-p data-key next))
5181 (<= pos end)
5182 (and last-container
5183 (let ((up data))
5184 (while (and up (not (eq up last-container)))
5185 (setq up (org-element-property :parent up)))
5186 up)))
5187 (progn (when (and (not last-container)
5188 (> (org-element-property :end data)
5189 end))
5190 (setq last-container data))
5191 (org-element--cache-remove data))
5192 (aset request 0 data-key)
5193 (aset request 1 pos)
5194 (aset request 5 1)
5195 (throw 'end-phase nil)))
5196 ;; No element starting after modifications left in
5197 ;; cache: further processing is futile.
5198 (throw 'quit t))))))
5199 (when (= (aref request 5) 1)
5200 ;; Phase 1.
5202 ;; Phase 0 left a hole in the cache. Some elements after it
5203 ;; could have parents within. For example, in the following
5204 ;; buffer:
5206 ;; - item
5209 ;; Paragraph1
5211 ;; Paragraph2
5213 ;; if we remove a blank line between "item" and "Paragraph1",
5214 ;; everything down to "Paragraph2" is removed from cache. But
5215 ;; the paragraph now belongs to the list, and its `:parent'
5216 ;; property no longer is accurate.
5218 ;; Therefore we need to parse again elements in the hole, or at
5219 ;; least in its last section, so that we can re-parent
5220 ;; subsequent elements, during phase 2.
5222 ;; Note that we only need to get the parent from the first
5223 ;; element in cache after the hole.
5225 ;; When next key is lesser or equal to the current one, delegate
5226 ;; phase 1 processing to next request in order to preserve key
5227 ;; order among requests.
5228 (let ((key (aref request 0)))
5229 (when (and next (not (org-element--cache-key-less-p key next)))
5230 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5231 (aset next-request 0 key)
5232 (aset next-request 1 (aref request 1))
5233 (aset next-request 5 1))
5234 (throw 'quit t)))
5235 ;; Next element will start at its beginning position plus
5236 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5237 ;; contains the real beginning position of the first element to
5238 ;; shift and re-parent.
5239 (let ((limit (+ (aref request 1) (aref request 3))))
5240 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5241 ((and future-change (>= limit future-change))
5242 ;; Changes are going to happen around this element and
5243 ;; they will trigger another phase 1 request. Skip the
5244 ;; current one.
5245 (aset request 5 2))
5247 (let ((parent (org-element--parse-to limit t time-limit)))
5248 (aset request 4 parent)
5249 (aset request 5 2))))))
5250 ;; Phase 2.
5252 ;; Shift all elements starting from key START, but before NEXT, by
5253 ;; OFFSET, and re-parent them when appropriate.
5255 ;; Elements are modified by side-effect so the tree structure
5256 ;; remains intact.
5258 ;; Once THRESHOLD, if any, is reached, or once there is an input
5259 ;; pending, exit. Before leaving, the current synchronization
5260 ;; request is updated.
5261 (let ((start (aref request 0))
5262 (offset (aref request 3))
5263 (parent (aref request 4))
5264 (node (org-element--cache-root))
5265 (stack (list nil))
5266 (leftp t)
5267 exit-flag)
5268 ;; No re-parenting nor shifting planned: request is over.
5269 (when (and (not parent) (zerop offset)) (throw 'quit t))
5270 (while node
5271 (let* ((data (avl-tree--node-data node))
5272 (key (org-element--cache-key data)))
5273 (if (and leftp (avl-tree--node-left node)
5274 (not (org-element--cache-key-less-p key start)))
5275 (progn (push node stack)
5276 (setq node (avl-tree--node-left node)))
5277 (unless (org-element--cache-key-less-p key start)
5278 ;; We reached NEXT. Request is complete.
5279 (when (equal key next) (throw 'quit t))
5280 ;; Handle interruption request. Update current request.
5281 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5282 (aset request 0 key)
5283 (aset request 4 parent)
5284 (throw 'interrupt nil))
5285 ;; Shift element.
5286 (unless (zerop offset)
5287 (org-element--cache-shift-positions data offset)
5288 ;; Shift associated objects data, if any.
5289 (dolist (object-data (gethash data org-element--cache-objects))
5290 (dolist (object (cddr object-data))
5291 (org-element--cache-shift-positions object offset))))
5292 (let ((begin (org-element-property :begin data)))
5293 ;; Update PARENT and re-parent DATA, only when
5294 ;; necessary. Propagate new structures for lists.
5295 (while (and parent
5296 (<= (org-element-property :end parent) begin))
5297 (setq parent (org-element-property :parent parent)))
5298 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5299 ((and parent
5300 (let ((p (org-element-property :parent data)))
5301 (or (not p)
5302 (< (org-element-property :begin p)
5303 (org-element-property :begin parent)))))
5304 (org-element-put-property data :parent parent)
5305 (let ((s (org-element-property :structure parent)))
5306 (when (and s (org-element-property :structure data))
5307 (org-element-put-property data :structure s)))))
5308 ;; Cache is up-to-date past THRESHOLD. Request
5309 ;; interruption.
5310 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5311 (setq node (if (setq leftp (avl-tree--node-right node))
5312 (avl-tree--node-right node)
5313 (pop stack))))))
5314 ;; We reached end of tree: synchronization complete.
5315 t)))
5317 (defun org-element--parse-to (pos &optional syncp time-limit)
5318 "Parse elements in current section, down to POS.
5320 Start parsing from the closest between the last known element in
5321 cache or headline above. Return the smallest element containing
5322 POS.
5324 When optional argument SYNCP is non-nil, return the parent of the
5325 element containing POS instead. In that case, it is also
5326 possible to provide TIME-LIMIT, which is a time value specifying
5327 when the parsing should stop. The function throws `interrupt' if
5328 the process stopped before finding the expected result."
5329 (catch 'exit
5330 (org-with-wide-buffer
5331 (goto-char pos)
5332 (let* ((cached (and (org-element--cache-active-p)
5333 (org-element--cache-find pos nil)))
5334 (begin (org-element-property :begin cached))
5335 element next mode)
5336 (cond
5337 ;; Nothing in cache before point: start parsing from first
5338 ;; element following headline above, or first element in
5339 ;; buffer.
5340 ((not cached)
5341 (when (org-with-limited-levels (outline-previous-heading))
5342 (setq mode 'planning)
5343 (forward-line))
5344 (skip-chars-forward " \r\t\n")
5345 (beginning-of-line))
5346 ;; Cache returned exact match: return it.
5347 ((= pos begin)
5348 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5349 ;; There's a headline between cached value and POS: cached
5350 ;; value is invalid. Start parsing from first element
5351 ;; following the headline.
5352 ((re-search-backward
5353 (org-with-limited-levels org-outline-regexp-bol) begin t)
5354 (forward-line)
5355 (skip-chars-forward " \r\t\n")
5356 (beginning-of-line)
5357 (setq mode 'planning))
5358 ;; Check if CACHED or any of its ancestors contain point.
5360 ;; If there is such an element, we inspect it in order to know
5361 ;; if we return it or if we need to parse its contents.
5362 ;; Otherwise, we just start parsing from current location,
5363 ;; which is right after the top-most element containing
5364 ;; CACHED.
5366 ;; As a special case, if POS is at the end of the buffer, we
5367 ;; want to return the innermost element ending there.
5369 ;; Also, if we find an ancestor and discover that we need to
5370 ;; parse its contents, make sure we don't start from
5371 ;; `:contents-begin', as we would otherwise go past CACHED
5372 ;; again. Instead, in that situation, we will resume parsing
5373 ;; from NEXT, which is located after CACHED or its higher
5374 ;; ancestor not containing point.
5376 (let ((up cached)
5377 (pos (if (= (point-max) pos) (1- pos) pos)))
5378 (goto-char (or (org-element-property :contents-begin cached) begin))
5379 (while (let ((end (org-element-property :end up)))
5380 (and (<= end pos)
5381 (goto-char end)
5382 (setq up (org-element-property :parent up)))))
5383 (cond ((not up))
5384 ((eobp) (setq element up))
5385 (t (setq element up next (point)))))))
5386 ;; Parse successively each element until we reach POS.
5387 (let ((end (or (org-element-property :end element)
5388 (save-excursion
5389 (org-with-limited-levels (outline-next-heading))
5390 (point))))
5391 (parent element))
5392 (while t
5393 (when syncp
5394 (cond ((= (point) pos) (throw 'exit parent))
5395 ((org-element--cache-interrupt-p time-limit)
5396 (throw 'interrupt nil))))
5397 (unless element
5398 (setq element (org-element--current-element
5399 end 'element mode
5400 (org-element-property :structure parent)))
5401 (org-element-put-property element :parent parent)
5402 (org-element--cache-put element))
5403 (let ((elem-end (org-element-property :end element))
5404 (type (org-element-type element)))
5405 (cond
5406 ;; Skip any element ending before point. Also skip
5407 ;; element ending at point (unless it is also the end of
5408 ;; buffer) since we're sure that another element begins
5409 ;; after it.
5410 ((and (<= elem-end pos) (/= (point-max) elem-end))
5411 (goto-char elem-end)
5412 (setq mode (org-element--next-mode type nil)))
5413 ;; A non-greater element contains point: return it.
5414 ((not (memq type org-element-greater-elements))
5415 (throw 'exit element))
5416 ;; Otherwise, we have to decide if ELEMENT really
5417 ;; contains POS. In that case we start parsing from
5418 ;; contents' beginning.
5420 ;; If POS is at contents' beginning but it is also at
5421 ;; the beginning of the first item in a list or a table.
5422 ;; In that case, we need to create an anchor for that
5423 ;; list or table, so return it.
5425 ;; Also, if POS is at the end of the buffer, no element
5426 ;; can start after it, but more than one may end there.
5427 ;; Arbitrarily, we choose to return the innermost of
5428 ;; such elements.
5429 ((let ((cbeg (org-element-property :contents-begin element))
5430 (cend (org-element-property :contents-end element)))
5431 (when (or syncp
5432 (and cbeg cend
5433 (or (< cbeg pos)
5434 (and (= cbeg pos)
5435 (not (memq type '(plain-list table)))))
5436 (or (> cend pos)
5437 (and (= cend pos) (= (point-max) pos)))))
5438 (goto-char (or next cbeg))
5439 (setq next nil
5440 mode (org-element--next-mode type t)
5441 parent element
5442 end cend))))
5443 ;; Otherwise, return ELEMENT as it is the smallest
5444 ;; element containing POS.
5445 (t (throw 'exit element))))
5446 (setq element nil)))))))
5449 ;;;; Staging Buffer Changes
5451 (defconst org-element--cache-sensitive-re
5452 (concat
5453 org-outline-regexp-bol "\\|"
5454 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5455 "^[ \t]*\\(?:"
5456 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5457 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5458 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5459 "\\)")
5460 "Regexp matching a sensitive line, structure wise.
5461 A sensitive line is a headline, inlinetask, block, drawer, or
5462 latex-environment boundary. When such a line is modified,
5463 structure changes in the document may propagate in the whole
5464 section, possibly making cache invalid.")
5466 (defvar org-element--cache-change-warning nil
5467 "Non-nil when a sensitive line is about to be changed.
5468 It is a symbol among nil, t and `headline'.")
5470 (defun org-element--cache-before-change (beg end)
5471 "Request extension of area going to be modified if needed.
5472 BEG and END are the beginning and end of the range of changed
5473 text. See `before-change-functions' for more information."
5474 (when (org-element--cache-active-p)
5475 (org-with-wide-buffer
5476 (goto-char beg)
5477 (beginning-of-line)
5478 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5479 (setq org-element--cache-change-warning
5480 (save-match-data
5481 (if (and (org-with-limited-levels (org-at-heading-p))
5482 (= (line-end-position) bottom))
5483 'headline
5484 (let ((case-fold-search t))
5485 (re-search-forward
5486 org-element--cache-sensitive-re bottom t)))))))))
5488 (defun org-element--cache-after-change (beg end pre)
5489 "Update buffer modifications for current buffer.
5490 BEG and END are the beginning and end of the range of changed
5491 text, and the length in bytes of the pre-change text replaced by
5492 that range. See `after-change-functions' for more information."
5493 (when (org-element--cache-active-p)
5494 (org-with-wide-buffer
5495 (goto-char beg)
5496 (beginning-of-line)
5497 (save-match-data
5498 (let ((top (point))
5499 (bottom (save-excursion (goto-char end) (line-end-position))))
5500 ;; Determine if modified area needs to be extended, according
5501 ;; to both previous and current state. We make a special
5502 ;; case for headline editing: if a headline is modified but
5503 ;; not removed, do not extend.
5504 (when (pcase org-element--cache-change-warning
5505 (`t t)
5506 (`headline
5507 (not (and (org-with-limited-levels (org-at-heading-p))
5508 (= (line-end-position) bottom))))
5510 (let ((case-fold-search t))
5511 (re-search-forward
5512 org-element--cache-sensitive-re bottom t))))
5513 ;; Effectively extend modified area.
5514 (org-with-limited-levels
5515 (setq top (progn (goto-char top)
5516 (when (outline-previous-heading) (forward-line))
5517 (point)))
5518 (setq bottom (progn (goto-char bottom)
5519 (if (outline-next-heading) (1- (point))
5520 (point))))))
5521 ;; Store synchronization request.
5522 (let ((offset (- end beg pre)))
5523 (org-element--cache-submit-request top (- bottom offset) offset)))))
5524 ;; Activate a timer to process the request during idle time.
5525 (org-element--cache-set-timer (current-buffer))))
5527 (defun org-element--cache-for-removal (beg end offset)
5528 "Return first element to remove from cache.
5530 BEG and END are buffer positions delimiting buffer modifications.
5531 OFFSET is the size of the changes.
5533 Returned element is usually the first element in cache containing
5534 any position between BEG and END. As an exception, greater
5535 elements around the changes that are robust to contents
5536 modifications are preserved and updated according to the
5537 changes."
5538 (let* ((elements (org-element--cache-find (1- beg) 'both))
5539 (before (car elements))
5540 (after (cdr elements)))
5541 (if (not before) after
5542 (let ((up before)
5543 (robust-flag t))
5544 (while up
5545 (if (let ((type (org-element-type up)))
5546 (and (or (memq type '(center-block dynamic-block quote-block
5547 special-block))
5548 ;; Drawers named "PROPERTIES" are probably
5549 ;; a properties drawer being edited. Force
5550 ;; parsing to check if editing is over.
5551 (and (eq type 'drawer)
5552 (not (string=
5553 (org-element-property :drawer-name up)
5554 "PROPERTIES"))))
5555 (let ((cbeg (org-element-property :contents-begin up)))
5556 (and cbeg
5557 (<= cbeg beg)
5558 (> (org-element-property :contents-end up) end)))))
5559 ;; UP is a robust greater element containing changes.
5560 ;; We only need to extend its ending boundaries.
5561 (org-element--cache-shift-positions
5562 up offset '(:contents-end :end))
5563 (setq before up)
5564 (when robust-flag (setq robust-flag nil)))
5565 (setq up (org-element-property :parent up)))
5566 ;; We're at top level element containing ELEMENT: if it's
5567 ;; altered by buffer modifications, it is first element in
5568 ;; cache to be removed. Otherwise, that first element is the
5569 ;; following one.
5571 ;; As a special case, do not remove BEFORE if it is a robust
5572 ;; container for current changes.
5573 (if (or (< (org-element-property :end before) beg) robust-flag) after
5574 before)))))
5576 (defun org-element--cache-submit-request (beg end offset)
5577 "Submit a new cache synchronization request for current buffer.
5578 BEG and END are buffer positions delimiting the minimal area
5579 where cache data should be removed. OFFSET is the size of the
5580 change, as an integer."
5581 (let ((next (car org-element--cache-sync-requests))
5582 delete-to delete-from)
5583 (if (and next
5584 (zerop (aref next 5))
5585 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5586 (<= (setq delete-from (aref next 1)) end))
5587 ;; Current changes can be merged with first sync request: we
5588 ;; can save a partial cache synchronization.
5589 (progn
5590 (incf (aref next 3) offset)
5591 ;; If last change happened within area to be removed, extend
5592 ;; boundaries of robust parents, if any. Otherwise, find
5593 ;; first element to remove and update request accordingly.
5594 (if (> beg delete-from)
5595 (let ((up (aref next 4)))
5596 (while up
5597 (org-element--cache-shift-positions
5598 up offset '(:contents-end :end))
5599 (setq up (org-element-property :parent up))))
5600 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5601 (when first
5602 (aset next 0 (org-element--cache-key first))
5603 (aset next 1 (org-element-property :begin first))
5604 (aset next 4 (org-element-property :parent first))))))
5605 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5606 ;; if any, is no longer a 0-phase request, thus ensuring that
5607 ;; phases are properly ordered. We need to provide OFFSET as
5608 ;; optional parameter since current modifications are not known
5609 ;; yet to the otherwise correct part of the cache (i.e, before
5610 ;; the first request).
5611 (when next (org-element--cache-sync (current-buffer) end beg))
5612 (let ((first (org-element--cache-for-removal beg end offset)))
5613 (if first
5614 (push (let ((beg (org-element-property :begin first))
5615 (key (org-element--cache-key first)))
5616 (cond
5617 ;; When changes happen before the first known
5618 ;; element, re-parent and shift the rest of the
5619 ;; cache.
5620 ((> beg end) (vector key beg nil offset nil 1))
5621 ;; Otherwise, we find the first non robust
5622 ;; element containing END. All elements between
5623 ;; FIRST and this one are to be removed.
5624 ((let ((first-end (org-element-property :end first)))
5625 (and (> first-end end)
5626 (vector key beg first-end offset first 0))))
5628 (let* ((element (org-element--cache-find end))
5629 (end (org-element-property :end element))
5630 (up element))
5631 (while (and (setq up (org-element-property :parent up))
5632 (>= (org-element-property :begin up) beg))
5633 (setq end (org-element-property :end up)
5634 element up))
5635 (vector key beg end offset element 0)))))
5636 org-element--cache-sync-requests)
5637 ;; No element to remove. No need to re-parent either.
5638 ;; Simply shift additional elements, if any, by OFFSET.
5639 (when org-element--cache-sync-requests
5640 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5643 ;;;; Public Functions
5645 ;;;###autoload
5646 (defun org-element-cache-reset (&optional all)
5647 "Reset cache in current buffer.
5648 When optional argument ALL is non-nil, reset cache in all Org
5649 buffers."
5650 (interactive "P")
5651 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5652 (with-current-buffer buffer
5653 (when (and org-element-use-cache (derived-mode-p 'org-mode))
5654 (setq-local org-element--cache
5655 (avl-tree-create #'org-element--cache-compare))
5656 (setq-local org-element--cache-objects (make-hash-table :test #'eq))
5657 (setq-local org-element--cache-sync-keys
5658 (make-hash-table :weakness 'key :test #'eq))
5659 (setq-local org-element--cache-change-warning nil)
5660 (setq-local org-element--cache-sync-requests nil)
5661 (setq-local org-element--cache-sync-timer nil)
5662 (add-hook 'before-change-functions
5663 #'org-element--cache-before-change nil t)
5664 (add-hook 'after-change-functions
5665 #'org-element--cache-after-change nil t)))))
5667 ;;;###autoload
5668 (defun org-element-cache-refresh (pos)
5669 "Refresh cache at position POS."
5670 (when (org-element--cache-active-p)
5671 (org-element--cache-sync (current-buffer) pos)
5672 (org-element--cache-submit-request pos pos 0)
5673 (org-element--cache-set-timer (current-buffer))))
5677 ;;; The Toolbox
5679 ;; The first move is to implement a way to obtain the smallest element
5680 ;; containing point. This is the job of `org-element-at-point'. It
5681 ;; basically jumps back to the beginning of section containing point
5682 ;; and proceed, one element after the other, with
5683 ;; `org-element--current-element' until the container is found. Note:
5684 ;; When using `org-element-at-point', secondary values are never
5685 ;; parsed since the function focuses on elements, not on objects.
5687 ;; At a deeper level, `org-element-context' lists all elements and
5688 ;; objects containing point.
5690 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5691 ;; internally by navigation and manipulation tools.
5694 ;;;###autoload
5695 (defun org-element-at-point ()
5696 "Determine closest element around point.
5698 Return value is a list like (TYPE PROPS) where TYPE is the type
5699 of the element and PROPS a plist of properties associated to the
5700 element.
5702 Possible types are defined in `org-element-all-elements'.
5703 Properties depend on element or object type, but always include
5704 `:begin', `:end', `:parent' and `:post-blank' properties.
5706 As a special case, if point is at the very beginning of the first
5707 item in a list or sub-list, returned element will be that list
5708 instead of the item. Likewise, if point is at the beginning of
5709 the first row of a table, returned element will be the table
5710 instead of the first row.
5712 When point is at the end of the buffer, return the innermost
5713 element ending there."
5714 (org-with-wide-buffer
5715 (let ((origin (point)))
5716 (end-of-line)
5717 (skip-chars-backward " \r\t\n")
5718 (cond
5719 ;; Within blank lines at the beginning of buffer, return nil.
5720 ((bobp) nil)
5721 ;; Within blank lines right after a headline, return that
5722 ;; headline.
5723 ((org-with-limited-levels (org-at-heading-p))
5724 (beginning-of-line)
5725 (org-element-headline-parser (point-max) t))
5726 ;; Otherwise parse until we find element containing ORIGIN.
5728 (when (org-element--cache-active-p)
5729 (if (not org-element--cache) (org-element-cache-reset)
5730 (org-element--cache-sync (current-buffer) origin)))
5731 (org-element--parse-to origin))))))
5733 ;;;###autoload
5734 (defun org-element-context (&optional element)
5735 "Return smallest element or object around point.
5737 Return value is a list like (TYPE PROPS) where TYPE is the type
5738 of the element or object and PROPS a plist of properties
5739 associated to it.
5741 Possible types are defined in `org-element-all-elements' and
5742 `org-element-all-objects'. Properties depend on element or
5743 object type, but always include `:begin', `:end', `:parent' and
5744 `:post-blank'.
5746 As a special case, if point is right after an object and not at
5747 the beginning of any other object, return that object.
5749 Optional argument ELEMENT, when non-nil, is the closest element
5750 containing point, as returned by `org-element-at-point'.
5751 Providing it allows for quicker computation."
5752 (catch 'objects-forbidden
5753 (org-with-wide-buffer
5754 (let* ((pos (point))
5755 (element (or element (org-element-at-point)))
5756 (type (org-element-type element))
5757 (post (org-element-property :post-affiliated element)))
5758 ;; If point is inside an element containing objects or
5759 ;; a secondary string, narrow buffer to the container and
5760 ;; proceed with parsing. Otherwise, return ELEMENT.
5761 (cond
5762 ;; At a parsed affiliated keyword, check if we're inside main
5763 ;; or dual value.
5764 ((and post (< pos post))
5765 (beginning-of-line)
5766 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5767 (cond
5768 ((not (member-ignore-case (match-string 1)
5769 org-element-parsed-keywords))
5770 (throw 'objects-forbidden element))
5771 ((< (match-end 0) pos)
5772 (narrow-to-region (match-end 0) (line-end-position)))
5773 ((and (match-beginning 2)
5774 (>= pos (match-beginning 2))
5775 (< pos (match-end 2)))
5776 (narrow-to-region (match-beginning 2) (match-end 2)))
5777 (t (throw 'objects-forbidden element)))
5778 ;; Also change type to retrieve correct restrictions.
5779 (setq type 'keyword))
5780 ;; At an item, objects can only be located within tag, if any.
5781 ((eq type 'item)
5782 (let ((tag (org-element-property :tag element)))
5783 (if (or (not tag) (/= (line-beginning-position) post))
5784 (throw 'objects-forbidden element)
5785 (beginning-of-line)
5786 (search-forward tag (line-end-position))
5787 (goto-char (match-beginning 0))
5788 (if (and (>= pos (point)) (< pos (match-end 0)))
5789 (narrow-to-region (point) (match-end 0))
5790 (throw 'objects-forbidden element)))))
5791 ;; At an headline or inlinetask, objects are in title.
5792 ((memq type '(headline inlinetask))
5793 (goto-char (org-element-property :begin element))
5794 (looking-at org-complex-heading-regexp)
5795 (let ((end (match-end 4)))
5796 (if (not end) (throw 'objects-forbidden element)
5797 (goto-char (match-beginning 4))
5798 (when (let (case-fold-search) (looking-at org-comment-string))
5799 (goto-char (match-end 0)))
5800 (if (>= (point) end) (throw 'objects-forbidden element)
5801 (narrow-to-region (point) end)))))
5802 ;; At a paragraph, a table-row or a verse block, objects are
5803 ;; located within their contents.
5804 ((memq type '(paragraph table-row verse-block))
5805 (let ((cbeg (org-element-property :contents-begin element))
5806 (cend (org-element-property :contents-end element)))
5807 ;; CBEG is nil for table rules.
5808 (if (and cbeg cend (>= pos cbeg)
5809 (or (< pos cend) (and (= pos cend) (eobp))))
5810 (narrow-to-region cbeg cend)
5811 (throw 'objects-forbidden element))))
5812 ;; At a planning line, if point is at a timestamp, return it,
5813 ;; otherwise, return element.
5814 ((eq type 'planning)
5815 (dolist (p '(:closed :deadline :scheduled))
5816 (let ((timestamp (org-element-property p element)))
5817 (when (and timestamp
5818 (<= (org-element-property :begin timestamp) pos)
5819 (> (org-element-property :end timestamp) pos))
5820 (throw 'objects-forbidden timestamp))))
5821 ;; All other locations cannot contain objects: bail out.
5822 (throw 'objects-forbidden element))
5823 (t (throw 'objects-forbidden element)))
5824 (goto-char (point-min))
5825 (let ((restriction (org-element-restriction type))
5826 (parent element)
5827 (cache (cond ((not (org-element--cache-active-p)) nil)
5828 (org-element--cache-objects
5829 (gethash element org-element--cache-objects))
5830 (t (org-element-cache-reset) nil)))
5831 next object-data last)
5832 (prog1
5833 (catch 'exit
5834 (while t
5835 ;; When entering PARENT for the first time, get list
5836 ;; of objects within known so far. Store it in
5837 ;; OBJECT-DATA.
5838 (unless next
5839 (let ((data (assq parent cache)))
5840 (if data (setq object-data data)
5841 (push (setq object-data (list parent nil)) cache))))
5842 ;; Find NEXT object for analysis.
5843 (catch 'found
5844 ;; If NEXT is non-nil, we already exhausted the
5845 ;; cache so we can parse buffer to find the object
5846 ;; after it.
5847 (if next (setq next (org-element--object-lex restriction))
5848 ;; Otherwise, check if cache can help us.
5849 (let ((objects (cddr object-data))
5850 (completep (nth 1 object-data)))
5851 (cond
5852 ((and (not objects) completep) (throw 'exit parent))
5853 ((not objects)
5854 (setq next (org-element--object-lex restriction)))
5856 (let ((cache-limit
5857 (org-element-property :end (car objects))))
5858 (if (>= cache-limit pos)
5859 ;; Cache contains the information needed.
5860 (dolist (object objects (throw 'exit parent))
5861 (when (<= (org-element-property :begin object)
5862 pos)
5863 (if (>= (org-element-property :end object)
5864 pos)
5865 (throw 'found (setq next object))
5866 (throw 'exit parent))))
5867 (goto-char cache-limit)
5868 (setq next
5869 (org-element--object-lex restriction))))))))
5870 ;; If we have a new object to analyze, store it in
5871 ;; cache. Otherwise record that there is nothing
5872 ;; more to parse in this element at this depth.
5873 (if next
5874 (progn (org-element-put-property next :parent parent)
5875 (push next (cddr object-data)))
5876 (setcar (cdr object-data) t)))
5877 ;; Process NEXT, if any, in order to know if we need
5878 ;; to skip it, return it or move into it.
5879 (if (or (not next) (> (org-element-property :begin next) pos))
5880 (throw 'exit (or last parent))
5881 (let ((end (org-element-property :end next))
5882 (cbeg (org-element-property :contents-begin next))
5883 (cend (org-element-property :contents-end next)))
5884 (cond
5885 ;; Skip objects ending before point. Also skip
5886 ;; objects ending at point unless it is also the
5887 ;; end of buffer, since we want to return the
5888 ;; innermost object.
5889 ((and (<= end pos) (/= (point-max) end))
5890 (goto-char end)
5891 ;; For convenience, when object ends at POS,
5892 ;; without any space, store it in LAST, as we
5893 ;; will return it if no object starts here.
5894 (when (and (= end pos)
5895 (not (memq (char-before) '(?\s ?\t))))
5896 (setq last next)))
5897 ;; If POS is within a container object, move
5898 ;; into that object.
5899 ((and cbeg cend
5900 (>= pos cbeg)
5901 (or (< pos cend)
5902 ;; At contents' end, if there is no
5903 ;; space before point, also move into
5904 ;; object, for consistency with
5905 ;; convenience feature above.
5906 (and (= pos cend)
5907 (or (= (point-max) pos)
5908 (not (memq (char-before pos)
5909 '(?\s ?\t)))))))
5910 (goto-char cbeg)
5911 (narrow-to-region (point) cend)
5912 (setq parent next
5913 restriction (org-element-restriction next)
5914 next nil
5915 object-data nil))
5916 ;; Otherwise, return NEXT.
5917 (t (throw 'exit next)))))))
5918 ;; Store results in cache, if applicable.
5919 (org-element--cache-put element cache)))))))
5921 (defun org-element-lineage (blob &optional types with-self)
5922 "List all ancestors of a given element or object.
5924 BLOB is an object or element.
5926 When optional argument TYPES is a list of symbols, return the
5927 first element or object in the lineage whose type belongs to that
5928 list.
5930 When optional argument WITH-SELF is non-nil, lineage includes
5931 BLOB itself as the first element, and TYPES, if provided, also
5932 apply to it.
5934 When BLOB is obtained through `org-element-context' or
5935 `org-element-at-point', only ancestors from its section can be
5936 found. There is no such limitation when BLOB belongs to a full
5937 parse tree."
5938 (let ((up (if with-self blob (org-element-property :parent blob)))
5939 ancestors)
5940 (while (and up (not (memq (org-element-type up) types)))
5941 (unless types (push up ancestors))
5942 (setq up (org-element-property :parent up)))
5943 (if types up (nreverse ancestors))))
5945 (defun org-element-nested-p (elem-A elem-B)
5946 "Non-nil when elements ELEM-A and ELEM-B are nested."
5947 (let ((beg-A (org-element-property :begin elem-A))
5948 (beg-B (org-element-property :begin elem-B))
5949 (end-A (org-element-property :end elem-A))
5950 (end-B (org-element-property :end elem-B)))
5951 (or (and (>= beg-A beg-B) (<= end-A end-B))
5952 (and (>= beg-B beg-A) (<= end-B end-A)))))
5954 (defun org-element-swap-A-B (elem-A elem-B)
5955 "Swap elements ELEM-A and ELEM-B.
5956 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5957 end of ELEM-A."
5958 (goto-char (org-element-property :begin elem-A))
5959 ;; There are two special cases when an element doesn't start at bol:
5960 ;; the first paragraph in an item or in a footnote definition.
5961 (let ((specialp (not (bolp))))
5962 ;; Only a paragraph without any affiliated keyword can be moved at
5963 ;; ELEM-A position in such a situation. Note that the case of
5964 ;; a footnote definition is impossible: it cannot contain two
5965 ;; paragraphs in a row because it cannot contain a blank line.
5966 (if (and specialp
5967 (or (not (eq (org-element-type elem-B) 'paragraph))
5968 (/= (org-element-property :begin elem-B)
5969 (org-element-property :contents-begin elem-B))))
5970 (error "Cannot swap elements"))
5971 ;; In a special situation, ELEM-A will have no indentation. We'll
5972 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5973 (let* ((ind-B (when specialp
5974 (goto-char (org-element-property :begin elem-B))
5975 (org-get-indentation)))
5976 (beg-A (org-element-property :begin elem-A))
5977 (end-A (save-excursion
5978 (goto-char (org-element-property :end elem-A))
5979 (skip-chars-backward " \r\t\n")
5980 (point-at-eol)))
5981 (beg-B (org-element-property :begin elem-B))
5982 (end-B (save-excursion
5983 (goto-char (org-element-property :end elem-B))
5984 (skip-chars-backward " \r\t\n")
5985 (point-at-eol)))
5986 ;; Store inner overlays responsible for visibility status.
5987 ;; We also need to store their boundaries as they will be
5988 ;; removed from buffer.
5989 (overlays
5990 (cons
5991 (delq nil
5992 (mapcar (lambda (o)
5993 (and (>= (overlay-start o) beg-A)
5994 (<= (overlay-end o) end-A)
5995 (list o (overlay-start o) (overlay-end o))))
5996 (overlays-in beg-A end-A)))
5997 (delq nil
5998 (mapcar (lambda (o)
5999 (and (>= (overlay-start o) beg-B)
6000 (<= (overlay-end o) end-B)
6001 (list o (overlay-start o) (overlay-end o))))
6002 (overlays-in beg-B end-B)))))
6003 ;; Get contents.
6004 (body-A (buffer-substring beg-A end-A))
6005 (body-B (delete-and-extract-region beg-B end-B)))
6006 (goto-char beg-B)
6007 (when specialp
6008 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
6009 (org-indent-to-column ind-B))
6010 (insert body-A)
6011 ;; Restore ex ELEM-A overlays.
6012 (let ((offset (- beg-B beg-A)))
6013 (dolist (o (car overlays))
6014 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
6015 (goto-char beg-A)
6016 (delete-region beg-A end-A)
6017 (insert body-B)
6018 ;; Restore ex ELEM-B overlays.
6019 (dolist (o (cdr overlays))
6020 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
6021 (goto-char (org-element-property :end elem-B)))))
6023 ;; For backward-compatibility with Org <= 8.3
6024 (define-obsolete-function-alias
6025 'org-element-remove-indentation 'org-remove-indentation "25.1")
6028 (provide 'org-element)
6030 ;; Local variables:
6031 ;; generated-autoload-file: "org-loaddefs.el"
6032 ;; End:
6034 ;;; org-element.el ends here