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