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