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