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