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