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