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