Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob12a4bc67c9a11487170519639ae0b1a0fbdf2036
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-p
3043 "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
3044 (point)))
3045 (pcase (char-after (1+ (point)))
3046 (?\( (search-forward "\\)" nil t))
3047 (?\[ (search-forward "\\]" nil t))
3049 ;; Macro.
3050 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
3051 \\|\\({[^{}\n]*}\\)\\)*")
3052 (match-end 0))))))
3053 (post-blank (if (not after-fragment) (throw 'no-object nil)
3054 (goto-char after-fragment)
3055 (skip-chars-forward " \t")))
3056 (end (point)))
3057 (list 'latex-fragment
3058 (list :value (buffer-substring-no-properties begin after-fragment)
3059 :begin begin
3060 :end end
3061 :post-blank post-blank))))))
3063 (defun org-element-latex-fragment-interpreter (latex-fragment _)
3064 "Interpret LATEX-FRAGMENT object as Org syntax."
3065 (org-element-property :value latex-fragment))
3067 ;;;; Line Break
3069 (defun org-element-line-break-parser ()
3070 "Parse line break at point, if any.
3072 When at a line break, return a list whose car is `line-break',
3073 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3074 Otherwise, return nil.
3076 Assume point is at the beginning of the line break."
3077 (when (and (looking-at-p "\\\\\\\\[ \t]*$")
3078 (not (eq (char-before) ?\\)))
3079 (list 'line-break
3080 (list :begin (point)
3081 :end (line-beginning-position 2)
3082 :post-blank 0))))
3084 (defun org-element-line-break-interpreter (&rest _)
3085 "Interpret LINE-BREAK object as Org syntax."
3086 "\\\\\n")
3089 ;;;; Link
3091 (defun org-element-link-parser ()
3092 "Parse link at point, if any.
3094 When at a link, return a list whose car is `link' and cdr a plist
3095 with `:type', `:path', `:format', `:raw-link', `:application',
3096 `:search-option', `:begin', `:end', `:contents-begin',
3097 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3098 nil.
3100 Assume point is at the beginning of the link."
3101 (catch 'no-object
3102 (let ((begin (point))
3103 end contents-begin contents-end link-end post-blank path type format
3104 raw-link search-option application)
3105 (cond
3106 ;; Type 1: Text targeted from a radio target.
3107 ((and org-target-link-regexp
3108 (save-excursion (or (bolp) (backward-char))
3109 (looking-at org-target-link-regexp)))
3110 (setq type "radio")
3111 (setq format 'plain)
3112 (setq link-end (match-end 1))
3113 (setq path (match-string-no-properties 1))
3114 (setq contents-begin (match-beginning 1))
3115 (setq contents-end (match-end 1)))
3116 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3117 ((looking-at org-bracket-link-regexp)
3118 (setq format 'bracket)
3119 (setq contents-begin (match-beginning 3))
3120 (setq contents-end (match-end 3))
3121 (setq link-end (match-end 0))
3122 ;; RAW-LINK is the original link. Expand any
3123 ;; abbreviation in it.
3125 ;; Also treat any newline character and associated
3126 ;; indentation as a single space character. This is not
3127 ;; compatible with RFC 3986, which requires to ignore
3128 ;; them altogether. However, doing so would require
3129 ;; users to encode spaces on the fly when writing links
3130 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3131 ;; [[shell:ls *.org]], which defeats Org's focus on
3132 ;; simplicity.
3133 (setq raw-link (org-link-expand-abbrev
3134 (replace-regexp-in-string
3135 "[ \t]*\n[ \t]*" " "
3136 (match-string-no-properties 1))))
3137 ;; Determine TYPE of link and set PATH accordingly. According
3138 ;; to RFC 3986, remove whitespaces from URI in external links.
3139 ;; In internal ones, treat indentation as a single space.
3140 (cond
3141 ;; File type.
3142 ((or (file-name-absolute-p raw-link)
3143 (string-match "\\`\\.\\.?/" raw-link))
3144 (setq type "file")
3145 (setq path raw-link))
3146 ;; Explicit type (http, irc, bbdb...).
3147 ((string-match org-link-types-re raw-link)
3148 (setq type (match-string 1 raw-link))
3149 (setq path (substring raw-link (match-end 0))))
3150 ;; Code-ref type: PATH is the name of the reference.
3151 ((and (string-match-p "\\`(" raw-link)
3152 (string-match-p ")\\'" raw-link))
3153 (setq type "coderef")
3154 (setq path (substring raw-link 1 -1)))
3155 ;; Custom-id type: PATH is the name of the custom id.
3156 ((= (string-to-char raw-link) ?#)
3157 (setq type "custom-id")
3158 (setq path (substring raw-link 1)))
3159 ;; Fuzzy type: Internal link either matches a target, an
3160 ;; headline name or nothing. PATH is the target or
3161 ;; headline's name.
3163 (setq type "fuzzy")
3164 (setq path raw-link))))
3165 ;; Type 3: Plain link, e.g., http://orgmode.org
3166 ((looking-at org-plain-link-re)
3167 (setq format 'plain)
3168 (setq raw-link (match-string-no-properties 0))
3169 (setq type (match-string-no-properties 1))
3170 (setq link-end (match-end 0))
3171 (setq path (match-string-no-properties 2)))
3172 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3173 ;; bracket links, follow RFC 3986 and remove any extra
3174 ;; whitespace in URI.
3175 ((looking-at org-angle-link-re)
3176 (setq format 'angle)
3177 (setq type (match-string-no-properties 1))
3178 (setq link-end (match-end 0))
3179 (setq raw-link
3180 (buffer-substring-no-properties
3181 (match-beginning 1) (match-end 2)))
3182 (setq path (replace-regexp-in-string
3183 "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
3184 (t (throw 'no-object nil)))
3185 ;; In any case, deduce end point after trailing white space from
3186 ;; LINK-END variable.
3187 (save-excursion
3188 (setq post-blank
3189 (progn (goto-char link-end) (skip-chars-forward " \t")))
3190 (setq end (point)))
3191 ;; Special "file" type link processing. Extract opening
3192 ;; application and search option, if any. Also normalize URI.
3193 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3194 (setq application (match-string 1 type) type "file")
3195 (when (string-match "::\\(.*\\)\\'" path)
3196 (setq search-option (match-string 1 path))
3197 (setq path (replace-match "" nil nil path)))
3198 (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
3199 ;; Translate link, if `org-link-translation-function' is set.
3200 (let ((trans (and (functionp org-link-translation-function)
3201 (funcall org-link-translation-function type path))))
3202 (when trans
3203 (setq type (car trans))
3204 (setq path (cdr trans))))
3205 (list 'link
3206 (list :type type
3207 :path path
3208 :format format
3209 :raw-link (or raw-link path)
3210 :application application
3211 :search-option search-option
3212 :begin begin
3213 :end end
3214 :contents-begin contents-begin
3215 :contents-end contents-end
3216 :post-blank post-blank)))))
3218 (defun org-element-link-interpreter (link contents)
3219 "Interpret LINK object as Org syntax.
3220 CONTENTS is the contents of the object, or nil."
3221 (let ((type (org-element-property :type link))
3222 (path (org-element-property :path link)))
3223 (if (string= type "radio") path
3224 (let ((fmt (pcase (org-element-property :format link)
3225 ;; Links with contents and internal links have to
3226 ;; use bracket syntax. Ignore `:format' in these
3227 ;; cases. This is also the default syntax when the
3228 ;; property is not defined, e.g., when the object
3229 ;; was crafted by the user.
3230 ((guard contents)
3231 (format "[[%%s][%s]]"
3232 ;; Since this is going to be used as
3233 ;; a format string, escape percent signs
3234 ;; in description.
3235 (replace-regexp-in-string "%" "%%" contents)))
3236 ((or `bracket
3237 `nil
3238 (guard (member type '("coderef" "custom-id" "fuzzy"))))
3239 "[[%s]]")
3240 ;; Otherwise, just obey to `:format'.
3241 (`angle "<%s>")
3242 (`plain "%s")
3243 (f (error "Wrong `:format' value: %s" f)))))
3244 (format fmt
3245 (pcase type
3246 ("coderef" (format "(%s)" path))
3247 ("custom-id" (concat "#" path))
3248 ("file"
3249 (let ((app (org-element-property :application link))
3250 (opt (org-element-property :search-option link)))
3251 (concat type (and app (concat "+" app)) ":"
3252 path
3253 (and opt (concat "::" opt)))))
3254 ("fuzzy" path)
3255 (_ (concat type ":" path))))))))
3258 ;;;; Macro
3260 (defun org-element-macro-parser ()
3261 "Parse macro at point, if any.
3263 When at a macro, return a list whose car is `macro' and cdr
3264 a plist with `:key', `:args', `:begin', `:end', `:value' and
3265 `:post-blank' as keywords. Otherwise, return nil.
3267 Assume point is at the macro."
3268 (save-excursion
3269 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3270 (let ((begin (point))
3271 (key (downcase (match-string-no-properties 1)))
3272 (value (match-string-no-properties 0))
3273 (post-blank (progn (goto-char (match-end 0))
3274 (skip-chars-forward " \t")))
3275 (end (point))
3276 (args (let ((args (match-string-no-properties 3)))
3277 (and args (org-macro-extract-arguments args)))))
3278 (list 'macro
3279 (list :key key
3280 :value value
3281 :args args
3282 :begin begin
3283 :end end
3284 :post-blank post-blank))))))
3286 (defun org-element-macro-interpreter (macro _)
3287 "Interpret MACRO object as Org syntax."
3288 (org-element-property :value macro))
3291 ;;;; Radio-target
3293 (defun org-element-radio-target-parser ()
3294 "Parse radio target at point, if any.
3296 When at a radio target, return a list whose car is `radio-target'
3297 and cdr a plist with `:begin', `:end', `:contents-begin',
3298 `:contents-end', `:value' and `:post-blank' as keywords.
3299 Otherwise, return nil.
3301 Assume point is at the radio target."
3302 (save-excursion
3303 (when (looking-at org-radio-target-regexp)
3304 (let ((begin (point))
3305 (contents-begin (match-beginning 1))
3306 (contents-end (match-end 1))
3307 (value (match-string-no-properties 1))
3308 (post-blank (progn (goto-char (match-end 0))
3309 (skip-chars-forward " \t")))
3310 (end (point)))
3311 (list 'radio-target
3312 (list :begin begin
3313 :end end
3314 :contents-begin contents-begin
3315 :contents-end contents-end
3316 :post-blank post-blank
3317 :value value))))))
3319 (defun org-element-radio-target-interpreter (_ contents)
3320 "Interpret target object as Org syntax.
3321 CONTENTS is the contents of the object."
3322 (concat "<<<" contents ">>>"))
3325 ;;;; Statistics Cookie
3327 (defun org-element-statistics-cookie-parser ()
3328 "Parse statistics cookie at point, if any.
3330 When at a statistics cookie, return a list whose car is
3331 `statistics-cookie', and cdr a plist with `:begin', `:end',
3332 `:value' and `:post-blank' keywords. Otherwise, return nil.
3334 Assume point is at the beginning of the statistics-cookie."
3335 (save-excursion
3336 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3337 (let* ((begin (point))
3338 (value (buffer-substring-no-properties
3339 (match-beginning 0) (match-end 0)))
3340 (post-blank (progn (goto-char (match-end 0))
3341 (skip-chars-forward " \t")))
3342 (end (point)))
3343 (list 'statistics-cookie
3344 (list :begin begin
3345 :end end
3346 :value value
3347 :post-blank post-blank))))))
3349 (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
3350 "Interpret STATISTICS-COOKIE object as Org syntax."
3351 (org-element-property :value statistics-cookie))
3354 ;;;; Strike-Through
3356 (defun org-element-strike-through-parser ()
3357 "Parse strike-through object at point, if any.
3359 When at a strike-through object, return a list whose car is
3360 `strike-through' and cdr is a plist with `:begin', `:end',
3361 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3362 Otherwise, return nil.
3364 Assume point is at the first plus sign marker."
3365 (save-excursion
3366 (unless (bolp) (backward-char 1))
3367 (when (looking-at org-emph-re)
3368 (let ((begin (match-beginning 2))
3369 (contents-begin (match-beginning 4))
3370 (contents-end (match-end 4))
3371 (post-blank (progn (goto-char (match-end 2))
3372 (skip-chars-forward " \t")))
3373 (end (point)))
3374 (list 'strike-through
3375 (list :begin begin
3376 :end end
3377 :contents-begin contents-begin
3378 :contents-end contents-end
3379 :post-blank post-blank))))))
3381 (defun org-element-strike-through-interpreter (_ contents)
3382 "Interpret strike-through object as Org syntax.
3383 CONTENTS is the contents of the object."
3384 (format "+%s+" contents))
3387 ;;;; Subscript
3389 (defun org-element-subscript-parser ()
3390 "Parse subscript at point, if any.
3392 When at a subscript object, return a list whose car is
3393 `subscript' and cdr a plist with `:begin', `:end',
3394 `:contents-begin', `:contents-end', `:use-brackets-p' and
3395 `:post-blank' as keywords. Otherwise, return nil.
3397 Assume point is at the underscore."
3398 (save-excursion
3399 (unless (bolp) (backward-char))
3400 (when (looking-at org-match-substring-regexp)
3401 (let ((bracketsp (match-beginning 4))
3402 (begin (match-beginning 2))
3403 (contents-begin (or (match-beginning 4)
3404 (match-beginning 3)))
3405 (contents-end (or (match-end 4) (match-end 3)))
3406 (post-blank (progn (goto-char (match-end 0))
3407 (skip-chars-forward " \t")))
3408 (end (point)))
3409 (list 'subscript
3410 (list :begin begin
3411 :end end
3412 :use-brackets-p bracketsp
3413 :contents-begin contents-begin
3414 :contents-end contents-end
3415 :post-blank post-blank))))))
3417 (defun org-element-subscript-interpreter (subscript contents)
3418 "Interpret SUBSCRIPT object as Org syntax.
3419 CONTENTS is the contents of the object."
3420 (format
3421 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3422 contents))
3425 ;;;; Superscript
3427 (defun org-element-superscript-parser ()
3428 "Parse superscript at point, if any.
3430 When at a superscript object, return a list whose car is
3431 `superscript' and cdr a plist with `:begin', `:end',
3432 `:contents-begin', `:contents-end', `:use-brackets-p' and
3433 `:post-blank' as keywords. Otherwise, return nil.
3435 Assume point is at the caret."
3436 (save-excursion
3437 (unless (bolp) (backward-char))
3438 (when (looking-at org-match-substring-regexp)
3439 (let ((bracketsp (match-beginning 4))
3440 (begin (match-beginning 2))
3441 (contents-begin (or (match-beginning 4)
3442 (match-beginning 3)))
3443 (contents-end (or (match-end 4) (match-end 3)))
3444 (post-blank (progn (goto-char (match-end 0))
3445 (skip-chars-forward " \t")))
3446 (end (point)))
3447 (list 'superscript
3448 (list :begin begin
3449 :end end
3450 :use-brackets-p bracketsp
3451 :contents-begin contents-begin
3452 :contents-end contents-end
3453 :post-blank post-blank))))))
3455 (defun org-element-superscript-interpreter (superscript contents)
3456 "Interpret SUPERSCRIPT object as Org syntax.
3457 CONTENTS is the contents of the object."
3458 (format
3459 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3460 contents))
3463 ;;;; Table Cell
3465 (defun org-element-table-cell-parser ()
3466 "Parse table cell at point.
3467 Return a list whose car is `table-cell' and cdr is a plist
3468 containing `:begin', `:end', `:contents-begin', `:contents-end'
3469 and `:post-blank' keywords."
3470 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3471 (let* ((begin (match-beginning 0))
3472 (end (match-end 0))
3473 (contents-begin (match-beginning 1))
3474 (contents-end (match-end 1)))
3475 (list 'table-cell
3476 (list :begin begin
3477 :end end
3478 :contents-begin contents-begin
3479 :contents-end contents-end
3480 :post-blank 0))))
3482 (defun org-element-table-cell-interpreter (_ contents)
3483 "Interpret table-cell element as Org syntax.
3484 CONTENTS is the contents of the cell, or nil."
3485 (concat " " contents " |"))
3488 ;;;; Target
3490 (defun org-element-target-parser ()
3491 "Parse target at point, if any.
3493 When at a target, return a list whose car is `target' and cdr
3494 a plist with `:begin', `:end', `:value' and `:post-blank' as
3495 keywords. Otherwise, return nil.
3497 Assume point is at the target."
3498 (save-excursion
3499 (when (looking-at org-target-regexp)
3500 (let ((begin (point))
3501 (value (match-string-no-properties 1))
3502 (post-blank (progn (goto-char (match-end 0))
3503 (skip-chars-forward " \t")))
3504 (end (point)))
3505 (list 'target
3506 (list :begin begin
3507 :end end
3508 :value value
3509 :post-blank post-blank))))))
3511 (defun org-element-target-interpreter (target _)
3512 "Interpret TARGET object as Org syntax."
3513 (format "<<%s>>" (org-element-property :value target)))
3516 ;;;; Timestamp
3518 (defconst org-element--timestamp-regexp
3519 (concat org-ts-regexp-both
3520 "\\|"
3521 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3522 "\\|"
3523 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3524 "Regexp matching any timestamp type object.")
3526 (defun org-element-timestamp-parser ()
3527 "Parse time stamp at point, if any.
3529 When at a time stamp, return a list whose car is `timestamp', and
3530 cdr a plist with `:type', `:raw-value', `:year-start',
3531 `:month-start', `:day-start', `:hour-start', `:minute-start',
3532 `:year-end', `:month-end', `:day-end', `:hour-end',
3533 `:minute-end', `:repeater-type', `:repeater-value',
3534 `:repeater-unit', `:warning-type', `:warning-value',
3535 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3536 Otherwise, return nil.
3538 Assume point is at the beginning of the timestamp."
3539 (when (looking-at-p org-element--timestamp-regexp)
3540 (save-excursion
3541 (let* ((begin (point))
3542 (activep (eq (char-after) ?<))
3543 (raw-value
3544 (progn
3545 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3546 (match-string-no-properties 0)))
3547 (date-start (match-string-no-properties 1))
3548 (date-end (match-string 3))
3549 (diaryp (match-beginning 2))
3550 (post-blank (progn (goto-char (match-end 0))
3551 (skip-chars-forward " \t")))
3552 (end (point))
3553 (time-range
3554 (and (not diaryp)
3555 (string-match
3556 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3557 date-start)
3558 (cons (string-to-number (match-string 2 date-start))
3559 (string-to-number (match-string 3 date-start)))))
3560 (type (cond (diaryp 'diary)
3561 ((and activep (or date-end time-range)) 'active-range)
3562 (activep 'active)
3563 ((or date-end time-range) 'inactive-range)
3564 (t 'inactive)))
3565 (repeater-props
3566 (and (not diaryp)
3567 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3568 raw-value)
3569 (list
3570 :repeater-type
3571 (let ((type (match-string 1 raw-value)))
3572 (cond ((equal "++" type) 'catch-up)
3573 ((equal ".+" type) 'restart)
3574 (t 'cumulate)))
3575 :repeater-value (string-to-number (match-string 2 raw-value))
3576 :repeater-unit
3577 (pcase (string-to-char (match-string 3 raw-value))
3578 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3579 (warning-props
3580 (and (not diaryp)
3581 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3582 (list
3583 :warning-type (if (match-string 1 raw-value) 'first 'all)
3584 :warning-value (string-to-number (match-string 2 raw-value))
3585 :warning-unit
3586 (pcase (string-to-char (match-string 3 raw-value))
3587 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3588 year-start month-start day-start hour-start minute-start year-end
3589 month-end day-end hour-end minute-end)
3590 ;; Parse date-start.
3591 (unless diaryp
3592 (let ((date (org-parse-time-string date-start t)))
3593 (setq year-start (nth 5 date)
3594 month-start (nth 4 date)
3595 day-start (nth 3 date)
3596 hour-start (nth 2 date)
3597 minute-start (nth 1 date))))
3598 ;; Compute date-end. It can be provided directly in time-stamp,
3599 ;; or extracted from time range. Otherwise, it defaults to the
3600 ;; same values as date-start.
3601 (unless diaryp
3602 (let ((date (and date-end (org-parse-time-string date-end t))))
3603 (setq year-end (or (nth 5 date) year-start)
3604 month-end (or (nth 4 date) month-start)
3605 day-end (or (nth 3 date) day-start)
3606 hour-end (or (nth 2 date) (car time-range) hour-start)
3607 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3608 (list 'timestamp
3609 (nconc (list :type type
3610 :raw-value raw-value
3611 :year-start year-start
3612 :month-start month-start
3613 :day-start day-start
3614 :hour-start hour-start
3615 :minute-start minute-start
3616 :year-end year-end
3617 :month-end month-end
3618 :day-end day-end
3619 :hour-end hour-end
3620 :minute-end minute-end
3621 :begin begin
3622 :end end
3623 :post-blank post-blank)
3624 repeater-props
3625 warning-props))))))
3627 (defun org-element-timestamp-interpreter (timestamp _)
3628 "Interpret TIMESTAMP object as Org syntax."
3629 (let* ((repeat-string
3630 (concat
3631 (pcase (org-element-property :repeater-type timestamp)
3632 (`cumulate "+") (`catch-up "++") (`restart ".+"))
3633 (let ((val (org-element-property :repeater-value timestamp)))
3634 (and val (number-to-string val)))
3635 (pcase (org-element-property :repeater-unit timestamp)
3636 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3637 (warning-string
3638 (concat
3639 (pcase (org-element-property :warning-type timestamp)
3640 (`first "--") (`all "-"))
3641 (let ((val (org-element-property :warning-value timestamp)))
3642 (and val (number-to-string val)))
3643 (pcase (org-element-property :warning-unit timestamp)
3644 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3645 (build-ts-string
3646 ;; Build an Org timestamp string from TIME. ACTIVEP is
3647 ;; non-nil when time stamp is active. If WITH-TIME-P is
3648 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3649 ;; specify a time range in the timestamp. REPEAT-STRING is
3650 ;; the repeater string, if any.
3651 (lambda (time activep &optional with-time-p hour-end minute-end)
3652 (let ((ts (format-time-string
3653 (funcall (if with-time-p #'cdr #'car)
3654 org-time-stamp-formats)
3655 time)))
3656 (when (and hour-end minute-end)
3657 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3658 (setq ts
3659 (replace-match
3660 (format "\\&-%02d:%02d" hour-end minute-end)
3661 nil nil ts)))
3662 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3663 (dolist (s (list repeat-string warning-string))
3664 (when (org-string-nw-p s)
3665 (setq ts (concat (substring ts 0 -1)
3668 (substring ts -1)))))
3669 ;; Return value.
3670 ts)))
3671 (type (org-element-property :type timestamp)))
3672 (pcase type
3673 ((or `active `inactive)
3674 (let* ((minute-start (org-element-property :minute-start timestamp))
3675 (minute-end (org-element-property :minute-end timestamp))
3676 (hour-start (org-element-property :hour-start timestamp))
3677 (hour-end (org-element-property :hour-end timestamp))
3678 (time-range-p (and hour-start hour-end minute-start minute-end
3679 (or (/= hour-start hour-end)
3680 (/= minute-start minute-end)))))
3681 (funcall
3682 build-ts-string
3683 (encode-time 0
3684 (or minute-start 0)
3685 (or hour-start 0)
3686 (org-element-property :day-start timestamp)
3687 (org-element-property :month-start timestamp)
3688 (org-element-property :year-start timestamp))
3689 (eq type 'active)
3690 (and hour-start minute-start)
3691 (and time-range-p hour-end)
3692 (and time-range-p minute-end))))
3693 ((or `active-range `inactive-range)
3694 (let ((minute-start (org-element-property :minute-start timestamp))
3695 (minute-end (org-element-property :minute-end timestamp))
3696 (hour-start (org-element-property :hour-start timestamp))
3697 (hour-end (org-element-property :hour-end timestamp)))
3698 (concat
3699 (funcall
3700 build-ts-string (encode-time
3702 (or minute-start 0)
3703 (or hour-start 0)
3704 (org-element-property :day-start timestamp)
3705 (org-element-property :month-start timestamp)
3706 (org-element-property :year-start timestamp))
3707 (eq type 'active-range)
3708 (and hour-start minute-start))
3709 "--"
3710 (funcall build-ts-string
3711 (encode-time 0
3712 (or minute-end 0)
3713 (or hour-end 0)
3714 (org-element-property :day-end timestamp)
3715 (org-element-property :month-end timestamp)
3716 (org-element-property :year-end timestamp))
3717 (eq type 'active-range)
3718 (and hour-end minute-end)))))
3719 (_ (org-element-property :raw-value timestamp)))))
3722 ;;;; Underline
3724 (defun org-element-underline-parser ()
3725 "Parse underline object at point, if any.
3727 When at an underline object, return a list whose car is
3728 `underline' and cdr is a plist with `:begin', `:end',
3729 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3730 Otherwise, return nil.
3732 Assume point is at the first underscore marker."
3733 (save-excursion
3734 (unless (bolp) (backward-char 1))
3735 (when (looking-at org-emph-re)
3736 (let ((begin (match-beginning 2))
3737 (contents-begin (match-beginning 4))
3738 (contents-end (match-end 4))
3739 (post-blank (progn (goto-char (match-end 2))
3740 (skip-chars-forward " \t")))
3741 (end (point)))
3742 (list 'underline
3743 (list :begin begin
3744 :end end
3745 :contents-begin contents-begin
3746 :contents-end contents-end
3747 :post-blank post-blank))))))
3749 (defun org-element-underline-interpreter (_ contents)
3750 "Interpret underline object as Org syntax.
3751 CONTENTS is the contents of the object."
3752 (format "_%s_" contents))
3755 ;;;; Verbatim
3757 (defun org-element-verbatim-parser ()
3758 "Parse verbatim object at point, if any.
3760 When at a verbatim object, return a list whose car is `verbatim'
3761 and cdr is a plist with `:value', `:begin', `:end' and
3762 `:post-blank' keywords. Otherwise, return nil.
3764 Assume point is at the first equal sign marker."
3765 (save-excursion
3766 (unless (bolp) (backward-char 1))
3767 (when (looking-at org-verbatim-re)
3768 (let ((begin (match-beginning 2))
3769 (value (match-string-no-properties 4))
3770 (post-blank (progn (goto-char (match-end 2))
3771 (skip-chars-forward " \t")))
3772 (end (point)))
3773 (list 'verbatim
3774 (list :value value
3775 :begin begin
3776 :end end
3777 :post-blank post-blank))))))
3779 (defun org-element-verbatim-interpreter (verbatim _)
3780 "Interpret VERBATIM object as Org syntax."
3781 (format "=%s=" (org-element-property :value verbatim)))
3785 ;;; Parsing Element Starting At Point
3787 ;; `org-element--current-element' is the core function of this section.
3788 ;; It returns the Lisp representation of the element starting at
3789 ;; point.
3791 ;; `org-element--current-element' makes use of special modes. They
3792 ;; are activated for fixed element chaining (e.g., `plain-list' >
3793 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3794 ;; `section'). Special modes are: `first-section', `item',
3795 ;; `node-property', `section' and `table-row'.
3797 (defun org-element--current-element (limit &optional granularity mode structure)
3798 "Parse the element starting at point.
3800 Return value is a list like (TYPE PROPS) where TYPE is the type
3801 of the element and PROPS a plist of properties associated to the
3802 element.
3804 Possible types are defined in `org-element-all-elements'.
3806 LIMIT bounds the search.
3808 Optional argument GRANULARITY determines the depth of the
3809 recursion. Allowed values are `headline', `greater-element',
3810 `element', `object' or nil. When it is broader than `object' (or
3811 nil), secondary values will not be parsed, since they only
3812 contain objects.
3814 Optional argument MODE, when non-nil, can be either
3815 `first-section', `section', `planning', `item', `node-property'
3816 and `table-row'.
3818 If STRUCTURE isn't provided but MODE is set to `item', it will be
3819 computed.
3821 This function assumes point is always at the beginning of the
3822 element it has to parse."
3823 (save-excursion
3824 (let ((case-fold-search t)
3825 ;; Determine if parsing depth allows for secondary strings
3826 ;; parsing. It only applies to elements referenced in
3827 ;; `org-element-secondary-value-alist'.
3828 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3829 (cond
3830 ;; Item.
3831 ((eq mode 'item)
3832 (org-element-item-parser limit structure raw-secondary-p))
3833 ;; Table Row.
3834 ((eq mode 'table-row) (org-element-table-row-parser limit))
3835 ;; Node Property.
3836 ((eq mode 'node-property) (org-element-node-property-parser limit))
3837 ;; Headline.
3838 ((org-with-limited-levels (org-at-heading-p))
3839 (org-element-headline-parser limit raw-secondary-p))
3840 ;; Sections (must be checked after headline).
3841 ((eq mode 'section) (org-element-section-parser limit))
3842 ((eq mode 'first-section)
3843 (org-element-section-parser
3844 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3845 limit)))
3846 ;; Planning.
3847 ((and (eq mode 'planning)
3848 (eq ?* (char-after (line-beginning-position 0)))
3849 (looking-at org-planning-line-re))
3850 (org-element-planning-parser limit))
3851 ;; Property drawer.
3852 ((and (memq mode '(planning property-drawer))
3853 (eq ?* (char-after (line-beginning-position
3854 (if (eq mode 'planning) 0 -1))))
3855 (looking-at org-property-drawer-re))
3856 (org-element-property-drawer-parser limit))
3857 ;; When not at bol, point is at the beginning of an item or
3858 ;; a footnote definition: next item is always a paragraph.
3859 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3860 ;; Clock.
3861 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3862 ;; Inlinetask.
3863 ((org-at-heading-p)
3864 (org-element-inlinetask-parser limit raw-secondary-p))
3865 ;; From there, elements can have affiliated keywords.
3866 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3867 (cond
3868 ;; Jumping over affiliated keywords put point off-limits.
3869 ;; Parse them as regular keywords.
3870 ((and (cdr affiliated) (>= (point) limit))
3871 (goto-char (car affiliated))
3872 (org-element-keyword-parser limit nil))
3873 ;; LaTeX Environment.
3874 ((looking-at org-element--latex-begin-environment)
3875 (org-element-latex-environment-parser limit affiliated))
3876 ;; Drawer and Property Drawer.
3877 ((looking-at org-drawer-regexp)
3878 (org-element-drawer-parser limit affiliated))
3879 ;; Fixed Width
3880 ((looking-at "[ \t]*:\\( \\|$\\)")
3881 (org-element-fixed-width-parser limit affiliated))
3882 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3883 ;; Keywords.
3884 ((looking-at "[ \t]*#")
3885 (goto-char (match-end 0))
3886 (cond
3887 ((looking-at "\\(?: \\|$\\)")
3888 (beginning-of-line)
3889 (org-element-comment-parser limit affiliated))
3890 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3891 (beginning-of-line)
3892 (funcall (pcase (upcase (match-string 1))
3893 ("CENTER" #'org-element-center-block-parser)
3894 ("COMMENT" #'org-element-comment-block-parser)
3895 ("EXAMPLE" #'org-element-example-block-parser)
3896 ("EXPORT" #'org-element-export-block-parser)
3897 ("QUOTE" #'org-element-quote-block-parser)
3898 ("SRC" #'org-element-src-block-parser)
3899 ("VERSE" #'org-element-verse-block-parser)
3900 (_ #'org-element-special-block-parser))
3901 limit
3902 affiliated))
3903 ((looking-at "\\+CALL:")
3904 (beginning-of-line)
3905 (org-element-babel-call-parser limit affiliated))
3906 ((looking-at "\\+BEGIN:? ")
3907 (beginning-of-line)
3908 (org-element-dynamic-block-parser limit affiliated))
3909 ((looking-at "\\+\\S-+:")
3910 (beginning-of-line)
3911 (org-element-keyword-parser limit affiliated))
3913 (beginning-of-line)
3914 (org-element-paragraph-parser limit affiliated))))
3915 ;; Footnote Definition.
3916 ((looking-at org-footnote-definition-re)
3917 (org-element-footnote-definition-parser limit affiliated))
3918 ;; Horizontal Rule.
3919 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3920 (org-element-horizontal-rule-parser limit affiliated))
3921 ;; Diary Sexp.
3922 ((looking-at "%%(")
3923 (org-element-diary-sexp-parser limit affiliated))
3924 ;; Table.
3925 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3926 (org-element-table-parser limit affiliated))
3927 ;; List.
3928 ((looking-at (org-item-re))
3929 (org-element-plain-list-parser
3930 limit affiliated
3931 (or structure (org-element--list-struct limit))))
3932 ;; Default element: Paragraph.
3933 (t (org-element-paragraph-parser limit affiliated)))))))))
3936 ;; Most elements can have affiliated keywords. When looking for an
3937 ;; element beginning, we want to move before them, as they belong to
3938 ;; that element, and, in the meantime, collect information they give
3939 ;; into appropriate properties. Hence the following function.
3941 (defun org-element--collect-affiliated-keywords (limit)
3942 "Collect affiliated keywords from point down to LIMIT.
3944 Return a list whose CAR is the position at the first of them and
3945 CDR a plist of keywords and values and move point to the
3946 beginning of the first line after them.
3948 As a special case, if element doesn't start at the beginning of
3949 the line (e.g., a paragraph starting an item), CAR is current
3950 position of point and CDR is nil."
3951 (if (not (bolp)) (list (point))
3952 (let ((case-fold-search t)
3953 (origin (point))
3954 ;; RESTRICT is the list of objects allowed in parsed
3955 ;; keywords value.
3956 (restrict (org-element-restriction 'keyword))
3957 output)
3958 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3959 (let* ((raw-kwd (upcase (match-string 1)))
3960 ;; Apply translation to RAW-KWD. From there, KWD is
3961 ;; the official keyword.
3962 (kwd (or (cdr (assoc raw-kwd
3963 org-element-keyword-translation-alist))
3964 raw-kwd))
3965 ;; Find main value for any keyword.
3966 (value
3967 (save-match-data
3968 (org-trim
3969 (buffer-substring-no-properties
3970 (match-end 0) (line-end-position)))))
3971 ;; PARSEDP is non-nil when keyword should have its
3972 ;; value parsed.
3973 (parsedp (member kwd org-element-parsed-keywords))
3974 ;; If KWD is a dual keyword, find its secondary
3975 ;; value. Maybe parse it.
3976 (dualp (member kwd org-element-dual-keywords))
3977 (dual-value
3978 (and dualp
3979 (let ((sec (match-string-no-properties 2)))
3980 (if (or (not sec) (not parsedp)) sec
3981 (save-match-data
3982 (org-element--parse-objects
3983 (match-beginning 2) (match-end 2) nil restrict))))))
3984 ;; Attribute a property name to KWD.
3985 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3986 ;; Now set final shape for VALUE.
3987 (when parsedp
3988 (setq value
3989 (org-element--parse-objects
3990 (match-end 0)
3991 (progn (end-of-line) (skip-chars-backward " \t") (point))
3992 nil restrict)))
3993 (when dualp
3994 (setq value (and (or value dual-value) (cons value dual-value))))
3995 (when (or (member kwd org-element-multiple-keywords)
3996 ;; Attributes can always appear on multiple lines.
3997 (string-match "^ATTR_" kwd))
3998 (setq value (cons value (plist-get output kwd-sym))))
3999 ;; Eventually store the new value in OUTPUT.
4000 (setq output (plist-put output kwd-sym value))
4001 ;; Move to next keyword.
4002 (forward-line)))
4003 ;; If affiliated keywords are orphaned: move back to first one.
4004 ;; They will be parsed as a paragraph.
4005 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
4006 ;; Return value.
4007 (cons origin output))))
4011 ;;; The Org Parser
4013 ;; The two major functions here are `org-element-parse-buffer', which
4014 ;; parses Org syntax inside the current buffer, taking into account
4015 ;; region, narrowing, or even visibility if specified, and
4016 ;; `org-element-parse-secondary-string', which parses objects within
4017 ;; a given string.
4019 ;; The (almost) almighty `org-element-map' allows applying a function
4020 ;; on elements or objects matching some type, and accumulating the
4021 ;; resulting values. In an export situation, it also skips unneeded
4022 ;; parts of the parse tree.
4024 (defun org-element-parse-buffer (&optional granularity visible-only)
4025 "Recursively parse the buffer and return structure.
4026 If narrowing is in effect, only parse the visible part of the
4027 buffer.
4029 Optional argument GRANULARITY determines the depth of the
4030 recursion. It can be set to the following symbols:
4032 `headline' Only parse headlines.
4033 `greater-element' Don't recurse into greater elements except
4034 headlines and sections. Thus, elements
4035 parsed are the top-level ones.
4036 `element' Parse everything but objects and plain text.
4037 `object' Parse the complete buffer (default).
4039 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4040 elements.
4042 An element or object is represented as a list with the
4043 pattern (TYPE PROPERTIES CONTENTS), where :
4045 TYPE is a symbol describing the element or object. See
4046 `org-element-all-elements' and `org-element-all-objects' for an
4047 exhaustive list of such symbols. One can retrieve it with
4048 `org-element-type' function.
4050 PROPERTIES is the list of attributes attached to the element or
4051 object, as a plist. Although most of them are specific to the
4052 element or object type, all types share `:begin', `:end',
4053 `:post-blank' and `:parent' properties, which respectively
4054 refer to buffer position where the element or object starts,
4055 ends, the number of white spaces or blank lines after it, and
4056 the element or object containing it. Properties values can be
4057 obtained by using `org-element-property' function.
4059 CONTENTS is a list of elements, objects or raw strings
4060 contained in the current element or object, when applicable.
4061 One can access them with `org-element-contents' function.
4063 The Org buffer has `org-data' as type and nil as properties.
4064 `org-element-map' function can be used to find specific elements
4065 or objects within the parse tree.
4067 This function assumes that current major mode is `org-mode'."
4068 (save-excursion
4069 (goto-char (point-min))
4070 (org-skip-whitespace)
4071 (org-element--parse-elements
4072 (point-at-bol) (point-max)
4073 ;; Start in `first-section' mode so text before the first
4074 ;; headline belongs to a section.
4075 'first-section nil granularity visible-only (list 'org-data nil))))
4077 (defun org-element-parse-secondary-string (string restriction &optional parent)
4078 "Recursively parse objects in STRING and return structure.
4080 RESTRICTION is a symbol limiting the object types that will be
4081 looked after.
4083 Optional argument PARENT, when non-nil, is the element or object
4084 containing the secondary string. It is used to set correctly
4085 `:parent' property within the string.
4087 If STRING is the empty string or nil, return nil."
4088 (cond
4089 ((not string) nil)
4090 ((equal string "") nil)
4091 (t (let ((local-variables (buffer-local-variables)))
4092 (with-temp-buffer
4093 (dolist (v local-variables)
4094 (ignore-errors
4095 (if (symbolp v) (makunbound v)
4096 (set (make-local-variable (car v)) (cdr v)))))
4097 (insert string)
4098 (restore-buffer-modified-p nil)
4099 (org-element--parse-objects
4100 (point-min) (point-max) nil restriction parent))))))
4102 (defun org-element-map
4103 (data types fun &optional info first-match no-recursion with-affiliated)
4104 "Map a function on selected elements or objects.
4106 DATA is a parse tree, an element, an object, a string, or a list
4107 of such constructs. TYPES is a symbol or list of symbols of
4108 elements or objects types (see `org-element-all-elements' and
4109 `org-element-all-objects' for a complete list of types). FUN is
4110 the function called on the matching element or object. It has to
4111 accept one argument: the element or object itself.
4113 When optional argument INFO is non-nil, it should be a plist
4114 holding export options. In that case, parts of the parse tree
4115 not exportable according to that property list will be skipped.
4117 When optional argument FIRST-MATCH is non-nil, stop at the first
4118 match for which FUN doesn't return nil, and return that value.
4120 Optional argument NO-RECURSION is a symbol or a list of symbols
4121 representing elements or objects types. `org-element-map' won't
4122 enter any recursive element or object whose type belongs to that
4123 list. Though, FUN can still be applied on them.
4125 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4126 apply to matching objects within parsed affiliated keywords (see
4127 `org-element-parsed-keywords').
4129 Nil values returned from FUN do not appear in the results.
4132 Examples:
4133 ---------
4135 Assuming TREE is a variable containing an Org buffer parse tree,
4136 the following example will return a flat list of all `src-block'
4137 and `example-block' elements in it:
4139 (org-element-map tree \\='(example-block src-block) #\\='identity)
4141 The following snippet will find the first headline with a level
4142 of 1 and a \"phone\" tag, and will return its beginning position:
4144 (org-element-map tree \\='headline
4145 (lambda (hl)
4146 (and (= (org-element-property :level hl) 1)
4147 (member \"phone\" (org-element-property :tags hl))
4148 (org-element-property :begin hl)))
4149 nil t)
4151 The next example will return a flat list of all `plain-list' type
4152 elements in TREE that are not a sub-list themselves:
4154 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4156 Eventually, this example will return a flat list of all `bold'
4157 type objects containing a `latex-snippet' type object, even
4158 looking into captions:
4160 (org-element-map tree \\='bold
4161 (lambda (b)
4162 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4163 nil nil nil t)"
4164 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4165 (let* ((types (if (listp types) types (list types)))
4166 (no-recursion (if (listp no-recursion) no-recursion
4167 (list no-recursion)))
4168 ;; Recursion depth is determined by --CATEGORY.
4169 (--category
4170 (catch :--found
4171 (let ((category 'greater-elements)
4172 (all-objects (cons 'plain-text org-element-all-objects)))
4173 (dolist (type types category)
4174 (cond ((memq type all-objects)
4175 ;; If one object is found, the function has
4176 ;; to recurse into every object.
4177 (throw :--found 'objects))
4178 ((not (memq type org-element-greater-elements))
4179 ;; If one regular element is found, the
4180 ;; function has to recurse, at least, into
4181 ;; every element it encounters.
4182 (and (not (eq category 'elements))
4183 (setq category 'elements))))))))
4184 --acc)
4185 (letrec ((--walk-tree
4186 (lambda (--data)
4187 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4188 ;; holding contextual information.
4189 (let ((--type (org-element-type --data)))
4190 (cond
4191 ((not --data))
4192 ;; Ignored element in an export context.
4193 ((and info (memq --data (plist-get info :ignore-list))))
4194 ;; List of elements or objects.
4195 ((not --type) (mapc --walk-tree --data))
4196 ;; Unconditionally enter parse trees.
4197 ((eq --type 'org-data)
4198 (mapc --walk-tree (org-element-contents --data)))
4200 ;; Check if TYPE is matching among TYPES. If so,
4201 ;; apply FUN to --DATA and accumulate return value
4202 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4203 (when (memq --type types)
4204 (let ((result (funcall fun --data)))
4205 (cond ((not result))
4206 (first-match (throw :--map-first-match result))
4207 (t (push result --acc)))))
4208 ;; If --DATA has a secondary string that can contain
4209 ;; objects with their type among TYPES, look inside.
4210 (when (and (eq --category 'objects) (not (stringp --data)))
4211 (dolist (p (cdr (assq --type
4212 org-element-secondary-value-alist)))
4213 (funcall --walk-tree (org-element-property p --data))))
4214 ;; If --DATA has any parsed affiliated keywords and
4215 ;; WITH-AFFILIATED is non-nil, look for objects in
4216 ;; them.
4217 (when (and with-affiliated
4218 (eq --category 'objects)
4219 (eq (org-element-class --data) 'element))
4220 (dolist (kwd-pair org-element--parsed-properties-alist)
4221 (let ((kwd (car kwd-pair))
4222 (value (org-element-property (cdr kwd-pair) --data)))
4223 ;; Pay attention to the type of parsed
4224 ;; keyword. In particular, preserve order for
4225 ;; multiple keywords.
4226 (cond
4227 ((not value))
4228 ((member kwd org-element-dual-keywords)
4229 (if (member kwd org-element-multiple-keywords)
4230 (dolist (line (reverse value))
4231 (funcall --walk-tree (cdr line))
4232 (funcall --walk-tree (car line)))
4233 (funcall --walk-tree (cdr value))
4234 (funcall --walk-tree (car value))))
4235 ((member kwd org-element-multiple-keywords)
4236 (mapc --walk-tree (reverse value)))
4237 (t (funcall --walk-tree value))))))
4238 ;; Determine if a recursion into --DATA is possible.
4239 (cond
4240 ;; --TYPE is explicitly removed from recursion.
4241 ((memq --type no-recursion))
4242 ;; --DATA has no contents.
4243 ((not (org-element-contents --data)))
4244 ;; Looking for greater elements but --DATA is
4245 ;; simply an element or an object.
4246 ((and (eq --category 'greater-elements)
4247 (not (memq --type org-element-greater-elements))))
4248 ;; Looking for elements but --DATA is an object.
4249 ((and (eq --category 'elements)
4250 (eq (org-element-class --data) 'object)))
4251 ;; In any other case, map contents.
4252 (t (mapc --walk-tree (org-element-contents --data))))))))))
4253 (catch :--map-first-match
4254 (funcall --walk-tree data)
4255 ;; Return value in a proper order.
4256 (nreverse --acc)))))
4257 (put 'org-element-map 'lisp-indent-function 2)
4259 ;; The following functions are internal parts of the parser.
4261 ;; The first one, `org-element--parse-elements' acts at the element's
4262 ;; level.
4264 ;; The second one, `org-element--parse-objects' applies on all objects
4265 ;; of a paragraph or a secondary string. It calls
4266 ;; `org-element--object-lex' to find the next object in the current
4267 ;; container.
4269 (defsubst org-element--next-mode (type parentp)
4270 "Return next special mode according to TYPE, or nil.
4271 TYPE is a symbol representing the type of an element or object
4272 containing next element if PARENTP is non-nil, or before it
4273 otherwise. Modes can be either `first-section', `item',
4274 `node-property', `planning', `property-drawer', `section',
4275 `table-row' or nil."
4276 (if parentp
4277 (pcase type
4278 (`headline 'section)
4279 (`inlinetask 'planning)
4280 (`plain-list 'item)
4281 (`property-drawer 'node-property)
4282 (`section 'planning)
4283 (`table 'table-row))
4284 (pcase type
4285 (`item 'item)
4286 (`node-property 'node-property)
4287 (`planning 'property-drawer)
4288 (`table-row 'table-row))))
4290 (defun org-element--parse-elements
4291 (beg end mode structure granularity visible-only acc)
4292 "Parse elements between BEG and END positions.
4294 MODE prioritizes some elements over the others. It can be set to
4295 `first-section', `section', `planning', `item', `node-property'
4296 or `table-row'.
4298 When value is `item', STRUCTURE will be used as the current list
4299 structure.
4301 GRANULARITY determines the depth of the recursion. See
4302 `org-element-parse-buffer' for more information.
4304 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4305 elements.
4307 Elements are accumulated into ACC."
4308 (save-excursion
4309 (goto-char beg)
4310 ;; Visible only: skip invisible parts at the beginning of the
4311 ;; element.
4312 (when (and visible-only (org-invisible-p2))
4313 (goto-char (min (1+ (org-find-visible)) end)))
4314 ;; When parsing only headlines, skip any text before first one.
4315 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4316 (org-with-limited-levels (outline-next-heading)))
4317 (let (elements)
4318 (while (< (point) end)
4319 ;; Find current element's type and parse it accordingly to
4320 ;; its category.
4321 (let* ((element (org-element--current-element
4322 end granularity mode structure))
4323 (type (org-element-type element))
4324 (cbeg (org-element-property :contents-begin element)))
4325 (goto-char (org-element-property :end element))
4326 ;; Visible only: skip invisible parts between siblings.
4327 (when (and visible-only (org-invisible-p2))
4328 (goto-char (min (1+ (org-find-visible)) end)))
4329 ;; Fill ELEMENT contents by side-effect.
4330 (cond
4331 ;; If element has no contents, don't modify it.
4332 ((not cbeg))
4333 ;; Greater element: parse it between `contents-begin' and
4334 ;; `contents-end'. Make sure GRANULARITY allows the
4335 ;; recursion, or ELEMENT is a headline, in which case going
4336 ;; inside is mandatory, in order to get sub-level headings.
4337 ((and (memq type org-element-greater-elements)
4338 (or (memq granularity '(element object nil))
4339 (and (eq granularity 'greater-element)
4340 (eq type 'section))
4341 (eq type 'headline)))
4342 (org-element--parse-elements
4343 cbeg (org-element-property :contents-end element)
4344 ;; Possibly switch to a special mode.
4345 (org-element--next-mode type t)
4346 (and (memq type '(item plain-list))
4347 (org-element-property :structure element))
4348 granularity visible-only element))
4349 ;; ELEMENT has contents. Parse objects inside, if
4350 ;; GRANULARITY allows it.
4351 ((memq granularity '(object nil))
4352 (org-element--parse-objects
4353 cbeg (org-element-property :contents-end element) element
4354 (org-element-restriction type))))
4355 (push (org-element-put-property element :parent acc) elements)
4356 ;; Update mode.
4357 (setq mode (org-element--next-mode type nil))))
4358 ;; Return result.
4359 (apply #'org-element-set-contents acc (nreverse elements)))))
4361 (defun org-element--object-lex (restriction)
4362 "Return next object in current buffer or nil.
4363 RESTRICTION is a list of object types, as symbols, that should be
4364 looked after. This function assumes that the buffer is narrowed
4365 to an appropriate container (e.g., a paragraph)."
4366 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4367 (let* ((start (point))
4368 (limit
4369 ;; Object regexp sometimes needs to have a peek at
4370 ;; a character ahead. Therefore, when there is a hard
4371 ;; limit, make it one more than the true beginning of the
4372 ;; radio target.
4373 (save-excursion
4374 (cond ((not org-target-link-regexp) nil)
4375 ((not (memq 'link restriction)) nil)
4376 ((progn
4377 (unless (bolp) (forward-char -1))
4378 (not (re-search-forward org-target-link-regexp nil t)))
4379 nil)
4380 ;; Since we moved backward, we do not want to
4381 ;; match again an hypothetical 1-character long
4382 ;; radio link before us. Realizing that this can
4383 ;; only happen if such a radio link starts at
4384 ;; beginning of line, we prevent this here.
4385 ((and (= start (1+ (line-beginning-position)))
4386 (= start (match-end 1)))
4387 (and (re-search-forward org-target-link-regexp nil t)
4388 (1+ (match-beginning 1))))
4389 (t (1+ (match-beginning 1))))))
4390 found)
4391 (save-excursion
4392 (while (and (not found)
4393 (re-search-forward org-element--object-regexp limit 'move))
4394 (goto-char (match-beginning 0))
4395 (let ((result (match-string 0)))
4396 (setq found
4397 (cond
4398 ((string-prefix-p "call_" result t)
4399 (and (memq 'inline-babel-call restriction)
4400 (org-element-inline-babel-call-parser)))
4401 ((string-prefix-p "src_" result t)
4402 (and (memq 'inline-src-block restriction)
4403 (org-element-inline-src-block-parser)))
4405 (pcase (char-after)
4406 (?^ (and (memq 'superscript restriction)
4407 (org-element-superscript-parser)))
4408 (?_ (or (and (memq 'subscript restriction)
4409 (org-element-subscript-parser))
4410 (and (memq 'underline restriction)
4411 (org-element-underline-parser))))
4412 (?* (and (memq 'bold restriction)
4413 (org-element-bold-parser)))
4414 (?/ (and (memq 'italic restriction)
4415 (org-element-italic-parser)))
4416 (?~ (and (memq 'code restriction)
4417 (org-element-code-parser)))
4418 (?= (and (memq 'verbatim restriction)
4419 (org-element-verbatim-parser)))
4420 (?+ (and (memq 'strike-through restriction)
4421 (org-element-strike-through-parser)))
4422 (?@ (and (memq 'export-snippet restriction)
4423 (org-element-export-snippet-parser)))
4424 (?{ (and (memq 'macro restriction)
4425 (org-element-macro-parser)))
4426 (?$ (and (memq 'latex-fragment restriction)
4427 (org-element-latex-fragment-parser)))
4429 (if (eq (aref result 1) ?<)
4430 (or (and (memq 'radio-target restriction)
4431 (org-element-radio-target-parser))
4432 (and (memq 'target restriction)
4433 (org-element-target-parser)))
4434 (or (and (memq 'timestamp restriction)
4435 (org-element-timestamp-parser))
4436 (and (memq 'link restriction)
4437 (org-element-link-parser)))))
4438 (?\\
4439 (if (eq (aref result 1) ?\\)
4440 (and (memq 'line-break restriction)
4441 (org-element-line-break-parser))
4442 (or (and (memq 'entity restriction)
4443 (org-element-entity-parser))
4444 (and (memq 'latex-fragment restriction)
4445 (org-element-latex-fragment-parser)))))
4446 (?\[
4447 (if (eq (aref result 1) ?\[)
4448 (and (memq 'link restriction)
4449 (org-element-link-parser))
4450 (or (and (memq 'footnote-reference restriction)
4451 (org-element-footnote-reference-parser))
4452 (and (memq 'timestamp restriction)
4453 (org-element-timestamp-parser))
4454 (and (memq 'statistics-cookie restriction)
4455 (org-element-statistics-cookie-parser)))))
4456 ;; This is probably a plain link.
4457 (_ (and (memq 'link restriction)
4458 (org-element-link-parser)))))))
4459 (or (eobp) (forward-char))))
4460 (cond (found)
4461 (limit (forward-char -1)
4462 (org-element-link-parser)) ;radio link
4463 (t nil))))))
4465 (defun org-element--parse-objects (beg end acc restriction &optional parent)
4466 "Parse objects between BEG and END and return recursive structure.
4468 Objects are accumulated in ACC. RESTRICTION is a list of object
4469 successors which are allowed in the current object.
4471 ACC becomes the parent for all parsed objects. However, if ACC
4472 is nil (i.e., a secondary string is being parsed) and optional
4473 argument PARENT is non-nil, use it as the parent for all objects.
4474 Eventually, if both ACC and PARENT are nil, the common parent is
4475 the list of objects itself."
4476 (save-excursion
4477 (save-restriction
4478 (narrow-to-region beg end)
4479 (goto-char (point-min))
4480 (let (next-object contents)
4481 (while (and (not (eobp))
4482 (setq next-object (org-element--object-lex restriction)))
4483 ;; Text before any object.
4484 (let ((obj-beg (org-element-property :begin next-object)))
4485 (unless (= (point) obj-beg)
4486 (let ((text (buffer-substring-no-properties (point) obj-beg)))
4487 (push (if acc (org-element-put-property text :parent acc) text)
4488 contents))))
4489 ;; Object...
4490 (let ((obj-end (org-element-property :end next-object))
4491 (cont-beg (org-element-property :contents-begin next-object)))
4492 (when acc (org-element-put-property next-object :parent acc))
4493 (push (if cont-beg
4494 ;; Fill contents of NEXT-OBJECT if possible.
4495 (org-element--parse-objects
4496 cont-beg
4497 (org-element-property :contents-end next-object)
4498 next-object
4499 (org-element-restriction next-object))
4500 next-object)
4501 contents)
4502 (goto-char obj-end)))
4503 ;; Text after last object.
4504 (unless (eobp)
4505 (let ((text (buffer-substring-no-properties (point) end)))
4506 (push (if acc (org-element-put-property text :parent acc) text)
4507 contents)))
4508 ;; Result. Set appropriate parent.
4509 (if acc (apply #'org-element-set-contents acc (nreverse contents))
4510 (let* ((contents (nreverse contents))
4511 (parent (or parent contents)))
4512 (dolist (datum contents contents)
4513 (org-element-put-property datum :parent parent))))))))
4517 ;;; Towards A Bijective Process
4519 ;; The parse tree obtained with `org-element-parse-buffer' is really
4520 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4521 ;; interpreted and expanded into a string with canonical Org syntax.
4522 ;; Hence `org-element-interpret-data'.
4524 ;; The function relies internally on
4525 ;; `org-element--interpret-affiliated-keywords'.
4527 ;;;###autoload
4528 (defun org-element-interpret-data (data)
4529 "Interpret DATA as Org syntax.
4530 DATA is a parse tree, an element, an object or a secondary string
4531 to interpret. Return Org syntax as a string."
4532 (letrec ((fun
4533 (lambda (data parent)
4534 (let* ((type (org-element-type data))
4535 ;; Find interpreter for current object or
4536 ;; element. If it doesn't exist (e.g. this is
4537 ;; a pseudo object or element), return contents,
4538 ;; if any.
4539 (interpret
4540 (let ((fun (intern
4541 (format "org-element-%s-interpreter" type))))
4542 (if (fboundp fun) fun (lambda (_ contents) contents))))
4543 (results
4544 (cond
4545 ;; Secondary string.
4546 ((not type)
4547 (mapconcat (lambda (obj) (funcall fun obj parent))
4548 data
4549 ""))
4550 ;; Full Org document.
4551 ((eq type 'org-data)
4552 (mapconcat (lambda (obj) (funcall fun obj parent))
4553 (org-element-contents data)
4554 ""))
4555 ;; Plain text: return it.
4556 ((stringp data) data)
4557 ;; Element or object without contents.
4558 ((not (org-element-contents data))
4559 (funcall interpret data nil))
4560 ;; Element or object with contents.
4562 (funcall
4563 interpret
4564 data
4565 ;; Recursively interpret contents.
4566 (mapconcat
4567 (lambda (datum) (funcall fun datum data))
4568 (org-element-contents
4569 (if (not (memq type '(paragraph verse-block)))
4570 data
4571 ;; Fix indentation of elements containing
4572 ;; objects. We ignore `table-row'
4573 ;; elements as they are one line long
4574 ;; anyway.
4575 (org-element-normalize-contents
4576 data
4577 ;; When normalizing first paragraph of
4578 ;; an item or a footnote-definition,
4579 ;; ignore first line's indentation.
4580 (and (eq type 'paragraph)
4581 (memq (org-element-type parent)
4582 '(footnote-definition item))
4583 (eq data
4584 (car (org-element-contents parent)))))))
4585 ""))))))
4586 (if (memq type '(org-data plain-text nil)) results
4587 ;; Build white spaces. If no `:post-blank' property
4588 ;; is specified, assume its value is 0.
4589 (let ((blank (or (org-element-property :post-blank data) 0)))
4590 (if (eq (org-element-class data parent) 'object)
4591 (concat results (make-string blank ?\s))
4592 (concat (org-element--interpret-affiliated-keywords data)
4593 (org-element-normalize-string results)
4594 (make-string blank ?\n)))))))))
4595 (funcall fun data nil)))
4597 (defun org-element--interpret-affiliated-keywords (element)
4598 "Return ELEMENT's affiliated keywords as Org syntax.
4599 If there is no affiliated keyword, return the empty string."
4600 (let ((keyword-to-org
4601 (function
4602 (lambda (key value)
4603 (let (dual)
4604 (when (member key org-element-dual-keywords)
4605 (setq dual (cdr value) value (car value)))
4606 (concat "#+" key
4607 (and dual
4608 (format "[%s]" (org-element-interpret-data dual)))
4609 ": "
4610 (if (member key org-element-parsed-keywords)
4611 (org-element-interpret-data value)
4612 value)
4613 "\n"))))))
4614 (mapconcat
4615 (lambda (prop)
4616 (let ((value (org-element-property prop element))
4617 (keyword (upcase (substring (symbol-name prop) 1))))
4618 (when value
4619 (if (or (member keyword org-element-multiple-keywords)
4620 ;; All attribute keywords can have multiple lines.
4621 (string-match "^ATTR_" keyword))
4622 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4623 (reverse value)
4625 (funcall keyword-to-org keyword value)))))
4626 ;; List all ELEMENT's properties matching an attribute line or an
4627 ;; affiliated keyword, but ignore translated keywords since they
4628 ;; cannot belong to the property list.
4629 (cl-loop for prop in (nth 1 element) by 'cddr
4630 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4631 (or (string-match "^ATTR_" keyword)
4632 (and
4633 (member keyword org-element-affiliated-keywords)
4634 (not (assoc keyword
4635 org-element-keyword-translation-alist)))))
4636 collect prop)
4637 "")))
4639 ;; Because interpretation of the parse tree must return the same
4640 ;; number of blank lines between elements and the same number of white
4641 ;; space after objects, some special care must be given to white
4642 ;; spaces.
4644 ;; The first function, `org-element-normalize-string', ensures any
4645 ;; string different from the empty string will end with a single
4646 ;; newline character.
4648 ;; The second function, `org-element-normalize-contents', removes
4649 ;; global indentation from the contents of the current element.
4651 (defun org-element-normalize-string (s)
4652 "Ensure string S ends with a single newline character.
4654 If S isn't a string return it unchanged. If S is the empty
4655 string, return it. Otherwise, return a new string with a single
4656 newline character at its end."
4657 (cond
4658 ((not (stringp s)) s)
4659 ((string= "" s) "")
4660 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4661 (replace-match "\n" nil nil s)))))
4663 (defun org-element-normalize-contents (element &optional ignore-first)
4664 "Normalize plain text in ELEMENT's contents.
4666 ELEMENT must only contain plain text and objects.
4668 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4669 indentation to compute maximal common indentation.
4671 Return the normalized element that is element with global
4672 indentation removed from its contents."
4673 (letrec ((find-min-ind
4674 ;; Return minimal common indentation within BLOB. This is
4675 ;; done by walking recursively BLOB and updating MIN-IND
4676 ;; along the way. FIRST-FLAG is non-nil when the next
4677 ;; object is expected to be a string that doesn't start
4678 ;; with a newline character. It happens for strings at
4679 ;; the beginnings of the contents or right after a line
4680 ;; break.
4681 (lambda (blob first-flag min-ind)
4682 (dolist (datum (org-element-contents blob) min-ind)
4683 (when first-flag
4684 (setq first-flag nil)
4685 (cond
4686 ;; Objects cannot start with spaces: in this
4687 ;; case, indentation is 0.
4688 ((not (stringp datum)) (throw :zero 0))
4689 ((not (string-match
4690 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
4691 (throw :zero 0))
4692 ((equal (match-string 2 datum) "\n")
4693 (put-text-property
4694 (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
4696 (let ((i (string-width (match-string 1 datum))))
4697 (put-text-property
4698 (match-beginning 1) (match-end 1) 'org-ind i datum)
4699 (setq min-ind (min i min-ind))))))
4700 (cond
4701 ((stringp datum)
4702 (let ((s 0))
4703 (while (string-match
4704 "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
4705 (setq s (match-end 1))
4706 (cond
4707 ((equal (match-string 1 datum) "")
4708 (unless (member (match-string 2 datum) '("" "\n"))
4709 (throw :zero 0)))
4710 ((equal (match-string 2 datum) "\n")
4711 (put-text-property (match-beginning 1) (match-end 1)
4712 'org-ind 'empty datum))
4714 (let ((i (string-width (match-string 1 datum))))
4715 (put-text-property (match-beginning 1) (match-end 1)
4716 'org-ind i datum)
4717 (setq min-ind (min i min-ind))))))))
4718 ((eq (org-element-type datum) 'line-break)
4719 (setq first-flag t))
4720 ((memq (org-element-type datum) org-element-recursive-objects)
4721 (setq min-ind
4722 (funcall find-min-ind datum first-flag min-ind)))))))
4723 (min-ind
4724 (catch :zero
4725 (funcall find-min-ind
4726 element (not ignore-first) most-positive-fixnum))))
4727 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4728 ;; Build ELEMENT back, replacing each string with the same
4729 ;; string minus common indentation.
4730 (letrec ((build
4731 (lambda (datum)
4732 ;; Return DATUM with all its strings indentation
4733 ;; shortened from MIN-IND white spaces.
4734 (setcdr
4735 (cdr datum)
4736 (mapcar
4737 (lambda (object)
4738 (cond
4739 ((stringp object)
4740 (with-temp-buffer
4741 (insert object)
4742 (let ((s (point-min)))
4743 (while (setq s (text-property-not-all
4744 s (point-max) 'org-ind nil))
4745 (goto-char s)
4746 (let ((i (get-text-property s 'org-ind)))
4747 (delete-region s (progn
4748 (skip-chars-forward " \t")
4749 (point)))
4750 (when (integerp i) (indent-to (- i min-ind))))))
4751 (buffer-string)))
4752 ((memq (org-element-type object)
4753 org-element-recursive-objects)
4754 (funcall build object))
4755 (t object)))
4756 (org-element-contents datum)))
4757 datum)))
4758 (funcall build element)))))
4762 ;;; Cache
4764 ;; Implement a caching mechanism for `org-element-at-point' and
4765 ;; `org-element-context', which see.
4767 ;; A single public function is provided: `org-element-cache-reset'.
4769 ;; Cache is enabled by default, but can be disabled globally with
4770 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4771 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4772 ;; can be tweaked to control caching behaviour.
4774 ;; Internally, parsed elements are stored in an AVL tree,
4775 ;; `org-element--cache'. This tree is updated lazily: whenever
4776 ;; a change happens to the buffer, a synchronization request is
4777 ;; registered in `org-element--cache-sync-requests' (see
4778 ;; `org-element--cache-submit-request'). During idle time, requests
4779 ;; are processed by `org-element--cache-sync'. Synchronization also
4780 ;; happens when an element is required from the cache. In this case,
4781 ;; the process stops as soon as the needed element is up-to-date.
4783 ;; A synchronization request can only apply on a synchronized part of
4784 ;; the cache. Therefore, the cache is updated at least to the
4785 ;; location where the new request applies. Thus, requests are ordered
4786 ;; from left to right and all elements starting before the first
4787 ;; request are correct. This property is used by functions like
4788 ;; `org-element--cache-find' to retrieve elements in the part of the
4789 ;; cache that can be trusted.
4791 ;; A request applies to every element, starting from its original
4792 ;; location (or key, see below). When a request is processed, it
4793 ;; moves forward and may collide the next one. In this case, both
4794 ;; requests are merged into a new one that starts from that element.
4795 ;; As a consequence, the whole synchronization complexity does not
4796 ;; depend on the number of pending requests, but on the number of
4797 ;; elements the very first request will be applied on.
4799 ;; Elements cannot be accessed through their beginning position, which
4800 ;; may or may not be up-to-date. Instead, each element in the tree is
4801 ;; associated to a key, obtained with `org-element--cache-key'. This
4802 ;; mechanism is robust enough to preserve total order among elements
4803 ;; even when the tree is only partially synchronized.
4806 (defvar org-element-use-cache nil
4807 "Non-nil when Org parser should cache its results.
4809 WARNING: for the time being, using cache sometimes triggers
4810 freezes. Therefore, it is disabled by default. Activate it if
4811 you want to help debugging the issue.")
4813 (defvar org-element-cache-sync-idle-time 0.6
4814 "Length, in seconds, of idle time before syncing cache.")
4816 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4817 "Maximum duration, as a time value, for a cache synchronization.
4818 If the synchronization is not over after this delay, the process
4819 pauses and resumes after `org-element-cache-sync-break'
4820 seconds.")
4822 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4823 "Duration, as a time value, of the pause between synchronizations.
4824 See `org-element-cache-sync-duration' for more information.")
4827 ;;;; Data Structure
4829 (defvar org-element--cache nil
4830 "AVL tree used to cache elements.
4831 Each node of the tree contains an element. Comparison is done
4832 with `org-element--cache-compare'. This cache is used in
4833 `org-element-at-point'.")
4835 (defvar org-element--cache-sync-requests nil
4836 "List of pending synchronization requests.
4838 A request is a vector with the following pattern:
4840 \[NEXT BEG END OFFSET PARENT PHASE]
4842 Processing a synchronization request consists of three phases:
4844 0. Delete modified elements,
4845 1. Fill missing area in cache,
4846 2. Shift positions and re-parent elements after the changes.
4848 During phase 0, NEXT is the key of the first element to be
4849 removed, BEG and END is buffer position delimiting the
4850 modifications. Elements starting between them (inclusive) are
4851 removed. So are elements whose parent is removed. PARENT, when
4852 non-nil, is the parent of the first element to be removed.
4854 During phase 1, NEXT is the key of the next known element in
4855 cache and BEG its beginning position. Parse buffer between that
4856 element and the one before it in order to determine the parent of
4857 the next element. Set PARENT to the element containing NEXT.
4859 During phase 2, NEXT is the key of the next element to shift in
4860 the parse tree. All elements starting from this one have their
4861 properties relatives to buffer positions shifted by integer
4862 OFFSET and, if they belong to element PARENT, are adopted by it.
4864 PHASE specifies the phase number, as an integer.")
4866 (defvar org-element--cache-sync-timer nil
4867 "Timer used for cache synchronization.")
4869 (defvar org-element--cache-sync-keys nil
4870 "Hash table used to store keys during synchronization.
4871 See `org-element--cache-key' for more information.")
4873 (defsubst org-element--cache-key (element)
4874 "Return a unique key for ELEMENT in cache tree.
4876 Keys are used to keep a total order among elements in the cache.
4877 Comparison is done with `org-element--cache-key-less-p'.
4879 When no synchronization is taking place, a key is simply the
4880 beginning position of the element, or that position plus one in
4881 the case of an first item (respectively row) in
4882 a list (respectively a table).
4884 During a synchronization, the key is the one the element had when
4885 the cache was synchronized for the last time. Elements added to
4886 cache during the synchronization get a new key generated with
4887 `org-element--cache-generate-key'.
4889 Such keys are stored in `org-element--cache-sync-keys'. The hash
4890 table is cleared once the synchronization is complete."
4891 (or (gethash element org-element--cache-sync-keys)
4892 (let* ((begin (org-element-property :begin element))
4893 ;; Increase beginning position of items (respectively
4894 ;; table rows) by one, so the first item can get
4895 ;; a different key from its parent list (respectively
4896 ;; table).
4897 (key (if (memq (org-element-type element) '(item table-row))
4898 (1+ begin)
4899 begin)))
4900 (if org-element--cache-sync-requests
4901 (puthash element key org-element--cache-sync-keys)
4902 key))))
4904 (defun org-element--cache-generate-key (lower upper)
4905 "Generate a key between LOWER and UPPER.
4907 LOWER and UPPER are integers or lists, possibly empty.
4909 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4910 a unique key, as an integer or a list of integers, according to
4911 the following rules:
4913 - LOWER and UPPER are compared level-wise until values differ.
4915 - If, at a given level, LOWER and UPPER differ from more than
4916 2, the new key shares all the levels above with LOWER and
4917 gets a new level. Its value is the mean between LOWER and
4918 UPPER:
4920 (1 2) + (1 4) --> (1 3)
4922 - If LOWER has no value to compare with, it is assumed that its
4923 value is `most-negative-fixnum'. E.g.,
4925 (1 1) + (1 1 2)
4927 is equivalent to
4929 (1 1 m) + (1 1 2)
4931 where m is `most-negative-fixnum'. Likewise, if UPPER is
4932 short of levels, the current value is `most-positive-fixnum'.
4934 - If they differ from only one, the new key inherits from
4935 current LOWER level and fork it at the next level. E.g.,
4937 (2 1) + (3 3)
4939 is equivalent to
4941 (2 1) + (2 M)
4943 where M is `most-positive-fixnum'.
4945 - If the key is only one level long, it is returned as an
4946 integer:
4948 (1 2) + (3 2) --> 2
4950 When they are not equals, the function assumes that LOWER is
4951 lesser than UPPER, per `org-element--cache-key-less-p'."
4952 (if (equal lower upper) lower
4953 (let ((lower (if (integerp lower) (list lower) lower))
4954 (upper (if (integerp upper) (list upper) upper))
4955 skip-upper key)
4956 (catch 'exit
4957 (while t
4958 (let ((min (or (car lower) most-negative-fixnum))
4959 (max (cond (skip-upper most-positive-fixnum)
4960 ((car upper))
4961 (t most-positive-fixnum))))
4962 (if (< (1+ min) max)
4963 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4964 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4965 (when (and (< min max) (not skip-upper))
4966 ;; When at a given level, LOWER and UPPER differ from
4967 ;; 1, ignore UPPER altogether. Instead create a key
4968 ;; between LOWER and the greatest key with the same
4969 ;; prefix as LOWER so far.
4970 (setq skip-upper t))
4971 (push min key)
4972 (setq lower (cdr lower) upper (cdr upper)))))))))
4974 (defsubst org-element--cache-key-less-p (a b)
4975 "Non-nil if key A is less than key B.
4976 A and B are either integers or lists of integers, as returned by
4977 `org-element--cache-key'."
4978 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4979 (if (integerp b) (< (car a) b)
4980 (catch 'exit
4981 (while (and a b)
4982 (cond ((car-less-than-car a b) (throw 'exit t))
4983 ((car-less-than-car b a) (throw 'exit nil))
4984 (t (setq a (cdr a) b (cdr b)))))
4985 ;; If A is empty, either keys are equal (B is also empty) and
4986 ;; we return nil, or A is lesser than B (B is longer) and we
4987 ;; return a non-nil value.
4989 ;; If A is not empty, B is necessarily empty and A is greater
4990 ;; than B (A is longer). Therefore, return nil.
4991 (and (null a) b)))))
4993 (defun org-element--cache-compare (a b)
4994 "Non-nil when element A is located before element B."
4995 (org-element--cache-key-less-p (org-element--cache-key a)
4996 (org-element--cache-key b)))
4998 (defsubst org-element--cache-root ()
4999 "Return root value in cache.
5000 This function assumes `org-element--cache' is a valid AVL tree."
5001 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
5004 ;;;; Tools
5006 (defsubst org-element--cache-active-p ()
5007 "Non-nil when cache is active in current buffer."
5008 (and org-element-use-cache
5009 org-element--cache
5010 (derived-mode-p 'org-mode)))
5012 (defun org-element--cache-find (pos &optional side)
5013 "Find element in cache starting at POS or before.
5015 POS refers to a buffer position.
5017 When optional argument SIDE is non-nil, the function checks for
5018 elements starting at or past POS instead. If SIDE is `both', the
5019 function returns a cons cell where car is the first element
5020 starting at or before POS and cdr the first element starting
5021 after POS.
5023 The function can only find elements in the synchronized part of
5024 the cache."
5025 (let ((limit (and org-element--cache-sync-requests
5026 (aref (car org-element--cache-sync-requests) 0)))
5027 (node (org-element--cache-root))
5028 lower upper)
5029 (while node
5030 (let* ((element (avl-tree--node-data node))
5031 (begin (org-element-property :begin element)))
5032 (cond
5033 ((and limit
5034 (not (org-element--cache-key-less-p
5035 (org-element--cache-key element) limit)))
5036 (setq node (avl-tree--node-left node)))
5037 ((> begin pos)
5038 (setq upper element
5039 node (avl-tree--node-left node)))
5040 ((< begin pos)
5041 (setq lower element
5042 node (avl-tree--node-right node)))
5043 ;; We found an element in cache starting at POS. If `side'
5044 ;; is `both' we also want the next one in order to generate
5045 ;; a key in-between.
5047 ;; If the element is the first row or item in a table or
5048 ;; a plain list, we always return the table or the plain
5049 ;; list.
5051 ;; In any other case, we return the element found.
5052 ((eq side 'both)
5053 (setq lower element)
5054 (setq node (avl-tree--node-right node)))
5055 ((and (memq (org-element-type element) '(item table-row))
5056 (let ((parent (org-element-property :parent element)))
5057 (and (= (org-element-property :begin element)
5058 (org-element-property :contents-begin parent))
5059 (setq node nil
5060 lower parent
5061 upper parent)))))
5063 (setq node nil
5064 lower element
5065 upper element)))))
5066 (pcase side
5067 (`both (cons lower upper))
5068 (`nil lower)
5069 (_ upper))))
5071 (defun org-element--cache-put (element)
5072 "Store ELEMENT in current buffer's cache, if allowed."
5073 (when (org-element--cache-active-p)
5074 (when org-element--cache-sync-requests
5075 ;; During synchronization, first build an appropriate key for
5076 ;; the new element so `avl-tree-enter' can insert it at the
5077 ;; right spot in the cache.
5078 (let ((keys (org-element--cache-find
5079 (org-element-property :begin element) 'both)))
5080 (puthash element
5081 (org-element--cache-generate-key
5082 (and (car keys) (org-element--cache-key (car keys)))
5083 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5084 (org-element--cache-sync-requests
5085 (aref (car org-element--cache-sync-requests) 0))))
5086 org-element--cache-sync-keys)))
5087 (avl-tree-enter org-element--cache element)))
5089 (defsubst org-element--cache-remove (element)
5090 "Remove ELEMENT from cache.
5091 Assume ELEMENT belongs to cache and that a cache is active."
5092 (avl-tree-delete org-element--cache element))
5095 ;;;; Synchronization
5097 (defsubst org-element--cache-set-timer (buffer)
5098 "Set idle timer for cache synchronization in BUFFER."
5099 (when org-element--cache-sync-timer
5100 (cancel-timer org-element--cache-sync-timer))
5101 (setq org-element--cache-sync-timer
5102 (run-with-idle-timer
5103 (let ((idle (current-idle-time)))
5104 (if idle (time-add idle org-element-cache-sync-break)
5105 org-element-cache-sync-idle-time))
5107 #'org-element--cache-sync
5108 buffer)))
5110 (defsubst org-element--cache-interrupt-p (time-limit)
5111 "Non-nil when synchronization process should be interrupted.
5112 TIME-LIMIT is a time value or nil."
5113 (and time-limit
5114 (or (input-pending-p)
5115 (time-less-p time-limit (current-time)))))
5117 (defsubst org-element--cache-shift-positions (element offset &optional props)
5118 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5120 Properties containing buffer positions are `:begin', `:end',
5121 `:contents-begin', `:contents-end' and `:structure'. When
5122 optional argument PROPS is a list of keywords, only shift
5123 properties provided in that list.
5125 Properties are modified by side-effect."
5126 (let ((properties (nth 1 element)))
5127 ;; Shift `:structure' property for the first plain list only: it
5128 ;; is the only one that really matters and it prevents from
5129 ;; shifting it more than once.
5130 (when (and (or (not props) (memq :structure props))
5131 (eq (org-element-type element) 'plain-list)
5132 (not (eq (org-element-type (plist-get properties :parent))
5133 'item)))
5134 (dolist (item (plist-get properties :structure))
5135 (cl-incf (car item) offset)
5136 (cl-incf (nth 6 item) offset)))
5137 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5138 (let ((value (and (or (not props) (memq key props))
5139 (plist-get properties key))))
5140 (and value (plist-put properties key (+ offset value)))))))
5142 (defun org-element--cache-sync (buffer &optional threshold future-change)
5143 "Synchronize cache with recent modification in BUFFER.
5145 When optional argument THRESHOLD is non-nil, do the
5146 synchronization for all elements starting before or at threshold,
5147 then exit. Otherwise, synchronize cache for as long as
5148 `org-element-cache-sync-duration' or until Emacs leaves idle
5149 state.
5151 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5152 not registered yet in the cache are going to happen. It is used
5153 in `org-element--cache-submit-request', where cache is partially
5154 updated before current modification are actually submitted."
5155 (when (buffer-live-p buffer)
5156 (with-current-buffer buffer
5157 (let ((inhibit-quit t) request next)
5158 (when org-element--cache-sync-timer
5159 (cancel-timer org-element--cache-sync-timer))
5160 (catch 'interrupt
5161 (while org-element--cache-sync-requests
5162 (setq request (car org-element--cache-sync-requests)
5163 next (nth 1 org-element--cache-sync-requests))
5164 (org-element--cache-process-request
5165 request
5166 (and next (aref next 0))
5167 threshold
5168 (and (not threshold)
5169 (time-add (current-time)
5170 org-element-cache-sync-duration))
5171 future-change)
5172 ;; Request processed. Merge current and next offsets and
5173 ;; transfer ending position.
5174 (when next
5175 (cl-incf (aref next 3) (aref request 3))
5176 (aset next 2 (aref request 2)))
5177 (setq org-element--cache-sync-requests
5178 (cdr org-element--cache-sync-requests))))
5179 ;; If more requests are awaiting, set idle timer accordingly.
5180 ;; Otherwise, reset keys.
5181 (if org-element--cache-sync-requests
5182 (org-element--cache-set-timer buffer)
5183 (clrhash org-element--cache-sync-keys))))))
5185 (defun org-element--cache-process-request
5186 (request next threshold time-limit future-change)
5187 "Process synchronization REQUEST for all entries before NEXT.
5189 REQUEST is a vector, built by `org-element--cache-submit-request'.
5191 NEXT is a cache key, as returned by `org-element--cache-key'.
5193 When non-nil, THRESHOLD is a buffer position. Synchronization
5194 stops as soon as a shifted element begins after it.
5196 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5197 after this time or when Emacs exits idle state.
5199 When non-nil, FUTURE-CHANGE is a buffer position where changes
5200 not registered yet in the cache are going to happen. See
5201 `org-element--cache-submit-request' for more information.
5203 Throw `interrupt' if the process stops before completing the
5204 request."
5205 (catch 'quit
5206 (when (= (aref request 5) 0)
5207 ;; Phase 0.
5209 ;; Delete all elements starting after BEG, but not after buffer
5210 ;; position END or past element with key NEXT. Also delete
5211 ;; elements contained within a previously removed element
5212 ;; (stored in `last-container').
5214 ;; At each iteration, we start again at tree root since
5215 ;; a deletion modifies structure of the balanced tree.
5216 (catch 'end-phase
5217 (while t
5218 (when (org-element--cache-interrupt-p time-limit)
5219 (throw 'interrupt nil))
5220 ;; Find first element in cache with key BEG or after it.
5221 (let ((beg (aref request 0))
5222 (end (aref request 2))
5223 (node (org-element--cache-root))
5224 data data-key last-container)
5225 (while node
5226 (let* ((element (avl-tree--node-data node))
5227 (key (org-element--cache-key element)))
5228 (cond
5229 ((org-element--cache-key-less-p key beg)
5230 (setq node (avl-tree--node-right node)))
5231 ((org-element--cache-key-less-p beg key)
5232 (setq data element
5233 data-key key
5234 node (avl-tree--node-left node)))
5235 (t (setq data element
5236 data-key key
5237 node nil)))))
5238 (if data
5239 (let ((pos (org-element-property :begin data)))
5240 (if (if (or (not next)
5241 (org-element--cache-key-less-p data-key next))
5242 (<= pos end)
5243 (and last-container
5244 (let ((up data))
5245 (while (and up (not (eq up last-container)))
5246 (setq up (org-element-property :parent up)))
5247 up)))
5248 (progn (when (and (not last-container)
5249 (> (org-element-property :end data)
5250 end))
5251 (setq last-container data))
5252 (org-element--cache-remove data))
5253 (aset request 0 data-key)
5254 (aset request 1 pos)
5255 (aset request 5 1)
5256 (throw 'end-phase nil)))
5257 ;; No element starting after modifications left in
5258 ;; cache: further processing is futile.
5259 (throw 'quit t))))))
5260 (when (= (aref request 5) 1)
5261 ;; Phase 1.
5263 ;; Phase 0 left a hole in the cache. Some elements after it
5264 ;; could have parents within. For example, in the following
5265 ;; buffer:
5267 ;; - item
5270 ;; Paragraph1
5272 ;; Paragraph2
5274 ;; if we remove a blank line between "item" and "Paragraph1",
5275 ;; everything down to "Paragraph2" is removed from cache. But
5276 ;; the paragraph now belongs to the list, and its `:parent'
5277 ;; property no longer is accurate.
5279 ;; Therefore we need to parse again elements in the hole, or at
5280 ;; least in its last section, so that we can re-parent
5281 ;; subsequent elements, during phase 2.
5283 ;; Note that we only need to get the parent from the first
5284 ;; element in cache after the hole.
5286 ;; When next key is lesser or equal to the current one, delegate
5287 ;; phase 1 processing to next request in order to preserve key
5288 ;; order among requests.
5289 (let ((key (aref request 0)))
5290 (when (and next (not (org-element--cache-key-less-p key next)))
5291 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5292 (aset next-request 0 key)
5293 (aset next-request 1 (aref request 1))
5294 (aset next-request 5 1))
5295 (throw 'quit t)))
5296 ;; Next element will start at its beginning position plus
5297 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5298 ;; contains the real beginning position of the first element to
5299 ;; shift and re-parent.
5300 (let ((limit (+ (aref request 1) (aref request 3))))
5301 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5302 ((and future-change (>= limit future-change))
5303 ;; Changes are going to happen around this element and
5304 ;; they will trigger another phase 1 request. Skip the
5305 ;; current one.
5306 (aset request 5 2))
5308 (let ((parent (org-element--parse-to limit t time-limit)))
5309 (aset request 4 parent)
5310 (aset request 5 2))))))
5311 ;; Phase 2.
5313 ;; Shift all elements starting from key START, but before NEXT, by
5314 ;; OFFSET, and re-parent them when appropriate.
5316 ;; Elements are modified by side-effect so the tree structure
5317 ;; remains intact.
5319 ;; Once THRESHOLD, if any, is reached, or once there is an input
5320 ;; pending, exit. Before leaving, the current synchronization
5321 ;; request is updated.
5322 (let ((start (aref request 0))
5323 (offset (aref request 3))
5324 (parent (aref request 4))
5325 (node (org-element--cache-root))
5326 (stack (list nil))
5327 (leftp t)
5328 exit-flag)
5329 ;; No re-parenting nor shifting planned: request is over.
5330 (when (and (not parent) (zerop offset)) (throw 'quit t))
5331 (while node
5332 (let* ((data (avl-tree--node-data node))
5333 (key (org-element--cache-key data)))
5334 (if (and leftp (avl-tree--node-left node)
5335 (not (org-element--cache-key-less-p key start)))
5336 (progn (push node stack)
5337 (setq node (avl-tree--node-left node)))
5338 (unless (org-element--cache-key-less-p key start)
5339 ;; We reached NEXT. Request is complete.
5340 (when (equal key next) (throw 'quit t))
5341 ;; Handle interruption request. Update current request.
5342 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5343 (aset request 0 key)
5344 (aset request 4 parent)
5345 (throw 'interrupt nil))
5346 ;; Shift element.
5347 (unless (zerop offset)
5348 (org-element--cache-shift-positions data offset))
5349 (let ((begin (org-element-property :begin data)))
5350 ;; Update PARENT and re-parent DATA, only when
5351 ;; necessary. Propagate new structures for lists.
5352 (while (and parent
5353 (<= (org-element-property :end parent) begin))
5354 (setq parent (org-element-property :parent parent)))
5355 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5356 ((and parent
5357 (let ((p (org-element-property :parent data)))
5358 (or (not p)
5359 (< (org-element-property :begin p)
5360 (org-element-property :begin parent)))))
5361 (org-element-put-property data :parent parent)
5362 (let ((s (org-element-property :structure parent)))
5363 (when (and s (org-element-property :structure data))
5364 (org-element-put-property data :structure s)))))
5365 ;; Cache is up-to-date past THRESHOLD. Request
5366 ;; interruption.
5367 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5368 (setq node (if (setq leftp (avl-tree--node-right node))
5369 (avl-tree--node-right node)
5370 (pop stack))))))
5371 ;; We reached end of tree: synchronization complete.
5372 t)))
5374 (defun org-element--parse-to (pos &optional syncp time-limit)
5375 "Parse elements in current section, down to POS.
5377 Start parsing from the closest between the last known element in
5378 cache or headline above. Return the smallest element containing
5379 POS.
5381 When optional argument SYNCP is non-nil, return the parent of the
5382 element containing POS instead. In that case, it is also
5383 possible to provide TIME-LIMIT, which is a time value specifying
5384 when the parsing should stop. The function throws `interrupt' if
5385 the process stopped before finding the expected result."
5386 (catch 'exit
5387 (org-with-wide-buffer
5388 (goto-char pos)
5389 (let* ((cached (and (org-element--cache-active-p)
5390 (org-element--cache-find pos nil)))
5391 (begin (org-element-property :begin cached))
5392 element next mode)
5393 (cond
5394 ;; Nothing in cache before point: start parsing from first
5395 ;; element following headline above, or first element in
5396 ;; buffer.
5397 ((not cached)
5398 (when (org-with-limited-levels (outline-previous-heading))
5399 (setq mode 'planning)
5400 (forward-line))
5401 (skip-chars-forward " \r\t\n")
5402 (beginning-of-line))
5403 ;; Cache returned exact match: return it.
5404 ((= pos begin)
5405 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5406 ;; There's a headline between cached value and POS: cached
5407 ;; value is invalid. Start parsing from first element
5408 ;; following the headline.
5409 ((re-search-backward
5410 (org-with-limited-levels org-outline-regexp-bol) begin t)
5411 (forward-line)
5412 (skip-chars-forward " \r\t\n")
5413 (beginning-of-line)
5414 (setq mode 'planning))
5415 ;; Check if CACHED or any of its ancestors contain point.
5417 ;; If there is such an element, we inspect it in order to know
5418 ;; if we return it or if we need to parse its contents.
5419 ;; Otherwise, we just start parsing from current location,
5420 ;; which is right after the top-most element containing
5421 ;; CACHED.
5423 ;; As a special case, if POS is at the end of the buffer, we
5424 ;; want to return the innermost element ending there.
5426 ;; Also, if we find an ancestor and discover that we need to
5427 ;; parse its contents, make sure we don't start from
5428 ;; `:contents-begin', as we would otherwise go past CACHED
5429 ;; again. Instead, in that situation, we will resume parsing
5430 ;; from NEXT, which is located after CACHED or its higher
5431 ;; ancestor not containing point.
5433 (let ((up cached)
5434 (pos (if (= (point-max) pos) (1- pos) pos)))
5435 (goto-char (or (org-element-property :contents-begin cached) begin))
5436 (while (let ((end (org-element-property :end up)))
5437 (and (<= end pos)
5438 (goto-char end)
5439 (setq up (org-element-property :parent up)))))
5440 (cond ((not up))
5441 ((eobp) (setq element up))
5442 (t (setq element up next (point)))))))
5443 ;; Parse successively each element until we reach POS.
5444 (let ((end (or (org-element-property :end element)
5445 (save-excursion
5446 (org-with-limited-levels (outline-next-heading))
5447 (point))))
5448 (parent element))
5449 (while t
5450 (when syncp
5451 (cond ((= (point) pos) (throw 'exit parent))
5452 ((org-element--cache-interrupt-p time-limit)
5453 (throw 'interrupt nil))))
5454 (unless element
5455 (setq element (org-element--current-element
5456 end 'element mode
5457 (org-element-property :structure parent)))
5458 (org-element-put-property element :parent parent)
5459 (org-element--cache-put element))
5460 (let ((elem-end (org-element-property :end element))
5461 (type (org-element-type element)))
5462 (cond
5463 ;; Skip any element ending before point. Also skip
5464 ;; element ending at point (unless it is also the end of
5465 ;; buffer) since we're sure that another element begins
5466 ;; after it.
5467 ((and (<= elem-end pos) (/= (point-max) elem-end))
5468 (goto-char elem-end)
5469 (setq mode (org-element--next-mode type nil)))
5470 ;; A non-greater element contains point: return it.
5471 ((not (memq type org-element-greater-elements))
5472 (throw 'exit element))
5473 ;; Otherwise, we have to decide if ELEMENT really
5474 ;; contains POS. In that case we start parsing from
5475 ;; contents' beginning.
5477 ;; If POS is at contents' beginning but it is also at
5478 ;; the beginning of the first item in a list or a table.
5479 ;; In that case, we need to create an anchor for that
5480 ;; list or table, so return it.
5482 ;; Also, if POS is at the end of the buffer, no element
5483 ;; can start after it, but more than one may end there.
5484 ;; Arbitrarily, we choose to return the innermost of
5485 ;; such elements.
5486 ((let ((cbeg (org-element-property :contents-begin element))
5487 (cend (org-element-property :contents-end element)))
5488 (when (or syncp
5489 (and cbeg cend
5490 (or (< cbeg pos)
5491 (and (= cbeg pos)
5492 (not (memq type '(plain-list table)))))
5493 (or (> cend pos)
5494 (and (= cend pos) (= (point-max) pos)))))
5495 (goto-char (or next cbeg))
5496 (setq next nil
5497 mode (org-element--next-mode type t)
5498 parent element
5499 end cend))))
5500 ;; Otherwise, return ELEMENT as it is the smallest
5501 ;; element containing POS.
5502 (t (throw 'exit element))))
5503 (setq element nil)))))))
5506 ;;;; Staging Buffer Changes
5508 (defconst org-element--cache-sensitive-re
5509 (concat
5510 org-outline-regexp-bol "\\|"
5511 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5512 "^[ \t]*\\(?:"
5513 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5514 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5515 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5516 "\\)")
5517 "Regexp matching a sensitive line, structure wise.
5518 A sensitive line is a headline, inlinetask, block, drawer, or
5519 latex-environment boundary. When such a line is modified,
5520 structure changes in the document may propagate in the whole
5521 section, possibly making cache invalid.")
5523 (defvar org-element--cache-change-warning nil
5524 "Non-nil when a sensitive line is about to be changed.
5525 It is a symbol among nil, t and `headline'.")
5527 (defun org-element--cache-before-change (beg end)
5528 "Request extension of area going to be modified if needed.
5529 BEG and END are the beginning and end of the range of changed
5530 text. See `before-change-functions' for more information."
5531 (when (org-element--cache-active-p)
5532 (org-with-wide-buffer
5533 (goto-char beg)
5534 (beginning-of-line)
5535 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5536 (setq org-element--cache-change-warning
5537 (save-match-data
5538 (if (and (org-with-limited-levels (org-at-heading-p))
5539 (= (line-end-position) bottom))
5540 'headline
5541 (let ((case-fold-search t))
5542 (re-search-forward
5543 org-element--cache-sensitive-re bottom t)))))))))
5545 (defun org-element--cache-after-change (beg end pre)
5546 "Update buffer modifications for current buffer.
5547 BEG and END are the beginning and end of the range of changed
5548 text, and the length in bytes of the pre-change text replaced by
5549 that range. See `after-change-functions' for more information."
5550 (when (org-element--cache-active-p)
5551 (org-with-wide-buffer
5552 (goto-char beg)
5553 (beginning-of-line)
5554 (save-match-data
5555 (let ((top (point))
5556 (bottom (save-excursion (goto-char end) (line-end-position))))
5557 ;; Determine if modified area needs to be extended, according
5558 ;; to both previous and current state. We make a special
5559 ;; case for headline editing: if a headline is modified but
5560 ;; not removed, do not extend.
5561 (when (pcase org-element--cache-change-warning
5562 (`t t)
5563 (`headline
5564 (not (and (org-with-limited-levels (org-at-heading-p))
5565 (= (line-end-position) bottom))))
5567 (let ((case-fold-search t))
5568 (re-search-forward
5569 org-element--cache-sensitive-re bottom t))))
5570 ;; Effectively extend modified area.
5571 (org-with-limited-levels
5572 (setq top (progn (goto-char top)
5573 (when (outline-previous-heading) (forward-line))
5574 (point)))
5575 (setq bottom (progn (goto-char bottom)
5576 (if (outline-next-heading) (1- (point))
5577 (point))))))
5578 ;; Store synchronization request.
5579 (let ((offset (- end beg pre)))
5580 (org-element--cache-submit-request top (- bottom offset) offset)))))
5581 ;; Activate a timer to process the request during idle time.
5582 (org-element--cache-set-timer (current-buffer))))
5584 (defun org-element--cache-for-removal (beg end offset)
5585 "Return first element to remove from cache.
5587 BEG and END are buffer positions delimiting buffer modifications.
5588 OFFSET is the size of the changes.
5590 Returned element is usually the first element in cache containing
5591 any position between BEG and END. As an exception, greater
5592 elements around the changes that are robust to contents
5593 modifications are preserved and updated according to the
5594 changes."
5595 (let* ((elements (org-element--cache-find (1- beg) 'both))
5596 (before (car elements))
5597 (after (cdr elements)))
5598 (if (not before) after
5599 (let ((up before)
5600 (robust-flag t))
5601 (while up
5602 (if (let ((type (org-element-type up)))
5603 (and (or (memq type '(center-block dynamic-block quote-block
5604 special-block))
5605 ;; Drawers named "PROPERTIES" are probably
5606 ;; a properties drawer being edited. Force
5607 ;; parsing to check if editing is over.
5608 (and (eq type 'drawer)
5609 (not (string=
5610 (org-element-property :drawer-name up)
5611 "PROPERTIES"))))
5612 (let ((cbeg (org-element-property :contents-begin up)))
5613 (and cbeg
5614 (<= cbeg beg)
5615 (> (org-element-property :contents-end up) end)))))
5616 ;; UP is a robust greater element containing changes.
5617 ;; We only need to extend its ending boundaries.
5618 (org-element--cache-shift-positions
5619 up offset '(:contents-end :end))
5620 (setq before up)
5621 (when robust-flag (setq robust-flag nil)))
5622 (setq up (org-element-property :parent up)))
5623 ;; We're at top level element containing ELEMENT: if it's
5624 ;; altered by buffer modifications, it is first element in
5625 ;; cache to be removed. Otherwise, that first element is the
5626 ;; following one.
5628 ;; As a special case, do not remove BEFORE if it is a robust
5629 ;; container for current changes.
5630 (if (or (< (org-element-property :end before) beg) robust-flag) after
5631 before)))))
5633 (defun org-element--cache-submit-request (beg end offset)
5634 "Submit a new cache synchronization request for current buffer.
5635 BEG and END are buffer positions delimiting the minimal area
5636 where cache data should be removed. OFFSET is the size of the
5637 change, as an integer."
5638 (let ((next (car org-element--cache-sync-requests))
5639 delete-to delete-from)
5640 (if (and next
5641 (zerop (aref next 5))
5642 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5643 (<= (setq delete-from (aref next 1)) end))
5644 ;; Current changes can be merged with first sync request: we
5645 ;; can save a partial cache synchronization.
5646 (progn
5647 (cl-incf (aref next 3) offset)
5648 ;; If last change happened within area to be removed, extend
5649 ;; boundaries of robust parents, if any. Otherwise, find
5650 ;; first element to remove and update request accordingly.
5651 (if (> beg delete-from)
5652 (let ((up (aref next 4)))
5653 (while up
5654 (org-element--cache-shift-positions
5655 up offset '(:contents-end :end))
5656 (setq up (org-element-property :parent up))))
5657 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5658 (when first
5659 (aset next 0 (org-element--cache-key first))
5660 (aset next 1 (org-element-property :begin first))
5661 (aset next 4 (org-element-property :parent first))))))
5662 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5663 ;; if any, is no longer a 0-phase request, thus ensuring that
5664 ;; phases are properly ordered. We need to provide OFFSET as
5665 ;; optional parameter since current modifications are not known
5666 ;; yet to the otherwise correct part of the cache (i.e, before
5667 ;; the first request).
5668 (when next (org-element--cache-sync (current-buffer) end beg))
5669 (let ((first (org-element--cache-for-removal beg end offset)))
5670 (if first
5671 (push (let ((beg (org-element-property :begin first))
5672 (key (org-element--cache-key first)))
5673 (cond
5674 ;; When changes happen before the first known
5675 ;; element, re-parent and shift the rest of the
5676 ;; cache.
5677 ((> beg end) (vector key beg nil offset nil 1))
5678 ;; Otherwise, we find the first non robust
5679 ;; element containing END. All elements between
5680 ;; FIRST and this one are to be removed.
5681 ((let ((first-end (org-element-property :end first)))
5682 (and (> first-end end)
5683 (vector key beg first-end offset first 0))))
5685 (let* ((element (org-element--cache-find end))
5686 (end (org-element-property :end element))
5687 (up element))
5688 (while (and (setq up (org-element-property :parent up))
5689 (>= (org-element-property :begin up) beg))
5690 (setq end (org-element-property :end up)
5691 element up))
5692 (vector key beg end offset element 0)))))
5693 org-element--cache-sync-requests)
5694 ;; No element to remove. No need to re-parent either.
5695 ;; Simply shift additional elements, if any, by OFFSET.
5696 (when org-element--cache-sync-requests
5697 (cl-incf (aref (car org-element--cache-sync-requests) 3)
5698 offset)))))))
5701 ;;;; Public Functions
5703 ;;;###autoload
5704 (defun org-element-cache-reset (&optional all)
5705 "Reset cache in current buffer.
5706 When optional argument ALL is non-nil, reset cache in all Org
5707 buffers."
5708 (interactive "P")
5709 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5710 (with-current-buffer buffer
5711 (when (and org-element-use-cache (derived-mode-p 'org-mode))
5712 (setq-local org-element--cache
5713 (avl-tree-create #'org-element--cache-compare))
5714 (setq-local org-element--cache-sync-keys
5715 (make-hash-table :weakness 'key :test #'eq))
5716 (setq-local org-element--cache-change-warning nil)
5717 (setq-local org-element--cache-sync-requests nil)
5718 (setq-local org-element--cache-sync-timer nil)
5719 (add-hook 'before-change-functions
5720 #'org-element--cache-before-change nil t)
5721 (add-hook 'after-change-functions
5722 #'org-element--cache-after-change nil t)))))
5724 ;;;###autoload
5725 (defun org-element-cache-refresh (pos)
5726 "Refresh cache at position POS."
5727 (when (org-element--cache-active-p)
5728 (org-element--cache-sync (current-buffer) pos)
5729 (org-element--cache-submit-request pos pos 0)
5730 (org-element--cache-set-timer (current-buffer))))
5734 ;;; The Toolbox
5736 ;; The first move is to implement a way to obtain the smallest element
5737 ;; containing point. This is the job of `org-element-at-point'. It
5738 ;; basically jumps back to the beginning of section containing point
5739 ;; and proceed, one element after the other, with
5740 ;; `org-element--current-element' until the container is found. Note:
5741 ;; When using `org-element-at-point', secondary values are never
5742 ;; parsed since the function focuses on elements, not on objects.
5744 ;; At a deeper level, `org-element-context' lists all elements and
5745 ;; objects containing point.
5747 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5748 ;; internally by navigation and manipulation tools.
5751 ;;;###autoload
5752 (defun org-element-at-point ()
5753 "Determine closest element around point.
5755 Return value is a list like (TYPE PROPS) where TYPE is the type
5756 of the element and PROPS a plist of properties associated to the
5757 element.
5759 Possible types are defined in `org-element-all-elements'.
5760 Properties depend on element or object type, but always include
5761 `:begin', `:end', `:parent' and `:post-blank' properties.
5763 As a special case, if point is at the very beginning of the first
5764 item in a list or sub-list, returned element will be that list
5765 instead of the item. Likewise, if point is at the beginning of
5766 the first row of a table, returned element will be the table
5767 instead of the first row.
5769 When point is at the end of the buffer, return the innermost
5770 element ending there."
5771 (org-with-wide-buffer
5772 (let ((origin (point)))
5773 (end-of-line)
5774 (skip-chars-backward " \r\t\n")
5775 (cond
5776 ;; Within blank lines at the beginning of buffer, return nil.
5777 ((bobp) nil)
5778 ;; Within blank lines right after a headline, return that
5779 ;; headline.
5780 ((org-with-limited-levels (org-at-heading-p))
5781 (beginning-of-line)
5782 (org-element-headline-parser (point-max) t))
5783 ;; Otherwise parse until we find element containing ORIGIN.
5785 (when (org-element--cache-active-p)
5786 (if (not org-element--cache) (org-element-cache-reset)
5787 (org-element--cache-sync (current-buffer) origin)))
5788 (org-element--parse-to origin))))))
5790 ;;;###autoload
5791 (defun org-element-context (&optional element)
5792 "Return smallest element or object around point.
5794 Return value is a list like (TYPE PROPS) where TYPE is the type
5795 of the element or object and PROPS a plist of properties
5796 associated to it.
5798 Possible types are defined in `org-element-all-elements' and
5799 `org-element-all-objects'. Properties depend on element or
5800 object type, but always include `:begin', `:end', `:parent' and
5801 `:post-blank'.
5803 As a special case, if point is right after an object and not at
5804 the beginning of any other object, return that object.
5806 Optional argument ELEMENT, when non-nil, is the closest element
5807 containing point, as returned by `org-element-at-point'.
5808 Providing it allows for quicker computation."
5809 (catch 'objects-forbidden
5810 (org-with-wide-buffer
5811 (let* ((pos (point))
5812 (element (or element (org-element-at-point)))
5813 (type (org-element-type element))
5814 (post (org-element-property :post-affiliated element)))
5815 ;; If point is inside an element containing objects or
5816 ;; a secondary string, narrow buffer to the container and
5817 ;; proceed with parsing. Otherwise, return ELEMENT.
5818 (cond
5819 ;; At a parsed affiliated keyword, check if we're inside main
5820 ;; or dual value.
5821 ((and post (< pos post))
5822 (beginning-of-line)
5823 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5824 (cond
5825 ((not (member-ignore-case (match-string 1)
5826 org-element-parsed-keywords))
5827 (throw 'objects-forbidden element))
5828 ((< (match-end 0) pos)
5829 (narrow-to-region (match-end 0) (line-end-position)))
5830 ((and (match-beginning 2)
5831 (>= pos (match-beginning 2))
5832 (< pos (match-end 2)))
5833 (narrow-to-region (match-beginning 2) (match-end 2)))
5834 (t (throw 'objects-forbidden element)))
5835 ;; Also change type to retrieve correct restrictions.
5836 (setq type 'keyword))
5837 ;; At an item, objects can only be located within tag, if any.
5838 ((eq type 'item)
5839 (let ((tag (org-element-property :tag element)))
5840 (if (or (not tag) (/= (line-beginning-position) post))
5841 (throw 'objects-forbidden element)
5842 (beginning-of-line)
5843 (search-forward tag (line-end-position))
5844 (goto-char (match-beginning 0))
5845 (if (and (>= pos (point)) (< pos (match-end 0)))
5846 (narrow-to-region (point) (match-end 0))
5847 (throw 'objects-forbidden element)))))
5848 ;; At an headline or inlinetask, objects are in title.
5849 ((memq type '(headline inlinetask))
5850 (let ((case-fold-search nil))
5851 (goto-char (org-element-property :begin element))
5852 (looking-at org-complex-heading-regexp)
5853 (let ((end (match-end 4)))
5854 (if (not end) (throw 'objects-forbidden element)
5855 (goto-char (match-beginning 4))
5856 (when (looking-at org-comment-string)
5857 (goto-char (match-end 0)))
5858 (if (>= (point) end) (throw 'objects-forbidden element)
5859 (narrow-to-region (point) end))))))
5860 ;; At a paragraph, a table-row or a verse block, objects are
5861 ;; located within their contents.
5862 ((memq type '(paragraph table-row verse-block))
5863 (let ((cbeg (org-element-property :contents-begin element))
5864 (cend (org-element-property :contents-end element)))
5865 ;; CBEG is nil for table rules.
5866 (if (and cbeg cend (>= pos cbeg)
5867 (or (< pos cend) (and (= pos cend) (eobp))))
5868 (narrow-to-region cbeg cend)
5869 (throw 'objects-forbidden element))))
5870 ;; At a planning line, if point is at a timestamp, return it,
5871 ;; otherwise, return element.
5872 ((eq type 'planning)
5873 (dolist (p '(:closed :deadline :scheduled))
5874 (let ((timestamp (org-element-property p element)))
5875 (when (and timestamp
5876 (<= (org-element-property :begin timestamp) pos)
5877 (> (org-element-property :end timestamp) pos))
5878 (throw 'objects-forbidden timestamp))))
5879 ;; All other locations cannot contain objects: bail out.
5880 (throw 'objects-forbidden element))
5881 (t (throw 'objects-forbidden element)))
5882 (goto-char (point-min))
5883 (let ((restriction (org-element-restriction type))
5884 (parent element)
5885 last)
5886 (catch 'exit
5887 (while t
5888 (let ((next (org-element--object-lex restriction)))
5889 (when next (org-element-put-property next :parent parent))
5890 ;; Process NEXT, if any, in order to know if we need to
5891 ;; skip it, return it or move into it.
5892 (if (or (not next) (> (org-element-property :begin next) pos))
5893 (throw 'exit (or last parent))
5894 (let ((end (org-element-property :end next))
5895 (cbeg (org-element-property :contents-begin next))
5896 (cend (org-element-property :contents-end next)))
5897 (cond
5898 ;; Skip objects ending before point. Also skip
5899 ;; objects ending at point unless it is also the
5900 ;; end of buffer, since we want to return the
5901 ;; innermost object.
5902 ((and (<= end pos) (/= (point-max) end))
5903 (goto-char end)
5904 ;; For convenience, when object ends at POS,
5905 ;; without any space, store it in LAST, as we
5906 ;; will return it if no object starts here.
5907 (when (and (= end pos)
5908 (not (memq (char-before) '(?\s ?\t))))
5909 (setq last next)))
5910 ;; If POS is within a container object, move into
5911 ;; that object.
5912 ((and cbeg cend
5913 (>= pos cbeg)
5914 (or (< pos cend)
5915 ;; At contents' end, if there is no
5916 ;; space before point, also move into
5917 ;; object, for consistency with
5918 ;; convenience feature above.
5919 (and (= pos cend)
5920 (or (= (point-max) pos)
5921 (not (memq (char-before pos)
5922 '(?\s ?\t)))))))
5923 (goto-char cbeg)
5924 (narrow-to-region (point) cend)
5925 (setq parent next)
5926 (setq restriction (org-element-restriction next)))
5927 ;; Otherwise, return NEXT.
5928 (t (throw 'exit next)))))))))))))
5930 (defun org-element-lineage (blob &optional types with-self)
5931 "List all ancestors of a given element or object.
5933 BLOB is an object or element.
5935 When optional argument TYPES is a list of symbols, return the
5936 first element or object in the lineage whose type belongs to that
5937 list.
5939 When optional argument WITH-SELF is non-nil, lineage includes
5940 BLOB itself as the first element, and TYPES, if provided, also
5941 apply to it.
5943 When BLOB is obtained through `org-element-context' or
5944 `org-element-at-point', only ancestors from its section can be
5945 found. There is no such limitation when BLOB belongs to a full
5946 parse tree."
5947 (let ((up (if with-self blob (org-element-property :parent blob)))
5948 ancestors)
5949 (while (and up (not (memq (org-element-type up) types)))
5950 (unless types (push up ancestors))
5951 (setq up (org-element-property :parent up)))
5952 (if types up (nreverse ancestors))))
5954 (defun org-element-nested-p (elem-A elem-B)
5955 "Non-nil when elements ELEM-A and ELEM-B are nested."
5956 (let ((beg-A (org-element-property :begin elem-A))
5957 (beg-B (org-element-property :begin elem-B))
5958 (end-A (org-element-property :end elem-A))
5959 (end-B (org-element-property :end elem-B)))
5960 (or (and (>= beg-A beg-B) (<= end-A end-B))
5961 (and (>= beg-B beg-A) (<= end-B end-A)))))
5963 (defun org-element-swap-A-B (elem-A elem-B)
5964 "Swap elements ELEM-A and ELEM-B.
5965 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5966 end of ELEM-A."
5967 (goto-char (org-element-property :begin elem-A))
5968 ;; There are two special cases when an element doesn't start at bol:
5969 ;; the first paragraph in an item or in a footnote definition.
5970 (let ((specialp (not (bolp))))
5971 ;; Only a paragraph without any affiliated keyword can be moved at
5972 ;; ELEM-A position in such a situation. Note that the case of
5973 ;; a footnote definition is impossible: it cannot contain two
5974 ;; paragraphs in a row because it cannot contain a blank line.
5975 (if (and specialp
5976 (or (not (eq (org-element-type elem-B) 'paragraph))
5977 (/= (org-element-property :begin elem-B)
5978 (org-element-property :contents-begin elem-B))))
5979 (error "Cannot swap elements"))
5980 ;; In a special situation, ELEM-A will have no indentation. We'll
5981 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5982 (let* ((ind-B (when specialp
5983 (goto-char (org-element-property :begin elem-B))
5984 (org-get-indentation)))
5985 (beg-A (org-element-property :begin elem-A))
5986 (end-A (save-excursion
5987 (goto-char (org-element-property :end elem-A))
5988 (skip-chars-backward " \r\t\n")
5989 (point-at-eol)))
5990 (beg-B (org-element-property :begin elem-B))
5991 (end-B (save-excursion
5992 (goto-char (org-element-property :end elem-B))
5993 (skip-chars-backward " \r\t\n")
5994 (point-at-eol)))
5995 ;; Store inner overlays responsible for visibility status.
5996 ;; We also need to store their boundaries as they will be
5997 ;; removed from buffer.
5998 (overlays
5999 (cons
6000 (delq nil
6001 (mapcar (lambda (o)
6002 (and (>= (overlay-start o) beg-A)
6003 (<= (overlay-end o) end-A)
6004 (list o (overlay-start o) (overlay-end o))))
6005 (overlays-in beg-A end-A)))
6006 (delq nil
6007 (mapcar (lambda (o)
6008 (and (>= (overlay-start o) beg-B)
6009 (<= (overlay-end o) end-B)
6010 (list o (overlay-start o) (overlay-end o))))
6011 (overlays-in beg-B end-B)))))
6012 ;; Get contents.
6013 (body-A (buffer-substring beg-A end-A))
6014 (body-B (delete-and-extract-region beg-B end-B)))
6015 (goto-char beg-B)
6016 (when specialp
6017 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
6018 (indent-to-column ind-B))
6019 (insert body-A)
6020 ;; Restore ex ELEM-A overlays.
6021 (let ((offset (- beg-B beg-A)))
6022 (dolist (o (car overlays))
6023 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
6024 (goto-char beg-A)
6025 (delete-region beg-A end-A)
6026 (insert body-B)
6027 ;; Restore ex ELEM-B overlays.
6028 (dolist (o (cdr overlays))
6029 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
6030 (goto-char (org-element-property :end elem-B)))))
6033 (provide 'org-element)
6035 ;; Local variables:
6036 ;; generated-autoload-file: "org-loaddefs.el"
6037 ;; End:
6039 ;;; org-element.el ends here