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