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