ox: Activate lexical binding
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob4760e09fbda87eac41606c225abb563b840521d2
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 (case org-plain-list-ordered-item-terminator
180 (?\) ")") (?. "\\.") (otherwise "[.)]")))
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 (case type
590 (org-data (list 'org-data nil))
591 (plain-text (substring-no-properties datum))
592 ((nil) (copy-sequence datum))
593 (otherwise
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 (case checkbox
1269 (on "[X] ")
1270 (off "[ ] ")
1271 (trans "[-] "))
1272 (and tag (format "%s :: " tag))
1273 (when contents
1274 (let ((contents (replace-regexp-in-string
1275 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1276 (if item-starts-with-par-p (org-trim contents)
1277 (concat "\n" contents)))))))
1280 ;;;; Plain List
1282 (defun org-element--list-struct (limit)
1283 ;; Return structure of list at point. Internal function. See
1284 ;; `org-list-struct' for details.
1285 (let ((case-fold-search t)
1286 (top-ind limit)
1287 (item-re (org-item-re))
1288 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1289 items struct)
1290 (save-excursion
1291 (catch 'exit
1292 (while t
1293 (cond
1294 ;; At limit: end all items.
1295 ((>= (point) limit)
1296 (throw 'exit
1297 (let ((end (progn (skip-chars-backward " \r\t\n")
1298 (forward-line)
1299 (point))))
1300 (dolist (item items (sort (nconc items struct)
1301 'car-less-than-car))
1302 (setcar (nthcdr 6 item) end)))))
1303 ;; At list end: end all items.
1304 ((looking-at org-list-end-re)
1305 (throw 'exit (dolist (item items (sort (nconc items struct)
1306 'car-less-than-car))
1307 (setcar (nthcdr 6 item) (point)))))
1308 ;; At a new item: end previous sibling.
1309 ((looking-at item-re)
1310 (let ((ind (save-excursion (skip-chars-forward " \t")
1311 (current-column))))
1312 (setq top-ind (min top-ind ind))
1313 (while (and items (<= ind (nth 1 (car items))))
1314 (let ((item (pop items)))
1315 (setcar (nthcdr 6 item) (point))
1316 (push item struct)))
1317 (push (progn (looking-at org-list-full-item-re)
1318 (let ((bullet (match-string-no-properties 1)))
1319 (list (point)
1321 bullet
1322 (match-string-no-properties 2) ; counter
1323 (match-string-no-properties 3) ; checkbox
1324 ;; Description tag.
1325 (and (save-match-data
1326 (string-match "[-+*]" bullet))
1327 (match-string-no-properties 4))
1328 ;; Ending position, unknown so far.
1329 nil)))
1330 items))
1331 (forward-line 1))
1332 ;; Skip empty lines.
1333 ((looking-at "^[ \t]*$") (forward-line))
1334 ;; Skip inline tasks and blank lines along the way.
1335 ((and inlinetask-re (looking-at inlinetask-re))
1336 (forward-line)
1337 (let ((origin (point)))
1338 (when (re-search-forward inlinetask-re limit t)
1339 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1340 (goto-char origin)))))
1341 ;; At some text line. Check if it ends any previous item.
1343 (let ((ind (save-excursion (skip-chars-forward " \t")
1344 (current-column))))
1345 (when (<= ind top-ind)
1346 (skip-chars-backward " \r\t\n")
1347 (forward-line))
1348 (while (<= ind (nth 1 (car items)))
1349 (let ((item (pop items)))
1350 (setcar (nthcdr 6 item) (line-beginning-position))
1351 (push item struct)
1352 (unless items
1353 (throw 'exit (sort struct #'car-less-than-car))))))
1354 ;; Skip blocks (any type) and drawers contents.
1355 (cond
1356 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1357 (re-search-forward
1358 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1359 limit t)))
1360 ((and (looking-at org-drawer-regexp)
1361 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1362 (forward-line))))))))
1364 (defun org-element-plain-list-parser (limit affiliated structure)
1365 "Parse a plain list.
1367 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1368 the buffer position at the beginning of the first affiliated
1369 keyword and CDR is a plist of affiliated keywords along with
1370 their value. STRUCTURE is the structure of the plain list being
1371 parsed.
1373 Return a list whose CAR is `plain-list' and CDR is a plist
1374 containing `:type', `:begin', `:end', `:contents-begin' and
1375 `:contents-end', `:structure', `:post-blank' and
1376 `:post-affiliated' keywords.
1378 Assume point is at the beginning of the list."
1379 (save-excursion
1380 (let* ((struct (or structure (org-element--list-struct limit)))
1381 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1382 ((nth 5 (assq (point) struct)) 'descriptive)
1383 (t 'unordered)))
1384 (contents-begin (point))
1385 (begin (car affiliated))
1386 (contents-end (let* ((item (assq contents-begin struct))
1387 (ind (nth 1 item))
1388 (pos (nth 6 item)))
1389 (while (and (setq item (assq pos struct))
1390 (= (nth 1 item) ind))
1391 (setq pos (nth 6 item)))
1392 pos))
1393 (end (progn (goto-char contents-end)
1394 (skip-chars-forward " \r\t\n" limit)
1395 (if (= (point) limit) limit (line-beginning-position)))))
1396 ;; Return value.
1397 (list 'plain-list
1398 (nconc
1399 (list :type type
1400 :begin begin
1401 :end end
1402 :contents-begin contents-begin
1403 :contents-end contents-end
1404 :structure struct
1405 :post-blank (count-lines contents-end end)
1406 :post-affiliated contents-begin)
1407 (cdr affiliated))))))
1409 (defun org-element-plain-list-interpreter (_ contents)
1410 "Interpret plain-list element as Org syntax.
1411 CONTENTS is the contents of the element."
1412 (with-temp-buffer
1413 (insert contents)
1414 (goto-char (point-min))
1415 (org-list-repair)
1416 (buffer-string)))
1419 ;;;; Property Drawer
1421 (defun org-element-property-drawer-parser (limit)
1422 "Parse a property drawer.
1424 LIMIT bounds the search.
1426 Return a list whose car is `property-drawer' and cdr is a plist
1427 containing `:begin', `:end', `:contents-begin', `:contents-end',
1428 `:post-blank' and `:post-affiliated' keywords.
1430 Assume point is at the beginning of the property drawer."
1431 (save-excursion
1432 (let ((case-fold-search t)
1433 (begin (point))
1434 (contents-begin (line-beginning-position 2)))
1435 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1436 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1437 (match-beginning 0)))
1438 (before-blank (progn (forward-line) (point)))
1439 (end (progn (skip-chars-forward " \r\t\n" limit)
1440 (if (eobp) (point) (line-beginning-position)))))
1441 (list 'property-drawer
1442 (list :begin begin
1443 :end end
1444 :contents-begin (and contents-end contents-begin)
1445 :contents-end contents-end
1446 :post-blank (count-lines before-blank end)
1447 :post-affiliated begin))))))
1449 (defun org-element-property-drawer-interpreter (_ contents)
1450 "Interpret property-drawer element as Org syntax.
1451 CONTENTS is the properties within the drawer."
1452 (format ":PROPERTIES:\n%s:END:" contents))
1455 ;;;; Quote Block
1457 (defun org-element-quote-block-parser (limit affiliated)
1458 "Parse a quote block.
1460 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1461 the buffer position at the beginning of the first affiliated
1462 keyword and CDR is a plist of affiliated keywords along with
1463 their value.
1465 Return a list whose CAR is `quote-block' and CDR is a plist
1466 containing `:begin', `:end', `:contents-begin', `:contents-end',
1467 `:post-blank' and `:post-affiliated' keywords.
1469 Assume point is at the beginning of the block."
1470 (let ((case-fold-search t))
1471 (if (not (save-excursion
1472 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1473 ;; Incomplete block: parse it as a paragraph.
1474 (org-element-paragraph-parser limit affiliated)
1475 (let ((block-end-line (match-beginning 0)))
1476 (save-excursion
1477 (let* ((begin (car affiliated))
1478 (post-affiliated (point))
1479 ;; Empty blocks have no contents.
1480 (contents-begin (progn (forward-line)
1481 (and (< (point) block-end-line)
1482 (point))))
1483 (contents-end (and contents-begin block-end-line))
1484 (pos-before-blank (progn (goto-char block-end-line)
1485 (forward-line)
1486 (point)))
1487 (end (progn (skip-chars-forward " \r\t\n" limit)
1488 (if (eobp) (point) (line-beginning-position)))))
1489 (list 'quote-block
1490 (nconc
1491 (list :begin begin
1492 :end end
1493 :contents-begin contents-begin
1494 :contents-end contents-end
1495 :post-blank (count-lines pos-before-blank end)
1496 :post-affiliated post-affiliated)
1497 (cdr affiliated)))))))))
1499 (defun org-element-quote-block-interpreter (_ contents)
1500 "Interpret quote-block element as Org syntax.
1501 CONTENTS is the contents of the element."
1502 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1505 ;;;; Section
1507 (defun org-element-section-parser (_)
1508 "Parse a section.
1510 Return a list whose CAR is `section' and CDR is a plist
1511 containing `:begin', `:end', `:contents-begin', `contents-end',
1512 `:post-blank' and `:post-affiliated' keywords."
1513 (save-excursion
1514 ;; Beginning of section is the beginning of the first non-blank
1515 ;; line after previous headline.
1516 (let ((begin (point))
1517 (end (progn (org-with-limited-levels (outline-next-heading))
1518 (point)))
1519 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1520 (line-beginning-position 2))))
1521 (list 'section
1522 (list :begin begin
1523 :end end
1524 :contents-begin begin
1525 :contents-end pos-before-blank
1526 :post-blank (count-lines pos-before-blank end)
1527 :post-affiliated begin)))))
1529 (defun org-element-section-interpreter (_ contents)
1530 "Interpret section element as Org syntax.
1531 CONTENTS is the contents of the element."
1532 contents)
1535 ;;;; Special Block
1537 (defun org-element-special-block-parser (limit affiliated)
1538 "Parse a special block.
1540 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1541 the buffer position at the beginning of the first affiliated
1542 keyword and CDR is a plist of affiliated keywords along with
1543 their value.
1545 Return a list whose CAR is `special-block' and CDR is a plist
1546 containing `:type', `:begin', `:end', `:contents-begin',
1547 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1549 Assume point is at the beginning of the block."
1550 (let* ((case-fold-search t)
1551 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1552 (match-string-no-properties 1))))
1553 (if (not (save-excursion
1554 (re-search-forward
1555 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1556 limit t)))
1557 ;; Incomplete block: parse it as a paragraph.
1558 (org-element-paragraph-parser limit affiliated)
1559 (let ((block-end-line (match-beginning 0)))
1560 (save-excursion
1561 (let* ((begin (car affiliated))
1562 (post-affiliated (point))
1563 ;; Empty blocks have no contents.
1564 (contents-begin (progn (forward-line)
1565 (and (< (point) block-end-line)
1566 (point))))
1567 (contents-end (and contents-begin block-end-line))
1568 (pos-before-blank (progn (goto-char block-end-line)
1569 (forward-line)
1570 (point)))
1571 (end (progn (skip-chars-forward " \r\t\n" limit)
1572 (if (eobp) (point) (line-beginning-position)))))
1573 (list 'special-block
1574 (nconc
1575 (list :type type
1576 :begin begin
1577 :end end
1578 :contents-begin contents-begin
1579 :contents-end contents-end
1580 :post-blank (count-lines pos-before-blank end)
1581 :post-affiliated post-affiliated)
1582 (cdr affiliated)))))))))
1584 (defun org-element-special-block-interpreter (special-block contents)
1585 "Interpret SPECIAL-BLOCK element as Org syntax.
1586 CONTENTS is the contents of the element."
1587 (let ((block-type (org-element-property :type special-block)))
1588 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1592 ;;; Elements
1594 ;; For each element, a parser and an interpreter are also defined.
1595 ;; Both follow the same naming convention used for greater elements.
1597 ;; Also, as for greater elements, adding a new element type is done
1598 ;; through the following steps: implement a parser and an interpreter,
1599 ;; tweak `org-element--current-element' so that it recognizes the new
1600 ;; type and add that new type to `org-element-all-elements'.
1602 ;; As a special case, when the newly defined type is a block type,
1603 ;; `org-element-block-name-alist' has to be modified accordingly.
1606 ;;;; Babel Call
1608 (defun org-element-babel-call-parser (limit affiliated)
1609 "Parse a babel call.
1611 LIMIT bounds the search. AFFILIATED is a list of which car is
1612 the buffer position at the beginning of the first affiliated
1613 keyword and cdr is a plist of affiliated keywords along with
1614 their value.
1616 Return a list whose car is `babel-call' and cdr is a plist
1617 containing `:call', `:inside-header', `:arguments',
1618 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1619 `:post-affiliated' as keywords."
1620 (save-excursion
1621 (let* ((begin (car affiliated))
1622 (post-affiliated (point))
1623 (value (progn (search-forward ":" nil t)
1624 (org-trim
1625 (buffer-substring-no-properties
1626 (point) (line-end-position)))))
1627 (pos-before-blank (progn (forward-line) (point)))
1628 (end (progn (skip-chars-forward " \r\t\n" limit)
1629 (if (eobp) (point) (line-beginning-position))))
1630 (valid-value
1631 (string-match
1632 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*\\))[ \t]*\\(.*\\)"
1633 value)))
1634 (list 'babel-call
1635 (nconc
1636 (list :call (and valid-value (match-string 1 value))
1637 :inside-header (and valid-value
1638 (org-string-nw-p (match-string 2 value)))
1639 :arguments (and valid-value
1640 (org-string-nw-p (match-string 3 value)))
1641 :end-header (and valid-value
1642 (org-string-nw-p (match-string 4 value)))
1643 :begin begin
1644 :end end
1645 :value value
1646 :post-blank (count-lines pos-before-blank end)
1647 :post-affiliated post-affiliated)
1648 (cdr affiliated))))))
1650 (defun org-element-babel-call-interpreter (babel-call _)
1651 "Interpret BABEL-CALL element as Org syntax."
1652 (concat "#+CALL: "
1653 (org-element-property :call babel-call)
1654 (let ((h (org-element-property :inside-header babel-call)))
1655 (and h (format "[%s]" h)))
1656 (concat "(" (org-element-property :arguments babel-call) ")")
1657 (let ((h (org-element-property :end-header babel-call)))
1658 (and h (concat " " h)))))
1661 ;;;; Clock
1663 (defun org-element-clock-parser (limit)
1664 "Parse a clock.
1666 LIMIT bounds the search.
1668 Return a list whose CAR is `clock' and CDR is a plist containing
1669 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1670 `:post-affiliated' as keywords."
1671 (save-excursion
1672 (let* ((case-fold-search nil)
1673 (begin (point))
1674 (value (progn (search-forward org-clock-string (line-end-position) t)
1675 (skip-chars-forward " \t")
1676 (org-element-timestamp-parser)))
1677 (duration (and (search-forward " => " (line-end-position) t)
1678 (progn (skip-chars-forward " \t")
1679 (looking-at "\\(\\S-+\\)[ \t]*$"))
1680 (org-match-string-no-properties 1)))
1681 (status (if duration 'closed 'running))
1682 (post-blank (let ((before-blank (progn (forward-line) (point))))
1683 (skip-chars-forward " \r\t\n" limit)
1684 (skip-chars-backward " \t")
1685 (unless (bolp) (end-of-line))
1686 (count-lines before-blank (point))))
1687 (end (point)))
1688 (list 'clock
1689 (list :status status
1690 :value value
1691 :duration duration
1692 :begin begin
1693 :end end
1694 :post-blank post-blank
1695 :post-affiliated begin)))))
1697 (defun org-element-clock-interpreter (clock _)
1698 "Interpret CLOCK element as Org syntax."
1699 (concat org-clock-string " "
1700 (org-element-timestamp-interpreter
1701 (org-element-property :value clock) nil)
1702 (let ((duration (org-element-property :duration clock)))
1703 (and duration
1704 (concat " => "
1705 (apply 'format
1706 "%2s:%02s"
1707 (org-split-string duration ":")))))))
1710 ;;;; Comment
1712 (defun org-element-comment-parser (limit affiliated)
1713 "Parse a comment.
1715 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1716 the buffer position at the beginning of the first affiliated
1717 keyword and CDR is a plist of affiliated keywords along with
1718 their value.
1720 Return a list whose CAR is `comment' and CDR is a plist
1721 containing `:begin', `:end', `:value', `:post-blank',
1722 `:post-affiliated' keywords.
1724 Assume point is at comment beginning."
1725 (save-excursion
1726 (let* ((begin (car affiliated))
1727 (post-affiliated (point))
1728 (value (prog2 (looking-at "[ \t]*# ?")
1729 (buffer-substring-no-properties
1730 (match-end 0) (line-end-position))
1731 (forward-line)))
1732 (com-end
1733 ;; Get comments ending.
1734 (progn
1735 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1736 ;; Accumulate lines without leading hash and first
1737 ;; whitespace.
1738 (setq value
1739 (concat value
1740 "\n"
1741 (buffer-substring-no-properties
1742 (match-end 0) (line-end-position))))
1743 (forward-line))
1744 (point)))
1745 (end (progn (goto-char com-end)
1746 (skip-chars-forward " \r\t\n" limit)
1747 (if (eobp) (point) (line-beginning-position)))))
1748 (list 'comment
1749 (nconc
1750 (list :begin begin
1751 :end end
1752 :value value
1753 :post-blank (count-lines com-end end)
1754 :post-affiliated post-affiliated)
1755 (cdr affiliated))))))
1757 (defun org-element-comment-interpreter (comment _)
1758 "Interpret COMMENT element as Org syntax.
1759 CONTENTS is nil."
1760 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1763 ;;;; Comment Block
1765 (defun org-element-comment-block-parser (limit affiliated)
1766 "Parse an export block.
1768 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1769 the buffer position at the beginning of the first affiliated
1770 keyword and CDR is a plist of affiliated keywords along with
1771 their value.
1773 Return a list whose CAR is `comment-block' and CDR is a plist
1774 containing `:begin', `:end', `:value', `:post-blank' and
1775 `:post-affiliated' keywords.
1777 Assume point is at comment block beginning."
1778 (let ((case-fold-search t))
1779 (if (not (save-excursion
1780 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1781 ;; Incomplete block: parse it as a paragraph.
1782 (org-element-paragraph-parser limit affiliated)
1783 (let ((contents-end (match-beginning 0)))
1784 (save-excursion
1785 (let* ((begin (car affiliated))
1786 (post-affiliated (point))
1787 (contents-begin (progn (forward-line) (point)))
1788 (pos-before-blank (progn (goto-char contents-end)
1789 (forward-line)
1790 (point)))
1791 (end (progn (skip-chars-forward " \r\t\n" limit)
1792 (if (eobp) (point) (line-beginning-position))))
1793 (value (buffer-substring-no-properties
1794 contents-begin contents-end)))
1795 (list 'comment-block
1796 (nconc
1797 (list :begin begin
1798 :end end
1799 :value value
1800 :post-blank (count-lines pos-before-blank end)
1801 :post-affiliated post-affiliated)
1802 (cdr affiliated)))))))))
1804 (defun org-element-comment-block-interpreter (comment-block _)
1805 "Interpret COMMENT-BLOCK element as Org syntax."
1806 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1807 (org-element-normalize-string
1808 (org-remove-indentation
1809 (org-element-property :value comment-block)))))
1812 ;;;; Diary Sexp
1814 (defun org-element-diary-sexp-parser (limit affiliated)
1815 "Parse a diary sexp.
1817 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1818 the buffer position at the beginning of the first affiliated
1819 keyword and CDR is a plist of affiliated keywords along with
1820 their value.
1822 Return a list whose CAR is `diary-sexp' and CDR is a plist
1823 containing `:begin', `:end', `:value', `:post-blank' and
1824 `:post-affiliated' keywords."
1825 (save-excursion
1826 (let ((begin (car affiliated))
1827 (post-affiliated (point))
1828 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1829 (org-match-string-no-properties 1)))
1830 (pos-before-blank (progn (forward-line) (point)))
1831 (end (progn (skip-chars-forward " \r\t\n" limit)
1832 (if (eobp) (point) (line-beginning-position)))))
1833 (list 'diary-sexp
1834 (nconc
1835 (list :value value
1836 :begin begin
1837 :end end
1838 :post-blank (count-lines pos-before-blank end)
1839 :post-affiliated post-affiliated)
1840 (cdr affiliated))))))
1842 (defun org-element-diary-sexp-interpreter (diary-sexp _)
1843 "Interpret DIARY-SEXP as Org syntax."
1844 (org-element-property :value diary-sexp))
1847 ;;;; Example Block
1849 (defun org-element-example-block-parser (limit affiliated)
1850 "Parse an example block.
1852 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1853 the buffer position at the beginning of the first affiliated
1854 keyword and CDR is a plist of affiliated keywords along with
1855 their value.
1857 Return a list whose CAR is `example-block' and CDR is a plist
1858 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1859 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1860 `:value', `:post-blank' and `:post-affiliated' keywords."
1861 (let ((case-fold-search t))
1862 (if (not (save-excursion
1863 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1864 ;; Incomplete block: parse it as a paragraph.
1865 (org-element-paragraph-parser limit affiliated)
1866 (let ((contents-end (match-beginning 0)))
1867 (save-excursion
1868 (let* ((switches
1869 (progn
1870 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1871 (org-match-string-no-properties 1)))
1872 ;; Switches analysis
1873 (number-lines
1874 (cond ((not switches) nil)
1875 ((string-match "-n\\>" switches) 'new)
1876 ((string-match "+n\\>" switches) 'continued)))
1877 (preserve-indent
1878 (and switches (string-match "-i\\>" switches)))
1879 ;; Should labels be retained in (or stripped from) example
1880 ;; blocks?
1881 (retain-labels
1882 (or (not switches)
1883 (not (string-match "-r\\>" switches))
1884 (and number-lines (string-match "-k\\>" switches))))
1885 ;; What should code-references use - labels or
1886 ;; line-numbers?
1887 (use-labels
1888 (or (not switches)
1889 (and retain-labels
1890 (not (string-match "-k\\>" switches)))))
1891 (label-fmt
1892 (and switches
1893 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1894 (match-string 1 switches)))
1895 ;; Standard block parsing.
1896 (begin (car affiliated))
1897 (post-affiliated (point))
1898 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1899 (contents-begin (progn (forward-line) (point)))
1900 (value (org-element-remove-indentation
1901 (org-unescape-code-in-string
1902 (buffer-substring-no-properties
1903 contents-begin contents-end))
1904 block-ind))
1905 (pos-before-blank (progn (goto-char contents-end)
1906 (forward-line)
1907 (point)))
1908 (end (progn (skip-chars-forward " \r\t\n" limit)
1909 (if (eobp) (point) (line-beginning-position)))))
1910 (list 'example-block
1911 (nconc
1912 (list :begin begin
1913 :end end
1914 :value value
1915 :switches switches
1916 :number-lines number-lines
1917 :preserve-indent preserve-indent
1918 :retain-labels retain-labels
1919 :use-labels use-labels
1920 :label-fmt label-fmt
1921 :post-blank (count-lines pos-before-blank end)
1922 :post-affiliated post-affiliated)
1923 (cdr affiliated)))))))))
1925 (defun org-element-example-block-interpreter (example-block _)
1926 "Interpret EXAMPLE-BLOCK element as Org syntax."
1927 (let ((switches (org-element-property :switches example-block))
1928 (value (org-element-property :value example-block)))
1929 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1930 (org-element-normalize-string
1931 (org-escape-code-in-string
1932 (if (or org-src-preserve-indentation
1933 (org-element-property :preserve-indent example-block))
1934 value
1935 (org-element-remove-indentation value))))
1936 "#+END_EXAMPLE")))
1939 ;;;; Export Block
1941 (defun org-element-export-block-parser (limit affiliated)
1942 "Parse an export block.
1944 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1945 the buffer position at the beginning of the first affiliated
1946 keyword and CDR is a plist of affiliated keywords along with
1947 their value.
1949 Return a list whose CAR is `export-block' and CDR is a plist
1950 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1951 `:post-affiliated' keywords.
1953 Assume point is at export-block beginning."
1954 (let* ((case-fold-search t)
1955 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1956 (upcase (org-match-string-no-properties 1)))))
1957 (if (not (save-excursion
1958 (re-search-forward
1959 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1960 ;; Incomplete block: parse it as a paragraph.
1961 (org-element-paragraph-parser limit affiliated)
1962 (let ((contents-end (match-beginning 0)))
1963 (save-excursion
1964 (let* ((begin (car affiliated))
1965 (post-affiliated (point))
1966 (contents-begin (progn (forward-line) (point)))
1967 (pos-before-blank (progn (goto-char contents-end)
1968 (forward-line)
1969 (point)))
1970 (end (progn (skip-chars-forward " \r\t\n" limit)
1971 (if (eobp) (point) (line-beginning-position))))
1972 (value (buffer-substring-no-properties contents-begin
1973 contents-end)))
1974 (list 'export-block
1975 (nconc
1976 (list :begin begin
1977 :end end
1978 :type type
1979 :value value
1980 :post-blank (count-lines pos-before-blank end)
1981 :post-affiliated post-affiliated)
1982 (cdr affiliated)))))))))
1984 (defun org-element-export-block-interpreter (export-block _)
1985 "Interpret EXPORT-BLOCK element as Org syntax."
1986 (let ((type (org-element-property :type export-block)))
1987 (concat (format "#+BEGIN_%s\n" type)
1988 (org-element-property :value export-block)
1989 (format "#+END_%s" type))))
1992 ;;;; Fixed-width
1994 (defun org-element-fixed-width-parser (limit affiliated)
1995 "Parse a fixed-width section.
1997 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1998 the buffer position at the beginning of the first affiliated
1999 keyword and CDR is a plist of affiliated keywords along with
2000 their value.
2002 Return a list whose CAR is `fixed-width' and CDR is a plist
2003 containing `:begin', `:end', `:value', `:post-blank' and
2004 `:post-affiliated' keywords.
2006 Assume point is at the beginning of the fixed-width area."
2007 (save-excursion
2008 (let* ((begin (car affiliated))
2009 (post-affiliated (point))
2010 value
2011 (end-area
2012 (progn
2013 (while (and (< (point) limit)
2014 (looking-at "[ \t]*:\\( \\|$\\)"))
2015 ;; Accumulate text without starting colons.
2016 (setq value
2017 (concat value
2018 (buffer-substring-no-properties
2019 (match-end 0) (point-at-eol))
2020 "\n"))
2021 (forward-line))
2022 (point)))
2023 (end (progn (skip-chars-forward " \r\t\n" limit)
2024 (if (eobp) (point) (line-beginning-position)))))
2025 (list 'fixed-width
2026 (nconc
2027 (list :begin begin
2028 :end end
2029 :value value
2030 :post-blank (count-lines end-area end)
2031 :post-affiliated post-affiliated)
2032 (cdr affiliated))))))
2034 (defun org-element-fixed-width-interpreter (fixed-width _)
2035 "Interpret FIXED-WIDTH element as Org syntax."
2036 (let ((value (org-element-property :value fixed-width)))
2037 (and value
2038 (replace-regexp-in-string
2039 "^" ": "
2040 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2043 ;;;; Horizontal Rule
2045 (defun org-element-horizontal-rule-parser (limit affiliated)
2046 "Parse an horizontal rule.
2048 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2049 the buffer position at the beginning of the first affiliated
2050 keyword and CDR is a plist of affiliated keywords along with
2051 their value.
2053 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2054 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2055 keywords."
2056 (save-excursion
2057 (let ((begin (car affiliated))
2058 (post-affiliated (point))
2059 (post-hr (progn (forward-line) (point)))
2060 (end (progn (skip-chars-forward " \r\t\n" limit)
2061 (if (eobp) (point) (line-beginning-position)))))
2062 (list 'horizontal-rule
2063 (nconc
2064 (list :begin begin
2065 :end end
2066 :post-blank (count-lines post-hr end)
2067 :post-affiliated post-affiliated)
2068 (cdr affiliated))))))
2070 (defun org-element-horizontal-rule-interpreter (&rest _)
2071 "Interpret HORIZONTAL-RULE element as Org syntax."
2072 "-----")
2075 ;;;; Keyword
2077 (defun org-element-keyword-parser (limit affiliated)
2078 "Parse a keyword at point.
2080 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2081 the buffer position at the beginning of the first affiliated
2082 keyword and CDR is a plist of affiliated keywords along with
2083 their value.
2085 Return a list whose CAR is `keyword' and CDR is a plist
2086 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2087 `:post-affiliated' keywords."
2088 (save-excursion
2089 ;; An orphaned affiliated keyword is considered as a regular
2090 ;; keyword. In this case AFFILIATED is nil, so we take care of
2091 ;; this corner case.
2092 (let ((begin (or (car affiliated) (point)))
2093 (post-affiliated (point))
2094 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2095 (upcase (org-match-string-no-properties 1))))
2096 (value (org-trim (buffer-substring-no-properties
2097 (match-end 0) (point-at-eol))))
2098 (pos-before-blank (progn (forward-line) (point)))
2099 (end (progn (skip-chars-forward " \r\t\n" limit)
2100 (if (eobp) (point) (line-beginning-position)))))
2101 (list 'keyword
2102 (nconc
2103 (list :key key
2104 :value value
2105 :begin begin
2106 :end end
2107 :post-blank (count-lines pos-before-blank end)
2108 :post-affiliated post-affiliated)
2109 (cdr affiliated))))))
2111 (defun org-element-keyword-interpreter (keyword _)
2112 "Interpret KEYWORD element as Org syntax."
2113 (format "#+%s: %s"
2114 (org-element-property :key keyword)
2115 (org-element-property :value keyword)))
2118 ;;;; Latex Environment
2120 (defconst org-element--latex-begin-environment
2121 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2122 "Regexp matching the beginning of a LaTeX environment.
2123 The environment is captured by the first group.
2125 See also `org-element--latex-end-environment'.")
2127 (defconst org-element--latex-end-environment
2128 "\\\\end{%s}[ \t]*$"
2129 "Format string matching the ending of a LaTeX environment.
2130 See also `org-element--latex-begin-environment'.")
2132 (defun org-element-latex-environment-parser (limit affiliated)
2133 "Parse a LaTeX environment.
2135 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2136 the buffer position at the beginning of the first affiliated
2137 keyword and CDR is a plist of affiliated keywords along with
2138 their value.
2140 Return a list whose CAR is `latex-environment' and CDR is a plist
2141 containing `:begin', `:end', `:value', `:post-blank' and
2142 `:post-affiliated' keywords.
2144 Assume point is at the beginning of the latex environment."
2145 (save-excursion
2146 (let ((case-fold-search t)
2147 (code-begin (point)))
2148 (looking-at org-element--latex-begin-environment)
2149 (if (not (re-search-forward (format org-element--latex-end-environment
2150 (regexp-quote (match-string 1)))
2151 limit t))
2152 ;; Incomplete latex environment: parse it as a paragraph.
2153 (org-element-paragraph-parser limit affiliated)
2154 (let* ((code-end (progn (forward-line) (point)))
2155 (begin (car affiliated))
2156 (value (buffer-substring-no-properties code-begin code-end))
2157 (end (progn (skip-chars-forward " \r\t\n" limit)
2158 (if (eobp) (point) (line-beginning-position)))))
2159 (list 'latex-environment
2160 (nconc
2161 (list :begin begin
2162 :end end
2163 :value value
2164 :post-blank (count-lines code-end end)
2165 :post-affiliated code-begin)
2166 (cdr affiliated))))))))
2168 (defun org-element-latex-environment-interpreter (latex-environment _)
2169 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2170 (org-element-property :value latex-environment))
2173 ;;;; Node Property
2175 (defun org-element-node-property-parser (limit)
2176 "Parse a node-property at point.
2178 LIMIT bounds the search.
2180 Return a list whose CAR is `node-property' and CDR is a plist
2181 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2182 `:post-affiliated' keywords."
2183 (looking-at org-property-re)
2184 (let ((case-fold-search t)
2185 (begin (point))
2186 (key (org-match-string-no-properties 2))
2187 (value (org-match-string-no-properties 3))
2188 (end (save-excursion
2189 (end-of-line)
2190 (if (re-search-forward org-property-re limit t)
2191 (line-beginning-position)
2192 limit))))
2193 (list 'node-property
2194 (list :key key
2195 :value value
2196 :begin begin
2197 :end end
2198 :post-blank 0
2199 :post-affiliated begin))))
2201 (defun org-element-node-property-interpreter (node-property _)
2202 "Interpret NODE-PROPERTY element as Org syntax."
2203 (format org-property-format
2204 (format ":%s:" (org-element-property :key node-property))
2205 (or (org-element-property :value node-property) "")))
2208 ;;;; Paragraph
2210 (defun org-element-paragraph-parser (limit affiliated)
2211 "Parse a paragraph.
2213 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2214 the buffer position at the beginning of the first affiliated
2215 keyword and CDR is a plist of affiliated keywords along with
2216 their value.
2218 Return a list whose CAR is `paragraph' and CDR is a plist
2219 containing `:begin', `:end', `:contents-begin' and
2220 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2222 Assume point is at the beginning of the paragraph."
2223 (save-excursion
2224 (let* ((begin (car affiliated))
2225 (contents-begin (point))
2226 (before-blank
2227 (let ((case-fold-search t))
2228 (end-of-line)
2229 ;; A matching `org-element-paragraph-separate' is not
2230 ;; necessarily the end of the paragraph. In particular,
2231 ;; drawers, blocks or LaTeX environments opening lines
2232 ;; must be closed. Moreover keywords with a secondary
2233 ;; value must belong to "dual keywords".
2234 (while (not
2235 (cond
2236 ((not (and (re-search-forward
2237 org-element-paragraph-separate limit 'move)
2238 (progn (beginning-of-line) t))))
2239 ((looking-at org-drawer-regexp)
2240 (save-excursion
2241 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2242 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2243 (save-excursion
2244 (re-search-forward
2245 (format "^[ \t]*#\\+END_%s[ \t]*$"
2246 (regexp-quote (match-string 1)))
2247 limit t)))
2248 ((looking-at org-element--latex-begin-environment)
2249 (save-excursion
2250 (re-search-forward
2251 (format org-element--latex-end-environment
2252 (regexp-quote (match-string 1)))
2253 limit t)))
2254 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2255 (member-ignore-case (match-string 1)
2256 org-element-dual-keywords))
2257 ;; Everything else is unambiguous.
2258 (t)))
2259 (end-of-line))
2260 (if (= (point) limit) limit
2261 (goto-char (line-beginning-position)))))
2262 (contents-end (save-excursion
2263 (skip-chars-backward " \r\t\n" contents-begin)
2264 (line-beginning-position 2)))
2265 (end (progn (skip-chars-forward " \r\t\n" limit)
2266 (if (eobp) (point) (line-beginning-position)))))
2267 (list 'paragraph
2268 (nconc
2269 (list :begin begin
2270 :end end
2271 :contents-begin contents-begin
2272 :contents-end contents-end
2273 :post-blank (count-lines before-blank end)
2274 :post-affiliated contents-begin)
2275 (cdr affiliated))))))
2277 (defun org-element-paragraph-interpreter (_ contents)
2278 "Interpret paragraph element as Org syntax.
2279 CONTENTS is the contents of the element."
2280 contents)
2283 ;;;; Planning
2285 (defun org-element-planning-parser (limit)
2286 "Parse a planning.
2288 LIMIT bounds the search.
2290 Return a list whose CAR is `planning' and CDR is a plist
2291 containing `:closed', `:deadline', `:scheduled', `:begin',
2292 `:end', `:post-blank' and `:post-affiliated' keywords."
2293 (save-excursion
2294 (let* ((case-fold-search nil)
2295 (begin (point))
2296 (post-blank (let ((before-blank (progn (forward-line) (point))))
2297 (skip-chars-forward " \r\t\n" limit)
2298 (skip-chars-backward " \t")
2299 (unless (bolp) (end-of-line))
2300 (count-lines before-blank (point))))
2301 (end (point))
2302 closed deadline scheduled)
2303 (goto-char begin)
2304 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2305 (goto-char (match-end 1))
2306 (skip-chars-forward " \t" end)
2307 (let ((keyword (match-string 1))
2308 (time (org-element-timestamp-parser)))
2309 (cond ((equal keyword org-closed-string) (setq closed time))
2310 ((equal keyword org-deadline-string) (setq deadline time))
2311 (t (setq scheduled time)))))
2312 (list 'planning
2313 (list :closed closed
2314 :deadline deadline
2315 :scheduled scheduled
2316 :begin begin
2317 :end end
2318 :post-blank post-blank
2319 :post-affiliated begin)))))
2321 (defun org-element-planning-interpreter (planning _)
2322 "Interpret PLANNING element as Org syntax."
2323 (mapconcat
2324 #'identity
2325 (delq nil
2326 (list (let ((deadline (org-element-property :deadline planning)))
2327 (when deadline
2328 (concat org-deadline-string " "
2329 (org-element-timestamp-interpreter deadline nil))))
2330 (let ((scheduled (org-element-property :scheduled planning)))
2331 (when scheduled
2332 (concat org-scheduled-string " "
2333 (org-element-timestamp-interpreter scheduled nil))))
2334 (let ((closed (org-element-property :closed planning)))
2335 (when closed
2336 (concat org-closed-string " "
2337 (org-element-timestamp-interpreter closed nil))))))
2338 " "))
2341 ;;;; Src Block
2343 (defun org-element-src-block-parser (limit affiliated)
2344 "Parse a src block.
2346 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2347 the buffer position at the beginning of the first affiliated
2348 keyword and CDR is a plist of affiliated keywords along with
2349 their value.
2351 Return a list whose CAR is `src-block' and CDR is a plist
2352 containing `:language', `:switches', `:parameters', `:begin',
2353 `:end', `:number-lines', `:retain-labels', `:use-labels',
2354 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2355 `:post-affiliated' keywords.
2357 Assume point is at the beginning of the block."
2358 (let ((case-fold-search t))
2359 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2360 limit t)))
2361 ;; Incomplete block: parse it as a paragraph.
2362 (org-element-paragraph-parser limit affiliated)
2363 (let ((contents-end (match-beginning 0)))
2364 (save-excursion
2365 (let* ((begin (car affiliated))
2366 (post-affiliated (point))
2367 ;; Get language as a string.
2368 (language
2369 (progn
2370 (looking-at
2371 (concat "^[ \t]*#\\+BEGIN_SRC"
2372 "\\(?: +\\(\\S-+\\)\\)?"
2373 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2374 "\\(.*\\)[ \t]*$"))
2375 (org-match-string-no-properties 1)))
2376 ;; Get switches.
2377 (switches (org-match-string-no-properties 2))
2378 ;; Get parameters.
2379 (parameters (org-match-string-no-properties 3))
2380 ;; Switches analysis
2381 (number-lines
2382 (cond ((not switches) nil)
2383 ((string-match "-n\\>" switches) 'new)
2384 ((string-match "+n\\>" switches) 'continued)))
2385 (preserve-indent (and switches
2386 (string-match "-i\\>" switches)))
2387 (label-fmt
2388 (and switches
2389 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2390 (match-string 1 switches)))
2391 ;; Should labels be retained in (or stripped from)
2392 ;; src blocks?
2393 (retain-labels
2394 (or (not switches)
2395 (not (string-match "-r\\>" switches))
2396 (and number-lines (string-match "-k\\>" switches))))
2397 ;; What should code-references use - labels or
2398 ;; line-numbers?
2399 (use-labels
2400 (or (not switches)
2401 (and retain-labels
2402 (not (string-match "-k\\>" switches)))))
2403 ;; Indentation.
2404 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2405 ;; Retrieve code.
2406 (value (org-element-remove-indentation
2407 (org-unescape-code-in-string
2408 (buffer-substring-no-properties
2409 (progn (forward-line) (point)) contents-end))
2410 block-ind))
2411 (pos-before-blank (progn (goto-char contents-end)
2412 (forward-line)
2413 (point)))
2414 ;; Get position after ending blank lines.
2415 (end (progn (skip-chars-forward " \r\t\n" limit)
2416 (if (eobp) (point) (line-beginning-position)))))
2417 (list 'src-block
2418 (nconc
2419 (list :language language
2420 :switches (and (org-string-nw-p switches)
2421 (org-trim switches))
2422 :parameters (and (org-string-nw-p parameters)
2423 (org-trim parameters))
2424 :begin begin
2425 :end end
2426 :number-lines number-lines
2427 :preserve-indent preserve-indent
2428 :retain-labels retain-labels
2429 :use-labels use-labels
2430 :label-fmt label-fmt
2431 :value value
2432 :post-blank (count-lines pos-before-blank end)
2433 :post-affiliated post-affiliated)
2434 (cdr affiliated)))))))))
2436 (defun org-element-src-block-interpreter (src-block _)
2437 "Interpret SRC-BLOCK element as Org syntax."
2438 (let ((lang (org-element-property :language src-block))
2439 (switches (org-element-property :switches src-block))
2440 (params (org-element-property :parameters src-block))
2441 (value
2442 (let ((val (org-element-property :value src-block)))
2443 (cond
2444 ((or org-src-preserve-indentation
2445 (org-element-property :preserve-indent src-block))
2446 val)
2447 ((zerop org-edit-src-content-indentation) val)
2449 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2450 (replace-regexp-in-string
2451 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2452 (concat (format "#+BEGIN_SRC%s\n"
2453 (concat (and lang (concat " " lang))
2454 (and switches (concat " " switches))
2455 (and params (concat " " params))))
2456 (org-element-normalize-string (org-escape-code-in-string value))
2457 "#+END_SRC")))
2460 ;;;; Table
2462 (defun org-element-table-parser (limit affiliated)
2463 "Parse a table at point.
2465 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2466 the buffer position at the beginning of the first affiliated
2467 keyword and CDR is a plist of affiliated keywords along with
2468 their value.
2470 Return a list whose CAR is `table' and CDR is a plist containing
2471 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2472 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2473 keywords.
2475 Assume point is at the beginning of the table."
2476 (save-excursion
2477 (let* ((case-fold-search t)
2478 (table-begin (point))
2479 (type (if (looking-at "[ \t]*|") 'org 'table.el))
2480 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2481 (if (eq type 'org) "" "+")))
2482 (begin (car affiliated))
2483 (table-end
2484 (if (re-search-forward end-re limit 'move)
2485 (goto-char (match-beginning 0))
2486 (point)))
2487 (tblfm (let (acc)
2488 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2489 (push (org-match-string-no-properties 1) acc)
2490 (forward-line))
2491 acc))
2492 (pos-before-blank (point))
2493 (end (progn (skip-chars-forward " \r\t\n" limit)
2494 (if (eobp) (point) (line-beginning-position)))))
2495 (list 'table
2496 (nconc
2497 (list :begin begin
2498 :end end
2499 :type type
2500 :tblfm tblfm
2501 ;; Only `org' tables have contents. `table.el' tables
2502 ;; use a `:value' property to store raw table as
2503 ;; a string.
2504 :contents-begin (and (eq type 'org) table-begin)
2505 :contents-end (and (eq type 'org) table-end)
2506 :value (and (eq type 'table.el)
2507 (buffer-substring-no-properties
2508 table-begin table-end))
2509 :post-blank (count-lines pos-before-blank end)
2510 :post-affiliated table-begin)
2511 (cdr affiliated))))))
2513 (defun org-element-table-interpreter (table contents)
2514 "Interpret TABLE element as Org syntax.
2515 CONTENTS is a string, if table's type is `org', or nil."
2516 (if (eq (org-element-property :type table) 'table.el)
2517 (org-remove-indentation (org-element-property :value table))
2518 (concat (with-temp-buffer (insert contents)
2519 (org-table-align)
2520 (buffer-string))
2521 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2522 (reverse (org-element-property :tblfm table))
2523 "\n"))))
2526 ;;;; Table Row
2528 (defun org-element-table-row-parser (_)
2529 "Parse table row at point.
2531 Return a list whose CAR is `table-row' and CDR is a plist
2532 containing `:begin', `:end', `:contents-begin', `:contents-end',
2533 `:type', `:post-blank' and `:post-affiliated' keywords."
2534 (save-excursion
2535 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2536 (begin (point))
2537 ;; A table rule has no contents. In that case, ensure
2538 ;; CONTENTS-BEGIN matches CONTENTS-END.
2539 (contents-begin (and (eq type 'standard) (search-forward "|")))
2540 (contents-end (and (eq type 'standard)
2541 (progn
2542 (end-of-line)
2543 (skip-chars-backward " \t")
2544 (point))))
2545 (end (line-beginning-position 2)))
2546 (list 'table-row
2547 (list :type type
2548 :begin begin
2549 :end end
2550 :contents-begin contents-begin
2551 :contents-end contents-end
2552 :post-blank 0
2553 :post-affiliated begin)))))
2555 (defun org-element-table-row-interpreter (table-row contents)
2556 "Interpret TABLE-ROW element as Org syntax.
2557 CONTENTS is the contents of the table row."
2558 (if (eq (org-element-property :type table-row) 'rule) "|-"
2559 (concat "| " contents)))
2562 ;;;; Verse Block
2564 (defun org-element-verse-block-parser (limit affiliated)
2565 "Parse a verse block.
2567 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2568 the buffer position at the beginning of the first affiliated
2569 keyword and CDR is a plist of affiliated keywords along with
2570 their value.
2572 Return a list whose CAR is `verse-block' and CDR is a plist
2573 containing `:begin', `:end', `:contents-begin', `:contents-end',
2574 `:post-blank' and `:post-affiliated' keywords.
2576 Assume point is at beginning of the block."
2577 (let ((case-fold-search t))
2578 (if (not (save-excursion
2579 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2580 ;; Incomplete block: parse it as a paragraph.
2581 (org-element-paragraph-parser limit affiliated)
2582 (let ((contents-end (match-beginning 0)))
2583 (save-excursion
2584 (let* ((begin (car affiliated))
2585 (post-affiliated (point))
2586 (contents-begin (progn (forward-line) (point)))
2587 (pos-before-blank (progn (goto-char contents-end)
2588 (forward-line)
2589 (point)))
2590 (end (progn (skip-chars-forward " \r\t\n" limit)
2591 (if (eobp) (point) (line-beginning-position)))))
2592 (list 'verse-block
2593 (nconc
2594 (list :begin begin
2595 :end end
2596 :contents-begin contents-begin
2597 :contents-end contents-end
2598 :post-blank (count-lines pos-before-blank end)
2599 :post-affiliated post-affiliated)
2600 (cdr affiliated)))))))))
2602 (defun org-element-verse-block-interpreter (_ contents)
2603 "Interpret verse-block element as Org syntax.
2604 CONTENTS is verse block contents."
2605 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2609 ;;; Objects
2611 ;; Unlike to elements, raw text can be found between objects. Hence,
2612 ;; `org-element--object-lex' is provided to find the next object in
2613 ;; buffer.
2615 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2616 ;; object types they can contain will be specified in
2617 ;; `org-element-object-restrictions'.
2619 ;; Creating a new type of object requires to alter
2620 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2621 ;; new type in `org-element-all-objects', and possibly add
2622 ;; restrictions in `org-element-object-restrictions'.
2624 ;;;; Bold
2626 (defun org-element-bold-parser ()
2627 "Parse bold object at point, if any.
2629 When at a bold object, return a list whose car is `bold' and cdr
2630 is a plist with `:begin', `:end', `:contents-begin' and
2631 `:contents-end' and `:post-blank' keywords. Otherwise, return
2632 nil.
2634 Assume point is at the first star marker."
2635 (save-excursion
2636 (unless (bolp) (backward-char 1))
2637 (when (looking-at org-emph-re)
2638 (let ((begin (match-beginning 2))
2639 (contents-begin (match-beginning 4))
2640 (contents-end (match-end 4))
2641 (post-blank (progn (goto-char (match-end 2))
2642 (skip-chars-forward " \t")))
2643 (end (point)))
2644 (list 'bold
2645 (list :begin begin
2646 :end end
2647 :contents-begin contents-begin
2648 :contents-end contents-end
2649 :post-blank post-blank))))))
2651 (defun org-element-bold-interpreter (_ contents)
2652 "Interpret bold object as Org syntax.
2653 CONTENTS is the contents of the object."
2654 (format "*%s*" contents))
2657 ;;;; Code
2659 (defun org-element-code-parser ()
2660 "Parse code object at point, if any.
2662 When at a code object, return a list whose car is `code' and cdr
2663 is a plist with `:value', `:begin', `:end' and `:post-blank'
2664 keywords. Otherwise, return nil.
2666 Assume point is at the first tilde marker."
2667 (save-excursion
2668 (unless (bolp) (backward-char 1))
2669 (when (looking-at org-emph-re)
2670 (let ((begin (match-beginning 2))
2671 (value (org-match-string-no-properties 4))
2672 (post-blank (progn (goto-char (match-end 2))
2673 (skip-chars-forward " \t")))
2674 (end (point)))
2675 (list 'code
2676 (list :value value
2677 :begin begin
2678 :end end
2679 :post-blank post-blank))))))
2681 (defun org-element-code-interpreter (code _)
2682 "Interpret CODE object as Org syntax."
2683 (format "~%s~" (org-element-property :value code)))
2686 ;;;; Entity
2688 (defun org-element-entity-parser ()
2689 "Parse entity at point, if any.
2691 When at an entity, return a list whose car is `entity' and cdr
2692 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2693 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2694 `:post-blank' as keywords. Otherwise, return nil.
2696 Assume point is at the beginning of the entity."
2697 (catch 'no-object
2698 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2699 (save-excursion
2700 (let* ((value (or (org-entity-get (match-string 1))
2701 (throw 'no-object nil)))
2702 (begin (match-beginning 0))
2703 (bracketsp (string= (match-string 2) "{}"))
2704 (post-blank (progn (goto-char (match-end 1))
2705 (when bracketsp (forward-char 2))
2706 (skip-chars-forward " \t")))
2707 (end (point)))
2708 (list 'entity
2709 (list :name (car value)
2710 :latex (nth 1 value)
2711 :latex-math-p (nth 2 value)
2712 :html (nth 3 value)
2713 :ascii (nth 4 value)
2714 :latin1 (nth 5 value)
2715 :utf-8 (nth 6 value)
2716 :begin begin
2717 :end end
2718 :use-brackets-p bracketsp
2719 :post-blank post-blank)))))))
2721 (defun org-element-entity-interpreter (entity _)
2722 "Interpret ENTITY object as Org syntax."
2723 (concat "\\"
2724 (org-element-property :name entity)
2725 (when (org-element-property :use-brackets-p entity) "{}")))
2728 ;;;; Export Snippet
2730 (defun org-element-export-snippet-parser ()
2731 "Parse export snippet at point.
2733 When at an export snippet, return a list whose car is
2734 `export-snippet' and cdr a plist with `:begin', `:end',
2735 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2736 return nil.
2738 Assume point is at the beginning of the snippet."
2739 (save-excursion
2740 (let (contents-end)
2741 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2742 (setq contents-end
2743 (save-match-data (goto-char (match-end 0))
2744 (re-search-forward "@@" nil t)
2745 (match-beginning 0))))
2746 (let* ((begin (match-beginning 0))
2747 (back-end (org-match-string-no-properties 1))
2748 (value (buffer-substring-no-properties
2749 (match-end 0) contents-end))
2750 (post-blank (skip-chars-forward " \t"))
2751 (end (point)))
2752 (list 'export-snippet
2753 (list :back-end back-end
2754 :value value
2755 :begin begin
2756 :end end
2757 :post-blank post-blank)))))))
2759 (defun org-element-export-snippet-interpreter (export-snippet _)
2760 "Interpret EXPORT-SNIPPET object as Org syntax."
2761 (format "@@%s:%s@@"
2762 (org-element-property :back-end export-snippet)
2763 (org-element-property :value export-snippet)))
2766 ;;;; Footnote Reference
2768 (defun org-element-footnote-reference-parser ()
2769 "Parse footnote reference at point, if any.
2771 When at a footnote reference, return a list whose car is
2772 `footnote-reference' and cdr a plist with `:label', `:type',
2773 `:begin', `:end', `:content-begin', `:contents-end' and
2774 `:post-blank' as keywords. Otherwise, return nil."
2775 (when (looking-at org-footnote-re)
2776 (let ((closing (with-syntax-table org-element--pair-square-table
2777 (ignore-errors (scan-lists (point) 1 0)))))
2778 (when closing
2779 (save-excursion
2780 (let* ((begin (point))
2781 (label
2782 (or (org-match-string-no-properties 2)
2783 (org-match-string-no-properties 3)
2784 (and (match-string 1)
2785 (concat "fn:" (org-match-string-no-properties 1)))))
2786 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2787 (inner-begin (match-end 0))
2788 (inner-end (1- closing))
2789 (post-blank (progn (goto-char closing)
2790 (skip-chars-forward " \t")))
2791 (end (point)))
2792 (list 'footnote-reference
2793 (list :label label
2794 :type type
2795 :begin begin
2796 :end end
2797 :contents-begin (and (eq type 'inline) inner-begin)
2798 :contents-end (and (eq type 'inline) inner-end)
2799 :post-blank post-blank))))))))
2801 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2802 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2803 CONTENTS is its definition, when inline, or nil."
2804 (format "[%s]"
2805 (concat (or (org-element-property :label footnote-reference) "fn:")
2806 (and contents (concat ":" contents)))))
2809 ;;;; Inline Babel Call
2811 (defun org-element-inline-babel-call-parser ()
2812 "Parse inline babel call at point, if any.
2814 When at an inline babel call, return a list whose car is
2815 `inline-babel-call' and cdr a plist with `:call',
2816 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2817 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2819 Assume point is at the beginning of the babel call."
2820 (save-excursion
2821 (unless (bolp) (backward-char))
2822 (when (let ((case-fold-search t))
2823 (looking-at org-babel-inline-lob-one-liner-regexp))
2824 (let ((begin (match-end 1))
2825 (call (org-match-string-no-properties 2))
2826 (inside-header (org-string-nw-p (org-match-string-no-properties 4)))
2827 (arguments (org-string-nw-p (org-match-string-no-properties 6)))
2828 (end-header (org-string-nw-p (org-match-string-no-properties 8)))
2829 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2830 (post-blank (progn (goto-char (match-end 0))
2831 (skip-chars-forward " \t")))
2832 (end (point)))
2833 (list 'inline-babel-call
2834 (list :call call
2835 :inside-header inside-header
2836 :arguments arguments
2837 :end-header end-header
2838 :begin begin
2839 :end end
2840 :value value
2841 :post-blank post-blank))))))
2843 (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
2844 "Interpret INLINE-BABEL-CALL object as Org syntax."
2845 (concat "call_"
2846 (org-element-property :call inline-babel-call)
2847 (let ((h (org-element-property :inside-header inline-babel-call)))
2848 (and h (format "[%s]" h)))
2849 "(" (org-element-property :arguments inline-babel-call) ")"
2850 (let ((h (org-element-property :end-header inline-babel-call)))
2851 (and h (format "[%s]" h)))))
2854 ;;;; Inline Src Block
2856 (defun org-element-inline-src-block-parser ()
2857 "Parse inline source block at point, if any.
2859 When at an inline source block, return a list whose car is
2860 `inline-src-block' and cdr a plist with `:begin', `:end',
2861 `:language', `:value', `:parameters' and `:post-blank' as
2862 keywords. Otherwise, return nil.
2864 Assume point is at the beginning of the inline src block."
2865 (save-excursion
2866 (unless (bolp) (backward-char))
2867 (when (looking-at org-babel-inline-src-block-regexp)
2868 (let ((begin (match-beginning 1))
2869 (language (org-match-string-no-properties 2))
2870 (parameters (org-match-string-no-properties 4))
2871 (value (org-match-string-no-properties 5))
2872 (post-blank (progn (goto-char (match-end 0))
2873 (skip-chars-forward " \t")))
2874 (end (point)))
2875 (list 'inline-src-block
2876 (list :language language
2877 :value value
2878 :parameters parameters
2879 :begin begin
2880 :end end
2881 :post-blank post-blank))))))
2883 (defun org-element-inline-src-block-interpreter (inline-src-block _)
2884 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2885 (let ((language (org-element-property :language inline-src-block))
2886 (arguments (org-element-property :parameters inline-src-block))
2887 (body (org-element-property :value inline-src-block)))
2888 (format "src_%s%s{%s}"
2889 language
2890 (if arguments (format "[%s]" arguments) "")
2891 body)))
2893 ;;;; Italic
2895 (defun org-element-italic-parser ()
2896 "Parse italic object at point, if any.
2898 When at an italic object, return a list whose car is `italic' and
2899 cdr is a plist with `:begin', `:end', `:contents-begin' and
2900 `:contents-end' and `:post-blank' keywords. Otherwise, return
2901 nil.
2903 Assume point is at the first slash marker."
2904 (save-excursion
2905 (unless (bolp) (backward-char 1))
2906 (when (looking-at org-emph-re)
2907 (let ((begin (match-beginning 2))
2908 (contents-begin (match-beginning 4))
2909 (contents-end (match-end 4))
2910 (post-blank (progn (goto-char (match-end 2))
2911 (skip-chars-forward " \t")))
2912 (end (point)))
2913 (list 'italic
2914 (list :begin begin
2915 :end end
2916 :contents-begin contents-begin
2917 :contents-end contents-end
2918 :post-blank post-blank))))))
2920 (defun org-element-italic-interpreter (_ contents)
2921 "Interpret italic object as Org syntax.
2922 CONTENTS is the contents of the object."
2923 (format "/%s/" contents))
2926 ;;;; Latex Fragment
2928 (defun org-element-latex-fragment-parser ()
2929 "Parse LaTeX fragment at point, if any.
2931 When at a LaTeX fragment, return a list whose car is
2932 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2933 and `:post-blank' as keywords. Otherwise, return nil.
2935 Assume point is at the beginning of the LaTeX fragment."
2936 (catch 'no-object
2937 (save-excursion
2938 (let* ((begin (point))
2939 (after-fragment
2940 (if (eq (char-after) ?$)
2941 (if (eq (char-after (1+ (point))) ?$)
2942 (search-forward "$$" nil t 2)
2943 (and (not (eq (char-before) ?$))
2944 (search-forward "$" nil t 2)
2945 (not (memq (char-before (match-beginning 0))
2946 '(?\s ?\t ?\n ?, ?.)))
2947 (looking-at "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|$\\)")
2948 (point)))
2949 (case (char-after (1+ (point)))
2950 (?\( (search-forward "\\)" nil t))
2951 (?\[ (search-forward "\\]" nil t))
2952 (otherwise
2953 ;; Macro.
2954 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2955 (match-end 0))))))
2956 (post-blank (if (not after-fragment) (throw 'no-object nil)
2957 (goto-char after-fragment)
2958 (skip-chars-forward " \t")))
2959 (end (point)))
2960 (list 'latex-fragment
2961 (list :value (buffer-substring-no-properties begin after-fragment)
2962 :begin begin
2963 :end end
2964 :post-blank post-blank))))))
2966 (defun org-element-latex-fragment-interpreter (latex-fragment _)
2967 "Interpret LATEX-FRAGMENT object as Org syntax."
2968 (org-element-property :value latex-fragment))
2970 ;;;; Line Break
2972 (defun org-element-line-break-parser ()
2973 "Parse line break at point, if any.
2975 When at a line break, return a list whose car is `line-break',
2976 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2977 Otherwise, return nil.
2979 Assume point is at the beginning of the line break."
2980 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2981 (not (eq (char-before) ?\\)))
2982 (list 'line-break
2983 (list :begin (point)
2984 :end (line-beginning-position 2)
2985 :post-blank 0))))
2987 (defun org-element-line-break-interpreter (&rest _)
2988 "Interpret LINE-BREAK object as Org syntax."
2989 "\\\\\n")
2992 ;;;; Link
2994 (defun org-element-link-parser ()
2995 "Parse link at point, if any.
2997 When at a link, return a list whose car is `link' and cdr a plist
2998 with `:type', `:path', `:raw-link', `:application',
2999 `:search-option', `:begin', `:end', `:contents-begin',
3000 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3001 nil.
3003 Assume point is at the beginning of the link."
3004 (catch 'no-object
3005 (let ((begin (point))
3006 end contents-begin contents-end link-end post-blank path type
3007 raw-link search-option application)
3008 (cond
3009 ;; Type 1: Text targeted from a radio target.
3010 ((and org-target-link-regexp
3011 (save-excursion (or (bolp) (backward-char))
3012 (looking-at org-target-link-regexp)))
3013 (setq type "radio"
3014 link-end (match-end 1)
3015 path (org-match-string-no-properties 1)
3016 contents-begin (match-beginning 1)
3017 contents-end (match-end 1)))
3018 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3019 ((looking-at org-bracket-link-regexp)
3020 (setq contents-begin (match-beginning 3))
3021 (setq contents-end (match-end 3))
3022 (setq link-end (match-end 0))
3023 ;; RAW-LINK is the original link. Expand any
3024 ;; abbreviation in it.
3026 ;; Also treat any newline character and associated
3027 ;; indentation as a single space character. This is not
3028 ;; compatible with RFC 3986, which requires to ignore
3029 ;; them altogether. However, doing so would require
3030 ;; users to encode spaces on the fly when writing links
3031 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3032 ;; [[shell:ls *.org]], which defeats Org's focus on
3033 ;; simplicity.
3034 (setq raw-link (org-translate-link
3035 (org-link-expand-abbrev
3036 (replace-regexp-in-string
3037 "[ \t]*\n[ \t]*" " "
3038 (org-match-string-no-properties 1)))))
3039 ;; Determine TYPE of link and set PATH accordingly. According
3040 ;; to RFC 3986, remove whitespaces from URI in external links.
3041 ;; In internal ones, treat indentation as a single space.
3042 (cond
3043 ;; File type.
3044 ((or (file-name-absolute-p raw-link)
3045 (string-match "\\`\\.\\.?/" raw-link))
3046 (setq type "file")
3047 (setq path raw-link))
3048 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3049 ((string-match org-link-types-re raw-link)
3050 (setq type (match-string 1 raw-link))
3051 (setq path (substring raw-link (match-end 0))))
3052 ;; Id type: PATH is the id.
3053 ((string-match "\\`id:\\([-a-f0-9]+\\)\\'" raw-link)
3054 (setq type "id" path (match-string 1 raw-link)))
3055 ;; Code-ref type: PATH is the name of the reference.
3056 ((and (org-string-match-p "\\`(" raw-link)
3057 (org-string-match-p ")\\'" raw-link))
3058 (setq type "coderef")
3059 (setq path (substring raw-link 1 -1)))
3060 ;; Custom-id type: PATH is the name of the custom id.
3061 ((= (string-to-char raw-link) ?#)
3062 (setq type "custom-id")
3063 (setq path (substring raw-link 1)))
3064 ;; Fuzzy type: Internal link either matches a target, an
3065 ;; headline name or nothing. PATH is the target or
3066 ;; headline's name.
3068 (setq type "fuzzy")
3069 (setq path raw-link))))
3070 ;; Type 3: Plain link, e.g., http://orgmode.org
3071 ((looking-at org-plain-link-re)
3072 (setq raw-link (org-match-string-no-properties 0)
3073 type (org-match-string-no-properties 1)
3074 link-end (match-end 0)
3075 path (org-match-string-no-properties 2)))
3076 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3077 ;; bracket links, follow RFC 3986 and remove any extra
3078 ;; whitespace in URI.
3079 ((looking-at org-angle-link-re)
3080 (setq type (org-match-string-no-properties 1))
3081 (setq link-end (match-end 0))
3082 (setq raw-link
3083 (buffer-substring-no-properties
3084 (match-beginning 1) (match-end 2)))
3085 (setq path (replace-regexp-in-string
3086 "[ \t]*\n[ \t]*" "" (org-match-string-no-properties 2))))
3087 (t (throw 'no-object nil)))
3088 ;; In any case, deduce end point after trailing white space from
3089 ;; LINK-END variable.
3090 (save-excursion
3091 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3092 end (point))
3093 ;; Special "file" type link processing. Extract opening
3094 ;; application and search option, if any. Also normalize URI.
3095 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3096 (setq application (match-string 1 type) type "file")
3097 (when (string-match "::\\(.*\\)\\'" path)
3098 (setq search-option (match-string 1 path)
3099 path (replace-match "" nil nil path)))
3100 (setq path (replace-regexp-in-string "\\`/+" "/" path)))
3101 (list 'link
3102 (list :type type
3103 :path path
3104 :raw-link (or raw-link path)
3105 :application application
3106 :search-option search-option
3107 :begin begin
3108 :end end
3109 :contents-begin contents-begin
3110 :contents-end contents-end
3111 :post-blank post-blank))))))
3113 (defun org-element-link-interpreter (link contents)
3114 "Interpret LINK object as Org syntax.
3115 CONTENTS is the contents of the object, or nil."
3116 (let ((type (org-element-property :type link))
3117 (raw-link (org-element-property :raw-link link)))
3118 (if (string= type "radio") raw-link
3119 (format "[[%s]%s]"
3120 raw-link
3121 (if contents (format "[%s]" contents) "")))))
3124 ;;;; Macro
3126 (defun org-element-macro-parser ()
3127 "Parse macro at point, if any.
3129 When at a macro, return a list whose car is `macro' and cdr
3130 a plist with `:key', `:args', `:begin', `:end', `:value' and
3131 `:post-blank' as keywords. Otherwise, return nil.
3133 Assume point is at the macro."
3134 (save-excursion
3135 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3136 (let ((begin (point))
3137 (key (downcase (org-match-string-no-properties 1)))
3138 (value (org-match-string-no-properties 0))
3139 (post-blank (progn (goto-char (match-end 0))
3140 (skip-chars-forward " \t")))
3141 (end (point))
3142 (args (let ((args (org-match-string-no-properties 3)))
3143 (and args (org-macro-extract-arguments args)))))
3144 (list 'macro
3145 (list :key key
3146 :value value
3147 :args args
3148 :begin begin
3149 :end end
3150 :post-blank post-blank))))))
3152 (defun org-element-macro-interpreter (macro _)
3153 "Interpret MACRO object as Org syntax."
3154 (org-element-property :value macro))
3157 ;;;; Radio-target
3159 (defun org-element-radio-target-parser ()
3160 "Parse radio target at point, if any.
3162 When at a radio target, return a list whose car is `radio-target'
3163 and cdr a plist with `:begin', `:end', `:contents-begin',
3164 `:contents-end', `:value' and `:post-blank' as keywords.
3165 Otherwise, return nil.
3167 Assume point is at the radio target."
3168 (save-excursion
3169 (when (looking-at org-radio-target-regexp)
3170 (let ((begin (point))
3171 (contents-begin (match-beginning 1))
3172 (contents-end (match-end 1))
3173 (value (org-match-string-no-properties 1))
3174 (post-blank (progn (goto-char (match-end 0))
3175 (skip-chars-forward " \t")))
3176 (end (point)))
3177 (list 'radio-target
3178 (list :begin begin
3179 :end end
3180 :contents-begin contents-begin
3181 :contents-end contents-end
3182 :post-blank post-blank
3183 :value value))))))
3185 (defun org-element-radio-target-interpreter (_ contents)
3186 "Interpret target object as Org syntax.
3187 CONTENTS is the contents of the object."
3188 (concat "<<<" contents ">>>"))
3191 ;;;; Statistics Cookie
3193 (defun org-element-statistics-cookie-parser ()
3194 "Parse statistics cookie at point, if any.
3196 When at a statistics cookie, return a list whose car is
3197 `statistics-cookie', and cdr a plist with `:begin', `:end',
3198 `:value' and `:post-blank' keywords. Otherwise, return nil.
3200 Assume point is at the beginning of the statistics-cookie."
3201 (save-excursion
3202 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3203 (let* ((begin (point))
3204 (value (buffer-substring-no-properties
3205 (match-beginning 0) (match-end 0)))
3206 (post-blank (progn (goto-char (match-end 0))
3207 (skip-chars-forward " \t")))
3208 (end (point)))
3209 (list 'statistics-cookie
3210 (list :begin begin
3211 :end end
3212 :value value
3213 :post-blank post-blank))))))
3215 (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
3216 "Interpret STATISTICS-COOKIE object as Org syntax."
3217 (org-element-property :value statistics-cookie))
3220 ;;;; Strike-Through
3222 (defun org-element-strike-through-parser ()
3223 "Parse strike-through object at point, if any.
3225 When at a strike-through object, return a list whose car is
3226 `strike-through' and cdr is a plist with `:begin', `:end',
3227 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3228 Otherwise, return nil.
3230 Assume point is at the first plus sign marker."
3231 (save-excursion
3232 (unless (bolp) (backward-char 1))
3233 (when (looking-at org-emph-re)
3234 (let ((begin (match-beginning 2))
3235 (contents-begin (match-beginning 4))
3236 (contents-end (match-end 4))
3237 (post-blank (progn (goto-char (match-end 2))
3238 (skip-chars-forward " \t")))
3239 (end (point)))
3240 (list 'strike-through
3241 (list :begin begin
3242 :end end
3243 :contents-begin contents-begin
3244 :contents-end contents-end
3245 :post-blank post-blank))))))
3247 (defun org-element-strike-through-interpreter (_ contents)
3248 "Interpret strike-through object as Org syntax.
3249 CONTENTS is the contents of the object."
3250 (format "+%s+" contents))
3253 ;;;; Subscript
3255 (defun org-element-subscript-parser ()
3256 "Parse subscript at point, if any.
3258 When at a subscript object, return a list whose car is
3259 `subscript' and cdr a plist with `:begin', `:end',
3260 `:contents-begin', `:contents-end', `:use-brackets-p' and
3261 `:post-blank' as keywords. Otherwise, return nil.
3263 Assume point is at the underscore."
3264 (save-excursion
3265 (unless (bolp) (backward-char))
3266 (when (looking-at org-match-substring-regexp)
3267 (let ((bracketsp (match-beginning 4))
3268 (begin (match-beginning 2))
3269 (contents-begin (or (match-beginning 4)
3270 (match-beginning 3)))
3271 (contents-end (or (match-end 4) (match-end 3)))
3272 (post-blank (progn (goto-char (match-end 0))
3273 (skip-chars-forward " \t")))
3274 (end (point)))
3275 (list 'subscript
3276 (list :begin begin
3277 :end end
3278 :use-brackets-p bracketsp
3279 :contents-begin contents-begin
3280 :contents-end contents-end
3281 :post-blank post-blank))))))
3283 (defun org-element-subscript-interpreter (subscript contents)
3284 "Interpret SUBSCRIPT object as Org syntax.
3285 CONTENTS is the contents of the object."
3286 (format
3287 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3288 contents))
3291 ;;;; Superscript
3293 (defun org-element-superscript-parser ()
3294 "Parse superscript at point, if any.
3296 When at a superscript object, return a list whose car is
3297 `superscript' and cdr a plist with `:begin', `:end',
3298 `:contents-begin', `:contents-end', `:use-brackets-p' and
3299 `:post-blank' as keywords. Otherwise, return nil.
3301 Assume point is at the caret."
3302 (save-excursion
3303 (unless (bolp) (backward-char))
3304 (when (looking-at org-match-substring-regexp)
3305 (let ((bracketsp (match-beginning 4))
3306 (begin (match-beginning 2))
3307 (contents-begin (or (match-beginning 4)
3308 (match-beginning 3)))
3309 (contents-end (or (match-end 4) (match-end 3)))
3310 (post-blank (progn (goto-char (match-end 0))
3311 (skip-chars-forward " \t")))
3312 (end (point)))
3313 (list 'superscript
3314 (list :begin begin
3315 :end end
3316 :use-brackets-p bracketsp
3317 :contents-begin contents-begin
3318 :contents-end contents-end
3319 :post-blank post-blank))))))
3321 (defun org-element-superscript-interpreter (superscript contents)
3322 "Interpret SUPERSCRIPT object as Org syntax.
3323 CONTENTS is the contents of the object."
3324 (format
3325 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3326 contents))
3329 ;;;; Table Cell
3331 (defun org-element-table-cell-parser ()
3332 "Parse table cell at point.
3333 Return a list whose car is `table-cell' and cdr is a plist
3334 containing `:begin', `:end', `:contents-begin', `:contents-end'
3335 and `:post-blank' keywords."
3336 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3337 (let* ((begin (match-beginning 0))
3338 (end (match-end 0))
3339 (contents-begin (match-beginning 1))
3340 (contents-end (match-end 1)))
3341 (list 'table-cell
3342 (list :begin begin
3343 :end end
3344 :contents-begin contents-begin
3345 :contents-end contents-end
3346 :post-blank 0))))
3348 (defun org-element-table-cell-interpreter (_ contents)
3349 "Interpret table-cell element as Org syntax.
3350 CONTENTS is the contents of the cell, or nil."
3351 (concat " " contents " |"))
3354 ;;;; Target
3356 (defun org-element-target-parser ()
3357 "Parse target at point, if any.
3359 When at a target, return a list whose car is `target' and cdr
3360 a plist with `:begin', `:end', `:value' and `:post-blank' as
3361 keywords. Otherwise, return nil.
3363 Assume point is at the target."
3364 (save-excursion
3365 (when (looking-at org-target-regexp)
3366 (let ((begin (point))
3367 (value (org-match-string-no-properties 1))
3368 (post-blank (progn (goto-char (match-end 0))
3369 (skip-chars-forward " \t")))
3370 (end (point)))
3371 (list 'target
3372 (list :begin begin
3373 :end end
3374 :value value
3375 :post-blank post-blank))))))
3377 (defun org-element-target-interpreter (target _)
3378 "Interpret TARGET object as Org syntax."
3379 (format "<<%s>>" (org-element-property :value target)))
3382 ;;;; Timestamp
3384 (defconst org-element--timestamp-regexp
3385 (concat org-ts-regexp-both
3386 "\\|"
3387 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3388 "\\|"
3389 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3390 "Regexp matching any timestamp type object.")
3392 (defun org-element-timestamp-parser ()
3393 "Parse time stamp at point, if any.
3395 When at a time stamp, return a list whose car is `timestamp', and
3396 cdr a plist with `:type', `:raw-value', `:year-start',
3397 `:month-start', `:day-start', `:hour-start', `:minute-start',
3398 `:year-end', `:month-end', `:day-end', `:hour-end',
3399 `:minute-end', `:repeater-type', `:repeater-value',
3400 `:repeater-unit', `:warning-type', `:warning-value',
3401 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3402 Otherwise, return nil.
3404 Assume point is at the beginning of the timestamp."
3405 (when (org-looking-at-p org-element--timestamp-regexp)
3406 (save-excursion
3407 (let* ((begin (point))
3408 (activep (eq (char-after) ?<))
3409 (raw-value
3410 (progn
3411 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3412 (match-string-no-properties 0)))
3413 (date-start (match-string-no-properties 1))
3414 (date-end (match-string 3))
3415 (diaryp (match-beginning 2))
3416 (post-blank (progn (goto-char (match-end 0))
3417 (skip-chars-forward " \t")))
3418 (end (point))
3419 (time-range
3420 (and (not diaryp)
3421 (string-match
3422 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3423 date-start)
3424 (cons (string-to-number (match-string 2 date-start))
3425 (string-to-number (match-string 3 date-start)))))
3426 (type (cond (diaryp 'diary)
3427 ((and activep (or date-end time-range)) 'active-range)
3428 (activep 'active)
3429 ((or date-end time-range) 'inactive-range)
3430 (t 'inactive)))
3431 (repeater-props
3432 (and (not diaryp)
3433 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3434 raw-value)
3435 (list
3436 :repeater-type
3437 (let ((type (match-string 1 raw-value)))
3438 (cond ((equal "++" type) 'catch-up)
3439 ((equal ".+" type) 'restart)
3440 (t 'cumulate)))
3441 :repeater-value (string-to-number (match-string 2 raw-value))
3442 :repeater-unit
3443 (case (string-to-char (match-string 3 raw-value))
3444 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3445 (warning-props
3446 (and (not diaryp)
3447 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3448 (list
3449 :warning-type (if (match-string 1 raw-value) 'first 'all)
3450 :warning-value (string-to-number (match-string 2 raw-value))
3451 :warning-unit
3452 (case (string-to-char (match-string 3 raw-value))
3453 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3454 year-start month-start day-start hour-start minute-start year-end
3455 month-end day-end hour-end minute-end)
3456 ;; Parse date-start.
3457 (unless diaryp
3458 (let ((date (org-parse-time-string date-start t)))
3459 (setq year-start (nth 5 date)
3460 month-start (nth 4 date)
3461 day-start (nth 3 date)
3462 hour-start (nth 2 date)
3463 minute-start (nth 1 date))))
3464 ;; Compute date-end. It can be provided directly in time-stamp,
3465 ;; or extracted from time range. Otherwise, it defaults to the
3466 ;; same values as date-start.
3467 (unless diaryp
3468 (let ((date (and date-end (org-parse-time-string date-end t))))
3469 (setq year-end (or (nth 5 date) year-start)
3470 month-end (or (nth 4 date) month-start)
3471 day-end (or (nth 3 date) day-start)
3472 hour-end (or (nth 2 date) (car time-range) hour-start)
3473 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3474 (list 'timestamp
3475 (nconc (list :type type
3476 :raw-value raw-value
3477 :year-start year-start
3478 :month-start month-start
3479 :day-start day-start
3480 :hour-start hour-start
3481 :minute-start minute-start
3482 :year-end year-end
3483 :month-end month-end
3484 :day-end day-end
3485 :hour-end hour-end
3486 :minute-end minute-end
3487 :begin begin
3488 :end end
3489 :post-blank post-blank)
3490 repeater-props
3491 warning-props))))))
3493 (defun org-element-timestamp-interpreter (timestamp _)
3494 "Interpret TIMESTAMP object as Org syntax."
3495 (let* ((repeat-string
3496 (concat
3497 (case (org-element-property :repeater-type timestamp)
3498 (cumulate "+") (catch-up "++") (restart ".+"))
3499 (let ((val (org-element-property :repeater-value timestamp)))
3500 (and val (number-to-string val)))
3501 (case (org-element-property :repeater-unit timestamp)
3502 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3503 (warning-string
3504 (concat
3505 (case (org-element-property :warning-type timestamp)
3506 (first "--")
3507 (all "-"))
3508 (let ((val (org-element-property :warning-value timestamp)))
3509 (and val (number-to-string val)))
3510 (case (org-element-property :warning-unit timestamp)
3511 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3512 (build-ts-string
3513 ;; Build an Org timestamp string from TIME. ACTIVEP is
3514 ;; non-nil when time stamp is active. If WITH-TIME-P is
3515 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3516 ;; specify a time range in the timestamp. REPEAT-STRING is
3517 ;; the repeater string, if any.
3518 (lambda (time activep &optional with-time-p hour-end minute-end)
3519 (let ((ts (format-time-string
3520 (funcall (if with-time-p #'cdr #'car)
3521 org-time-stamp-formats)
3522 time)))
3523 (when (and hour-end minute-end)
3524 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3525 (setq ts
3526 (replace-match
3527 (format "\\&-%02d:%02d" hour-end minute-end)
3528 nil nil ts)))
3529 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3530 (dolist (s (list repeat-string warning-string))
3531 (when (org-string-nw-p s)
3532 (setq ts (concat (substring ts 0 -1)
3535 (substring ts -1)))))
3536 ;; Return value.
3537 ts)))
3538 (type (org-element-property :type timestamp)))
3539 (case type
3540 ((active inactive)
3541 (let* ((minute-start (org-element-property :minute-start timestamp))
3542 (minute-end (org-element-property :minute-end timestamp))
3543 (hour-start (org-element-property :hour-start timestamp))
3544 (hour-end (org-element-property :hour-end timestamp))
3545 (time-range-p (and hour-start hour-end minute-start minute-end
3546 (or (/= hour-start hour-end)
3547 (/= minute-start minute-end)))))
3548 (funcall
3549 build-ts-string
3550 (encode-time 0
3551 (or minute-start 0)
3552 (or hour-start 0)
3553 (org-element-property :day-start timestamp)
3554 (org-element-property :month-start timestamp)
3555 (org-element-property :year-start timestamp))
3556 (eq type 'active)
3557 (and hour-start minute-start)
3558 (and time-range-p hour-end)
3559 (and time-range-p minute-end))))
3560 ((active-range inactive-range)
3561 (let ((minute-start (org-element-property :minute-start timestamp))
3562 (minute-end (org-element-property :minute-end timestamp))
3563 (hour-start (org-element-property :hour-start timestamp))
3564 (hour-end (org-element-property :hour-end timestamp)))
3565 (concat
3566 (funcall
3567 build-ts-string (encode-time
3569 (or minute-start 0)
3570 (or hour-start 0)
3571 (org-element-property :day-start timestamp)
3572 (org-element-property :month-start timestamp)
3573 (org-element-property :year-start timestamp))
3574 (eq type 'active-range)
3575 (and hour-start minute-start))
3576 "--"
3577 (funcall build-ts-string
3578 (encode-time 0
3579 (or minute-end 0)
3580 (or hour-end 0)
3581 (org-element-property :day-end timestamp)
3582 (org-element-property :month-end timestamp)
3583 (org-element-property :year-end timestamp))
3584 (eq type 'active-range)
3585 (and hour-end minute-end)))))
3586 (otherwise (org-element-property :raw-value timestamp)))))
3589 ;;;; Underline
3591 (defun org-element-underline-parser ()
3592 "Parse underline object at point, if any.
3594 When at an underline object, return a list whose car is
3595 `underline' and cdr is a plist with `:begin', `:end',
3596 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3597 Otherwise, return nil.
3599 Assume point is at the first underscore marker."
3600 (save-excursion
3601 (unless (bolp) (backward-char 1))
3602 (when (looking-at org-emph-re)
3603 (let ((begin (match-beginning 2))
3604 (contents-begin (match-beginning 4))
3605 (contents-end (match-end 4))
3606 (post-blank (progn (goto-char (match-end 2))
3607 (skip-chars-forward " \t")))
3608 (end (point)))
3609 (list 'underline
3610 (list :begin begin
3611 :end end
3612 :contents-begin contents-begin
3613 :contents-end contents-end
3614 :post-blank post-blank))))))
3616 (defun org-element-underline-interpreter (_ contents)
3617 "Interpret underline object as Org syntax.
3618 CONTENTS is the contents of the object."
3619 (format "_%s_" contents))
3622 ;;;; Verbatim
3624 (defun org-element-verbatim-parser ()
3625 "Parse verbatim object at point, if any.
3627 When at a verbatim object, return a list whose car is `verbatim'
3628 and cdr is a plist with `:value', `:begin', `:end' and
3629 `:post-blank' keywords. Otherwise, return nil.
3631 Assume point is at the first equal sign marker."
3632 (save-excursion
3633 (unless (bolp) (backward-char 1))
3634 (when (looking-at org-emph-re)
3635 (let ((begin (match-beginning 2))
3636 (value (org-match-string-no-properties 4))
3637 (post-blank (progn (goto-char (match-end 2))
3638 (skip-chars-forward " \t")))
3639 (end (point)))
3640 (list 'verbatim
3641 (list :value value
3642 :begin begin
3643 :end end
3644 :post-blank post-blank))))))
3646 (defun org-element-verbatim-interpreter (verbatim _)
3647 "Interpret VERBATIM object as Org syntax."
3648 (format "=%s=" (org-element-property :value verbatim)))
3652 ;;; Parsing Element Starting At Point
3654 ;; `org-element--current-element' is the core function of this section.
3655 ;; It returns the Lisp representation of the element starting at
3656 ;; point.
3658 ;; `org-element--current-element' makes use of special modes. They
3659 ;; are activated for fixed element chaining (e.g., `plain-list' >
3660 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3661 ;; `section'). Special modes are: `first-section', `item',
3662 ;; `node-property', `section' and `table-row'.
3664 (defun org-element--current-element (limit &optional granularity mode structure)
3665 "Parse the element starting at point.
3667 Return value is a list like (TYPE PROPS) where TYPE is the type
3668 of the element and PROPS a plist of properties associated to the
3669 element.
3671 Possible types are defined in `org-element-all-elements'.
3673 LIMIT bounds the search.
3675 Optional argument GRANULARITY determines the depth of the
3676 recursion. Allowed values are `headline', `greater-element',
3677 `element', `object' or nil. When it is broader than `object' (or
3678 nil), secondary values will not be parsed, since they only
3679 contain objects.
3681 Optional argument MODE, when non-nil, can be either
3682 `first-section', `section', `planning', `item', `node-property'
3683 and `table-row'.
3685 If STRUCTURE isn't provided but MODE is set to `item', it will be
3686 computed.
3688 This function assumes point is always at the beginning of the
3689 element it has to parse."
3690 (save-excursion
3691 (let ((case-fold-search t)
3692 ;; Determine if parsing depth allows for secondary strings
3693 ;; parsing. It only applies to elements referenced in
3694 ;; `org-element-secondary-value-alist'.
3695 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3696 (cond
3697 ;; Item.
3698 ((eq mode 'item)
3699 (org-element-item-parser limit structure raw-secondary-p))
3700 ;; Table Row.
3701 ((eq mode 'table-row) (org-element-table-row-parser limit))
3702 ;; Node Property.
3703 ((eq mode 'node-property) (org-element-node-property-parser limit))
3704 ;; Headline.
3705 ((org-with-limited-levels (org-at-heading-p))
3706 (org-element-headline-parser limit raw-secondary-p))
3707 ;; Sections (must be checked after headline).
3708 ((eq mode 'section) (org-element-section-parser limit))
3709 ((eq mode 'first-section)
3710 (org-element-section-parser
3711 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3712 limit)))
3713 ;; Planning.
3714 ((and (eq mode 'planning) (looking-at org-planning-line-re))
3715 (org-element-planning-parser limit))
3716 ;; Property drawer.
3717 ((and (memq mode '(planning property-drawer))
3718 (looking-at org-property-drawer-re))
3719 (org-element-property-drawer-parser limit))
3720 ;; When not at bol, point is at the beginning of an item or
3721 ;; a footnote definition: next item is always a paragraph.
3722 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3723 ;; Clock.
3724 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3725 ;; Inlinetask.
3726 ((org-at-heading-p)
3727 (org-element-inlinetask-parser limit raw-secondary-p))
3728 ;; From there, elements can have affiliated keywords.
3729 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3730 (cond
3731 ;; Jumping over affiliated keywords put point off-limits.
3732 ;; Parse them as regular keywords.
3733 ((and (cdr affiliated) (>= (point) limit))
3734 (goto-char (car affiliated))
3735 (org-element-keyword-parser limit nil))
3736 ;; LaTeX Environment.
3737 ((looking-at org-element--latex-begin-environment)
3738 (org-element-latex-environment-parser limit affiliated))
3739 ;; Drawer and Property Drawer.
3740 ((looking-at org-drawer-regexp)
3741 (org-element-drawer-parser limit affiliated))
3742 ;; Fixed Width
3743 ((looking-at "[ \t]*:\\( \\|$\\)")
3744 (org-element-fixed-width-parser limit affiliated))
3745 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3746 ;; Keywords.
3747 ((looking-at "[ \t]*#")
3748 (goto-char (match-end 0))
3749 (cond ((looking-at "\\(?: \\|$\\)")
3750 (beginning-of-line)
3751 (org-element-comment-parser limit affiliated))
3752 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3753 (beginning-of-line)
3754 (let ((parser (assoc (upcase (match-string 1))
3755 org-element-block-name-alist)))
3756 (if parser (funcall (cdr parser) limit affiliated)
3757 (org-element-special-block-parser limit affiliated))))
3758 ((looking-at "\\+CALL:")
3759 (beginning-of-line)
3760 (org-element-babel-call-parser limit affiliated))
3761 ((looking-at "\\+BEGIN:? ")
3762 (beginning-of-line)
3763 (org-element-dynamic-block-parser limit affiliated))
3764 ((looking-at "\\+\\S-+:")
3765 (beginning-of-line)
3766 (org-element-keyword-parser limit affiliated))
3768 (beginning-of-line)
3769 (org-element-paragraph-parser limit affiliated))))
3770 ;; Footnote Definition.
3771 ((looking-at org-footnote-definition-re)
3772 (org-element-footnote-definition-parser limit affiliated))
3773 ;; Horizontal Rule.
3774 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3775 (org-element-horizontal-rule-parser limit affiliated))
3776 ;; Diary Sexp.
3777 ((looking-at "%%(")
3778 (org-element-diary-sexp-parser limit affiliated))
3779 ;; Table.
3780 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3781 (org-element-table-parser limit affiliated))
3782 ;; List.
3783 ((looking-at (org-item-re))
3784 (org-element-plain-list-parser
3785 limit affiliated
3786 (or structure (org-element--list-struct limit))))
3787 ;; Default element: Paragraph.
3788 (t (org-element-paragraph-parser limit affiliated)))))))))
3791 ;; Most elements can have affiliated keywords. When looking for an
3792 ;; element beginning, we want to move before them, as they belong to
3793 ;; that element, and, in the meantime, collect information they give
3794 ;; into appropriate properties. Hence the following function.
3796 (defun org-element--collect-affiliated-keywords (limit)
3797 "Collect affiliated keywords from point down to LIMIT.
3799 Return a list whose CAR is the position at the first of them and
3800 CDR a plist of keywords and values and move point to the
3801 beginning of the first line after them.
3803 As a special case, if element doesn't start at the beginning of
3804 the line (e.g., a paragraph starting an item), CAR is current
3805 position of point and CDR is nil."
3806 (if (not (bolp)) (list (point))
3807 (let ((case-fold-search t)
3808 (origin (point))
3809 ;; RESTRICT is the list of objects allowed in parsed
3810 ;; keywords value.
3811 (restrict (org-element-restriction 'keyword))
3812 output)
3813 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3814 (let* ((raw-kwd (upcase (match-string 1)))
3815 ;; Apply translation to RAW-KWD. From there, KWD is
3816 ;; the official keyword.
3817 (kwd (or (cdr (assoc raw-kwd
3818 org-element-keyword-translation-alist))
3819 raw-kwd))
3820 ;; Find main value for any keyword.
3821 (value
3822 (save-match-data
3823 (org-trim
3824 (buffer-substring-no-properties
3825 (match-end 0) (line-end-position)))))
3826 ;; PARSEDP is non-nil when keyword should have its
3827 ;; value parsed.
3828 (parsedp (member kwd org-element-parsed-keywords))
3829 ;; If KWD is a dual keyword, find its secondary
3830 ;; value. Maybe parse it.
3831 (dualp (member kwd org-element-dual-keywords))
3832 (dual-value
3833 (and dualp
3834 (let ((sec (org-match-string-no-properties 2)))
3835 (if (or (not sec) (not parsedp)) sec
3836 (org-element--parse-objects
3837 (match-beginning 2) (match-end 2) nil restrict)))))
3838 ;; Attribute a property name to KWD.
3839 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3840 ;; Now set final shape for VALUE.
3841 (when parsedp
3842 (setq value
3843 (org-element--parse-objects
3844 (match-end 0)
3845 (progn (end-of-line) (skip-chars-backward " \t") (point))
3846 nil restrict)))
3847 (when dualp
3848 (setq value (and (or value dual-value) (cons value dual-value))))
3849 (when (or (member kwd org-element-multiple-keywords)
3850 ;; Attributes can always appear on multiple lines.
3851 (string-match "^ATTR_" kwd))
3852 (setq value (cons value (plist-get output kwd-sym))))
3853 ;; Eventually store the new value in OUTPUT.
3854 (setq output (plist-put output kwd-sym value))
3855 ;; Move to next keyword.
3856 (forward-line)))
3857 ;; If affiliated keywords are orphaned: move back to first one.
3858 ;; They will be parsed as a paragraph.
3859 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3860 ;; Return value.
3861 (cons origin output))))
3865 ;;; The Org Parser
3867 ;; The two major functions here are `org-element-parse-buffer', which
3868 ;; parses Org syntax inside the current buffer, taking into account
3869 ;; region, narrowing, or even visibility if specified, and
3870 ;; `org-element-parse-secondary-string', which parses objects within
3871 ;; a given string.
3873 ;; The (almost) almighty `org-element-map' allows to apply a function
3874 ;; on elements or objects matching some type, and accumulate the
3875 ;; resulting values. In an export situation, it also skips unneeded
3876 ;; parts of the parse tree.
3878 (defun org-element-parse-buffer (&optional granularity visible-only)
3879 "Recursively parse the buffer and return structure.
3880 If narrowing is in effect, only parse the visible part of the
3881 buffer.
3883 Optional argument GRANULARITY determines the depth of the
3884 recursion. It can be set to the following symbols:
3886 `headline' Only parse headlines.
3887 `greater-element' Don't recurse into greater elements excepted
3888 headlines and sections. Thus, elements
3889 parsed are the top-level ones.
3890 `element' Parse everything but objects and plain text.
3891 `object' Parse the complete buffer (default).
3893 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3894 elements.
3896 An element or an objects is represented as a list with the
3897 pattern (TYPE PROPERTIES CONTENTS), where :
3899 TYPE is a symbol describing the element or object. See
3900 `org-element-all-elements' and `org-element-all-objects' for an
3901 exhaustive list of such symbols. One can retrieve it with
3902 `org-element-type' function.
3904 PROPERTIES is the list of attributes attached to the element or
3905 object, as a plist. Although most of them are specific to the
3906 element or object type, all types share `:begin', `:end',
3907 `:post-blank' and `:parent' properties, which respectively
3908 refer to buffer position where the element or object starts,
3909 ends, the number of white spaces or blank lines after it, and
3910 the element or object containing it. Properties values can be
3911 obtained by using `org-element-property' function.
3913 CONTENTS is a list of elements, objects or raw strings
3914 contained in the current element or object, when applicable.
3915 One can access them with `org-element-contents' function.
3917 The Org buffer has `org-data' as type and nil as properties.
3918 `org-element-map' function can be used to find specific elements
3919 or objects within the parse tree.
3921 This function assumes that current major mode is `org-mode'."
3922 (save-excursion
3923 (goto-char (point-min))
3924 (org-skip-whitespace)
3925 (org-element--parse-elements
3926 (point-at-bol) (point-max)
3927 ;; Start in `first-section' mode so text before the first
3928 ;; headline belongs to a section.
3929 'first-section nil granularity visible-only (list 'org-data nil))))
3931 (defun org-element-parse-secondary-string (string restriction &optional parent)
3932 "Recursively parse objects in STRING and return structure.
3934 RESTRICTION is a symbol limiting the object types that will be
3935 looked after.
3937 Optional argument PARENT, when non-nil, is the element or object
3938 containing the secondary string. It is used to set correctly
3939 `:parent' property within the string.
3941 If STRING is the empty string or nil, return nil."
3942 (cond
3943 ((not string) nil)
3944 ((equal string "") nil)
3945 (t (let ((local-variables (buffer-local-variables)))
3946 (with-temp-buffer
3947 (dolist (v local-variables)
3948 (ignore-errors
3949 (if (symbolp v) (makunbound v)
3950 (org-set-local (car v) (cdr v)))))
3951 (insert string)
3952 (restore-buffer-modified-p nil)
3953 (let ((data (org-element--parse-objects
3954 (point-min) (point-max) nil restriction)))
3955 (when parent
3956 (dolist (o data) (org-element-put-property o :parent parent)))
3957 data))))))
3959 (defun org-element-map
3960 (data types fun &optional info first-match no-recursion with-affiliated)
3961 "Map a function on selected elements or objects.
3963 DATA is a parse tree, an element, an object, a string, or a list
3964 of such constructs. TYPES is a symbol or list of symbols of
3965 elements or objects types (see `org-element-all-elements' and
3966 `org-element-all-objects' for a complete list of types). FUN is
3967 the function called on the matching element or object. It has to
3968 accept one argument: the element or object itself.
3970 When optional argument INFO is non-nil, it should be a plist
3971 holding export options. In that case, parts of the parse tree
3972 not exportable according to that property list will be skipped.
3974 When optional argument FIRST-MATCH is non-nil, stop at the first
3975 match for which FUN doesn't return nil, and return that value.
3977 Optional argument NO-RECURSION is a symbol or a list of symbols
3978 representing elements or objects types. `org-element-map' won't
3979 enter any recursive element or object whose type belongs to that
3980 list. Though, FUN can still be applied on them.
3982 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3983 apply to matching objects within parsed affiliated keywords (see
3984 `org-element-parsed-keywords').
3986 Nil values returned from FUN do not appear in the results.
3989 Examples:
3990 ---------
3992 Assuming TREE is a variable containing an Org buffer parse tree,
3993 the following example will return a flat list of all `src-block'
3994 and `example-block' elements in it:
3996 \(org-element-map tree '(example-block src-block) #'identity)
3998 The following snippet will find the first headline with a level
3999 of 1 and a \"phone\" tag, and will return its beginning position:
4001 \(org-element-map tree 'headline
4002 \(lambda (hl)
4003 \(and (= (org-element-property :level hl) 1)
4004 \(member \"phone\" (org-element-property :tags hl))
4005 \(org-element-property :begin hl)))
4006 nil t)
4008 The next example will return a flat list of all `plain-list' type
4009 elements in TREE that are not a sub-list themselves:
4011 \(org-element-map tree 'plain-list #'identity nil nil 'plain-list)
4013 Eventually, this example will return a flat list of all `bold'
4014 type objects containing a `latex-snippet' type object, even
4015 looking into captions:
4017 \(org-element-map tree 'bold
4018 \(lambda (b)
4019 \(and (org-element-map b 'latex-snippet #'identity nil t) b))
4020 nil nil nil t)"
4021 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4022 (let* ((types (if (listp types) types (list types)))
4023 (no-recursion (if (listp no-recursion) no-recursion
4024 (list no-recursion)))
4025 ;; Recursion depth is determined by --CATEGORY.
4026 (--category
4027 (catch :--found
4028 (let ((category 'greater-elements)
4029 (all-objects (cons 'plain-text org-element-all-objects)))
4030 (dolist (type types category)
4031 (cond ((memq type all-objects)
4032 ;; If one object is found, the function has
4033 ;; to recurse into every object.
4034 (throw :--found 'objects))
4035 ((not (memq type org-element-greater-elements))
4036 ;; If one regular element is found, the
4037 ;; function has to recurse, at least, into
4038 ;; every element it encounters.
4039 (and (not (eq category 'elements))
4040 (setq category 'elements))))))))
4041 --acc)
4042 (letrec ((--walk-tree
4043 (lambda (--data)
4044 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4045 ;; holding contextual information.
4046 (let ((--type (org-element-type --data)))
4047 (cond
4048 ((not --data))
4049 ;; Ignored element in an export context.
4050 ((and info (memq --data (plist-get info :ignore-list))))
4051 ;; List of elements or objects.
4052 ((not --type) (mapc --walk-tree --data))
4053 ;; Unconditionally enter parse trees.
4054 ((eq --type 'org-data)
4055 (mapc --walk-tree (org-element-contents --data)))
4057 ;; Check if TYPE is matching among TYPES. If so,
4058 ;; apply FUN to --DATA and accumulate return value
4059 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4060 (when (memq --type types)
4061 (let ((result (funcall fun --data)))
4062 (cond ((not result))
4063 (first-match (throw :--map-first-match result))
4064 (t (push result --acc)))))
4065 ;; If --DATA has a secondary string that can contain
4066 ;; objects with their type among TYPES, look inside.
4067 (when (and (eq --category 'objects) (not (stringp --data)))
4068 (dolist (p (cdr (assq --type
4069 org-element-secondary-value-alist)))
4070 (funcall --walk-tree (org-element-property p --data))))
4071 ;; If --DATA has any parsed affiliated keywords and
4072 ;; WITH-AFFILIATED is non-nil, look for objects in
4073 ;; them.
4074 (when (and with-affiliated
4075 (eq --category 'objects)
4076 (memq --type org-element-all-elements))
4077 (dolist (kwd-pair org-element--parsed-properties-alist)
4078 (let ((kwd (car kwd-pair))
4079 (value (org-element-property (cdr kwd-pair) --data)))
4080 ;; Pay attention to the type of parsed
4081 ;; keyword. In particular, preserve order for
4082 ;; multiple keywords.
4083 (cond
4084 ((not value))
4085 ((member kwd org-element-dual-keywords)
4086 (if (member kwd org-element-multiple-keywords)
4087 (dolist (line (reverse value))
4088 (funcall --walk-tree (cdr line))
4089 (funcall --walk-tree (car line)))
4090 (funcall --walk-tree (cdr value))
4091 (funcall --walk-tree (car value))))
4092 ((member kwd org-element-multiple-keywords)
4093 (mapc --walk-tree (reverse value)))
4094 (t (funcall --walk-tree value))))))
4095 ;; Determine if a recursion into --DATA is possible.
4096 (cond
4097 ;; --TYPE is explicitly removed from recursion.
4098 ((memq --type no-recursion))
4099 ;; --DATA has no contents.
4100 ((not (org-element-contents --data)))
4101 ;; Looking for greater elements but --DATA is
4102 ;; simply an element or an object.
4103 ((and (eq --category 'greater-elements)
4104 (not (memq --type org-element-greater-elements))))
4105 ;; Looking for elements but --DATA is an object.
4106 ((and (eq --category 'elements)
4107 (memq --type org-element-all-objects)))
4108 ;; In any other case, map contents.
4109 (t (mapc --walk-tree (org-element-contents --data))))))))))
4110 (catch :--map-first-match
4111 (funcall --walk-tree data)
4112 ;; Return value in a proper order.
4113 (nreverse --acc)))))
4114 (put 'org-element-map 'lisp-indent-function 2)
4116 ;; The following functions are internal parts of the parser.
4118 ;; The first one, `org-element--parse-elements' acts at the element's
4119 ;; level.
4121 ;; The second one, `org-element--parse-objects' applies on all objects
4122 ;; of a paragraph or a secondary string. It calls
4123 ;; `org-element--object-lex' to find the next object in the current
4124 ;; container.
4126 (defsubst org-element--next-mode (type parentp)
4127 "Return next special mode according to TYPE, or nil.
4128 TYPE is a symbol representing the type of an element or object
4129 containing next element if PARENTP is non-nil, or before it
4130 otherwise. Modes can be either `first-section', `item',
4131 `node-property', `planning', `property-drawer', `section',
4132 `table-row' or nil."
4133 (if parentp
4134 (case type
4135 (headline 'section)
4136 (plain-list 'item)
4137 (property-drawer 'node-property)
4138 (section 'planning)
4139 (table 'table-row))
4140 (case type
4141 (item 'item)
4142 (node-property 'node-property)
4143 (planning 'property-drawer)
4144 (table-row 'table-row))))
4146 (defun org-element--parse-elements
4147 (beg end mode structure granularity visible-only acc)
4148 "Parse elements between BEG and END positions.
4150 MODE prioritizes some elements over the others. It can be set to
4151 `first-section', `section', `planning', `item', `node-property'
4152 or `table-row'.
4154 When value is `item', STRUCTURE will be used as the current list
4155 structure.
4157 GRANULARITY determines the depth of the recursion. See
4158 `org-element-parse-buffer' for more information.
4160 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4161 elements.
4163 Elements are accumulated into ACC."
4164 (save-excursion
4165 (goto-char beg)
4166 ;; Visible only: skip invisible parts at the beginning of the
4167 ;; element.
4168 (when (and visible-only (org-invisible-p2))
4169 (goto-char (min (1+ (org-find-visible)) end)))
4170 ;; When parsing only headlines, skip any text before first one.
4171 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4172 (org-with-limited-levels (outline-next-heading)))
4173 ;; Main loop start.
4174 (while (< (point) end)
4175 ;; Find current element's type and parse it accordingly to
4176 ;; its category.
4177 (let* ((element (org-element--current-element
4178 end granularity mode structure))
4179 (type (org-element-type element))
4180 (cbeg (org-element-property :contents-begin element)))
4181 (goto-char (org-element-property :end element))
4182 ;; Visible only: skip invisible parts between siblings.
4183 (when (and visible-only (org-invisible-p2))
4184 (goto-char (min (1+ (org-find-visible)) end)))
4185 ;; Fill ELEMENT contents by side-effect.
4186 (cond
4187 ;; If element has no contents, don't modify it.
4188 ((not cbeg))
4189 ;; Greater element: parse it between `contents-begin' and
4190 ;; `contents-end'. Make sure GRANULARITY allows the
4191 ;; recursion, or ELEMENT is a headline, in which case going
4192 ;; inside is mandatory, in order to get sub-level headings.
4193 ((and (memq type org-element-greater-elements)
4194 (or (memq granularity '(element object nil))
4195 (and (eq granularity 'greater-element)
4196 (eq type 'section))
4197 (eq type 'headline)))
4198 (org-element--parse-elements
4199 cbeg (org-element-property :contents-end element)
4200 ;; Possibly switch to a special mode.
4201 (org-element--next-mode type t)
4202 (and (memq type '(item plain-list))
4203 (org-element-property :structure element))
4204 granularity visible-only element))
4205 ;; ELEMENT has contents. Parse objects inside, if
4206 ;; GRANULARITY allows it.
4207 ((memq granularity '(object nil))
4208 (org-element--parse-objects
4209 cbeg (org-element-property :contents-end element) element
4210 (org-element-restriction type))))
4211 (org-element-adopt-elements acc element)
4212 ;; Update mode.
4213 (setq mode (org-element--next-mode type nil))))
4214 ;; Return result.
4215 acc))
4217 (defun org-element--object-lex (restriction)
4218 "Return next object in current buffer or nil.
4219 RESTRICTION is a list of object types, as symbols, that should be
4220 looked after. This function assumes that the buffer is narrowed
4221 to an appropriate container (e.g., a paragraph)."
4222 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4223 (save-excursion
4224 (let ((limit (and org-target-link-regexp
4225 (save-excursion
4226 (or (bolp) (backward-char))
4227 (re-search-forward org-target-link-regexp nil t))
4228 (match-beginning 1)))
4229 found)
4230 (while (and (not found)
4231 (re-search-forward org-element--object-regexp limit t))
4232 (goto-char (match-beginning 0))
4233 (let ((result (match-string 0)))
4234 (setq found
4235 (cond
4236 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4237 (and (memq 'inline-babel-call restriction)
4238 (org-element-inline-babel-call-parser)))
4239 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4240 (and (memq 'inline-src-block restriction)
4241 (org-element-inline-src-block-parser)))
4243 (case (char-after)
4244 (?^ (and (memq 'superscript restriction)
4245 (org-element-superscript-parser)))
4246 (?_ (or (and (memq 'subscript restriction)
4247 (org-element-subscript-parser))
4248 (and (memq 'underline restriction)
4249 (org-element-underline-parser))))
4250 (?* (and (memq 'bold restriction)
4251 (org-element-bold-parser)))
4252 (?/ (and (memq 'italic restriction)
4253 (org-element-italic-parser)))
4254 (?~ (and (memq 'code restriction)
4255 (org-element-code-parser)))
4256 (?= (and (memq 'verbatim restriction)
4257 (org-element-verbatim-parser)))
4258 (?+ (and (memq 'strike-through restriction)
4259 (org-element-strike-through-parser)))
4260 (?@ (and (memq 'export-snippet restriction)
4261 (org-element-export-snippet-parser)))
4262 (?{ (and (memq 'macro restriction)
4263 (org-element-macro-parser)))
4264 (?$ (and (memq 'latex-fragment restriction)
4265 (org-element-latex-fragment-parser)))
4267 (if (eq (aref result 1) ?<)
4268 (or (and (memq 'radio-target restriction)
4269 (org-element-radio-target-parser))
4270 (and (memq 'target restriction)
4271 (org-element-target-parser)))
4272 (or (and (memq 'timestamp restriction)
4273 (org-element-timestamp-parser))
4274 (and (memq 'link restriction)
4275 (org-element-link-parser)))))
4276 (?\\
4277 (if (eq (aref result 1) ?\\)
4278 (and (memq 'line-break restriction)
4279 (org-element-line-break-parser))
4280 (or (and (memq 'entity restriction)
4281 (org-element-entity-parser))
4282 (and (memq 'latex-fragment restriction)
4283 (org-element-latex-fragment-parser)))))
4284 (?\[
4285 (if (eq (aref result 1) ?\[)
4286 (and (memq 'link restriction)
4287 (org-element-link-parser))
4288 (or (and (memq 'footnote-reference restriction)
4289 (org-element-footnote-reference-parser))
4290 (and (memq 'timestamp restriction)
4291 (org-element-timestamp-parser))
4292 (and (memq 'statistics-cookie restriction)
4293 (org-element-statistics-cookie-parser)))))
4294 ;; This is probably a plain link.
4295 (otherwise (and (or (memq 'link restriction)
4296 (memq 'plain-link restriction))
4297 (org-element-link-parser)))))))
4298 (or (eobp) (forward-char))))
4299 (cond (found)
4300 ;; Radio link.
4301 ((and limit (memq 'link restriction))
4302 (goto-char limit) (org-element-link-parser)))))))
4304 (defun org-element--parse-objects (beg end acc restriction)
4305 "Parse objects between BEG and END and return recursive structure.
4307 Objects are accumulated in ACC.
4309 RESTRICTION is a list of object successors which are allowed in
4310 the current object."
4311 (save-excursion
4312 (save-restriction
4313 (narrow-to-region beg end)
4314 (goto-char (point-min))
4315 (let (next-object)
4316 (while (and (not (eobp))
4317 (setq next-object (org-element--object-lex restriction)))
4318 ;; 1. Text before any object. Untabify it.
4319 (let ((obj-beg (org-element-property :begin next-object)))
4320 (unless (= (point) obj-beg)
4321 (setq acc
4322 (org-element-adopt-elements
4324 (replace-regexp-in-string
4325 "\t" (make-string tab-width ?\s)
4326 (buffer-substring-no-properties (point) obj-beg))))))
4327 ;; 2. Object...
4328 (let ((obj-end (org-element-property :end next-object))
4329 (cont-beg (org-element-property :contents-begin next-object)))
4330 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4331 ;; a recursive type.
4332 (when (and cont-beg
4333 (memq (car next-object) org-element-recursive-objects))
4334 (org-element--parse-objects
4335 cont-beg (org-element-property :contents-end next-object)
4336 next-object (org-element-restriction next-object)))
4337 (setq acc (org-element-adopt-elements acc next-object))
4338 (goto-char obj-end))))
4339 ;; 3. Text after last object. Untabify it.
4340 (unless (eobp)
4341 (setq acc
4342 (org-element-adopt-elements
4344 (replace-regexp-in-string
4345 "\t" (make-string tab-width ?\s)
4346 (buffer-substring-no-properties (point) end)))))
4347 ;; Result.
4348 acc)))
4352 ;;; Towards A Bijective Process
4354 ;; The parse tree obtained with `org-element-parse-buffer' is really
4355 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4356 ;; interpreted and expanded into a string with canonical Org syntax.
4357 ;; Hence `org-element-interpret-data'.
4359 ;; The function relies internally on
4360 ;; `org-element--interpret-affiliated-keywords'.
4362 ;;;###autoload
4363 (defun org-element-interpret-data (data)
4364 "Interpret DATA as Org syntax.
4365 DATA is a parse tree, an element, an object or a secondary string
4366 to interpret. Return Org syntax as a string."
4367 (letrec ((fun
4368 (lambda (--data parent)
4369 (let* ((type (org-element-type --data))
4370 ;; Find interpreter for current object or
4371 ;; element. If it doesn't exist (e.g. this is
4372 ;; a pseudo object or element), return contents,
4373 ;; if any.
4374 (interpret
4375 (let ((fun (intern
4376 (format "org-element-%s-interpreter" type))))
4377 (if (fboundp fun) fun (lambda (_ contents) contents))))
4378 (results
4379 (cond
4380 ;; Secondary string.
4381 ((not type)
4382 (mapconcat (lambda (obj) (funcall fun obj parent))
4383 --data ""))
4384 ;; Full Org document.
4385 ((eq type 'org-data)
4386 (mapconcat (lambda (obj) (funcall fun obj parent))
4387 (org-element-contents --data) ""))
4388 ;; Plain text: return it.
4389 ((stringp --data) --data)
4390 ;; Element or object without contents.
4391 ((not (org-element-contents --data))
4392 (funcall interpret --data nil))
4393 ;; Element or object with contents.
4395 (funcall
4396 interpret
4397 --data
4398 ;; Recursively interpret contents.
4399 (mapconcat
4400 (lambda (obj) (funcall fun obj --data))
4401 (org-element-contents
4402 (if (not (memq type '(paragraph verse-block)))
4403 --data
4404 ;; Fix indentation of elements containing
4405 ;; objects. We ignore `table-row'
4406 ;; elements as they are one line long
4407 ;; anyway.
4408 (org-element-normalize-contents
4409 --data
4410 ;; When normalizing first paragraph of
4411 ;; an item or a footnote-definition,
4412 ;; ignore first line's indentation.
4413 (and (eq type 'paragraph)
4414 (equal --data
4415 (car (org-element-contents parent)))
4416 (memq (org-element-type parent)
4417 '(footnote-definition item))))))
4418 ""))))))
4419 (if (memq type '(org-data plain-text nil)) results
4420 ;; Build white spaces. If no `:post-blank' property
4421 ;; is specified, assume its value is 0.
4422 (let ((blank (or (org-element-property :post-blank --data) 0)))
4423 (if (or (memq type org-element-all-objects)
4424 (and parent
4425 (let ((type (org-element-type parent)))
4426 (or (not type)
4427 (memq type org-element-object-containers)))))
4428 (concat results (make-string blank ?\s))
4429 (concat
4430 (org-element--interpret-affiliated-keywords --data)
4431 (org-element-normalize-string results)
4432 (make-string blank ?\n)))))))))
4433 (funcall fun data nil)))
4435 (defun org-element--interpret-affiliated-keywords (element)
4436 "Return ELEMENT's affiliated keywords as Org syntax.
4437 If there is no affiliated keyword, return the empty string."
4438 (let ((keyword-to-org
4439 (function
4440 (lambda (key value)
4441 (let (dual)
4442 (when (member key org-element-dual-keywords)
4443 (setq dual (cdr value) value (car value)))
4444 (concat "#+" key
4445 (and dual
4446 (format "[%s]" (org-element-interpret-data dual)))
4447 ": "
4448 (if (member key org-element-parsed-keywords)
4449 (org-element-interpret-data value)
4450 value)
4451 "\n"))))))
4452 (mapconcat
4453 (lambda (prop)
4454 (let ((value (org-element-property prop element))
4455 (keyword (upcase (substring (symbol-name prop) 1))))
4456 (when value
4457 (if (or (member keyword org-element-multiple-keywords)
4458 ;; All attribute keywords can have multiple lines.
4459 (string-match "^ATTR_" keyword))
4460 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4461 (reverse value)
4463 (funcall keyword-to-org keyword value)))))
4464 ;; List all ELEMENT's properties matching an attribute line or an
4465 ;; affiliated keyword, but ignore translated keywords since they
4466 ;; cannot belong to the property list.
4467 (loop for prop in (nth 1 element) by 'cddr
4468 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4469 (or (string-match "^ATTR_" keyword)
4470 (and
4471 (member keyword org-element-affiliated-keywords)
4472 (not (assoc keyword
4473 org-element-keyword-translation-alist)))))
4474 collect prop)
4475 "")))
4477 ;; Because interpretation of the parse tree must return the same
4478 ;; number of blank lines between elements and the same number of white
4479 ;; space after objects, some special care must be given to white
4480 ;; spaces.
4482 ;; The first function, `org-element-normalize-string', ensures any
4483 ;; string different from the empty string will end with a single
4484 ;; newline character.
4486 ;; The second function, `org-element-normalize-contents', removes
4487 ;; global indentation from the contents of the current element.
4489 (defun org-element-normalize-string (s)
4490 "Ensure string S ends with a single newline character.
4492 If S isn't a string return it unchanged. If S is the empty
4493 string, return it. Otherwise, return a new string with a single
4494 newline character at its end."
4495 (cond
4496 ((not (stringp s)) s)
4497 ((string= "" s) "")
4498 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4499 (replace-match "\n" nil nil s)))))
4501 (defun org-element-normalize-contents (element &optional ignore-first)
4502 "Normalize plain text in ELEMENT's contents.
4504 ELEMENT must only contain plain text and objects.
4506 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4507 indentation to compute maximal common indentation.
4509 Return the normalized element that is element with global
4510 indentation removed from its contents. The function assumes that
4511 indentation is not done with TAB characters."
4512 (letrec ((find-min-ind
4513 ;; Return minimal common indentation within BLOB. This is
4514 ;; done by walking recursively BLOB and updating MIN-IND
4515 ;; along the way. FIRST-FLAG is non-nil when the next
4516 ;; object is expected to be a string that doesn't start
4517 ;; with a newline character. It happens for strings at
4518 ;; the beginnings of the contents or right after a line
4519 ;; break.
4520 (lambda (blob first-flag min-ind)
4521 (catch 'zero
4522 (dolist (object (org-element-contents blob) min-ind)
4523 (when first-flag
4524 (setq first-flag nil)
4525 ;; Objects cannot start with spaces: in this case,
4526 ;; indentation is 0.
4527 (if (not (stringp object)) (throw 'zero 0)
4528 (string-match "\\` *" object)
4529 (let ((len (match-end 0)))
4530 ;; An indentation of zero means no string will
4531 ;; be modified. Quit the process.
4532 (if (zerop len) (throw 'zero 0)
4533 (setq min-ind (min len min-ind))))))
4534 (cond
4535 ((stringp object)
4536 (dolist (line (cdr (org-split-string object " *\n")))
4537 (unless (string= line "")
4538 (setq min-ind
4539 (min (org-get-indentation line) min-ind)))))
4540 ((eq (org-element-type object) 'line-break)
4541 (setq first-flag t))
4542 ((memq (org-element-type object)
4543 org-element-recursive-objects)
4544 (setq min-ind
4545 (funcall find-min-ind
4546 object first-flag min-ind))))))))
4547 (min-ind (funcall find-min-ind
4548 element (not ignore-first) most-positive-fixnum)))
4549 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4550 ;; Build ELEMENT back, replacing each string with the same
4551 ;; string minus common indentation.
4552 (letrec ((build
4553 (lambda (datum first-flag)
4554 ;; Return DATUM with all its strings indentation
4555 ;; shortened from MIN-IND white spaces.
4556 ;; FIRST-FLAG is non-nil when the next object is
4557 ;; expected to be a string that doesn't start with
4558 ;; a newline character.
4559 (setcdr (cdr datum)
4560 (mapcar
4561 (lambda (object)
4562 (when first-flag
4563 (setq first-flag nil)
4564 (when (stringp object)
4565 (setq object
4566 (replace-regexp-in-string
4567 (format "\\` \\{%d\\}" min-ind)
4568 "" object))))
4569 (cond
4570 ((stringp object)
4571 (replace-regexp-in-string
4572 (format "\n \\{%d\\}" min-ind) "\n" object))
4573 ((memq (org-element-type object)
4574 org-element-recursive-objects)
4575 (funcall build object first-flag))
4576 ((eq (org-element-type object) 'line-break)
4577 (setq first-flag t)
4578 object)
4579 (t object)))
4580 (org-element-contents datum)))
4581 datum)))
4582 (funcall build element (not ignore-first))))))
4586 ;;; Cache
4588 ;; Implement a caching mechanism for `org-element-at-point' and
4589 ;; `org-element-context', which see.
4591 ;; A single public function is provided: `org-element-cache-reset'.
4593 ;; Cache is enabled by default, but can be disabled globally with
4594 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4595 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4596 ;; can be tweaked to control caching behaviour.
4598 ;; Internally, parsed elements are stored in an AVL tree,
4599 ;; `org-element--cache'. This tree is updated lazily: whenever
4600 ;; a change happens to the buffer, a synchronization request is
4601 ;; registered in `org-element--cache-sync-requests' (see
4602 ;; `org-element--cache-submit-request'). During idle time, requests
4603 ;; are processed by `org-element--cache-sync'. Synchronization also
4604 ;; happens when an element is required from the cache. In this case,
4605 ;; the process stops as soon as the needed element is up-to-date.
4607 ;; A synchronization request can only apply on a synchronized part of
4608 ;; the cache. Therefore, the cache is updated at least to the
4609 ;; location where the new request applies. Thus, requests are ordered
4610 ;; from left to right and all elements starting before the first
4611 ;; request are correct. This property is used by functions like
4612 ;; `org-element--cache-find' to retrieve elements in the part of the
4613 ;; cache that can be trusted.
4615 ;; A request applies to every element, starting from its original
4616 ;; location (or key, see below). When a request is processed, it
4617 ;; moves forward and may collide the next one. In this case, both
4618 ;; requests are merged into a new one that starts from that element.
4619 ;; As a consequence, the whole synchronization complexity does not
4620 ;; depend on the number of pending requests, but on the number of
4621 ;; elements the very first request will be applied on.
4623 ;; Elements cannot be accessed through their beginning position, which
4624 ;; may or may not be up-to-date. Instead, each element in the tree is
4625 ;; associated to a key, obtained with `org-element--cache-key'. This
4626 ;; mechanism is robust enough to preserve total order among elements
4627 ;; even when the tree is only partially synchronized.
4629 ;; Objects contained in an element are stored in a hash table,
4630 ;; `org-element--cache-objects'.
4633 (defvar org-element-use-cache t
4634 "Non nil when Org parser should cache its results.
4635 This is mostly for debugging purpose.")
4637 (defvar org-element-cache-sync-idle-time 0.6
4638 "Length, in seconds, of idle time before syncing cache.")
4640 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4641 "Maximum duration, as a time value, for a cache synchronization.
4642 If the synchronization is not over after this delay, the process
4643 pauses and resumes after `org-element-cache-sync-break'
4644 seconds.")
4646 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4647 "Duration, as a time value, of the pause between synchronizations.
4648 See `org-element-cache-sync-duration' for more information.")
4651 ;;;; Data Structure
4653 (defvar org-element--cache nil
4654 "AVL tree used to cache elements.
4655 Each node of the tree contains an element. Comparison is done
4656 with `org-element--cache-compare'. This cache is used in
4657 `org-element-at-point'.")
4659 (defvar org-element--cache-objects nil
4660 "Hash table used as to cache objects.
4661 Key is an element, as returned by `org-element-at-point', and
4662 value is an alist where each association is:
4664 \(PARENT COMPLETEP . OBJECTS)
4666 where PARENT is an element or object, COMPLETEP is a boolean,
4667 non-nil when all direct children of parent are already cached and
4668 OBJECTS is a list of such children, as objects, from farthest to
4669 closest.
4671 In the following example, \\alpha, bold object and \\beta are
4672 contained within a paragraph
4674 \\alpha *\\beta*
4676 If the paragraph is completely parsed, OBJECTS-DATA will be
4678 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4679 \(BOLD-OBJECT t ENTITY-OBJECT))
4681 whereas in a partially parsed paragraph, it could be
4683 \((PARAGRAPH nil ENTITY-OBJECT))
4685 This cache is used in `org-element-context'.")
4687 (defvar org-element--cache-sync-requests nil
4688 "List of pending synchronization requests.
4690 A request is a vector with the following pattern:
4692 \[NEXT BEG END OFFSET PARENT PHASE]
4694 Processing a synchronization request consists of three phases:
4696 0. Delete modified elements,
4697 1. Fill missing area in cache,
4698 2. Shift positions and re-parent elements after the changes.
4700 During phase 0, NEXT is the key of the first element to be
4701 removed, BEG and END is buffer position delimiting the
4702 modifications. Elements starting between them (inclusive) are
4703 removed. So are elements whose parent is removed. PARENT, when
4704 non-nil, is the parent of the first element to be removed.
4706 During phase 1, NEXT is the key of the next known element in
4707 cache and BEG its beginning position. Parse buffer between that
4708 element and the one before it in order to determine the parent of
4709 the next element. Set PARENT to the element containing NEXT.
4711 During phase 2, NEXT is the key of the next element to shift in
4712 the parse tree. All elements starting from this one have their
4713 properties relatives to buffer positions shifted by integer
4714 OFFSET and, if they belong to element PARENT, are adopted by it.
4716 PHASE specifies the phase number, as an integer.")
4718 (defvar org-element--cache-sync-timer nil
4719 "Timer used for cache synchronization.")
4721 (defvar org-element--cache-sync-keys nil
4722 "Hash table used to store keys during synchronization.
4723 See `org-element--cache-key' for more information.")
4725 (defsubst org-element--cache-key (element)
4726 "Return a unique key for ELEMENT in cache tree.
4728 Keys are used to keep a total order among elements in the cache.
4729 Comparison is done with `org-element--cache-key-less-p'.
4731 When no synchronization is taking place, a key is simply the
4732 beginning position of the element, or that position plus one in
4733 the case of an first item (respectively row) in
4734 a list (respectively a table).
4736 During a synchronization, the key is the one the element had when
4737 the cache was synchronized for the last time. Elements added to
4738 cache during the synchronization get a new key generated with
4739 `org-element--cache-generate-key'.
4741 Such keys are stored in `org-element--cache-sync-keys'. The hash
4742 table is cleared once the synchronization is complete."
4743 (or (gethash element org-element--cache-sync-keys)
4744 (let* ((begin (org-element-property :begin element))
4745 ;; Increase beginning position of items (respectively
4746 ;; table rows) by one, so the first item can get
4747 ;; a different key from its parent list (respectively
4748 ;; table).
4749 (key (if (memq (org-element-type element) '(item table-row))
4750 (1+ begin)
4751 begin)))
4752 (if org-element--cache-sync-requests
4753 (puthash element key org-element--cache-sync-keys)
4754 key))))
4756 (defun org-element--cache-generate-key (lower upper)
4757 "Generate a key between LOWER and UPPER.
4759 LOWER and UPPER are integers or lists, possibly empty.
4761 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4762 a unique key, as an integer or a list of integers, according to
4763 the following rules:
4765 - LOWER and UPPER are compared level-wise until values differ.
4767 - If, at a given level, LOWER and UPPER differ from more than
4768 2, the new key shares all the levels above with LOWER and
4769 gets a new level. Its value is the mean between LOWER and
4770 UPPER:
4772 \(1 2) + (1 4) --> (1 3)
4774 - If LOWER has no value to compare with, it is assumed that its
4775 value is `most-negative-fixnum'. E.g.,
4777 \(1 1) + (1 1 2)
4779 is equivalent to
4781 \(1 1 m) + (1 1 2)
4783 where m is `most-negative-fixnum'. Likewise, if UPPER is
4784 short of levels, the current value is `most-positive-fixnum'.
4786 - If they differ from only one, the new key inherits from
4787 current LOWER level and fork it at the next level. E.g.,
4789 \(2 1) + (3 3)
4791 is equivalent to
4793 \(2 1) + (2 M)
4795 where M is `most-positive-fixnum'.
4797 - If the key is only one level long, it is returned as an
4798 integer:
4800 \(1 2) + (3 2) --> 2
4802 When they are not equals, the function assumes that LOWER is
4803 lesser than UPPER, per `org-element--cache-key-less-p'."
4804 (if (equal lower upper) lower
4805 (let ((lower (if (integerp lower) (list lower) lower))
4806 (upper (if (integerp upper) (list upper) upper))
4807 skip-upper key)
4808 (catch 'exit
4809 (while t
4810 (let ((min (or (car lower) most-negative-fixnum))
4811 (max (cond (skip-upper most-positive-fixnum)
4812 ((car upper))
4813 (t most-positive-fixnum))))
4814 (if (< (1+ min) max)
4815 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4816 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4817 (when (and (< min max) (not skip-upper))
4818 ;; When at a given level, LOWER and UPPER differ from
4819 ;; 1, ignore UPPER altogether. Instead create a key
4820 ;; between LOWER and the greatest key with the same
4821 ;; prefix as LOWER so far.
4822 (setq skip-upper t))
4823 (push min key)
4824 (setq lower (cdr lower) upper (cdr upper)))))))))
4826 (defsubst org-element--cache-key-less-p (a b)
4827 "Non-nil if key A is less than key B.
4828 A and B are either integers or lists of integers, as returned by
4829 `org-element--cache-key'."
4830 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4831 (if (integerp b) (< (car a) b)
4832 (catch 'exit
4833 (while (and a b)
4834 (cond ((car-less-than-car a b) (throw 'exit t))
4835 ((car-less-than-car b a) (throw 'exit nil))
4836 (t (setq a (cdr a) b (cdr b)))))
4837 ;; If A is empty, either keys are equal (B is also empty) and
4838 ;; we return nil, or A is lesser than B (B is longer) and we
4839 ;; return a non-nil value.
4841 ;; If A is not empty, B is necessarily empty and A is greater
4842 ;; than B (A is longer). Therefore, return nil.
4843 (and (null a) b)))))
4845 (defun org-element--cache-compare (a b)
4846 "Non-nil when element A is located before element B."
4847 (org-element--cache-key-less-p (org-element--cache-key a)
4848 (org-element--cache-key b)))
4850 (defsubst org-element--cache-root ()
4851 "Return root value in cache.
4852 This function assumes `org-element--cache' is a valid AVL tree."
4853 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4856 ;;;; Tools
4858 (defsubst org-element--cache-active-p ()
4859 "Non-nil when cache is active in current buffer."
4860 (and org-element-use-cache
4861 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4863 (defun org-element--cache-find (pos &optional side)
4864 "Find element in cache starting at POS or before.
4866 POS refers to a buffer position.
4868 When optional argument SIDE is non-nil, the function checks for
4869 elements starting at or past POS instead. If SIDE is `both', the
4870 function returns a cons cell where car is the first element
4871 starting at or before POS and cdr the first element starting
4872 after POS.
4874 The function can only find elements in the synchronized part of
4875 the cache."
4876 (let ((limit (and org-element--cache-sync-requests
4877 (aref (car org-element--cache-sync-requests) 0)))
4878 (node (org-element--cache-root))
4879 lower upper)
4880 (while node
4881 (let* ((element (avl-tree--node-data node))
4882 (begin (org-element-property :begin element)))
4883 (cond
4884 ((and limit
4885 (not (org-element--cache-key-less-p
4886 (org-element--cache-key element) limit)))
4887 (setq node (avl-tree--node-left node)))
4888 ((> begin pos)
4889 (setq upper element
4890 node (avl-tree--node-left node)))
4891 ((< begin pos)
4892 (setq lower element
4893 node (avl-tree--node-right node)))
4894 ;; We found an element in cache starting at POS. If `side'
4895 ;; is `both' we also want the next one in order to generate
4896 ;; a key in-between.
4898 ;; If the element is the first row or item in a table or
4899 ;; a plain list, we always return the table or the plain
4900 ;; list.
4902 ;; In any other case, we return the element found.
4903 ((eq side 'both)
4904 (setq lower element)
4905 (setq node (avl-tree--node-right node)))
4906 ((and (memq (org-element-type element) '(item table-row))
4907 (let ((parent (org-element-property :parent element)))
4908 (and (= (org-element-property :begin element)
4909 (org-element-property :contents-begin parent))
4910 (setq node nil
4911 lower parent
4912 upper parent)))))
4914 (setq node nil
4915 lower element
4916 upper element)))))
4917 (case side
4918 (both (cons lower upper))
4919 ((nil) lower)
4920 (otherwise upper))))
4922 (defun org-element--cache-put (element &optional data)
4923 "Store ELEMENT in current buffer's cache, if allowed.
4924 When optional argument DATA is non-nil, assume is it object data
4925 relative to ELEMENT and store it in the objects cache."
4926 (cond ((not (org-element--cache-active-p)) nil)
4927 ((not data)
4928 (when org-element--cache-sync-requests
4929 ;; During synchronization, first build an appropriate key
4930 ;; for the new element so `avl-tree-enter' can insert it at
4931 ;; the right spot in the cache.
4932 (let ((keys (org-element--cache-find
4933 (org-element-property :begin element) 'both)))
4934 (puthash element
4935 (org-element--cache-generate-key
4936 (and (car keys) (org-element--cache-key (car keys)))
4937 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4938 (org-element--cache-sync-requests
4939 (aref (car org-element--cache-sync-requests) 0))))
4940 org-element--cache-sync-keys)))
4941 (avl-tree-enter org-element--cache element))
4942 ;; Headlines are not stored in cache, so objects in titles are
4943 ;; not stored either.
4944 ((eq (org-element-type element) 'headline) nil)
4945 (t (puthash element data org-element--cache-objects))))
4947 (defsubst org-element--cache-remove (element)
4948 "Remove ELEMENT from cache.
4949 Assume ELEMENT belongs to cache and that a cache is active."
4950 (avl-tree-delete org-element--cache element)
4951 (remhash element org-element--cache-objects))
4954 ;;;; Synchronization
4956 (defsubst org-element--cache-set-timer (buffer)
4957 "Set idle timer for cache synchronization in BUFFER."
4958 (when org-element--cache-sync-timer
4959 (cancel-timer org-element--cache-sync-timer))
4960 (setq org-element--cache-sync-timer
4961 (run-with-idle-timer
4962 (let ((idle (current-idle-time)))
4963 (if idle (time-add idle org-element-cache-sync-break)
4964 org-element-cache-sync-idle-time))
4966 #'org-element--cache-sync
4967 buffer)))
4969 (defsubst org-element--cache-interrupt-p (time-limit)
4970 "Non-nil when synchronization process should be interrupted.
4971 TIME-LIMIT is a time value or nil."
4972 (and time-limit
4973 (or (input-pending-p)
4974 (time-less-p time-limit (current-time)))))
4976 (defsubst org-element--cache-shift-positions (element offset &optional props)
4977 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4979 Properties containing buffer positions are `:begin', `:end',
4980 `:contents-begin', `:contents-end' and `:structure'. When
4981 optional argument PROPS is a list of keywords, only shift
4982 properties provided in that list.
4984 Properties are modified by side-effect."
4985 (let ((properties (nth 1 element)))
4986 ;; Shift `:structure' property for the first plain list only: it
4987 ;; is the only one that really matters and it prevents from
4988 ;; shifting it more than once.
4989 (when (and (or (not props) (memq :structure props))
4990 (eq (org-element-type element) 'plain-list)
4991 (not (eq (org-element-type (plist-get properties :parent))
4992 'item)))
4993 (dolist (item (plist-get properties :structure))
4994 (incf (car item) offset)
4995 (incf (nth 6 item) offset)))
4996 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
4997 (let ((value (and (or (not props) (memq key props))
4998 (plist-get properties key))))
4999 (and value (plist-put properties key (+ offset value)))))))
5001 (defun org-element--cache-sync (buffer &optional threshold future-change)
5002 "Synchronize cache with recent modification in BUFFER.
5004 When optional argument THRESHOLD is non-nil, do the
5005 synchronization for all elements starting before or at threshold,
5006 then exit. Otherwise, synchronize cache for as long as
5007 `org-element-cache-sync-duration' or until Emacs leaves idle
5008 state.
5010 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5011 not registered yet in the cache are going to happen. It is used
5012 in `org-element--cache-submit-request', where cache is partially
5013 updated before current modification are actually submitted."
5014 (when (buffer-live-p buffer)
5015 (with-current-buffer buffer
5016 (let ((inhibit-quit t) request next)
5017 (when org-element--cache-sync-timer
5018 (cancel-timer org-element--cache-sync-timer))
5019 (catch 'interrupt
5020 (while org-element--cache-sync-requests
5021 (setq request (car org-element--cache-sync-requests)
5022 next (nth 1 org-element--cache-sync-requests))
5023 (org-element--cache-process-request
5024 request
5025 (and next (aref next 0))
5026 threshold
5027 (and (not threshold)
5028 (time-add (current-time)
5029 org-element-cache-sync-duration))
5030 future-change)
5031 ;; Request processed. Merge current and next offsets and
5032 ;; transfer ending position.
5033 (when next
5034 (incf (aref next 3) (aref request 3))
5035 (aset next 2 (aref request 2)))
5036 (setq org-element--cache-sync-requests
5037 (cdr org-element--cache-sync-requests))))
5038 ;; If more requests are awaiting, set idle timer accordingly.
5039 ;; Otherwise, reset keys.
5040 (if org-element--cache-sync-requests
5041 (org-element--cache-set-timer buffer)
5042 (clrhash org-element--cache-sync-keys))))))
5044 (defun org-element--cache-process-request
5045 (request next threshold time-limit future-change)
5046 "Process synchronization REQUEST for all entries before NEXT.
5048 REQUEST is a vector, built by `org-element--cache-submit-request'.
5050 NEXT is a cache key, as returned by `org-element--cache-key'.
5052 When non-nil, THRESHOLD is a buffer position. Synchronization
5053 stops as soon as a shifted element begins after it.
5055 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5056 after this time or when Emacs exits idle state.
5058 When non-nil, FUTURE-CHANGE is a buffer position where changes
5059 not registered yet in the cache are going to happen. See
5060 `org-element--cache-submit-request' for more information.
5062 Throw `interrupt' if the process stops before completing the
5063 request."
5064 (catch 'quit
5065 (when (= (aref request 5) 0)
5066 ;; Phase 0.
5068 ;; Delete all elements starting after BEG, but not after buffer
5069 ;; position END or past element with key NEXT. Also delete
5070 ;; elements contained within a previously removed element
5071 ;; (stored in `last-container').
5073 ;; At each iteration, we start again at tree root since
5074 ;; a deletion modifies structure of the balanced tree.
5075 (catch 'end-phase
5076 (while t
5077 (when (org-element--cache-interrupt-p time-limit)
5078 (throw 'interrupt nil))
5079 ;; Find first element in cache with key BEG or after it.
5080 (let ((beg (aref request 0))
5081 (end (aref request 2))
5082 (node (org-element--cache-root))
5083 data data-key last-container)
5084 (while node
5085 (let* ((element (avl-tree--node-data node))
5086 (key (org-element--cache-key element)))
5087 (cond
5088 ((org-element--cache-key-less-p key beg)
5089 (setq node (avl-tree--node-right node)))
5090 ((org-element--cache-key-less-p beg key)
5091 (setq data element
5092 data-key key
5093 node (avl-tree--node-left node)))
5094 (t (setq data element
5095 data-key key
5096 node nil)))))
5097 (if data
5098 (let ((pos (org-element-property :begin data)))
5099 (if (if (or (not next)
5100 (org-element--cache-key-less-p data-key next))
5101 (<= pos end)
5102 (and last-container
5103 (let ((up data))
5104 (while (and up (not (eq up last-container)))
5105 (setq up (org-element-property :parent up)))
5106 up)))
5107 (progn (when (and (not last-container)
5108 (> (org-element-property :end data)
5109 end))
5110 (setq last-container data))
5111 (org-element--cache-remove data))
5112 (aset request 0 data-key)
5113 (aset request 1 pos)
5114 (aset request 5 1)
5115 (throw 'end-phase nil)))
5116 ;; No element starting after modifications left in
5117 ;; cache: further processing is futile.
5118 (throw 'quit t))))))
5119 (when (= (aref request 5) 1)
5120 ;; Phase 1.
5122 ;; Phase 0 left a hole in the cache. Some elements after it
5123 ;; could have parents within. For example, in the following
5124 ;; buffer:
5126 ;; - item
5129 ;; Paragraph1
5131 ;; Paragraph2
5133 ;; if we remove a blank line between "item" and "Paragraph1",
5134 ;; everything down to "Paragraph2" is removed from cache. But
5135 ;; the paragraph now belongs to the list, and its `:parent'
5136 ;; property no longer is accurate.
5138 ;; Therefore we need to parse again elements in the hole, or at
5139 ;; least in its last section, so that we can re-parent
5140 ;; subsequent elements, during phase 2.
5142 ;; Note that we only need to get the parent from the first
5143 ;; element in cache after the hole.
5145 ;; When next key is lesser or equal to the current one, delegate
5146 ;; phase 1 processing to next request in order to preserve key
5147 ;; order among requests.
5148 (let ((key (aref request 0)))
5149 (when (and next (not (org-element--cache-key-less-p key next)))
5150 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5151 (aset next-request 0 key)
5152 (aset next-request 1 (aref request 1))
5153 (aset next-request 5 1))
5154 (throw 'quit t)))
5155 ;; Next element will start at its beginning position plus
5156 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5157 ;; contains the real beginning position of the first element to
5158 ;; shift and re-parent.
5159 (let ((limit (+ (aref request 1) (aref request 3))))
5160 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5161 ((and future-change (>= limit future-change))
5162 ;; Changes are going to happen around this element and
5163 ;; they will trigger another phase 1 request. Skip the
5164 ;; current one.
5165 (aset request 5 2))
5167 (let ((parent (org-element--parse-to limit t time-limit)))
5168 (aset request 4 parent)
5169 (aset request 5 2))))))
5170 ;; Phase 2.
5172 ;; Shift all elements starting from key START, but before NEXT, by
5173 ;; OFFSET, and re-parent them when appropriate.
5175 ;; Elements are modified by side-effect so the tree structure
5176 ;; remains intact.
5178 ;; Once THRESHOLD, if any, is reached, or once there is an input
5179 ;; pending, exit. Before leaving, the current synchronization
5180 ;; request is updated.
5181 (let ((start (aref request 0))
5182 (offset (aref request 3))
5183 (parent (aref request 4))
5184 (node (org-element--cache-root))
5185 (stack (list nil))
5186 (leftp t)
5187 exit-flag)
5188 ;; No re-parenting nor shifting planned: request is over.
5189 (when (and (not parent) (zerop offset)) (throw 'quit t))
5190 (while node
5191 (let* ((data (avl-tree--node-data node))
5192 (key (org-element--cache-key data)))
5193 (if (and leftp (avl-tree--node-left node)
5194 (not (org-element--cache-key-less-p key start)))
5195 (progn (push node stack)
5196 (setq node (avl-tree--node-left node)))
5197 (unless (org-element--cache-key-less-p key start)
5198 ;; We reached NEXT. Request is complete.
5199 (when (equal key next) (throw 'quit t))
5200 ;; Handle interruption request. Update current request.
5201 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5202 (aset request 0 key)
5203 (aset request 4 parent)
5204 (throw 'interrupt nil))
5205 ;; Shift element.
5206 (unless (zerop offset)
5207 (org-element--cache-shift-positions data offset)
5208 ;; Shift associated objects data, if any.
5209 (dolist (object-data (gethash data org-element--cache-objects))
5210 (dolist (object (cddr object-data))
5211 (org-element--cache-shift-positions object offset))))
5212 (let ((begin (org-element-property :begin data)))
5213 ;; Update PARENT and re-parent DATA, only when
5214 ;; necessary. Propagate new structures for lists.
5215 (while (and parent
5216 (<= (org-element-property :end parent) begin))
5217 (setq parent (org-element-property :parent parent)))
5218 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5219 ((and parent
5220 (let ((p (org-element-property :parent data)))
5221 (or (not p)
5222 (< (org-element-property :begin p)
5223 (org-element-property :begin parent)))))
5224 (org-element-put-property data :parent parent)
5225 (let ((s (org-element-property :structure parent)))
5226 (when (and s (org-element-property :structure data))
5227 (org-element-put-property data :structure s)))))
5228 ;; Cache is up-to-date past THRESHOLD. Request
5229 ;; interruption.
5230 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5231 (setq node (if (setq leftp (avl-tree--node-right node))
5232 (avl-tree--node-right node)
5233 (pop stack))))))
5234 ;; We reached end of tree: synchronization complete.
5235 t)))
5237 (defun org-element--parse-to (pos &optional syncp time-limit)
5238 "Parse elements in current section, down to POS.
5240 Start parsing from the closest between the last known element in
5241 cache or headline above. Return the smallest element containing
5242 POS.
5244 When optional argument SYNCP is non-nil, return the parent of the
5245 element containing POS instead. In that case, it is also
5246 possible to provide TIME-LIMIT, which is a time value specifying
5247 when the parsing should stop. The function throws `interrupt' if
5248 the process stopped before finding the expected result."
5249 (catch 'exit
5250 (org-with-wide-buffer
5251 (goto-char pos)
5252 (let* ((cached (and (org-element--cache-active-p)
5253 (org-element--cache-find pos nil)))
5254 (begin (org-element-property :begin cached))
5255 element next mode)
5256 (cond
5257 ;; Nothing in cache before point: start parsing from first
5258 ;; element following headline above, or first element in
5259 ;; buffer.
5260 ((not cached)
5261 (when (org-with-limited-levels (outline-previous-heading))
5262 (setq mode 'planning)
5263 (forward-line))
5264 (skip-chars-forward " \r\t\n")
5265 (beginning-of-line))
5266 ;; Cache returned exact match: return it.
5267 ((= pos begin)
5268 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5269 ;; There's a headline between cached value and POS: cached
5270 ;; value is invalid. Start parsing from first element
5271 ;; following the headline.
5272 ((re-search-backward
5273 (org-with-limited-levels org-outline-regexp-bol) begin t)
5274 (forward-line)
5275 (skip-chars-forward " \r\t\n")
5276 (beginning-of-line)
5277 (setq mode 'planning))
5278 ;; Check if CACHED or any of its ancestors contain point.
5280 ;; If there is such an element, we inspect it in order to know
5281 ;; if we return it or if we need to parse its contents.
5282 ;; Otherwise, we just start parsing from current location,
5283 ;; which is right after the top-most element containing
5284 ;; CACHED.
5286 ;; As a special case, if POS is at the end of the buffer, we
5287 ;; want to return the innermost element ending there.
5289 ;; Also, if we find an ancestor and discover that we need to
5290 ;; parse its contents, make sure we don't start from
5291 ;; `:contents-begin', as we would otherwise go past CACHED
5292 ;; again. Instead, in that situation, we will resume parsing
5293 ;; from NEXT, which is located after CACHED or its higher
5294 ;; ancestor not containing point.
5296 (let ((up cached)
5297 (pos (if (= (point-max) pos) (1- pos) pos)))
5298 (goto-char (or (org-element-property :contents-begin cached) begin))
5299 (while (let ((end (org-element-property :end up)))
5300 (and (<= end pos)
5301 (goto-char end)
5302 (setq up (org-element-property :parent up)))))
5303 (cond ((not up))
5304 ((eobp) (setq element up))
5305 (t (setq element up next (point)))))))
5306 ;; Parse successively each element until we reach POS.
5307 (let ((end (or (org-element-property :end element)
5308 (save-excursion
5309 (org-with-limited-levels (outline-next-heading))
5310 (point))))
5311 (parent element))
5312 (while t
5313 (when syncp
5314 (cond ((= (point) pos) (throw 'exit parent))
5315 ((org-element--cache-interrupt-p time-limit)
5316 (throw 'interrupt nil))))
5317 (unless element
5318 (setq element (org-element--current-element
5319 end 'element mode
5320 (org-element-property :structure parent)))
5321 (org-element-put-property element :parent parent)
5322 (org-element--cache-put element))
5323 (let ((elem-end (org-element-property :end element))
5324 (type (org-element-type element)))
5325 (cond
5326 ;; Skip any element ending before point. Also skip
5327 ;; element ending at point (unless it is also the end of
5328 ;; buffer) since we're sure that another element begins
5329 ;; after it.
5330 ((and (<= elem-end pos) (/= (point-max) elem-end))
5331 (goto-char elem-end)
5332 (setq mode (org-element--next-mode type nil)))
5333 ;; A non-greater element contains point: return it.
5334 ((not (memq type org-element-greater-elements))
5335 (throw 'exit element))
5336 ;; Otherwise, we have to decide if ELEMENT really
5337 ;; contains POS. In that case we start parsing from
5338 ;; contents' beginning.
5340 ;; If POS is at contents' beginning but it is also at
5341 ;; the beginning of the first item in a list or a table.
5342 ;; In that case, we need to create an anchor for that
5343 ;; list or table, so return it.
5345 ;; Also, if POS is at the end of the buffer, no element
5346 ;; can start after it, but more than one may end there.
5347 ;; Arbitrarily, we choose to return the innermost of
5348 ;; such elements.
5349 ((let ((cbeg (org-element-property :contents-begin element))
5350 (cend (org-element-property :contents-end element)))
5351 (when (or syncp
5352 (and cbeg cend
5353 (or (< cbeg pos)
5354 (and (= cbeg pos)
5355 (not (memq type '(plain-list table)))))
5356 (or (> cend pos)
5357 (and (= cend pos) (= (point-max) pos)))))
5358 (goto-char (or next cbeg))
5359 (setq next nil
5360 mode (org-element--next-mode type t)
5361 parent element
5362 end cend))))
5363 ;; Otherwise, return ELEMENT as it is the smallest
5364 ;; element containing POS.
5365 (t (throw 'exit element))))
5366 (setq element nil)))))))
5369 ;;;; Staging Buffer Changes
5371 (defconst org-element--cache-sensitive-re
5372 (concat
5373 org-outline-regexp-bol "\\|"
5374 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5375 "^[ \t]*\\(?:"
5376 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5377 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5378 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5379 "\\)")
5380 "Regexp matching a sensitive line, structure wise.
5381 A sensitive line is a headline, inlinetask, block, drawer, or
5382 latex-environment boundary. When such a line is modified,
5383 structure changes in the document may propagate in the whole
5384 section, possibly making cache invalid.")
5386 (defvar org-element--cache-change-warning nil
5387 "Non-nil when a sensitive line is about to be changed.
5388 It is a symbol among nil, t and `headline'.")
5390 (defun org-element--cache-before-change (beg end)
5391 "Request extension of area going to be modified if needed.
5392 BEG and END are the beginning and end of the range of changed
5393 text. See `before-change-functions' for more information."
5394 (when (org-element--cache-active-p)
5395 (org-with-wide-buffer
5396 (goto-char beg)
5397 (beginning-of-line)
5398 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5399 (setq org-element--cache-change-warning
5400 (save-match-data
5401 (if (and (org-with-limited-levels (org-at-heading-p))
5402 (= (line-end-position) bottom))
5403 'headline
5404 (let ((case-fold-search t))
5405 (re-search-forward
5406 org-element--cache-sensitive-re bottom t)))))))))
5408 (defun org-element--cache-after-change (beg end pre)
5409 "Update buffer modifications for current buffer.
5410 BEG and END are the beginning and end of the range of changed
5411 text, and the length in bytes of the pre-change text replaced by
5412 that range. See `after-change-functions' for more information."
5413 (when (org-element--cache-active-p)
5414 (org-with-wide-buffer
5415 (goto-char beg)
5416 (beginning-of-line)
5417 (save-match-data
5418 (let ((top (point))
5419 (bottom (save-excursion (goto-char end) (line-end-position))))
5420 ;; Determine if modified area needs to be extended, according
5421 ;; to both previous and current state. We make a special
5422 ;; case for headline editing: if a headline is modified but
5423 ;; not removed, do not extend.
5424 (when (case org-element--cache-change-warning
5425 ((t) t)
5426 (headline
5427 (not (and (org-with-limited-levels (org-at-heading-p))
5428 (= (line-end-position) bottom))))
5429 (otherwise
5430 (let ((case-fold-search t))
5431 (re-search-forward
5432 org-element--cache-sensitive-re bottom t))))
5433 ;; Effectively extend modified area.
5434 (org-with-limited-levels
5435 (setq top (progn (goto-char top)
5436 (when (outline-previous-heading) (forward-line))
5437 (point)))
5438 (setq bottom (progn (goto-char bottom)
5439 (if (outline-next-heading) (1- (point))
5440 (point))))))
5441 ;; Store synchronization request.
5442 (let ((offset (- end beg pre)))
5443 (org-element--cache-submit-request top (- bottom offset) offset)))))
5444 ;; Activate a timer to process the request during idle time.
5445 (org-element--cache-set-timer (current-buffer))))
5447 (defun org-element--cache-for-removal (beg end offset)
5448 "Return first element to remove from cache.
5450 BEG and END are buffer positions delimiting buffer modifications.
5451 OFFSET is the size of the changes.
5453 Returned element is usually the first element in cache containing
5454 any position between BEG and END. As an exception, greater
5455 elements around the changes that are robust to contents
5456 modifications are preserved and updated according to the
5457 changes."
5458 (let* ((elements (org-element--cache-find (1- beg) 'both))
5459 (before (car elements))
5460 (after (cdr elements)))
5461 (if (not before) after
5462 (let ((up before)
5463 (robust-flag t))
5464 (while up
5465 (if (let ((type (org-element-type up)))
5466 (and (or (memq type '(center-block dynamic-block quote-block
5467 special-block))
5468 ;; Drawers named "PROPERTIES" are probably
5469 ;; a properties drawer being edited. Force
5470 ;; parsing to check if editing is over.
5471 (and (eq type 'drawer)
5472 (not (string=
5473 (org-element-property :drawer-name up)
5474 "PROPERTIES"))))
5475 (let ((cbeg (org-element-property :contents-begin up)))
5476 (and cbeg
5477 (<= cbeg beg)
5478 (> (org-element-property :contents-end up) end)))))
5479 ;; UP is a robust greater element containing changes.
5480 ;; We only need to extend its ending boundaries.
5481 (org-element--cache-shift-positions
5482 up offset '(:contents-end :end))
5483 (setq before up)
5484 (when robust-flag (setq robust-flag nil)))
5485 (setq up (org-element-property :parent up)))
5486 ;; We're at top level element containing ELEMENT: if it's
5487 ;; altered by buffer modifications, it is first element in
5488 ;; cache to be removed. Otherwise, that first element is the
5489 ;; following one.
5491 ;; As a special case, do not remove BEFORE if it is a robust
5492 ;; container for current changes.
5493 (if (or (< (org-element-property :end before) beg) robust-flag) after
5494 before)))))
5496 (defun org-element--cache-submit-request (beg end offset)
5497 "Submit a new cache synchronization request for current buffer.
5498 BEG and END are buffer positions delimiting the minimal area
5499 where cache data should be removed. OFFSET is the size of the
5500 change, as an integer."
5501 (let ((next (car org-element--cache-sync-requests))
5502 delete-to delete-from)
5503 (if (and next
5504 (zerop (aref next 5))
5505 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5506 (<= (setq delete-from (aref next 1)) end))
5507 ;; Current changes can be merged with first sync request: we
5508 ;; can save a partial cache synchronization.
5509 (progn
5510 (incf (aref next 3) offset)
5511 ;; If last change happened within area to be removed, extend
5512 ;; boundaries of robust parents, if any. Otherwise, find
5513 ;; first element to remove and update request accordingly.
5514 (if (> beg delete-from)
5515 (let ((up (aref next 4)))
5516 (while up
5517 (org-element--cache-shift-positions
5518 up offset '(:contents-end :end))
5519 (setq up (org-element-property :parent up))))
5520 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5521 (when first
5522 (aset next 0 (org-element--cache-key first))
5523 (aset next 1 (org-element-property :begin first))
5524 (aset next 4 (org-element-property :parent first))))))
5525 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5526 ;; if any, is no longer a 0-phase request, thus ensuring that
5527 ;; phases are properly ordered. We need to provide OFFSET as
5528 ;; optional parameter since current modifications are not known
5529 ;; yet to the otherwise correct part of the cache (i.e, before
5530 ;; the first request).
5531 (when next (org-element--cache-sync (current-buffer) end beg))
5532 (let ((first (org-element--cache-for-removal beg end offset)))
5533 (if first
5534 (push (let ((beg (org-element-property :begin first))
5535 (key (org-element--cache-key first)))
5536 (cond
5537 ;; When changes happen before the first known
5538 ;; element, re-parent and shift the rest of the
5539 ;; cache.
5540 ((> beg end) (vector key beg nil offset nil 1))
5541 ;; Otherwise, we find the first non robust
5542 ;; element containing END. All elements between
5543 ;; FIRST and this one are to be removed.
5544 ((let ((first-end (org-element-property :end first)))
5545 (and (> first-end end)
5546 (vector key beg first-end offset first 0))))
5548 (let* ((element (org-element--cache-find end))
5549 (end (org-element-property :end element))
5550 (up element))
5551 (while (and (setq up (org-element-property :parent up))
5552 (>= (org-element-property :begin up) beg))
5553 (setq end (org-element-property :end up)
5554 element up))
5555 (vector key beg end offset element 0)))))
5556 org-element--cache-sync-requests)
5557 ;; No element to remove. No need to re-parent either.
5558 ;; Simply shift additional elements, if any, by OFFSET.
5559 (when org-element--cache-sync-requests
5560 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5563 ;;;; Public Functions
5565 ;;;###autoload
5566 (defun org-element-cache-reset (&optional all)
5567 "Reset cache in current buffer.
5568 When optional argument ALL is non-nil, reset cache in all Org
5569 buffers."
5570 (interactive "P")
5571 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5572 (with-current-buffer buffer
5573 (when (org-element--cache-active-p)
5574 (org-set-local 'org-element--cache
5575 (avl-tree-create #'org-element--cache-compare))
5576 (org-set-local 'org-element--cache-objects (make-hash-table :test #'eq))
5577 (org-set-local 'org-element--cache-sync-keys
5578 (make-hash-table :weakness 'key :test #'eq))
5579 (org-set-local 'org-element--cache-change-warning nil)
5580 (org-set-local 'org-element--cache-sync-requests nil)
5581 (org-set-local 'org-element--cache-sync-timer nil)
5582 (add-hook 'before-change-functions
5583 #'org-element--cache-before-change nil t)
5584 (add-hook 'after-change-functions
5585 #'org-element--cache-after-change nil t)))))
5587 ;;;###autoload
5588 (defun org-element-cache-refresh (pos)
5589 "Refresh cache at position POS."
5590 (when (org-element--cache-active-p)
5591 (org-element--cache-sync (current-buffer) pos)
5592 (org-element--cache-submit-request pos pos 0)
5593 (org-element--cache-set-timer (current-buffer))))
5597 ;;; The Toolbox
5599 ;; The first move is to implement a way to obtain the smallest element
5600 ;; containing point. This is the job of `org-element-at-point'. It
5601 ;; basically jumps back to the beginning of section containing point
5602 ;; and proceed, one element after the other, with
5603 ;; `org-element--current-element' until the container is found. Note:
5604 ;; When using `org-element-at-point', secondary values are never
5605 ;; parsed since the function focuses on elements, not on objects.
5607 ;; At a deeper level, `org-element-context' lists all elements and
5608 ;; objects containing point.
5610 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5611 ;; internally by navigation and manipulation tools.
5614 ;;;###autoload
5615 (defun org-element-at-point ()
5616 "Determine closest element around point.
5618 Return value is a list like (TYPE PROPS) where TYPE is the type
5619 of the element and PROPS a plist of properties associated to the
5620 element.
5622 Possible types are defined in `org-element-all-elements'.
5623 Properties depend on element or object type, but always include
5624 `:begin', `:end', `:parent' and `:post-blank' properties.
5626 As a special case, if point is at the very beginning of the first
5627 item in a list or sub-list, returned element will be that list
5628 instead of the item. Likewise, if point is at the beginning of
5629 the first row of a table, returned element will be the table
5630 instead of the first row.
5632 When point is at the end of the buffer, return the innermost
5633 element ending there."
5634 (org-with-wide-buffer
5635 (let ((origin (point)))
5636 (end-of-line)
5637 (skip-chars-backward " \r\t\n")
5638 (cond
5639 ;; Within blank lines at the beginning of buffer, return nil.
5640 ((bobp) nil)
5641 ;; Within blank lines right after a headline, return that
5642 ;; headline.
5643 ((org-with-limited-levels (org-at-heading-p))
5644 (beginning-of-line)
5645 (org-element-headline-parser (point-max) t))
5646 ;; Otherwise parse until we find element containing ORIGIN.
5648 (when (org-element--cache-active-p)
5649 (if (not org-element--cache) (org-element-cache-reset)
5650 (org-element--cache-sync (current-buffer) origin)))
5651 (org-element--parse-to origin))))))
5653 ;;;###autoload
5654 (defun org-element-context (&optional element)
5655 "Return smallest element or object around point.
5657 Return value is a list like (TYPE PROPS) where TYPE is the type
5658 of the element or object and PROPS a plist of properties
5659 associated to it.
5661 Possible types are defined in `org-element-all-elements' and
5662 `org-element-all-objects'. Properties depend on element or
5663 object type, but always include `:begin', `:end', `:parent' and
5664 `:post-blank'.
5666 As a special case, if point is right after an object and not at
5667 the beginning of any other object, return that object.
5669 Optional argument ELEMENT, when non-nil, is the closest element
5670 containing point, as returned by `org-element-at-point'.
5671 Providing it allows for quicker computation."
5672 (catch 'objects-forbidden
5673 (org-with-wide-buffer
5674 (let* ((pos (point))
5675 (element (or element (org-element-at-point)))
5676 (type (org-element-type element)))
5677 ;; If point is inside an element containing objects or
5678 ;; a secondary string, narrow buffer to the container and
5679 ;; proceed with parsing. Otherwise, return ELEMENT.
5680 (cond
5681 ;; At a parsed affiliated keyword, check if we're inside main
5682 ;; or dual value.
5683 ((let ((post (org-element-property :post-affiliated element)))
5684 (and post (< pos post)))
5685 (beginning-of-line)
5686 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5687 (cond
5688 ((not (member-ignore-case (match-string 1)
5689 org-element-parsed-keywords))
5690 (throw 'objects-forbidden element))
5691 ((< (match-end 0) pos)
5692 (narrow-to-region (match-end 0) (line-end-position)))
5693 ((and (match-beginning 2)
5694 (>= pos (match-beginning 2))
5695 (< pos (match-end 2)))
5696 (narrow-to-region (match-beginning 2) (match-end 2)))
5697 (t (throw 'objects-forbidden element)))
5698 ;; Also change type to retrieve correct restrictions.
5699 (setq type 'keyword))
5700 ;; At an item, objects can only be located within tag, if any.
5701 ((eq type 'item)
5702 (let ((tag (org-element-property :tag element)))
5703 (if (not tag) (throw 'objects-forbidden element)
5704 (beginning-of-line)
5705 (search-forward tag (line-end-position))
5706 (goto-char (match-beginning 0))
5707 (if (and (>= pos (point)) (< pos (match-end 0)))
5708 (narrow-to-region (point) (match-end 0))
5709 (throw 'objects-forbidden element)))))
5710 ;; At an headline or inlinetask, objects are in title.
5711 ((memq type '(headline inlinetask))
5712 (goto-char (org-element-property :begin element))
5713 (skip-chars-forward "*")
5714 (if (and (> pos (point)) (< pos (line-end-position)))
5715 (narrow-to-region (point) (line-end-position))
5716 (throw 'objects-forbidden element)))
5717 ;; At a paragraph, a table-row or a verse block, objects are
5718 ;; located within their contents.
5719 ((memq type '(paragraph table-row verse-block))
5720 (let ((cbeg (org-element-property :contents-begin element))
5721 (cend (org-element-property :contents-end element)))
5722 ;; CBEG is nil for table rules.
5723 (if (and cbeg cend (>= pos cbeg)
5724 (or (< pos cend) (and (= pos cend) (eobp))))
5725 (narrow-to-region cbeg cend)
5726 (throw 'objects-forbidden element))))
5727 ;; At a planning line, if point is at a timestamp, return it,
5728 ;; otherwise, return element.
5729 ((eq type 'planning)
5730 (dolist (p '(:closed :deadline :scheduled))
5731 (let ((timestamp (org-element-property p element)))
5732 (when (and timestamp
5733 (<= (org-element-property :begin timestamp) pos)
5734 (> (org-element-property :end timestamp) pos))
5735 (throw 'objects-forbidden timestamp))))
5736 ;; All other locations cannot contain objects: bail out.
5737 (throw 'objects-forbidden element))
5738 (t (throw 'objects-forbidden element)))
5739 (goto-char (point-min))
5740 (let ((restriction (org-element-restriction type))
5741 (parent element)
5742 (cache (cond ((not (org-element--cache-active-p)) nil)
5743 (org-element--cache-objects
5744 (gethash element org-element--cache-objects))
5745 (t (org-element-cache-reset) nil)))
5746 next object-data last)
5747 (prog1
5748 (catch 'exit
5749 (while t
5750 ;; When entering PARENT for the first time, get list
5751 ;; of objects within known so far. Store it in
5752 ;; OBJECT-DATA.
5753 (unless next
5754 (let ((data (assq parent cache)))
5755 (if data (setq object-data data)
5756 (push (setq object-data (list parent nil)) cache))))
5757 ;; Find NEXT object for analysis.
5758 (catch 'found
5759 ;; If NEXT is non-nil, we already exhausted the
5760 ;; cache so we can parse buffer to find the object
5761 ;; after it.
5762 (if next (setq next (org-element--object-lex restriction))
5763 ;; Otherwise, check if cache can help us.
5764 (let ((objects (cddr object-data))
5765 (completep (nth 1 object-data)))
5766 (cond
5767 ((and (not objects) completep) (throw 'exit parent))
5768 ((not objects)
5769 (setq next (org-element--object-lex restriction)))
5771 (let ((cache-limit
5772 (org-element-property :end (car objects))))
5773 (if (>= cache-limit pos)
5774 ;; Cache contains the information needed.
5775 (dolist (object objects (throw 'exit parent))
5776 (when (<= (org-element-property :begin object)
5777 pos)
5778 (if (>= (org-element-property :end object)
5779 pos)
5780 (throw 'found (setq next object))
5781 (throw 'exit parent))))
5782 (goto-char cache-limit)
5783 (setq next
5784 (org-element--object-lex restriction))))))))
5785 ;; If we have a new object to analyze, store it in
5786 ;; cache. Otherwise record that there is nothing
5787 ;; more to parse in this element at this depth.
5788 (if next
5789 (progn (org-element-put-property next :parent parent)
5790 (push next (cddr object-data)))
5791 (setcar (cdr object-data) t)))
5792 ;; Process NEXT, if any, in order to know if we need
5793 ;; to skip it, return it or move into it.
5794 (if (or (not next) (> (org-element-property :begin next) pos))
5795 (throw 'exit (or last parent))
5796 (let ((end (org-element-property :end next))
5797 (cbeg (org-element-property :contents-begin next))
5798 (cend (org-element-property :contents-end next)))
5799 (cond
5800 ;; Skip objects ending before point. Also skip
5801 ;; objects ending at point unless it is also the
5802 ;; end of buffer, since we want to return the
5803 ;; innermost object.
5804 ((and (<= end pos) (/= (point-max) end))
5805 (goto-char end)
5806 ;; For convenience, when object ends at POS,
5807 ;; without any space, store it in LAST, as we
5808 ;; will return it if no object starts here.
5809 (when (and (= end pos)
5810 (not (memq (char-before) '(?\s ?\t))))
5811 (setq last next)))
5812 ;; If POS is within a container object, move
5813 ;; into that object.
5814 ((and cbeg cend
5815 (>= pos cbeg)
5816 (or (< pos cend)
5817 ;; At contents' end, if there is no
5818 ;; space before point, also move into
5819 ;; object, for consistency with
5820 ;; convenience feature above.
5821 (and (= pos cend)
5822 (or (= (point-max) pos)
5823 (not (memq (char-before pos)
5824 '(?\s ?\t)))))))
5825 (goto-char cbeg)
5826 (narrow-to-region (point) cend)
5827 (setq parent next
5828 restriction (org-element-restriction next)
5829 next nil
5830 object-data nil))
5831 ;; Otherwise, return NEXT.
5832 (t (throw 'exit next)))))))
5833 ;; Store results in cache, if applicable.
5834 (org-element--cache-put element cache)))))))
5836 (defun org-element-lineage (blob &optional types with-self)
5837 "List all ancestors of a given element or object.
5839 BLOB is an object or element.
5841 When optional argument TYPES is a list of symbols, return the
5842 first element or object in the lineage whose type belongs to that
5843 list.
5845 When optional argument WITH-SELF is non-nil, lineage includes
5846 BLOB itself as the first element, and TYPES, if provided, also
5847 apply to it.
5849 When BLOB is obtained through `org-element-context' or
5850 `org-element-at-point', only ancestors from its section can be
5851 found. There is no such limitation when BLOB belongs to a full
5852 parse tree."
5853 (let ((up (if with-self blob (org-element-property :parent blob)))
5854 ancestors)
5855 (while (and up (not (memq (org-element-type up) types)))
5856 (unless types (push up ancestors))
5857 (setq up (org-element-property :parent up)))
5858 (if types up (nreverse ancestors))))
5860 (defun org-element-nested-p (elem-A elem-B)
5861 "Non-nil when elements ELEM-A and ELEM-B are nested."
5862 (let ((beg-A (org-element-property :begin elem-A))
5863 (beg-B (org-element-property :begin elem-B))
5864 (end-A (org-element-property :end elem-A))
5865 (end-B (org-element-property :end elem-B)))
5866 (or (and (>= beg-A beg-B) (<= end-A end-B))
5867 (and (>= beg-B beg-A) (<= end-B end-A)))))
5869 (defun org-element-swap-A-B (elem-A elem-B)
5870 "Swap elements ELEM-A and ELEM-B.
5871 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5872 end of ELEM-A."
5873 (goto-char (org-element-property :begin elem-A))
5874 ;; There are two special cases when an element doesn't start at bol:
5875 ;; the first paragraph in an item or in a footnote definition.
5876 (let ((specialp (not (bolp))))
5877 ;; Only a paragraph without any affiliated keyword can be moved at
5878 ;; ELEM-A position in such a situation. Note that the case of
5879 ;; a footnote definition is impossible: it cannot contain two
5880 ;; paragraphs in a row because it cannot contain a blank line.
5881 (if (and specialp
5882 (or (not (eq (org-element-type elem-B) 'paragraph))
5883 (/= (org-element-property :begin elem-B)
5884 (org-element-property :contents-begin elem-B))))
5885 (error "Cannot swap elements"))
5886 ;; In a special situation, ELEM-A will have no indentation. We'll
5887 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5888 (let* ((ind-B (when specialp
5889 (goto-char (org-element-property :begin elem-B))
5890 (org-get-indentation)))
5891 (beg-A (org-element-property :begin elem-A))
5892 (end-A (save-excursion
5893 (goto-char (org-element-property :end elem-A))
5894 (skip-chars-backward " \r\t\n")
5895 (point-at-eol)))
5896 (beg-B (org-element-property :begin elem-B))
5897 (end-B (save-excursion
5898 (goto-char (org-element-property :end elem-B))
5899 (skip-chars-backward " \r\t\n")
5900 (point-at-eol)))
5901 ;; Store inner overlays responsible for visibility status.
5902 ;; We also need to store their boundaries as they will be
5903 ;; removed from buffer.
5904 (overlays
5905 (cons
5906 (delq nil
5907 (mapcar (lambda (o)
5908 (and (>= (overlay-start o) beg-A)
5909 (<= (overlay-end o) end-A)
5910 (list o (overlay-start o) (overlay-end o))))
5911 (overlays-in beg-A end-A)))
5912 (delq nil
5913 (mapcar (lambda (o)
5914 (and (>= (overlay-start o) beg-B)
5915 (<= (overlay-end o) end-B)
5916 (list o (overlay-start o) (overlay-end o))))
5917 (overlays-in beg-B end-B)))))
5918 ;; Get contents.
5919 (body-A (buffer-substring beg-A end-A))
5920 (body-B (delete-and-extract-region beg-B end-B)))
5921 (goto-char beg-B)
5922 (when specialp
5923 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5924 (org-indent-to-column ind-B))
5925 (insert body-A)
5926 ;; Restore ex ELEM-A overlays.
5927 (let ((offset (- beg-B beg-A)))
5928 (dolist (o (car overlays))
5929 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
5930 (goto-char beg-A)
5931 (delete-region beg-A end-A)
5932 (insert body-B)
5933 ;; Restore ex ELEM-B overlays.
5934 (dolist (o (cdr overlays))
5935 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
5936 (goto-char (org-element-property :end elem-B)))))
5938 (defun org-element-remove-indentation (s &optional n)
5939 "Remove maximum common indentation in string S and return it.
5940 When optional argument N is a positive integer, remove exactly
5941 that much characters from indentation, if possible, or return
5942 S as-is otherwise. Unlike to `org-remove-indentation', this
5943 function doesn't call `untabify' on S."
5944 (catch 'exit
5945 (with-temp-buffer
5946 (insert s)
5947 (goto-char (point-min))
5948 ;; Find maximum common indentation, if not specified.
5949 (setq n (or n
5950 (let ((min-ind (point-max)))
5951 (save-excursion
5952 (while (re-search-forward "^[ \t]*\\S-" nil t)
5953 (let ((ind (1- (current-column))))
5954 (if (zerop ind) (throw 'exit s)
5955 (setq min-ind (min min-ind ind))))))
5956 min-ind)))
5957 (if (zerop n) s
5958 ;; Remove exactly N indentation, but give up if not possible.
5959 (while (not (eobp))
5960 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5961 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5962 ((< ind n) (throw 'exit s))
5963 (t (org-indent-line-to (- ind n))))
5964 (forward-line)))
5965 (buffer-string)))))
5969 (provide 'org-element)
5971 ;; Local variables:
5972 ;; generated-autoload-file: "org-loaddefs.el"
5973 ;; End:
5975 ;;; org-element.el ends here