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