Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob6bd0091c80a80306f8b576247b154211c9141240
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 (org-element-property :value example-block)))
1984 (concat "#+begin_example" (and switches (concat " " switches)) "\n"
1985 (org-element-normalize-string
1986 (org-escape-code-in-string
1987 (if (or org-src-preserve-indentation
1988 (org-element-property :preserve-indent example-block))
1989 value
1990 (org-remove-indentation value))))
1991 "#+end_example")))
1994 ;;;; Export Block
1996 (defun org-element-export-block-parser (limit affiliated)
1997 "Parse an export block.
1999 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2000 the buffer position at the beginning of the first affiliated
2001 keyword and CDR is a plist of affiliated keywords along with
2002 their value.
2004 Return a list whose CAR is `export-block' and CDR is a plist
2005 containing `:begin', `:end', `:type', `:value', `:post-blank' and
2006 `:post-affiliated' keywords.
2008 Assume point is at export-block beginning."
2009 (let* ((case-fold-search t))
2010 (if (not (save-excursion
2011 (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
2012 ;; Incomplete block: parse it as a paragraph.
2013 (org-element-paragraph-parser limit affiliated)
2014 (save-excursion
2015 (let* ((contents-end (match-beginning 0))
2016 (backend
2017 (progn
2018 (looking-at
2019 "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
2020 (match-string-no-properties 1)))
2021 (begin (car affiliated))
2022 (post-affiliated (point))
2023 (contents-begin (progn (forward-line) (point)))
2024 (pos-before-blank (progn (goto-char contents-end)
2025 (forward-line)
2026 (point)))
2027 (end (progn (skip-chars-forward " \r\t\n" limit)
2028 (if (eobp) (point) (line-beginning-position))))
2029 (value (org-unescape-code-in-string
2030 (buffer-substring-no-properties contents-begin
2031 contents-end))))
2032 (list 'export-block
2033 (nconc
2034 (list :type (and backend (upcase backend))
2035 :begin begin
2036 :end end
2037 :value value
2038 :post-blank (count-lines pos-before-blank end)
2039 :post-affiliated post-affiliated)
2040 (cdr affiliated))))))))
2042 (defun org-element-export-block-interpreter (export-block _)
2043 "Interpret EXPORT-BLOCK element as Org syntax."
2044 (format "#+begin_export %s\n%s#+end_export"
2045 (org-element-property :type export-block)
2046 (org-element-property :value export-block)))
2049 ;;;; Fixed-width
2051 (defun org-element-fixed-width-parser (limit affiliated)
2052 "Parse a fixed-width section.
2054 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2055 the buffer position at the beginning of the first affiliated
2056 keyword and CDR is a plist of affiliated keywords along with
2057 their value.
2059 Return a list whose CAR is `fixed-width' and CDR is a plist
2060 containing `:begin', `:end', `:value', `:post-blank' and
2061 `:post-affiliated' keywords.
2063 Assume point is at the beginning of the fixed-width area."
2064 (save-excursion
2065 (let* ((begin (car affiliated))
2066 (post-affiliated (point))
2067 value
2068 (end-area
2069 (progn
2070 (while (and (< (point) limit)
2071 (looking-at "[ \t]*:\\( \\|$\\)"))
2072 ;; Accumulate text without starting colons.
2073 (setq value
2074 (concat value
2075 (buffer-substring-no-properties
2076 (match-end 0) (point-at-eol))
2077 "\n"))
2078 (forward-line))
2079 (point)))
2080 (end (progn (skip-chars-forward " \r\t\n" limit)
2081 (if (eobp) (point) (line-beginning-position)))))
2082 (list 'fixed-width
2083 (nconc
2084 (list :begin begin
2085 :end end
2086 :value value
2087 :post-blank (count-lines end-area end)
2088 :post-affiliated post-affiliated)
2089 (cdr affiliated))))))
2091 (defun org-element-fixed-width-interpreter (fixed-width _)
2092 "Interpret FIXED-WIDTH element as Org syntax."
2093 (let ((value (org-element-property :value fixed-width)))
2094 (and value
2095 (replace-regexp-in-string
2096 "^" ": "
2097 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2100 ;;;; Horizontal Rule
2102 (defun org-element-horizontal-rule-parser (limit affiliated)
2103 "Parse an horizontal rule.
2105 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2106 the buffer position at the beginning of the first affiliated
2107 keyword and CDR is a plist of affiliated keywords along with
2108 their value.
2110 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2111 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2112 keywords."
2113 (save-excursion
2114 (let ((begin (car affiliated))
2115 (post-affiliated (point))
2116 (post-hr (progn (forward-line) (point)))
2117 (end (progn (skip-chars-forward " \r\t\n" limit)
2118 (if (eobp) (point) (line-beginning-position)))))
2119 (list 'horizontal-rule
2120 (nconc
2121 (list :begin begin
2122 :end end
2123 :post-blank (count-lines post-hr end)
2124 :post-affiliated post-affiliated)
2125 (cdr affiliated))))))
2127 (defun org-element-horizontal-rule-interpreter (&rest _)
2128 "Interpret HORIZONTAL-RULE element as Org syntax."
2129 "-----")
2132 ;;;; Keyword
2134 (defun org-element-keyword-parser (limit affiliated)
2135 "Parse a keyword at point.
2137 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2138 the buffer position at the beginning of the first affiliated
2139 keyword and CDR is a plist of affiliated keywords along with
2140 their value.
2142 Return a list whose CAR is `keyword' and CDR is a plist
2143 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2144 `:post-affiliated' keywords."
2145 (save-excursion
2146 ;; An orphaned affiliated keyword is considered as a regular
2147 ;; keyword. In this case AFFILIATED is nil, so we take care of
2148 ;; this corner case.
2149 (let ((begin (or (car affiliated) (point)))
2150 (post-affiliated (point))
2151 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2152 (upcase (match-string-no-properties 1))))
2153 (value (org-trim (buffer-substring-no-properties
2154 (match-end 0) (point-at-eol))))
2155 (pos-before-blank (progn (forward-line) (point)))
2156 (end (progn (skip-chars-forward " \r\t\n" limit)
2157 (if (eobp) (point) (line-beginning-position)))))
2158 (list 'keyword
2159 (nconc
2160 (list :key key
2161 :value value
2162 :begin begin
2163 :end end
2164 :post-blank (count-lines pos-before-blank end)
2165 :post-affiliated post-affiliated)
2166 (cdr affiliated))))))
2168 (defun org-element-keyword-interpreter (keyword _)
2169 "Interpret KEYWORD element as Org syntax."
2170 (format "#+%s: %s"
2171 (downcase (org-element-property :key keyword))
2172 (org-element-property :value keyword)))
2175 ;;;; Latex Environment
2177 (defconst org-element--latex-begin-environment
2178 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2179 "Regexp matching the beginning of a LaTeX environment.
2180 The environment is captured by the first group.
2182 See also `org-element--latex-end-environment'.")
2184 (defconst org-element--latex-end-environment
2185 "\\\\end{%s}[ \t]*$"
2186 "Format string matching the ending of a LaTeX environment.
2187 See also `org-element--latex-begin-environment'.")
2189 (defun org-element-latex-environment-parser (limit affiliated)
2190 "Parse a LaTeX environment.
2192 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2193 the buffer position at the beginning of the first affiliated
2194 keyword and CDR is a plist of affiliated keywords along with
2195 their value.
2197 Return a list whose CAR is `latex-environment' and CDR is a plist
2198 containing `:begin', `:end', `:value', `:post-blank' and
2199 `:post-affiliated' keywords.
2201 Assume point is at the beginning of the latex environment."
2202 (save-excursion
2203 (let ((case-fold-search t)
2204 (code-begin (point)))
2205 (looking-at org-element--latex-begin-environment)
2206 (if (not (re-search-forward (format org-element--latex-end-environment
2207 (regexp-quote (match-string 1)))
2208 limit t))
2209 ;; Incomplete latex environment: parse it as a paragraph.
2210 (org-element-paragraph-parser limit affiliated)
2211 (let* ((code-end (progn (forward-line) (point)))
2212 (begin (car affiliated))
2213 (value (buffer-substring-no-properties code-begin code-end))
2214 (end (progn (skip-chars-forward " \r\t\n" limit)
2215 (if (eobp) (point) (line-beginning-position)))))
2216 (list 'latex-environment
2217 (nconc
2218 (list :begin begin
2219 :end end
2220 :value value
2221 :post-blank (count-lines code-end end)
2222 :post-affiliated code-begin)
2223 (cdr affiliated))))))))
2225 (defun org-element-latex-environment-interpreter (latex-environment _)
2226 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2227 (org-element-property :value latex-environment))
2230 ;;;; Node Property
2232 (defun org-element-node-property-parser (limit)
2233 "Parse a node-property at point.
2235 LIMIT bounds the search.
2237 Return a list whose CAR is `node-property' and CDR is a plist
2238 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2239 `:post-affiliated' keywords."
2240 (looking-at org-property-re)
2241 (let ((case-fold-search t)
2242 (begin (point))
2243 (key (match-string-no-properties 2))
2244 (value (match-string-no-properties 3))
2245 (end (save-excursion
2246 (end-of-line)
2247 (if (re-search-forward org-property-re limit t)
2248 (line-beginning-position)
2249 limit))))
2250 (list 'node-property
2251 (list :key key
2252 :value value
2253 :begin begin
2254 :end end
2255 :post-blank 0
2256 :post-affiliated begin))))
2258 (defun org-element-node-property-interpreter (node-property _)
2259 "Interpret NODE-PROPERTY element as Org syntax."
2260 (format org-property-format
2261 (format ":%s:" (org-element-property :key node-property))
2262 (or (org-element-property :value node-property) "")))
2265 ;;;; Paragraph
2267 (defun org-element-paragraph-parser (limit affiliated)
2268 "Parse a paragraph.
2270 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2271 the buffer position at the beginning of the first affiliated
2272 keyword and CDR is a plist of affiliated keywords along with
2273 their value.
2275 Return a list whose CAR is `paragraph' and CDR is a plist
2276 containing `:begin', `:end', `:contents-begin' and
2277 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2279 Assume point is at the beginning of the paragraph."
2280 (save-excursion
2281 (let* ((begin (car affiliated))
2282 (contents-begin (point))
2283 (before-blank
2284 (let ((case-fold-search t))
2285 (end-of-line)
2286 ;; A matching `org-element-paragraph-separate' is not
2287 ;; necessarily the end of the paragraph. In particular,
2288 ;; drawers, blocks or LaTeX environments opening lines
2289 ;; must be closed. Moreover keywords with a secondary
2290 ;; value must belong to "dual keywords".
2291 (while (not
2292 (cond
2293 ((not (and (re-search-forward
2294 org-element-paragraph-separate limit 'move)
2295 (progn (beginning-of-line) t))))
2296 ((looking-at org-drawer-regexp)
2297 (save-excursion
2298 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2299 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2300 (save-excursion
2301 (re-search-forward
2302 (format "^[ \t]*#\\+END_%s[ \t]*$"
2303 (regexp-quote (match-string 1)))
2304 limit t)))
2305 ((looking-at org-element--latex-begin-environment)
2306 (save-excursion
2307 (re-search-forward
2308 (format org-element--latex-end-environment
2309 (regexp-quote (match-string 1)))
2310 limit t)))
2311 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2312 (member-ignore-case (match-string 1)
2313 org-element-dual-keywords))
2314 ;; Everything else is unambiguous.
2315 (t)))
2316 (end-of-line))
2317 (if (= (point) limit) limit
2318 (goto-char (line-beginning-position)))))
2319 (contents-end (save-excursion
2320 (skip-chars-backward " \r\t\n" contents-begin)
2321 (line-beginning-position 2)))
2322 (end (progn (skip-chars-forward " \r\t\n" limit)
2323 (if (eobp) (point) (line-beginning-position)))))
2324 (list 'paragraph
2325 (nconc
2326 (list :begin begin
2327 :end end
2328 :contents-begin contents-begin
2329 :contents-end contents-end
2330 :post-blank (count-lines before-blank end)
2331 :post-affiliated contents-begin)
2332 (cdr affiliated))))))
2334 (defun org-element-paragraph-interpreter (_ contents)
2335 "Interpret paragraph element as Org syntax.
2336 CONTENTS is the contents of the element."
2337 contents)
2340 ;;;; Planning
2342 (defun org-element-planning-parser (limit)
2343 "Parse a planning.
2345 LIMIT bounds the search.
2347 Return a list whose CAR is `planning' and CDR is a plist
2348 containing `:closed', `:deadline', `:scheduled', `:begin',
2349 `:end', `:post-blank' and `:post-affiliated' keywords."
2350 (save-excursion
2351 (let* ((case-fold-search nil)
2352 (begin (point))
2353 (post-blank (let ((before-blank (progn (forward-line) (point))))
2354 (skip-chars-forward " \r\t\n" limit)
2355 (skip-chars-backward " \t")
2356 (unless (bolp) (end-of-line))
2357 (count-lines before-blank (point))))
2358 (end (point))
2359 closed deadline scheduled)
2360 (goto-char begin)
2361 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2362 (goto-char (match-end 1))
2363 (skip-chars-forward " \t" end)
2364 (let ((keyword (match-string 1))
2365 (time (org-element-timestamp-parser)))
2366 (cond ((equal keyword org-closed-string) (setq closed time))
2367 ((equal keyword org-deadline-string) (setq deadline time))
2368 (t (setq scheduled time)))))
2369 (list 'planning
2370 (list :closed closed
2371 :deadline deadline
2372 :scheduled scheduled
2373 :begin begin
2374 :end end
2375 :post-blank post-blank
2376 :post-affiliated begin)))))
2378 (defun org-element-planning-interpreter (planning _)
2379 "Interpret PLANNING element as Org syntax."
2380 (mapconcat
2381 #'identity
2382 (delq nil
2383 (list (let ((deadline (org-element-property :deadline planning)))
2384 (when deadline
2385 (concat org-deadline-string " "
2386 (org-element-timestamp-interpreter deadline nil))))
2387 (let ((scheduled (org-element-property :scheduled planning)))
2388 (when scheduled
2389 (concat org-scheduled-string " "
2390 (org-element-timestamp-interpreter scheduled nil))))
2391 (let ((closed (org-element-property :closed planning)))
2392 (when closed
2393 (concat org-closed-string " "
2394 (org-element-timestamp-interpreter closed nil))))))
2395 " "))
2398 ;;;; Src Block
2400 (defun org-element-src-block-parser (limit affiliated)
2401 "Parse a src block.
2403 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2404 the buffer position at the beginning of the first affiliated
2405 keyword and CDR is a plist of affiliated keywords along with
2406 their value.
2408 Return a list whose CAR is `src-block' and CDR is a plist
2409 containing `:language', `:switches', `:parameters', `:begin',
2410 `:end', `:number-lines', `:retain-labels', `:use-labels',
2411 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2412 `:post-affiliated' keywords.
2414 Assume point is at the beginning of the block."
2415 (let ((case-fold-search t))
2416 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2417 limit t)))
2418 ;; Incomplete block: parse it as a paragraph.
2419 (org-element-paragraph-parser limit affiliated)
2420 (let ((contents-end (match-beginning 0)))
2421 (save-excursion
2422 (let* ((begin (car affiliated))
2423 (post-affiliated (point))
2424 ;; Get language as a string.
2425 (language
2426 (progn
2427 (looking-at
2428 "^[ \t]*#\\+BEGIN_SRC\
2429 \\(?: +\\(\\S-+\\)\\)?\
2430 \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
2431 \\(.*\\)[ \t]*$")
2432 (match-string-no-properties 1)))
2433 ;; Get switches.
2434 (switches (match-string-no-properties 2))
2435 ;; Get parameters.
2436 (parameters (match-string-no-properties 3))
2437 ;; Switches analysis.
2438 (number-lines
2439 (and switches
2440 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
2441 switches)
2442 (cons
2443 (if (equal (match-string 1 switches) "-")
2444 'new
2445 'continued)
2446 (if (not (match-end 2)) 0
2447 ;; Subtract 1 to give number of lines before
2448 ;; first line.
2449 (1- (string-to-number (match-string 2 switches)))))))
2450 (preserve-indent (and switches
2451 (string-match "-i\\>" switches)))
2452 (label-fmt
2453 (and switches
2454 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2455 (match-string 1 switches)))
2456 ;; Should labels be retained in (or stripped from)
2457 ;; src blocks?
2458 (retain-labels
2459 (or (not switches)
2460 (not (string-match "-r\\>" switches))
2461 (and number-lines (string-match "-k\\>" switches))))
2462 ;; What should code-references use - labels or
2463 ;; line-numbers?
2464 (use-labels
2465 (or (not switches)
2466 (and retain-labels
2467 (not (string-match "-k\\>" switches)))))
2468 ;; Retrieve code.
2469 (value (org-unescape-code-in-string
2470 (buffer-substring-no-properties
2471 (line-beginning-position 2) contents-end)))
2472 (pos-before-blank (progn (goto-char contents-end)
2473 (forward-line)
2474 (point)))
2475 ;; Get position after ending blank lines.
2476 (end (progn (skip-chars-forward " \r\t\n" limit)
2477 (if (eobp) (point) (line-beginning-position)))))
2478 (list 'src-block
2479 (nconc
2480 (list :language language
2481 :switches (and (org-string-nw-p switches)
2482 (org-trim switches))
2483 :parameters (and (org-string-nw-p parameters)
2484 (org-trim parameters))
2485 :begin begin
2486 :end end
2487 :number-lines number-lines
2488 :preserve-indent preserve-indent
2489 :retain-labels retain-labels
2490 :use-labels use-labels
2491 :label-fmt label-fmt
2492 :value value
2493 :post-blank (count-lines pos-before-blank end)
2494 :post-affiliated post-affiliated)
2495 (cdr affiliated)))))))))
2497 (defun org-element-src-block-interpreter (src-block _)
2498 "Interpret SRC-BLOCK element as Org syntax."
2499 (let ((lang (org-element-property :language src-block))
2500 (switches (org-element-property :switches src-block))
2501 (params (org-element-property :parameters src-block))
2502 (value
2503 (let ((val (org-element-property :value src-block)))
2504 (cond
2505 ((or org-src-preserve-indentation
2506 (org-element-property :preserve-indent src-block))
2507 val)
2508 ((zerop org-edit-src-content-indentation)
2509 (org-remove-indentation val))
2511 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2512 (replace-regexp-in-string
2513 "^" ind (org-remove-indentation val))))))))
2514 (concat (format "#+begin_src%s\n"
2515 (concat (and lang (concat " " lang))
2516 (and switches (concat " " switches))
2517 (and params (concat " " params))))
2518 (org-element-normalize-string (org-escape-code-in-string value))
2519 "#+end_src")))
2522 ;;;; Table
2524 (defun org-element-table-parser (limit affiliated)
2525 "Parse a table at point.
2527 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2528 the buffer position at the beginning of the first affiliated
2529 keyword and CDR is a plist of affiliated keywords along with
2530 their value.
2532 Return a list whose CAR is `table' and CDR is a plist containing
2533 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2534 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2535 keywords.
2537 Assume point is at the beginning of the table."
2538 (save-excursion
2539 (let* ((case-fold-search t)
2540 (table-begin (point))
2541 (type (if (looking-at "[ \t]*|") 'org 'table.el))
2542 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2543 (if (eq type 'org) "" "+")))
2544 (begin (car affiliated))
2545 (table-end
2546 (if (re-search-forward end-re limit 'move)
2547 (goto-char (match-beginning 0))
2548 (point)))
2549 (tblfm (let (acc)
2550 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2551 (push (match-string-no-properties 1) acc)
2552 (forward-line))
2553 acc))
2554 (pos-before-blank (point))
2555 (end (progn (skip-chars-forward " \r\t\n" limit)
2556 (if (eobp) (point) (line-beginning-position)))))
2557 (list 'table
2558 (nconc
2559 (list :begin begin
2560 :end end
2561 :type type
2562 :tblfm tblfm
2563 ;; Only `org' tables have contents. `table.el' tables
2564 ;; use a `:value' property to store raw table as
2565 ;; a string.
2566 :contents-begin (and (eq type 'org) table-begin)
2567 :contents-end (and (eq type 'org) table-end)
2568 :value (and (eq type 'table.el)
2569 (buffer-substring-no-properties
2570 table-begin table-end))
2571 :post-blank (count-lines pos-before-blank end)
2572 :post-affiliated table-begin)
2573 (cdr affiliated))))))
2575 (defun org-element-table-interpreter (table contents)
2576 "Interpret TABLE element as Org syntax.
2577 CONTENTS is a string, if table's type is `org', or nil."
2578 (if (eq (org-element-property :type table) 'table.el)
2579 (org-remove-indentation (org-element-property :value table))
2580 (concat (with-temp-buffer (insert contents)
2581 (org-table-align)
2582 (buffer-string))
2583 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2584 (reverse (org-element-property :tblfm table))
2585 "\n"))))
2588 ;;;; Table Row
2590 (defun org-element-table-row-parser (_)
2591 "Parse table row at point.
2593 Return a list whose CAR is `table-row' and CDR is a plist
2594 containing `:begin', `:end', `:contents-begin', `:contents-end',
2595 `:type', `:post-blank' and `:post-affiliated' keywords."
2596 (save-excursion
2597 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2598 (begin (point))
2599 ;; A table rule has no contents. In that case, ensure
2600 ;; CONTENTS-BEGIN matches CONTENTS-END.
2601 (contents-begin (and (eq type 'standard) (search-forward "|")))
2602 (contents-end (and (eq type 'standard)
2603 (progn
2604 (end-of-line)
2605 (skip-chars-backward " \t")
2606 (point))))
2607 (end (line-beginning-position 2)))
2608 (list 'table-row
2609 (list :type type
2610 :begin begin
2611 :end end
2612 :contents-begin contents-begin
2613 :contents-end contents-end
2614 :post-blank 0
2615 :post-affiliated begin)))))
2617 (defun org-element-table-row-interpreter (table-row contents)
2618 "Interpret TABLE-ROW element as Org syntax.
2619 CONTENTS is the contents of the table row."
2620 (if (eq (org-element-property :type table-row) 'rule) "|-"
2621 (concat "|" contents)))
2624 ;;;; Verse Block
2626 (defun org-element-verse-block-parser (limit affiliated)
2627 "Parse a verse block.
2629 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2630 the buffer position at the beginning of the first affiliated
2631 keyword and CDR is a plist of affiliated keywords along with
2632 their value.
2634 Return a list whose CAR is `verse-block' and CDR is a plist
2635 containing `:begin', `:end', `:contents-begin', `:contents-end',
2636 `:post-blank' and `:post-affiliated' keywords.
2638 Assume point is at beginning of the block."
2639 (let ((case-fold-search t))
2640 (if (not (save-excursion
2641 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2642 ;; Incomplete block: parse it as a paragraph.
2643 (org-element-paragraph-parser limit affiliated)
2644 (let ((contents-end (match-beginning 0)))
2645 (save-excursion
2646 (let* ((begin (car affiliated))
2647 (post-affiliated (point))
2648 (contents-begin (progn (forward-line) (point)))
2649 (pos-before-blank (progn (goto-char contents-end)
2650 (forward-line)
2651 (point)))
2652 (end (progn (skip-chars-forward " \r\t\n" limit)
2653 (if (eobp) (point) (line-beginning-position)))))
2654 (list 'verse-block
2655 (nconc
2656 (list :begin begin
2657 :end end
2658 :contents-begin contents-begin
2659 :contents-end contents-end
2660 :post-blank (count-lines pos-before-blank end)
2661 :post-affiliated post-affiliated)
2662 (cdr affiliated)))))))))
2664 (defun org-element-verse-block-interpreter (_ contents)
2665 "Interpret verse-block element as Org syntax.
2666 CONTENTS is verse block contents."
2667 (format "#+begin_verse\n%s#+end_verse" contents))
2671 ;;; Objects
2673 ;; Unlike to elements, raw text can be found between objects. Hence,
2674 ;; `org-element--object-lex' is provided to find the next object in
2675 ;; buffer.
2677 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2678 ;; object types they can contain will be specified in
2679 ;; `org-element-object-restrictions'.
2681 ;; Creating a new type of object requires to alter
2682 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2683 ;; new type in `org-element-all-objects', and possibly add
2684 ;; restrictions in `org-element-object-restrictions'.
2686 ;;;; Bold
2688 (defun org-element-bold-parser ()
2689 "Parse bold object at point, if any.
2691 When at a bold object, return a list whose car is `bold' and cdr
2692 is a plist with `:begin', `:end', `:contents-begin' and
2693 `:contents-end' and `:post-blank' keywords. Otherwise, return
2694 nil.
2696 Assume point is at the first star marker."
2697 (save-excursion
2698 (unless (bolp) (backward-char 1))
2699 (when (looking-at org-emph-re)
2700 (let ((begin (match-beginning 2))
2701 (contents-begin (match-beginning 4))
2702 (contents-end (match-end 4))
2703 (post-blank (progn (goto-char (match-end 2))
2704 (skip-chars-forward " \t")))
2705 (end (point)))
2706 (list 'bold
2707 (list :begin begin
2708 :end end
2709 :contents-begin contents-begin
2710 :contents-end contents-end
2711 :post-blank post-blank))))))
2713 (defun org-element-bold-interpreter (_ contents)
2714 "Interpret bold object as Org syntax.
2715 CONTENTS is the contents of the object."
2716 (format "*%s*" contents))
2719 ;;;; Code
2721 (defun org-element-code-parser ()
2722 "Parse code object at point, if any.
2724 When at a code object, return a list whose car is `code' and cdr
2725 is a plist with `:value', `:begin', `:end' and `:post-blank'
2726 keywords. Otherwise, return nil.
2728 Assume point is at the first tilde marker."
2729 (save-excursion
2730 (unless (bolp) (backward-char 1))
2731 (when (looking-at org-verbatim-re)
2732 (let ((begin (match-beginning 2))
2733 (value (match-string-no-properties 4))
2734 (post-blank (progn (goto-char (match-end 2))
2735 (skip-chars-forward " \t")))
2736 (end (point)))
2737 (list 'code
2738 (list :value value
2739 :begin begin
2740 :end end
2741 :post-blank post-blank))))))
2743 (defun org-element-code-interpreter (code _)
2744 "Interpret CODE object as Org syntax."
2745 (format "~%s~" (org-element-property :value code)))
2748 ;;;; Entity
2750 (defun org-element-entity-parser ()
2751 "Parse entity at point, if any.
2753 When at an entity, return a list whose car is `entity' and cdr
2754 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2755 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2756 `:post-blank' as keywords. Otherwise, return nil.
2758 Assume point is at the beginning of the entity."
2759 (catch 'no-object
2760 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2761 (save-excursion
2762 (let* ((value (or (org-entity-get (match-string 1))
2763 (throw 'no-object nil)))
2764 (begin (match-beginning 0))
2765 (bracketsp (string= (match-string 2) "{}"))
2766 (post-blank (progn (goto-char (match-end 1))
2767 (when bracketsp (forward-char 2))
2768 (skip-chars-forward " \t")))
2769 (end (point)))
2770 (list 'entity
2771 (list :name (car value)
2772 :latex (nth 1 value)
2773 :latex-math-p (nth 2 value)
2774 :html (nth 3 value)
2775 :ascii (nth 4 value)
2776 :latin1 (nth 5 value)
2777 :utf-8 (nth 6 value)
2778 :begin begin
2779 :end end
2780 :use-brackets-p bracketsp
2781 :post-blank post-blank)))))))
2783 (defun org-element-entity-interpreter (entity _)
2784 "Interpret ENTITY object as Org syntax."
2785 (concat "\\"
2786 (org-element-property :name entity)
2787 (when (org-element-property :use-brackets-p entity) "{}")))
2790 ;;;; Export Snippet
2792 (defun org-element-export-snippet-parser ()
2793 "Parse export snippet at point.
2795 When at an export snippet, return a list whose car is
2796 `export-snippet' and cdr a plist with `:begin', `:end',
2797 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2798 return nil.
2800 Assume point is at the beginning of the snippet."
2801 (save-excursion
2802 (let (contents-end)
2803 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2804 (setq contents-end
2805 (save-match-data (goto-char (match-end 0))
2806 (re-search-forward "@@" nil t)
2807 (match-beginning 0))))
2808 (let* ((begin (match-beginning 0))
2809 (back-end (match-string-no-properties 1))
2810 (value (buffer-substring-no-properties
2811 (match-end 0) contents-end))
2812 (post-blank (skip-chars-forward " \t"))
2813 (end (point)))
2814 (list 'export-snippet
2815 (list :back-end back-end
2816 :value value
2817 :begin begin
2818 :end end
2819 :post-blank post-blank)))))))
2821 (defun org-element-export-snippet-interpreter (export-snippet _)
2822 "Interpret EXPORT-SNIPPET object as Org syntax."
2823 (format "@@%s:%s@@"
2824 (org-element-property :back-end export-snippet)
2825 (org-element-property :value export-snippet)))
2828 ;;;; Footnote Reference
2830 (defun org-element-footnote-reference-parser ()
2831 "Parse footnote reference at point, if any.
2833 When at a footnote reference, return a list whose car is
2834 `footnote-reference' and cdr a plist with `:label', `:type',
2835 `:begin', `:end', `:content-begin', `:contents-end' and
2836 `:post-blank' as keywords. Otherwise, return nil."
2837 (when (looking-at org-footnote-re)
2838 (let ((closing (with-syntax-table org-element--pair-square-table
2839 (ignore-errors (scan-lists (point) 1 0)))))
2840 (when closing
2841 (save-excursion
2842 (let* ((begin (point))
2843 (label (match-string-no-properties 1))
2844 (inner-begin (match-end 0))
2845 (inner-end (1- closing))
2846 (type (if (match-end 2) 'inline 'standard))
2847 (post-blank (progn (goto-char closing)
2848 (skip-chars-forward " \t")))
2849 (end (point)))
2850 (list 'footnote-reference
2851 (list :label label
2852 :type type
2853 :begin begin
2854 :end end
2855 :contents-begin (and (eq type 'inline) inner-begin)
2856 :contents-end (and (eq type 'inline) inner-end)
2857 :post-blank post-blank))))))))
2859 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2860 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2861 CONTENTS is its definition, when inline, or nil."
2862 (format "[fn:%s%s]"
2863 (or (org-element-property :label footnote-reference) "")
2864 (if contents (concat ":" contents) "")))
2867 ;;;; Inline Babel Call
2869 (defun org-element-inline-babel-call-parser ()
2870 "Parse inline babel call at point, if any.
2872 When at an inline babel call, return a list whose car is
2873 `inline-babel-call' and cdr a plist with `:call',
2874 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2875 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2877 Assume point is at the beginning of the babel call."
2878 (save-excursion
2879 (catch :no-object
2880 (when (let ((case-fold-search nil))
2881 (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
2882 (goto-char (match-end 1))
2883 (let* ((begin (match-beginning 0))
2884 (call (match-string-no-properties 1))
2885 (inside-header
2886 (let ((p (org-element--parse-paired-brackets ?\[)))
2887 (and (org-string-nw-p p)
2888 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2889 (arguments (org-string-nw-p
2890 (or (org-element--parse-paired-brackets ?\()
2891 ;; Parenthesis are mandatory.
2892 (throw :no-object nil))))
2893 (end-header
2894 (let ((p (org-element--parse-paired-brackets ?\[)))
2895 (and (org-string-nw-p p)
2896 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2897 (value (buffer-substring-no-properties begin (point)))
2898 (post-blank (skip-chars-forward " \t"))
2899 (end (point)))
2900 (list 'inline-babel-call
2901 (list :call call
2902 :inside-header inside-header
2903 :arguments arguments
2904 :end-header end-header
2905 :begin begin
2906 :end end
2907 :value value
2908 :post-blank post-blank)))))))
2910 (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
2911 "Interpret INLINE-BABEL-CALL object as Org syntax."
2912 (concat "call_"
2913 (org-element-property :call inline-babel-call)
2914 (let ((h (org-element-property :inside-header inline-babel-call)))
2915 (and h (format "[%s]" h)))
2916 "(" (org-element-property :arguments inline-babel-call) ")"
2917 (let ((h (org-element-property :end-header inline-babel-call)))
2918 (and h (format "[%s]" h)))))
2921 ;;;; Inline Src Block
2923 (defun org-element-inline-src-block-parser ()
2924 "Parse inline source block at point, if any.
2926 When at an inline source block, return a list whose car is
2927 `inline-src-block' and cdr a plist with `:begin', `:end',
2928 `:language', `:value', `:parameters' and `:post-blank' as
2929 keywords. Otherwise, return nil.
2931 Assume point is at the beginning of the inline src block."
2932 (save-excursion
2933 (catch :no-object
2934 (when (let ((case-fold-search nil))
2935 (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
2936 (goto-char (match-end 1))
2937 (let ((begin (match-beginning 0))
2938 (language (match-string-no-properties 1))
2939 (parameters
2940 (let ((p (org-element--parse-paired-brackets ?\[)))
2941 (and (org-string-nw-p p)
2942 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2943 (value (or (org-element--parse-paired-brackets ?\{)
2944 (throw :no-object nil)))
2945 (post-blank (skip-chars-forward " \t")))
2946 (list 'inline-src-block
2947 (list :language language
2948 :value value
2949 :parameters parameters
2950 :begin begin
2951 :end (point)
2952 :post-blank post-blank)))))))
2954 (defun org-element-inline-src-block-interpreter (inline-src-block _)
2955 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2956 (let ((language (org-element-property :language inline-src-block))
2957 (arguments (org-element-property :parameters inline-src-block))
2958 (body (org-element-property :value inline-src-block)))
2959 (format "src_%s%s{%s}"
2960 language
2961 (if arguments (format "[%s]" arguments) "")
2962 body)))
2964 ;;;; Italic
2966 (defun org-element-italic-parser ()
2967 "Parse italic object at point, if any.
2969 When at an italic object, return a list whose car is `italic' and
2970 cdr is a plist with `:begin', `:end', `:contents-begin' and
2971 `:contents-end' and `:post-blank' keywords. Otherwise, return
2972 nil.
2974 Assume point is at the first slash marker."
2975 (save-excursion
2976 (unless (bolp) (backward-char 1))
2977 (when (looking-at org-emph-re)
2978 (let ((begin (match-beginning 2))
2979 (contents-begin (match-beginning 4))
2980 (contents-end (match-end 4))
2981 (post-blank (progn (goto-char (match-end 2))
2982 (skip-chars-forward " \t")))
2983 (end (point)))
2984 (list 'italic
2985 (list :begin begin
2986 :end end
2987 :contents-begin contents-begin
2988 :contents-end contents-end
2989 :post-blank post-blank))))))
2991 (defun org-element-italic-interpreter (_ contents)
2992 "Interpret italic object as Org syntax.
2993 CONTENTS is the contents of the object."
2994 (format "/%s/" contents))
2997 ;;;; Latex Fragment
2999 (defun org-element-latex-fragment-parser ()
3000 "Parse LaTeX fragment at point, if any.
3002 When at a LaTeX fragment, return a list whose car is
3003 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
3004 and `:post-blank' as keywords. Otherwise, return nil.
3006 Assume point is at the beginning of the LaTeX fragment."
3007 (catch 'no-object
3008 (save-excursion
3009 (let* ((begin (point))
3010 (after-fragment
3011 (cond
3012 ((not (eq ?$ (char-after)))
3013 (pcase (char-after (1+ (point)))
3014 (?\( (search-forward "\\)" nil t))
3015 (?\[ (search-forward "\\]" nil t))
3017 ;; Macro.
3018 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
3019 \\|\\({[^{}\n]*}\\)\\)*")
3020 (match-end 0)))))
3021 ((eq ?$ (char-after (1+ (point))))
3022 (search-forward "$$" nil t 2))
3024 (and (not (eq ?$ (char-before)))
3025 (not (memq (char-after (1+ (point)))
3026 '(?\s ?\t ?\n ?, ?. ?\;)))
3027 (search-forward "$" nil t 2)
3028 (not (memq (char-before (match-beginning 0))
3029 '(?\s ?\t ?\n ?, ?.)))
3030 (looking-at-p
3031 "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
3032 (point)))))
3033 (post-blank
3034 (if (not after-fragment) (throw 'no-object nil)
3035 (goto-char after-fragment)
3036 (skip-chars-forward " \t")))
3037 (end (point)))
3038 (list 'latex-fragment
3039 (list :value (buffer-substring-no-properties begin after-fragment)
3040 :begin begin
3041 :end end
3042 :post-blank post-blank))))))
3044 (defun org-element-latex-fragment-interpreter (latex-fragment _)
3045 "Interpret LATEX-FRAGMENT object as Org syntax."
3046 (org-element-property :value latex-fragment))
3048 ;;;; Line Break
3050 (defun org-element-line-break-parser ()
3051 "Parse line break at point, if any.
3053 When at a line break, return a list whose car is `line-break',
3054 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3055 Otherwise, return nil.
3057 Assume point is at the beginning of the line break."
3058 (when (and (looking-at-p "\\\\\\\\[ \t]*$")
3059 (not (eq (char-before) ?\\)))
3060 (list 'line-break
3061 (list :begin (point)
3062 :end (line-beginning-position 2)
3063 :post-blank 0))))
3065 (defun org-element-line-break-interpreter (&rest _)
3066 "Interpret LINE-BREAK object as Org syntax."
3067 "\\\\\n")
3070 ;;;; Link
3072 (defun org-element-link-parser ()
3073 "Parse link at point, if any.
3075 When at a link, return a list whose car is `link' and cdr a plist
3076 with `:type', `:path', `:format', `:raw-link', `:application',
3077 `:search-option', `:begin', `:end', `:contents-begin',
3078 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3079 nil.
3081 Assume point is at the beginning of the link."
3082 (catch 'no-object
3083 (let ((begin (point))
3084 end contents-begin contents-end link-end post-blank path type format
3085 raw-link search-option application)
3086 (cond
3087 ;; Type 1: Text targeted from a radio target.
3088 ((and org-target-link-regexp
3089 (save-excursion (or (bolp) (backward-char))
3090 (looking-at org-target-link-regexp)))
3091 (setq type "radio")
3092 (setq format 'plain)
3093 (setq link-end (match-end 1))
3094 (setq path (match-string-no-properties 1))
3095 (setq contents-begin (match-beginning 1))
3096 (setq contents-end (match-end 1)))
3097 ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
3098 ((looking-at org-bracket-link-regexp)
3099 (setq format 'bracket)
3100 (setq contents-begin (match-beginning 3))
3101 (setq contents-end (match-end 3))
3102 (setq link-end (match-end 0))
3103 ;; RAW-LINK is the original link. Expand any
3104 ;; abbreviation in it.
3106 ;; Also treat any newline character and associated
3107 ;; indentation as a single space character. This is not
3108 ;; compatible with RFC 3986, which requires to ignore
3109 ;; them altogether. However, doing so would require
3110 ;; users to encode spaces on the fly when writing links
3111 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3112 ;; [[shell:ls *.org]], which defeats Org's focus on
3113 ;; simplicity.
3114 (setq raw-link (org-link-expand-abbrev
3115 (replace-regexp-in-string
3116 "[ \t]*\n[ \t]*" " "
3117 (match-string-no-properties 1))))
3118 ;; Determine TYPE of link and set PATH accordingly. According
3119 ;; to RFC 3986, remove whitespaces from URI in external links.
3120 ;; In internal ones, treat indentation as a single space.
3121 (cond
3122 ;; File type.
3123 ((or (file-name-absolute-p raw-link)
3124 (string-match "\\`\\.\\.?/" raw-link))
3125 (setq type "file")
3126 (setq path raw-link))
3127 ;; Explicit type (http, irc, bbdb...).
3128 ((string-match org-link-types-re raw-link)
3129 (setq type (match-string 1 raw-link))
3130 (setq path (substring raw-link (match-end 0))))
3131 ;; Code-ref type: PATH is the name of the reference.
3132 ((and (string-match-p "\\`(" raw-link)
3133 (string-match-p ")\\'" raw-link))
3134 (setq type "coderef")
3135 (setq path (substring raw-link 1 -1)))
3136 ;; Custom-id type: PATH is the name of the custom id.
3137 ((= (string-to-char raw-link) ?#)
3138 (setq type "custom-id")
3139 (setq path (substring raw-link 1)))
3140 ;; Fuzzy type: Internal link either matches a target, an
3141 ;; headline name or nothing. PATH is the target or
3142 ;; headline's name.
3144 (setq type "fuzzy")
3145 (setq path raw-link))))
3146 ;; Type 3: Plain link, e.g., https://orgmode.org
3147 ((looking-at org-plain-link-re)
3148 (setq format 'plain)
3149 (setq raw-link (match-string-no-properties 0))
3150 (setq type (match-string-no-properties 1))
3151 (setq link-end (match-end 0))
3152 (setq path (match-string-no-properties 2)))
3153 ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
3154 ;; bracket links, follow RFC 3986 and remove any extra
3155 ;; whitespace in URI.
3156 ((looking-at org-angle-link-re)
3157 (setq format 'angle)
3158 (setq type (match-string-no-properties 1))
3159 (setq link-end (match-end 0))
3160 (setq raw-link
3161 (buffer-substring-no-properties
3162 (match-beginning 1) (match-end 2)))
3163 (setq path (replace-regexp-in-string
3164 "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
3165 (t (throw 'no-object nil)))
3166 ;; In any case, deduce end point after trailing white space from
3167 ;; LINK-END variable.
3168 (save-excursion
3169 (setq post-blank
3170 (progn (goto-char link-end) (skip-chars-forward " \t")))
3171 (setq end (point)))
3172 ;; Special "file" type link processing. Extract opening
3173 ;; application and search option, if any. Also normalize URI.
3174 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3175 (setq application (match-string 1 type) type "file")
3176 (when (string-match "::\\(.*\\)\\'" path)
3177 (setq search-option (match-string 1 path))
3178 (setq path (replace-match "" nil nil path)))
3179 (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
3180 ;; Translate link, if `org-link-translation-function' is set.
3181 (let ((trans (and (functionp org-link-translation-function)
3182 (funcall org-link-translation-function type path))))
3183 (when trans
3184 (setq type (car trans))
3185 (setq path (cdr trans))))
3186 (list 'link
3187 (list :type type
3188 :path path
3189 :format format
3190 :raw-link (or raw-link path)
3191 :application application
3192 :search-option search-option
3193 :begin begin
3194 :end end
3195 :contents-begin contents-begin
3196 :contents-end contents-end
3197 :post-blank post-blank)))))
3199 (defun org-element-link-interpreter (link contents)
3200 "Interpret LINK object as Org syntax.
3201 CONTENTS is the contents of the object, or nil."
3202 (let ((type (org-element-property :type link))
3203 (path (org-element-property :path link)))
3204 (if (string= type "radio") path
3205 (let ((fmt (pcase (org-element-property :format link)
3206 ;; Links with contents and internal links have to
3207 ;; use bracket syntax. Ignore `:format' in these
3208 ;; cases. This is also the default syntax when the
3209 ;; property is not defined, e.g., when the object
3210 ;; was crafted by the user.
3211 ((guard contents)
3212 (format "[[%%s][%s]]"
3213 ;; Since this is going to be used as
3214 ;; a format string, escape percent signs
3215 ;; in description.
3216 (replace-regexp-in-string "%" "%%" contents)))
3217 ((or `bracket
3218 `nil
3219 (guard (member type '("coderef" "custom-id" "fuzzy"))))
3220 "[[%s]]")
3221 ;; Otherwise, just obey to `:format'.
3222 (`angle "<%s>")
3223 (`plain "%s")
3224 (f (error "Wrong `:format' value: %s" f)))))
3225 (format fmt
3226 (pcase type
3227 ("coderef" (format "(%s)" path))
3228 ("custom-id" (concat "#" path))
3229 ("file"
3230 (let ((app (org-element-property :application link))
3231 (opt (org-element-property :search-option link)))
3232 (concat type (and app (concat "+" app)) ":"
3233 path
3234 (and opt (concat "::" opt)))))
3235 ("fuzzy" path)
3236 (_ (concat type ":" path))))))))
3239 ;;;; Macro
3241 (defun org-element-macro-parser ()
3242 "Parse macro at point, if any.
3244 When at a macro, return a list whose car is `macro' and cdr
3245 a plist with `:key', `:args', `:begin', `:end', `:value' and
3246 `:post-blank' as keywords. Otherwise, return nil.
3248 Assume point is at the macro."
3249 (save-excursion
3250 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
3251 (let ((begin (point))
3252 (key (downcase (match-string-no-properties 1)))
3253 (value (match-string-no-properties 0))
3254 (post-blank (progn (goto-char (match-end 0))
3255 (skip-chars-forward " \t")))
3256 (end (point))
3257 (args (pcase (match-string-no-properties 3)
3258 (`nil nil)
3259 (a (org-macro-extract-arguments
3260 (replace-regexp-in-string
3261 "[ \t\r\n]+" " " (org-trim a)))))))
3262 (list 'macro
3263 (list :key key
3264 :value value
3265 :args args
3266 :begin begin
3267 :end end
3268 :post-blank post-blank))))))
3270 (defun org-element-macro-interpreter (macro _)
3271 "Interpret MACRO object as Org syntax."
3272 (format "{{{%s%s}}}"
3273 (org-element-property :key macro)
3274 (pcase (org-element-property :args macro)
3275 (`nil "")
3276 (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
3279 ;;;; Radio-target
3281 (defun org-element-radio-target-parser ()
3282 "Parse radio target at point, if any.
3284 When at a radio target, return a list whose car is `radio-target'
3285 and cdr a plist with `:begin', `:end', `:contents-begin',
3286 `:contents-end', `:value' and `:post-blank' as keywords.
3287 Otherwise, return nil.
3289 Assume point is at the radio target."
3290 (save-excursion
3291 (when (looking-at org-radio-target-regexp)
3292 (let ((begin (point))
3293 (contents-begin (match-beginning 1))
3294 (contents-end (match-end 1))
3295 (value (match-string-no-properties 1))
3296 (post-blank (progn (goto-char (match-end 0))
3297 (skip-chars-forward " \t")))
3298 (end (point)))
3299 (list 'radio-target
3300 (list :begin begin
3301 :end end
3302 :contents-begin contents-begin
3303 :contents-end contents-end
3304 :post-blank post-blank
3305 :value value))))))
3307 (defun org-element-radio-target-interpreter (_ contents)
3308 "Interpret target object as Org syntax.
3309 CONTENTS is the contents of the object."
3310 (concat "<<<" contents ">>>"))
3313 ;;;; Statistics Cookie
3315 (defun org-element-statistics-cookie-parser ()
3316 "Parse statistics cookie at point, if any.
3318 When at a statistics cookie, return a list whose car is
3319 `statistics-cookie', and cdr a plist with `:begin', `:end',
3320 `:value' and `:post-blank' keywords. Otherwise, return nil.
3322 Assume point is at the beginning of the statistics-cookie."
3323 (save-excursion
3324 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3325 (let* ((begin (point))
3326 (value (buffer-substring-no-properties
3327 (match-beginning 0) (match-end 0)))
3328 (post-blank (progn (goto-char (match-end 0))
3329 (skip-chars-forward " \t")))
3330 (end (point)))
3331 (list 'statistics-cookie
3332 (list :begin begin
3333 :end end
3334 :value value
3335 :post-blank post-blank))))))
3337 (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
3338 "Interpret STATISTICS-COOKIE object as Org syntax."
3339 (org-element-property :value statistics-cookie))
3342 ;;;; Strike-Through
3344 (defun org-element-strike-through-parser ()
3345 "Parse strike-through object at point, if any.
3347 When at a strike-through object, return a list whose car is
3348 `strike-through' and cdr is a plist with `:begin', `:end',
3349 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3350 Otherwise, return nil.
3352 Assume point is at the first plus sign marker."
3353 (save-excursion
3354 (unless (bolp) (backward-char 1))
3355 (when (looking-at org-emph-re)
3356 (let ((begin (match-beginning 2))
3357 (contents-begin (match-beginning 4))
3358 (contents-end (match-end 4))
3359 (post-blank (progn (goto-char (match-end 2))
3360 (skip-chars-forward " \t")))
3361 (end (point)))
3362 (list 'strike-through
3363 (list :begin begin
3364 :end end
3365 :contents-begin contents-begin
3366 :contents-end contents-end
3367 :post-blank post-blank))))))
3369 (defun org-element-strike-through-interpreter (_ contents)
3370 "Interpret strike-through object as Org syntax.
3371 CONTENTS is the contents of the object."
3372 (format "+%s+" contents))
3375 ;;;; Subscript
3377 (defun org-element-subscript-parser ()
3378 "Parse subscript at point, if any.
3380 When at a subscript object, return a list whose car is
3381 `subscript' and cdr a plist with `:begin', `:end',
3382 `:contents-begin', `:contents-end', `:use-brackets-p' and
3383 `:post-blank' as keywords. Otherwise, return nil.
3385 Assume point is at the underscore."
3386 (save-excursion
3387 (unless (bolp) (backward-char))
3388 (when (looking-at org-match-substring-regexp)
3389 (let ((bracketsp (match-beginning 4))
3390 (begin (match-beginning 2))
3391 (contents-begin (or (match-beginning 4)
3392 (match-beginning 3)))
3393 (contents-end (or (match-end 4) (match-end 3)))
3394 (post-blank (progn (goto-char (match-end 0))
3395 (skip-chars-forward " \t")))
3396 (end (point)))
3397 (list 'subscript
3398 (list :begin begin
3399 :end end
3400 :use-brackets-p bracketsp
3401 :contents-begin contents-begin
3402 :contents-end contents-end
3403 :post-blank post-blank))))))
3405 (defun org-element-subscript-interpreter (subscript contents)
3406 "Interpret SUBSCRIPT object as Org syntax.
3407 CONTENTS is the contents of the object."
3408 (format
3409 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3410 contents))
3413 ;;;; Superscript
3415 (defun org-element-superscript-parser ()
3416 "Parse superscript at point, if any.
3418 When at a superscript object, return a list whose car is
3419 `superscript' and cdr a plist with `:begin', `:end',
3420 `:contents-begin', `:contents-end', `:use-brackets-p' and
3421 `:post-blank' as keywords. Otherwise, return nil.
3423 Assume point is at the caret."
3424 (save-excursion
3425 (unless (bolp) (backward-char))
3426 (when (looking-at org-match-substring-regexp)
3427 (let ((bracketsp (match-beginning 4))
3428 (begin (match-beginning 2))
3429 (contents-begin (or (match-beginning 4)
3430 (match-beginning 3)))
3431 (contents-end (or (match-end 4) (match-end 3)))
3432 (post-blank (progn (goto-char (match-end 0))
3433 (skip-chars-forward " \t")))
3434 (end (point)))
3435 (list 'superscript
3436 (list :begin begin
3437 :end end
3438 :use-brackets-p bracketsp
3439 :contents-begin contents-begin
3440 :contents-end contents-end
3441 :post-blank post-blank))))))
3443 (defun org-element-superscript-interpreter (superscript contents)
3444 "Interpret SUPERSCRIPT object as Org syntax.
3445 CONTENTS is the contents of the object."
3446 (format
3447 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3448 contents))
3451 ;;;; Table Cell
3453 (defun org-element-table-cell-parser ()
3454 "Parse table cell at point.
3455 Return a list whose car is `table-cell' and cdr is a plist
3456 containing `:begin', `:end', `:contents-begin', `:contents-end'
3457 and `:post-blank' keywords."
3458 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3459 (let* ((begin (match-beginning 0))
3460 (end (match-end 0))
3461 (contents-begin (match-beginning 1))
3462 (contents-end (match-end 1)))
3463 (list 'table-cell
3464 (list :begin begin
3465 :end end
3466 :contents-begin contents-begin
3467 :contents-end contents-end
3468 :post-blank 0))))
3470 (defun org-element-table-cell-interpreter (_ contents)
3471 "Interpret table-cell element as Org syntax.
3472 CONTENTS is the contents of the cell, or nil."
3473 (concat " " contents " |"))
3476 ;;;; Target
3478 (defun org-element-target-parser ()
3479 "Parse target at point, if any.
3481 When at a target, return a list whose car is `target' and cdr
3482 a plist with `:begin', `:end', `:value' and `:post-blank' as
3483 keywords. Otherwise, return nil.
3485 Assume point is at the target."
3486 (save-excursion
3487 (when (looking-at org-target-regexp)
3488 (let ((begin (point))
3489 (value (match-string-no-properties 1))
3490 (post-blank (progn (goto-char (match-end 0))
3491 (skip-chars-forward " \t")))
3492 (end (point)))
3493 (list 'target
3494 (list :begin begin
3495 :end end
3496 :value value
3497 :post-blank post-blank))))))
3499 (defun org-element-target-interpreter (target _)
3500 "Interpret TARGET object as Org syntax."
3501 (format "<<%s>>" (org-element-property :value target)))
3504 ;;;; Timestamp
3506 (defconst org-element--timestamp-regexp
3507 (concat org-ts-regexp-both
3508 "\\|"
3509 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3510 "\\|"
3511 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3512 "Regexp matching any timestamp type object.")
3514 (defun org-element-timestamp-parser ()
3515 "Parse time stamp at point, if any.
3517 When at a time stamp, return a list whose car is `timestamp', and
3518 cdr a plist with `:type', `:raw-value', `:year-start',
3519 `:month-start', `:day-start', `:hour-start', `:minute-start',
3520 `:year-end', `:month-end', `:day-end', `:hour-end',
3521 `:minute-end', `:repeater-type', `:repeater-value',
3522 `:repeater-unit', `:warning-type', `:warning-value',
3523 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3524 Otherwise, return nil.
3526 Assume point is at the beginning of the timestamp."
3527 (when (looking-at-p org-element--timestamp-regexp)
3528 (save-excursion
3529 (let* ((begin (point))
3530 (activep (eq (char-after) ?<))
3531 (raw-value
3532 (progn
3533 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3534 (match-string-no-properties 0)))
3535 (date-start (match-string-no-properties 1))
3536 (date-end (match-string 3))
3537 (diaryp (match-beginning 2))
3538 (post-blank (progn (goto-char (match-end 0))
3539 (skip-chars-forward " \t")))
3540 (end (point))
3541 (time-range
3542 (and (not diaryp)
3543 (string-match
3544 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3545 date-start)
3546 (cons (string-to-number (match-string 2 date-start))
3547 (string-to-number (match-string 3 date-start)))))
3548 (type (cond (diaryp 'diary)
3549 ((and activep (or date-end time-range)) 'active-range)
3550 (activep 'active)
3551 ((or date-end time-range) 'inactive-range)
3552 (t 'inactive)))
3553 (repeater-props
3554 (and (not diaryp)
3555 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3556 raw-value)
3557 (list
3558 :repeater-type
3559 (let ((type (match-string 1 raw-value)))
3560 (cond ((equal "++" type) 'catch-up)
3561 ((equal ".+" type) 'restart)
3562 (t 'cumulate)))
3563 :repeater-value (string-to-number (match-string 2 raw-value))
3564 :repeater-unit
3565 (pcase (string-to-char (match-string 3 raw-value))
3566 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3567 (warning-props
3568 (and (not diaryp)
3569 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3570 (list
3571 :warning-type (if (match-string 1 raw-value) 'first 'all)
3572 :warning-value (string-to-number (match-string 2 raw-value))
3573 :warning-unit
3574 (pcase (string-to-char (match-string 3 raw-value))
3575 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3576 year-start month-start day-start hour-start minute-start year-end
3577 month-end day-end hour-end minute-end)
3578 ;; Parse date-start.
3579 (unless diaryp
3580 (let ((date (org-parse-time-string date-start t)))
3581 (setq year-start (nth 5 date)
3582 month-start (nth 4 date)
3583 day-start (nth 3 date)
3584 hour-start (nth 2 date)
3585 minute-start (nth 1 date))))
3586 ;; Compute date-end. It can be provided directly in time-stamp,
3587 ;; or extracted from time range. Otherwise, it defaults to the
3588 ;; same values as date-start.
3589 (unless diaryp
3590 (let ((date (and date-end (org-parse-time-string date-end t))))
3591 (setq year-end (or (nth 5 date) year-start)
3592 month-end (or (nth 4 date) month-start)
3593 day-end (or (nth 3 date) day-start)
3594 hour-end (or (nth 2 date) (car time-range) hour-start)
3595 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3596 (list 'timestamp
3597 (nconc (list :type type
3598 :raw-value raw-value
3599 :year-start year-start
3600 :month-start month-start
3601 :day-start day-start
3602 :hour-start hour-start
3603 :minute-start minute-start
3604 :year-end year-end
3605 :month-end month-end
3606 :day-end day-end
3607 :hour-end hour-end
3608 :minute-end minute-end
3609 :begin begin
3610 :end end
3611 :post-blank post-blank)
3612 repeater-props
3613 warning-props))))))
3615 (defun org-element-timestamp-interpreter (timestamp _)
3616 "Interpret TIMESTAMP object as Org syntax."
3617 (let* ((repeat-string
3618 (concat
3619 (pcase (org-element-property :repeater-type timestamp)
3620 (`cumulate "+") (`catch-up "++") (`restart ".+"))
3621 (let ((val (org-element-property :repeater-value timestamp)))
3622 (and val (number-to-string val)))
3623 (pcase (org-element-property :repeater-unit timestamp)
3624 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3625 (warning-string
3626 (concat
3627 (pcase (org-element-property :warning-type timestamp)
3628 (`first "--") (`all "-"))
3629 (let ((val (org-element-property :warning-value timestamp)))
3630 (and val (number-to-string val)))
3631 (pcase (org-element-property :warning-unit timestamp)
3632 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3633 (build-ts-string
3634 ;; Build an Org timestamp string from TIME. ACTIVEP is
3635 ;; non-nil when time stamp is active. If WITH-TIME-P is
3636 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3637 ;; specify a time range in the timestamp. REPEAT-STRING is
3638 ;; the repeater string, if any.
3639 (lambda (time activep &optional with-time-p hour-end minute-end)
3640 (let ((ts (format-time-string
3641 (funcall (if with-time-p #'cdr #'car)
3642 org-time-stamp-formats)
3643 time)))
3644 (when (and hour-end minute-end)
3645 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3646 (setq ts
3647 (replace-match
3648 (format "\\&-%02d:%02d" hour-end minute-end)
3649 nil nil ts)))
3650 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3651 (dolist (s (list repeat-string warning-string))
3652 (when (org-string-nw-p s)
3653 (setq ts (concat (substring ts 0 -1)
3656 (substring ts -1)))))
3657 ;; Return value.
3658 ts)))
3659 (type (org-element-property :type timestamp)))
3660 (pcase type
3661 ((or `active `inactive)
3662 (let* ((minute-start (org-element-property :minute-start timestamp))
3663 (minute-end (org-element-property :minute-end timestamp))
3664 (hour-start (org-element-property :hour-start timestamp))
3665 (hour-end (org-element-property :hour-end timestamp))
3666 (time-range-p (and hour-start hour-end minute-start minute-end
3667 (or (/= hour-start hour-end)
3668 (/= minute-start minute-end)))))
3669 (funcall
3670 build-ts-string
3671 (encode-time 0
3672 (or minute-start 0)
3673 (or hour-start 0)
3674 (org-element-property :day-start timestamp)
3675 (org-element-property :month-start timestamp)
3676 (org-element-property :year-start timestamp))
3677 (eq type 'active)
3678 (and hour-start minute-start)
3679 (and time-range-p hour-end)
3680 (and time-range-p minute-end))))
3681 ((or `active-range `inactive-range)
3682 (let ((minute-start (org-element-property :minute-start timestamp))
3683 (minute-end (org-element-property :minute-end timestamp))
3684 (hour-start (org-element-property :hour-start timestamp))
3685 (hour-end (org-element-property :hour-end timestamp)))
3686 (concat
3687 (funcall
3688 build-ts-string (encode-time
3690 (or minute-start 0)
3691 (or hour-start 0)
3692 (org-element-property :day-start timestamp)
3693 (org-element-property :month-start timestamp)
3694 (org-element-property :year-start timestamp))
3695 (eq type 'active-range)
3696 (and hour-start minute-start))
3697 "--"
3698 (funcall build-ts-string
3699 (encode-time 0
3700 (or minute-end 0)
3701 (or hour-end 0)
3702 (org-element-property :day-end timestamp)
3703 (org-element-property :month-end timestamp)
3704 (org-element-property :year-end timestamp))
3705 (eq type 'active-range)
3706 (and hour-end minute-end)))))
3707 (_ (org-element-property :raw-value timestamp)))))
3710 ;;;; Underline
3712 (defun org-element-underline-parser ()
3713 "Parse underline object at point, if any.
3715 When at an underline object, return a list whose car is
3716 `underline' and cdr is a plist with `:begin', `:end',
3717 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3718 Otherwise, return nil.
3720 Assume point is at the first underscore marker."
3721 (save-excursion
3722 (unless (bolp) (backward-char 1))
3723 (when (looking-at org-emph-re)
3724 (let ((begin (match-beginning 2))
3725 (contents-begin (match-beginning 4))
3726 (contents-end (match-end 4))
3727 (post-blank (progn (goto-char (match-end 2))
3728 (skip-chars-forward " \t")))
3729 (end (point)))
3730 (list 'underline
3731 (list :begin begin
3732 :end end
3733 :contents-begin contents-begin
3734 :contents-end contents-end
3735 :post-blank post-blank))))))
3737 (defun org-element-underline-interpreter (_ contents)
3738 "Interpret underline object as Org syntax.
3739 CONTENTS is the contents of the object."
3740 (format "_%s_" contents))
3743 ;;;; Verbatim
3745 (defun org-element-verbatim-parser ()
3746 "Parse verbatim object at point, if any.
3748 When at a verbatim object, return a list whose car is `verbatim'
3749 and cdr is a plist with `:value', `:begin', `:end' and
3750 `:post-blank' keywords. Otherwise, return nil.
3752 Assume point is at the first equal sign marker."
3753 (save-excursion
3754 (unless (bolp) (backward-char 1))
3755 (when (looking-at org-verbatim-re)
3756 (let ((begin (match-beginning 2))
3757 (value (match-string-no-properties 4))
3758 (post-blank (progn (goto-char (match-end 2))
3759 (skip-chars-forward " \t")))
3760 (end (point)))
3761 (list 'verbatim
3762 (list :value value
3763 :begin begin
3764 :end end
3765 :post-blank post-blank))))))
3767 (defun org-element-verbatim-interpreter (verbatim _)
3768 "Interpret VERBATIM object as Org syntax."
3769 (format "=%s=" (org-element-property :value verbatim)))
3773 ;;; Parsing Element Starting At Point
3775 ;; `org-element--current-element' is the core function of this section.
3776 ;; It returns the Lisp representation of the element starting at
3777 ;; point.
3779 ;; `org-element--current-element' makes use of special modes. They
3780 ;; are activated for fixed element chaining (e.g., `plain-list' >
3781 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3782 ;; `section'). Special modes are: `first-section', `item',
3783 ;; `node-property', `section' and `table-row'.
3785 (defun org-element--current-element (limit &optional granularity mode structure)
3786 "Parse the element starting at point.
3788 Return value is a list like (TYPE PROPS) where TYPE is the type
3789 of the element and PROPS a plist of properties associated to the
3790 element.
3792 Possible types are defined in `org-element-all-elements'.
3794 LIMIT bounds the search.
3796 Optional argument GRANULARITY determines the depth of the
3797 recursion. Allowed values are `headline', `greater-element',
3798 `element', `object' or nil. When it is broader than `object' (or
3799 nil), secondary values will not be parsed, since they only
3800 contain objects.
3802 Optional argument MODE, when non-nil, can be either
3803 `first-section', `section', `planning', `item', `node-property'
3804 and `table-row'.
3806 If STRUCTURE isn't provided but MODE is set to `item', it will be
3807 computed.
3809 This function assumes point is always at the beginning of the
3810 element it has to parse."
3811 (save-excursion
3812 (let ((case-fold-search t)
3813 ;; Determine if parsing depth allows for secondary strings
3814 ;; parsing. It only applies to elements referenced in
3815 ;; `org-element-secondary-value-alist'.
3816 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3817 (cond
3818 ;; Item.
3819 ((eq mode 'item)
3820 (org-element-item-parser limit structure raw-secondary-p))
3821 ;; Table Row.
3822 ((eq mode 'table-row) (org-element-table-row-parser limit))
3823 ;; Node Property.
3824 ((eq mode 'node-property) (org-element-node-property-parser limit))
3825 ;; Headline.
3826 ((org-with-limited-levels (org-at-heading-p))
3827 (org-element-headline-parser limit raw-secondary-p))
3828 ;; Sections (must be checked after headline).
3829 ((eq mode 'section) (org-element-section-parser limit))
3830 ((eq mode 'first-section)
3831 (org-element-section-parser
3832 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3833 limit)))
3834 ;; Planning.
3835 ((and (eq mode 'planning)
3836 (eq ?* (char-after (line-beginning-position 0)))
3837 (looking-at org-planning-line-re))
3838 (org-element-planning-parser limit))
3839 ;; Property drawer.
3840 ((and (memq mode '(planning property-drawer))
3841 (eq ?* (char-after (line-beginning-position
3842 (if (eq mode 'planning) 0 -1))))
3843 (looking-at org-property-drawer-re))
3844 (org-element-property-drawer-parser limit))
3845 ;; When not at bol, point is at the beginning of an item or
3846 ;; a footnote definition: next item is always a paragraph.
3847 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3848 ;; Clock.
3849 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3850 ;; Inlinetask.
3851 ((org-at-heading-p)
3852 (org-element-inlinetask-parser limit raw-secondary-p))
3853 ;; From there, elements can have affiliated keywords.
3854 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3855 (cond
3856 ;; Jumping over affiliated keywords put point off-limits.
3857 ;; Parse them as regular keywords.
3858 ((and (cdr affiliated) (>= (point) limit))
3859 (goto-char (car affiliated))
3860 (org-element-keyword-parser limit nil))
3861 ;; LaTeX Environment.
3862 ((looking-at org-element--latex-begin-environment)
3863 (org-element-latex-environment-parser limit affiliated))
3864 ;; Drawer and Property Drawer.
3865 ((looking-at org-drawer-regexp)
3866 (org-element-drawer-parser limit affiliated))
3867 ;; Fixed Width
3868 ((looking-at "[ \t]*:\\( \\|$\\)")
3869 (org-element-fixed-width-parser limit affiliated))
3870 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3871 ;; Keywords.
3872 ((looking-at "[ \t]*#")
3873 (goto-char (match-end 0))
3874 (cond
3875 ((looking-at "\\(?: \\|$\\)")
3876 (beginning-of-line)
3877 (org-element-comment-parser limit affiliated))
3878 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3879 (beginning-of-line)
3880 (funcall (pcase (upcase (match-string 1))
3881 ("CENTER" #'org-element-center-block-parser)
3882 ("COMMENT" #'org-element-comment-block-parser)
3883 ("EXAMPLE" #'org-element-example-block-parser)
3884 ("EXPORT" #'org-element-export-block-parser)
3885 ("QUOTE" #'org-element-quote-block-parser)
3886 ("SRC" #'org-element-src-block-parser)
3887 ("VERSE" #'org-element-verse-block-parser)
3888 (_ #'org-element-special-block-parser))
3889 limit
3890 affiliated))
3891 ((looking-at "\\+CALL:")
3892 (beginning-of-line)
3893 (org-element-babel-call-parser limit affiliated))
3894 ((looking-at "\\+BEGIN:? ")
3895 (beginning-of-line)
3896 (org-element-dynamic-block-parser limit affiliated))
3897 ((looking-at "\\+\\S-+:")
3898 (beginning-of-line)
3899 (org-element-keyword-parser limit affiliated))
3901 (beginning-of-line)
3902 (org-element-paragraph-parser limit affiliated))))
3903 ;; Footnote Definition.
3904 ((looking-at org-footnote-definition-re)
3905 (org-element-footnote-definition-parser limit affiliated))
3906 ;; Horizontal Rule.
3907 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3908 (org-element-horizontal-rule-parser limit affiliated))
3909 ;; Diary Sexp.
3910 ((looking-at "%%(")
3911 (org-element-diary-sexp-parser limit affiliated))
3912 ;; Table.
3913 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3914 (org-element-table-parser limit affiliated))
3915 ;; List.
3916 ((looking-at (org-item-re))
3917 (org-element-plain-list-parser
3918 limit affiliated
3919 (or structure (org-element--list-struct limit))))
3920 ;; Default element: Paragraph.
3921 (t (org-element-paragraph-parser limit affiliated)))))))))
3924 ;; Most elements can have affiliated keywords. When looking for an
3925 ;; element beginning, we want to move before them, as they belong to
3926 ;; that element, and, in the meantime, collect information they give
3927 ;; into appropriate properties. Hence the following function.
3929 (defun org-element--collect-affiliated-keywords (limit)
3930 "Collect affiliated keywords from point down to LIMIT.
3932 Return a list whose CAR is the position at the first of them and
3933 CDR a plist of keywords and values and move point to the
3934 beginning of the first line after them.
3936 As a special case, if element doesn't start at the beginning of
3937 the line (e.g., a paragraph starting an item), CAR is current
3938 position of point and CDR is nil."
3939 (if (not (bolp)) (list (point))
3940 (let ((case-fold-search t)
3941 (origin (point))
3942 ;; RESTRICT is the list of objects allowed in parsed
3943 ;; keywords value.
3944 (restrict (org-element-restriction 'keyword))
3945 output)
3946 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3947 (let* ((raw-kwd (upcase (match-string 1)))
3948 ;; Apply translation to RAW-KWD. From there, KWD is
3949 ;; the official keyword.
3950 (kwd (or (cdr (assoc raw-kwd
3951 org-element-keyword-translation-alist))
3952 raw-kwd))
3953 ;; Find main value for any keyword.
3954 (value
3955 (save-match-data
3956 (org-trim
3957 (buffer-substring-no-properties
3958 (match-end 0) (line-end-position)))))
3959 ;; PARSEDP is non-nil when keyword should have its
3960 ;; value parsed.
3961 (parsedp (member kwd org-element-parsed-keywords))
3962 ;; If KWD is a dual keyword, find its secondary
3963 ;; value. Maybe parse it.
3964 (dualp (member kwd org-element-dual-keywords))
3965 (dual-value
3966 (and dualp
3967 (let ((sec (match-string-no-properties 2)))
3968 (if (or (not sec) (not parsedp)) sec
3969 (save-match-data
3970 (org-element--parse-objects
3971 (match-beginning 2) (match-end 2) nil restrict))))))
3972 ;; Attribute a property name to KWD.
3973 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3974 ;; Now set final shape for VALUE.
3975 (when parsedp
3976 (setq value
3977 (org-element--parse-objects
3978 (match-end 0)
3979 (progn (end-of-line) (skip-chars-backward " \t") (point))
3980 nil restrict)))
3981 (when dualp
3982 (setq value (and (or value dual-value) (cons value dual-value))))
3983 (when (or (member kwd org-element-multiple-keywords)
3984 ;; Attributes can always appear on multiple lines.
3985 (string-match "^ATTR_" kwd))
3986 (setq value (cons value (plist-get output kwd-sym))))
3987 ;; Eventually store the new value in OUTPUT.
3988 (setq output (plist-put output kwd-sym value))
3989 ;; Move to next keyword.
3990 (forward-line)))
3991 ;; If affiliated keywords are orphaned: move back to first one.
3992 ;; They will be parsed as a paragraph.
3993 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3994 ;; Return value.
3995 (cons origin output))))
3999 ;;; The Org Parser
4001 ;; The two major functions here are `org-element-parse-buffer', which
4002 ;; parses Org syntax inside the current buffer, taking into account
4003 ;; region, narrowing, or even visibility if specified, and
4004 ;; `org-element-parse-secondary-string', which parses objects within
4005 ;; a given string.
4007 ;; The (almost) almighty `org-element-map' allows applying a function
4008 ;; on elements or objects matching some type, and accumulating the
4009 ;; resulting values. In an export situation, it also skips unneeded
4010 ;; parts of the parse tree.
4012 (defun org-element-parse-buffer (&optional granularity visible-only)
4013 "Recursively parse the buffer and return structure.
4014 If narrowing is in effect, only parse the visible part of the
4015 buffer.
4017 Optional argument GRANULARITY determines the depth of the
4018 recursion. It can be set to the following symbols:
4020 `headline' Only parse headlines.
4021 `greater-element' Don't recurse into greater elements except
4022 headlines and sections. Thus, elements
4023 parsed are the top-level ones.
4024 `element' Parse everything but objects and plain text.
4025 `object' Parse the complete buffer (default).
4027 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4028 elements.
4030 An element or object is represented as a list with the
4031 pattern (TYPE PROPERTIES CONTENTS), where :
4033 TYPE is a symbol describing the element or object. See
4034 `org-element-all-elements' and `org-element-all-objects' for an
4035 exhaustive list of such symbols. One can retrieve it with
4036 `org-element-type' function.
4038 PROPERTIES is the list of attributes attached to the element or
4039 object, as a plist. Although most of them are specific to the
4040 element or object type, all types share `:begin', `:end',
4041 `:post-blank' and `:parent' properties, which respectively
4042 refer to buffer position where the element or object starts,
4043 ends, the number of white spaces or blank lines after it, and
4044 the element or object containing it. Properties values can be
4045 obtained by using `org-element-property' function.
4047 CONTENTS is a list of elements, objects or raw strings
4048 contained in the current element or object, when applicable.
4049 One can access them with `org-element-contents' function.
4051 The Org buffer has `org-data' as type and nil as properties.
4052 `org-element-map' function can be used to find specific elements
4053 or objects within the parse tree.
4055 This function assumes that current major mode is `org-mode'."
4056 (save-excursion
4057 (goto-char (point-min))
4058 (org-skip-whitespace)
4059 (org-element--parse-elements
4060 (point-at-bol) (point-max)
4061 ;; Start in `first-section' mode so text before the first
4062 ;; headline belongs to a section.
4063 'first-section nil granularity visible-only (list 'org-data nil))))
4065 (defun org-element-parse-secondary-string (string restriction &optional parent)
4066 "Recursively parse objects in STRING and return structure.
4068 RESTRICTION is a symbol limiting the object types that will be
4069 looked after.
4071 Optional argument PARENT, when non-nil, is the element or object
4072 containing the secondary string. It is used to set correctly
4073 `:parent' property within the string.
4075 If STRING is the empty string or nil, return nil."
4076 (cond
4077 ((not string) nil)
4078 ((equal string "") nil)
4079 (t (let ((local-variables (buffer-local-variables)))
4080 (with-temp-buffer
4081 (dolist (v local-variables)
4082 (ignore-errors
4083 (if (symbolp v) (makunbound v)
4084 (set (make-local-variable (car v)) (cdr v)))))
4085 (insert string)
4086 (restore-buffer-modified-p nil)
4087 (org-element--parse-objects
4088 (point-min) (point-max) nil restriction parent))))))
4090 (defun org-element-map
4091 (data types fun &optional info first-match no-recursion with-affiliated)
4092 "Map a function on selected elements or objects.
4094 DATA is a parse tree, an element, an object, a string, or a list
4095 of such constructs. TYPES is a symbol or list of symbols of
4096 elements or objects types (see `org-element-all-elements' and
4097 `org-element-all-objects' for a complete list of types). FUN is
4098 the function called on the matching element or object. It has to
4099 accept one argument: the element or object itself.
4101 When optional argument INFO is non-nil, it should be a plist
4102 holding export options. In that case, parts of the parse tree
4103 not exportable according to that property list will be skipped.
4105 When optional argument FIRST-MATCH is non-nil, stop at the first
4106 match for which FUN doesn't return nil, and return that value.
4108 Optional argument NO-RECURSION is a symbol or a list of symbols
4109 representing elements or objects types. `org-element-map' won't
4110 enter any recursive element or object whose type belongs to that
4111 list. Though, FUN can still be applied on them.
4113 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4114 apply to matching objects within parsed affiliated keywords (see
4115 `org-element-parsed-keywords').
4117 Nil values returned from FUN do not appear in the results.
4120 Examples:
4121 ---------
4123 Assuming TREE is a variable containing an Org buffer parse tree,
4124 the following example will return a flat list of all `src-block'
4125 and `example-block' elements in it:
4127 (org-element-map tree \\='(example-block src-block) #\\='identity)
4129 The following snippet will find the first headline with a level
4130 of 1 and a \"phone\" tag, and will return its beginning position:
4132 (org-element-map tree \\='headline
4133 (lambda (hl)
4134 (and (= (org-element-property :level hl) 1)
4135 (member \"phone\" (org-element-property :tags hl))
4136 (org-element-property :begin hl)))
4137 nil t)
4139 The next example will return a flat list of all `plain-list' type
4140 elements in TREE that are not a sub-list themselves:
4142 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4144 Eventually, this example will return a flat list of all `bold'
4145 type objects containing a `latex-snippet' type object, even
4146 looking into captions:
4148 (org-element-map tree \\='bold
4149 (lambda (b)
4150 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4151 nil nil nil t)"
4152 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4153 (let* ((types (if (listp types) types (list types)))
4154 (no-recursion (if (listp no-recursion) no-recursion
4155 (list no-recursion)))
4156 ;; Recursion depth is determined by --CATEGORY.
4157 (--category
4158 (catch :--found
4159 (let ((category 'greater-elements)
4160 (all-objects (cons 'plain-text org-element-all-objects)))
4161 (dolist (type types category)
4162 (cond ((memq type all-objects)
4163 ;; If one object is found, the function has
4164 ;; to recurse into every object.
4165 (throw :--found 'objects))
4166 ((not (memq type org-element-greater-elements))
4167 ;; If one regular element is found, the
4168 ;; function has to recurse, at least, into
4169 ;; every element it encounters.
4170 (and (not (eq category 'elements))
4171 (setq category 'elements))))))))
4172 --acc)
4173 (letrec ((--walk-tree
4174 (lambda (--data)
4175 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4176 ;; holding contextual information.
4177 (let ((--type (org-element-type --data)))
4178 (cond
4179 ((not --data))
4180 ;; Ignored element in an export context.
4181 ((and info (memq --data (plist-get info :ignore-list))))
4182 ;; List of elements or objects.
4183 ((not --type) (mapc --walk-tree --data))
4184 ;; Unconditionally enter parse trees.
4185 ((eq --type 'org-data)
4186 (mapc --walk-tree (org-element-contents --data)))
4188 ;; Check if TYPE is matching among TYPES. If so,
4189 ;; apply FUN to --DATA and accumulate return value
4190 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4191 (when (memq --type types)
4192 (let ((result (funcall fun --data)))
4193 (cond ((not result))
4194 (first-match (throw :--map-first-match result))
4195 (t (push result --acc)))))
4196 ;; If --DATA has a secondary string that can contain
4197 ;; objects with their type among TYPES, look inside.
4198 (when (and (eq --category 'objects) (not (stringp --data)))
4199 (dolist (p (cdr (assq --type
4200 org-element-secondary-value-alist)))
4201 (funcall --walk-tree (org-element-property p --data))))
4202 ;; If --DATA has any parsed affiliated keywords and
4203 ;; WITH-AFFILIATED is non-nil, look for objects in
4204 ;; them.
4205 (when (and with-affiliated
4206 (eq --category 'objects)
4207 (eq (org-element-class --data) 'element))
4208 (dolist (kwd-pair org-element--parsed-properties-alist)
4209 (let ((kwd (car kwd-pair))
4210 (value (org-element-property (cdr kwd-pair) --data)))
4211 ;; Pay attention to the type of parsed
4212 ;; keyword. In particular, preserve order for
4213 ;; multiple keywords.
4214 (cond
4215 ((not value))
4216 ((member kwd org-element-dual-keywords)
4217 (if (member kwd org-element-multiple-keywords)
4218 (dolist (line (reverse value))
4219 (funcall --walk-tree (cdr line))
4220 (funcall --walk-tree (car line)))
4221 (funcall --walk-tree (cdr value))
4222 (funcall --walk-tree (car value))))
4223 ((member kwd org-element-multiple-keywords)
4224 (mapc --walk-tree (reverse value)))
4225 (t (funcall --walk-tree value))))))
4226 ;; Determine if a recursion into --DATA is possible.
4227 (cond
4228 ;; --TYPE is explicitly removed from recursion.
4229 ((memq --type no-recursion))
4230 ;; --DATA has no contents.
4231 ((not (org-element-contents --data)))
4232 ;; Looking for greater elements but --DATA is
4233 ;; simply an element or an object.
4234 ((and (eq --category 'greater-elements)
4235 (not (memq --type org-element-greater-elements))))
4236 ;; Looking for elements but --DATA is an object.
4237 ((and (eq --category 'elements)
4238 (eq (org-element-class --data) 'object)))
4239 ;; In any other case, map contents.
4240 (t (mapc --walk-tree (org-element-contents --data))))))))))
4241 (catch :--map-first-match
4242 (funcall --walk-tree data)
4243 ;; Return value in a proper order.
4244 (nreverse --acc)))))
4245 (put 'org-element-map 'lisp-indent-function 2)
4247 ;; The following functions are internal parts of the parser.
4249 ;; The first one, `org-element--parse-elements' acts at the element's
4250 ;; level.
4252 ;; The second one, `org-element--parse-objects' applies on all objects
4253 ;; of a paragraph or a secondary string. It calls
4254 ;; `org-element--object-lex' to find the next object in the current
4255 ;; container.
4257 (defsubst org-element--next-mode (type parentp)
4258 "Return next special mode according to TYPE, or nil.
4259 TYPE is a symbol representing the type of an element or object
4260 containing next element if PARENTP is non-nil, or before it
4261 otherwise. Modes can be either `first-section', `item',
4262 `node-property', `planning', `property-drawer', `section',
4263 `table-row' or nil."
4264 (if parentp
4265 (pcase type
4266 (`headline 'section)
4267 (`inlinetask 'planning)
4268 (`plain-list 'item)
4269 (`property-drawer 'node-property)
4270 (`section 'planning)
4271 (`table 'table-row))
4272 (pcase type
4273 (`item 'item)
4274 (`node-property 'node-property)
4275 (`planning 'property-drawer)
4276 (`table-row 'table-row))))
4278 (defun org-element--parse-elements
4279 (beg end mode structure granularity visible-only acc)
4280 "Parse elements between BEG and END positions.
4282 MODE prioritizes some elements over the others. It can be set to
4283 `first-section', `section', `planning', `item', `node-property'
4284 or `table-row'.
4286 When value is `item', STRUCTURE will be used as the current list
4287 structure.
4289 GRANULARITY determines the depth of the recursion. See
4290 `org-element-parse-buffer' for more information.
4292 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4293 elements.
4295 Elements are accumulated into ACC."
4296 (save-excursion
4297 (goto-char beg)
4298 ;; Visible only: skip invisible parts at the beginning of the
4299 ;; element.
4300 (when (and visible-only (org-invisible-p2))
4301 (goto-char (min (1+ (org-find-visible)) end)))
4302 ;; When parsing only headlines, skip any text before first one.
4303 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4304 (org-with-limited-levels (outline-next-heading)))
4305 (let (elements)
4306 (while (< (point) end)
4307 ;; Find current element's type and parse it accordingly to
4308 ;; its category.
4309 (let* ((element (org-element--current-element
4310 end granularity mode structure))
4311 (type (org-element-type element))
4312 (cbeg (org-element-property :contents-begin element)))
4313 (goto-char (org-element-property :end element))
4314 ;; Visible only: skip invisible parts between siblings.
4315 (when (and visible-only (org-invisible-p2))
4316 (goto-char (min (1+ (org-find-visible)) end)))
4317 ;; Fill ELEMENT contents by side-effect.
4318 (cond
4319 ;; If element has no contents, don't modify it.
4320 ((not cbeg))
4321 ;; Greater element: parse it between `contents-begin' and
4322 ;; `contents-end'. Make sure GRANULARITY allows the
4323 ;; recursion, or ELEMENT is a headline, in which case going
4324 ;; inside is mandatory, in order to get sub-level headings.
4325 ((and (memq type org-element-greater-elements)
4326 (or (memq granularity '(element object nil))
4327 (and (eq granularity 'greater-element)
4328 (eq type 'section))
4329 (eq type 'headline)))
4330 (org-element--parse-elements
4331 cbeg (org-element-property :contents-end element)
4332 ;; Possibly switch to a special mode.
4333 (org-element--next-mode type t)
4334 (and (memq type '(item plain-list))
4335 (org-element-property :structure element))
4336 granularity visible-only element))
4337 ;; ELEMENT has contents. Parse objects inside, if
4338 ;; GRANULARITY allows it.
4339 ((memq granularity '(object nil))
4340 (org-element--parse-objects
4341 cbeg (org-element-property :contents-end element) element
4342 (org-element-restriction type))))
4343 (push (org-element-put-property element :parent acc) elements)
4344 ;; Update mode.
4345 (setq mode (org-element--next-mode type nil))))
4346 ;; Return result.
4347 (apply #'org-element-set-contents acc (nreverse elements)))))
4349 (defun org-element--object-lex (restriction)
4350 "Return next object in current buffer or nil.
4351 RESTRICTION is a list of object types, as symbols, that should be
4352 looked after. This function assumes that the buffer is narrowed
4353 to an appropriate container (e.g., a paragraph)."
4354 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4355 (let* ((start (point))
4356 (limit
4357 ;; Object regexp sometimes needs to have a peek at
4358 ;; a character ahead. Therefore, when there is a hard
4359 ;; limit, make it one more than the true beginning of the
4360 ;; radio target.
4361 (save-excursion
4362 (cond ((not org-target-link-regexp) nil)
4363 ((not (memq 'link restriction)) nil)
4364 ((progn
4365 (unless (bolp) (forward-char -1))
4366 (not (re-search-forward org-target-link-regexp nil t)))
4367 nil)
4368 ;; Since we moved backward, we do not want to
4369 ;; match again an hypothetical 1-character long
4370 ;; radio link before us. Realizing that this can
4371 ;; only happen if such a radio link starts at
4372 ;; beginning of line, we prevent this here.
4373 ((and (= start (1+ (line-beginning-position)))
4374 (= start (match-end 1)))
4375 (and (re-search-forward org-target-link-regexp nil t)
4376 (1+ (match-beginning 1))))
4377 (t (1+ (match-beginning 1))))))
4378 found)
4379 (save-excursion
4380 (while (and (not found)
4381 (re-search-forward org-element--object-regexp limit 'move))
4382 (goto-char (match-beginning 0))
4383 (let ((result (match-string 0)))
4384 (setq found
4385 (cond
4386 ((string-prefix-p "call_" result t)
4387 (and (memq 'inline-babel-call restriction)
4388 (org-element-inline-babel-call-parser)))
4389 ((string-prefix-p "src_" result t)
4390 (and (memq 'inline-src-block restriction)
4391 (org-element-inline-src-block-parser)))
4393 (pcase (char-after)
4394 (?^ (and (memq 'superscript restriction)
4395 (org-element-superscript-parser)))
4396 (?_ (or (and (memq 'subscript restriction)
4397 (org-element-subscript-parser))
4398 (and (memq 'underline restriction)
4399 (org-element-underline-parser))))
4400 (?* (and (memq 'bold restriction)
4401 (org-element-bold-parser)))
4402 (?/ (and (memq 'italic restriction)
4403 (org-element-italic-parser)))
4404 (?~ (and (memq 'code restriction)
4405 (org-element-code-parser)))
4406 (?= (and (memq 'verbatim restriction)
4407 (org-element-verbatim-parser)))
4408 (?+ (and (memq 'strike-through restriction)
4409 (org-element-strike-through-parser)))
4410 (?@ (and (memq 'export-snippet restriction)
4411 (org-element-export-snippet-parser)))
4412 (?{ (and (memq 'macro restriction)
4413 (org-element-macro-parser)))
4414 (?$ (and (memq 'latex-fragment restriction)
4415 (org-element-latex-fragment-parser)))
4417 (if (eq (aref result 1) ?<)
4418 (or (and (memq 'radio-target restriction)
4419 (org-element-radio-target-parser))
4420 (and (memq 'target restriction)
4421 (org-element-target-parser)))
4422 (or (and (memq 'timestamp restriction)
4423 (org-element-timestamp-parser))
4424 (and (memq 'link restriction)
4425 (org-element-link-parser)))))
4426 (?\\
4427 (if (eq (aref result 1) ?\\)
4428 (and (memq 'line-break restriction)
4429 (org-element-line-break-parser))
4430 (or (and (memq 'entity restriction)
4431 (org-element-entity-parser))
4432 (and (memq 'latex-fragment restriction)
4433 (org-element-latex-fragment-parser)))))
4434 (?\[
4435 (if (eq (aref result 1) ?\[)
4436 (and (memq 'link restriction)
4437 (org-element-link-parser))
4438 (or (and (memq 'footnote-reference restriction)
4439 (org-element-footnote-reference-parser))
4440 (and (memq 'timestamp restriction)
4441 (org-element-timestamp-parser))
4442 (and (memq 'statistics-cookie restriction)
4443 (org-element-statistics-cookie-parser)))))
4444 ;; This is probably a plain link.
4445 (_ (and (memq 'link restriction)
4446 (org-element-link-parser)))))))
4447 (or (eobp) (forward-char))))
4448 (cond (found)
4449 (limit (forward-char -1)
4450 (org-element-link-parser)) ;radio link
4451 (t nil))))))
4453 (defun org-element--parse-objects (beg end acc restriction &optional parent)
4454 "Parse objects between BEG and END and return recursive structure.
4456 Objects are accumulated in ACC. RESTRICTION is a list of object
4457 successors which are allowed in the current object.
4459 ACC becomes the parent for all parsed objects. However, if ACC
4460 is nil (i.e., a secondary string is being parsed) and optional
4461 argument PARENT is non-nil, use it as the parent for all objects.
4462 Eventually, if both ACC and PARENT are nil, the common parent is
4463 the list of objects itself."
4464 (save-excursion
4465 (save-restriction
4466 (narrow-to-region beg end)
4467 (goto-char (point-min))
4468 (let (next-object contents)
4469 (while (and (not (eobp))
4470 (setq next-object (org-element--object-lex restriction)))
4471 ;; Text before any object.
4472 (let ((obj-beg (org-element-property :begin next-object)))
4473 (unless (= (point) obj-beg)
4474 (let ((text (buffer-substring-no-properties (point) obj-beg)))
4475 (push (if acc (org-element-put-property text :parent acc) text)
4476 contents))))
4477 ;; Object...
4478 (let ((obj-end (org-element-property :end next-object))
4479 (cont-beg (org-element-property :contents-begin next-object)))
4480 (when acc (org-element-put-property next-object :parent acc))
4481 (push (if cont-beg
4482 ;; Fill contents of NEXT-OBJECT if possible.
4483 (org-element--parse-objects
4484 cont-beg
4485 (org-element-property :contents-end next-object)
4486 next-object
4487 (org-element-restriction next-object))
4488 next-object)
4489 contents)
4490 (goto-char obj-end)))
4491 ;; Text after last object.
4492 (unless (eobp)
4493 (let ((text (buffer-substring-no-properties (point) end)))
4494 (push (if acc (org-element-put-property text :parent acc) text)
4495 contents)))
4496 ;; Result. Set appropriate parent.
4497 (if acc (apply #'org-element-set-contents acc (nreverse contents))
4498 (let* ((contents (nreverse contents))
4499 (parent (or parent contents)))
4500 (dolist (datum contents contents)
4501 (org-element-put-property datum :parent parent))))))))
4505 ;;; Towards A Bijective Process
4507 ;; The parse tree obtained with `org-element-parse-buffer' is really
4508 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4509 ;; interpreted and expanded into a string with canonical Org syntax.
4510 ;; Hence `org-element-interpret-data'.
4512 ;; The function relies internally on
4513 ;; `org-element--interpret-affiliated-keywords'.
4515 ;;;###autoload
4516 (defun org-element-interpret-data (data)
4517 "Interpret DATA as Org syntax.
4518 DATA is a parse tree, an element, an object or a secondary string
4519 to interpret. Return Org syntax as a string."
4520 (letrec ((fun
4521 (lambda (data parent)
4522 (let* ((type (org-element-type data))
4523 ;; Find interpreter for current object or
4524 ;; element. If it doesn't exist (e.g. this is
4525 ;; a pseudo object or element), return contents,
4526 ;; if any.
4527 (interpret
4528 (let ((fun (intern
4529 (format "org-element-%s-interpreter" type))))
4530 (if (fboundp fun) fun (lambda (_ contents) contents))))
4531 (results
4532 (cond
4533 ;; Secondary string.
4534 ((not type)
4535 (mapconcat (lambda (obj) (funcall fun obj parent))
4536 data
4537 ""))
4538 ;; Full Org document.
4539 ((eq type 'org-data)
4540 (mapconcat (lambda (obj) (funcall fun obj parent))
4541 (org-element-contents data)
4542 ""))
4543 ;; Plain text: return it.
4544 ((stringp data) data)
4545 ;; Element or object without contents.
4546 ((not (org-element-contents data))
4547 (funcall interpret data nil))
4548 ;; Element or object with contents.
4550 (funcall
4551 interpret
4552 data
4553 ;; Recursively interpret contents.
4554 (mapconcat
4555 (lambda (datum) (funcall fun datum data))
4556 (org-element-contents
4557 (if (not (memq type '(paragraph verse-block)))
4558 data
4559 ;; Fix indentation of elements containing
4560 ;; objects. We ignore `table-row'
4561 ;; elements as they are one line long
4562 ;; anyway.
4563 (org-element-normalize-contents
4564 data
4565 ;; When normalizing first paragraph of
4566 ;; an item or a footnote-definition,
4567 ;; ignore first line's indentation.
4568 (and (eq type 'paragraph)
4569 (memq (org-element-type parent)
4570 '(footnote-definition item))
4571 (eq data (car (org-element-contents parent)))
4572 (eq (org-element-property :pre-blank parent)
4573 0)))))
4574 ""))))))
4575 (if (memq type '(org-data plain-text nil)) results
4576 ;; Build white spaces. If no `:post-blank' property
4577 ;; is specified, assume its value is 0.
4578 (let ((blank (or (org-element-property :post-blank data) 0)))
4579 (if (eq (org-element-class data parent) 'object)
4580 (concat results (make-string blank ?\s))
4581 (concat (org-element--interpret-affiliated-keywords data)
4582 (org-element-normalize-string results)
4583 (make-string blank ?\n)))))))))
4584 (funcall fun data nil)))
4586 (defun org-element--interpret-affiliated-keywords (element)
4587 "Return ELEMENT's affiliated keywords as Org syntax.
4588 If there is no affiliated keyword, return the empty string."
4589 (let ((keyword-to-org
4590 (function
4591 (lambda (key value)
4592 (let (dual)
4593 (when (member key org-element-dual-keywords)
4594 (setq dual (cdr value) value (car value)))
4595 (concat "#+" (downcase key)
4596 (and dual
4597 (format "[%s]" (org-element-interpret-data dual)))
4598 ": "
4599 (if (member key org-element-parsed-keywords)
4600 (org-element-interpret-data value)
4601 value)
4602 "\n"))))))
4603 (mapconcat
4604 (lambda (prop)
4605 (let ((value (org-element-property prop element))
4606 (keyword (upcase (substring (symbol-name prop) 1))))
4607 (when value
4608 (if (or (member keyword org-element-multiple-keywords)
4609 ;; All attribute keywords can have multiple lines.
4610 (string-match "^ATTR_" keyword))
4611 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4612 (reverse value)
4614 (funcall keyword-to-org keyword value)))))
4615 ;; List all ELEMENT's properties matching an attribute line or an
4616 ;; affiliated keyword, but ignore translated keywords since they
4617 ;; cannot belong to the property list.
4618 (cl-loop for prop in (nth 1 element) by 'cddr
4619 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4620 (or (string-match "^ATTR_" keyword)
4621 (and
4622 (member keyword org-element-affiliated-keywords)
4623 (not (assoc keyword
4624 org-element-keyword-translation-alist)))))
4625 collect prop)
4626 "")))
4628 ;; Because interpretation of the parse tree must return the same
4629 ;; number of blank lines between elements and the same number of white
4630 ;; space after objects, some special care must be given to white
4631 ;; spaces.
4633 ;; The first function, `org-element-normalize-string', ensures any
4634 ;; string different from the empty string will end with a single
4635 ;; newline character.
4637 ;; The second function, `org-element-normalize-contents', removes
4638 ;; global indentation from the contents of the current element.
4640 (defun org-element-normalize-string (s)
4641 "Ensure string S ends with a single newline character.
4643 If S isn't a string return it unchanged. If S is the empty
4644 string, return it. Otherwise, return a new string with a single
4645 newline character at its end."
4646 (cond
4647 ((not (stringp s)) s)
4648 ((string= "" s) "")
4649 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4650 (replace-match "\n" nil nil s)))))
4652 (defun org-element-normalize-contents (element &optional ignore-first)
4653 "Normalize plain text in ELEMENT's contents.
4655 ELEMENT must only contain plain text and objects.
4657 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4658 indentation to compute maximal common indentation.
4660 Return the normalized element that is element with global
4661 indentation removed from its contents."
4662 (letrec ((find-min-ind
4663 ;; Return minimal common indentation within BLOB. This is
4664 ;; done by walking recursively BLOB and updating MIN-IND
4665 ;; along the way. FIRST-FLAG is non-nil when the next
4666 ;; object is expected to be a string that doesn't start
4667 ;; with a newline character. It happens for strings at
4668 ;; the beginnings of the contents or right after a line
4669 ;; break.
4670 (lambda (blob first-flag min-ind)
4671 (dolist (datum (org-element-contents blob) min-ind)
4672 (when first-flag
4673 (setq first-flag nil)
4674 (cond
4675 ;; Objects cannot start with spaces: in this
4676 ;; case, indentation is 0.
4677 ((not (stringp datum)) (throw :zero 0))
4678 ((not (string-match
4679 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
4680 (throw :zero 0))
4681 ((equal (match-string 2 datum) "\n")
4682 (put-text-property
4683 (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
4685 (let ((i (string-width (match-string 1 datum))))
4686 (put-text-property
4687 (match-beginning 1) (match-end 1) 'org-ind i datum)
4688 (setq min-ind (min i min-ind))))))
4689 (cond
4690 ((stringp datum)
4691 (let ((s 0))
4692 (while (string-match
4693 "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
4694 (setq s (match-end 1))
4695 (cond
4696 ((equal (match-string 1 datum) "")
4697 (unless (member (match-string 2 datum) '("" "\n"))
4698 (throw :zero 0)))
4699 ((equal (match-string 2 datum) "\n")
4700 (put-text-property (match-beginning 1) (match-end 1)
4701 'org-ind 'empty datum))
4703 (let ((i (string-width (match-string 1 datum))))
4704 (put-text-property (match-beginning 1) (match-end 1)
4705 'org-ind i datum)
4706 (setq min-ind (min i min-ind))))))))
4707 ((eq (org-element-type datum) 'line-break)
4708 (setq first-flag t))
4709 ((memq (org-element-type datum) org-element-recursive-objects)
4710 (setq min-ind
4711 (funcall find-min-ind datum first-flag min-ind)))))))
4712 (min-ind
4713 (catch :zero
4714 (funcall find-min-ind
4715 element (not ignore-first) most-positive-fixnum))))
4716 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4717 ;; Build ELEMENT back, replacing each string with the same
4718 ;; string minus common indentation.
4719 (letrec ((build
4720 (lambda (datum)
4721 ;; Return DATUM with all its strings indentation
4722 ;; shortened from MIN-IND white spaces.
4723 (setcdr
4724 (cdr datum)
4725 (mapcar
4726 (lambda (object)
4727 (cond
4728 ((stringp object)
4729 (with-temp-buffer
4730 (insert object)
4731 (let ((s (point-min)))
4732 (while (setq s (text-property-not-all
4733 s (point-max) 'org-ind nil))
4734 (goto-char s)
4735 (let ((i (get-text-property s 'org-ind)))
4736 (delete-region s (progn
4737 (skip-chars-forward " \t")
4738 (point)))
4739 (when (integerp i) (indent-to (- i min-ind))))))
4740 (buffer-string)))
4741 ((memq (org-element-type object)
4742 org-element-recursive-objects)
4743 (funcall build object))
4744 (t object)))
4745 (org-element-contents datum)))
4746 datum)))
4747 (funcall build element)))))
4751 ;;; Cache
4753 ;; Implement a caching mechanism for `org-element-at-point' and
4754 ;; `org-element-context', which see.
4756 ;; A single public function is provided: `org-element-cache-reset'.
4758 ;; Cache is enabled by default, but can be disabled globally with
4759 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4760 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4761 ;; can be tweaked to control caching behaviour.
4763 ;; Internally, parsed elements are stored in an AVL tree,
4764 ;; `org-element--cache'. This tree is updated lazily: whenever
4765 ;; a change happens to the buffer, a synchronization request is
4766 ;; registered in `org-element--cache-sync-requests' (see
4767 ;; `org-element--cache-submit-request'). During idle time, requests
4768 ;; are processed by `org-element--cache-sync'. Synchronization also
4769 ;; happens when an element is required from the cache. In this case,
4770 ;; the process stops as soon as the needed element is up-to-date.
4772 ;; A synchronization request can only apply on a synchronized part of
4773 ;; the cache. Therefore, the cache is updated at least to the
4774 ;; location where the new request applies. Thus, requests are ordered
4775 ;; from left to right and all elements starting before the first
4776 ;; request are correct. This property is used by functions like
4777 ;; `org-element--cache-find' to retrieve elements in the part of the
4778 ;; cache that can be trusted.
4780 ;; A request applies to every element, starting from its original
4781 ;; location (or key, see below). When a request is processed, it
4782 ;; moves forward and may collide the next one. In this case, both
4783 ;; requests are merged into a new one that starts from that element.
4784 ;; As a consequence, the whole synchronization complexity does not
4785 ;; depend on the number of pending requests, but on the number of
4786 ;; elements the very first request will be applied on.
4788 ;; Elements cannot be accessed through their beginning position, which
4789 ;; may or may not be up-to-date. Instead, each element in the tree is
4790 ;; associated to a key, obtained with `org-element--cache-key'. This
4791 ;; mechanism is robust enough to preserve total order among elements
4792 ;; even when the tree is only partially synchronized.
4795 (defvar org-element-use-cache nil
4796 "Non-nil when Org parser should cache its results.
4798 WARNING: for the time being, using cache sometimes triggers
4799 freezes. Therefore, it is disabled by default. Activate it if
4800 you want to help debugging the issue.")
4802 (defvar org-element-cache-sync-idle-time 0.6
4803 "Length, in seconds, of idle time before syncing cache.")
4805 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4806 "Maximum duration, as a time value, for a cache synchronization.
4807 If the synchronization is not over after this delay, the process
4808 pauses and resumes after `org-element-cache-sync-break'
4809 seconds.")
4811 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4812 "Duration, as a time value, of the pause between synchronizations.
4813 See `org-element-cache-sync-duration' for more information.")
4816 ;;;; Data Structure
4818 (defvar org-element--cache nil
4819 "AVL tree used to cache elements.
4820 Each node of the tree contains an element. Comparison is done
4821 with `org-element--cache-compare'. This cache is used in
4822 `org-element-at-point'.")
4824 (defvar org-element--cache-sync-requests nil
4825 "List of pending synchronization requests.
4827 A request is a vector with the following pattern:
4829 \[NEXT BEG END OFFSET PARENT PHASE]
4831 Processing a synchronization request consists of three phases:
4833 0. Delete modified elements,
4834 1. Fill missing area in cache,
4835 2. Shift positions and re-parent elements after the changes.
4837 During phase 0, NEXT is the key of the first element to be
4838 removed, BEG and END is buffer position delimiting the
4839 modifications. Elements starting between them (inclusive) are
4840 removed. So are elements whose parent is removed. PARENT, when
4841 non-nil, is the parent of the first element to be removed.
4843 During phase 1, NEXT is the key of the next known element in
4844 cache and BEG its beginning position. Parse buffer between that
4845 element and the one before it in order to determine the parent of
4846 the next element. Set PARENT to the element containing NEXT.
4848 During phase 2, NEXT is the key of the next element to shift in
4849 the parse tree. All elements starting from this one have their
4850 properties relatives to buffer positions shifted by integer
4851 OFFSET and, if they belong to element PARENT, are adopted by it.
4853 PHASE specifies the phase number, as an integer.")
4855 (defvar org-element--cache-sync-timer nil
4856 "Timer used for cache synchronization.")
4858 (defvar org-element--cache-sync-keys nil
4859 "Hash table used to store keys during synchronization.
4860 See `org-element--cache-key' for more information.")
4862 (defsubst org-element--cache-key (element)
4863 "Return a unique key for ELEMENT in cache tree.
4865 Keys are used to keep a total order among elements in the cache.
4866 Comparison is done with `org-element--cache-key-less-p'.
4868 When no synchronization is taking place, a key is simply the
4869 beginning position of the element, or that position plus one in
4870 the case of an first item (respectively row) in
4871 a list (respectively a table).
4873 During a synchronization, the key is the one the element had when
4874 the cache was synchronized for the last time. Elements added to
4875 cache during the synchronization get a new key generated with
4876 `org-element--cache-generate-key'.
4878 Such keys are stored in `org-element--cache-sync-keys'. The hash
4879 table is cleared once the synchronization is complete."
4880 (or (gethash element org-element--cache-sync-keys)
4881 (let* ((begin (org-element-property :begin element))
4882 ;; Increase beginning position of items (respectively
4883 ;; table rows) by one, so the first item can get
4884 ;; a different key from its parent list (respectively
4885 ;; table).
4886 (key (if (memq (org-element-type element) '(item table-row))
4887 (1+ begin)
4888 begin)))
4889 (if org-element--cache-sync-requests
4890 (puthash element key org-element--cache-sync-keys)
4891 key))))
4893 (defun org-element--cache-generate-key (lower upper)
4894 "Generate a key between LOWER and UPPER.
4896 LOWER and UPPER are integers or lists, possibly empty.
4898 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4899 a unique key, as an integer or a list of integers, according to
4900 the following rules:
4902 - LOWER and UPPER are compared level-wise until values differ.
4904 - If, at a given level, LOWER and UPPER differ from more than
4905 2, the new key shares all the levels above with LOWER and
4906 gets a new level. Its value is the mean between LOWER and
4907 UPPER:
4909 (1 2) + (1 4) --> (1 3)
4911 - If LOWER has no value to compare with, it is assumed that its
4912 value is `most-negative-fixnum'. E.g.,
4914 (1 1) + (1 1 2)
4916 is equivalent to
4918 (1 1 m) + (1 1 2)
4920 where m is `most-negative-fixnum'. Likewise, if UPPER is
4921 short of levels, the current value is `most-positive-fixnum'.
4923 - If they differ from only one, the new key inherits from
4924 current LOWER level and fork it at the next level. E.g.,
4926 (2 1) + (3 3)
4928 is equivalent to
4930 (2 1) + (2 M)
4932 where M is `most-positive-fixnum'.
4934 - If the key is only one level long, it is returned as an
4935 integer:
4937 (1 2) + (3 2) --> 2
4939 When they are not equals, the function assumes that LOWER is
4940 lesser than UPPER, per `org-element--cache-key-less-p'."
4941 (if (equal lower upper) lower
4942 (let ((lower (if (integerp lower) (list lower) lower))
4943 (upper (if (integerp upper) (list upper) upper))
4944 skip-upper key)
4945 (catch 'exit
4946 (while t
4947 (let ((min (or (car lower) most-negative-fixnum))
4948 (max (cond (skip-upper most-positive-fixnum)
4949 ((car upper))
4950 (t most-positive-fixnum))))
4951 (if (< (1+ min) max)
4952 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4953 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4954 (when (and (< min max) (not skip-upper))
4955 ;; When at a given level, LOWER and UPPER differ from
4956 ;; 1, ignore UPPER altogether. Instead create a key
4957 ;; between LOWER and the greatest key with the same
4958 ;; prefix as LOWER so far.
4959 (setq skip-upper t))
4960 (push min key)
4961 (setq lower (cdr lower) upper (cdr upper)))))))))
4963 (defsubst org-element--cache-key-less-p (a b)
4964 "Non-nil if key A is less than key B.
4965 A and B are either integers or lists of integers, as returned by
4966 `org-element--cache-key'."
4967 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4968 (if (integerp b) (< (car a) b)
4969 (catch 'exit
4970 (while (and a b)
4971 (cond ((car-less-than-car a b) (throw 'exit t))
4972 ((car-less-than-car b a) (throw 'exit nil))
4973 (t (setq a (cdr a) b (cdr b)))))
4974 ;; If A is empty, either keys are equal (B is also empty) and
4975 ;; we return nil, or A is lesser than B (B is longer) and we
4976 ;; return a non-nil value.
4978 ;; If A is not empty, B is necessarily empty and A is greater
4979 ;; than B (A is longer). Therefore, return nil.
4980 (and (null a) b)))))
4982 (defun org-element--cache-compare (a b)
4983 "Non-nil when element A is located before element B."
4984 (org-element--cache-key-less-p (org-element--cache-key a)
4985 (org-element--cache-key b)))
4987 (defsubst org-element--cache-root ()
4988 "Return root value in cache.
4989 This function assumes `org-element--cache' is a valid AVL tree."
4990 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4993 ;;;; Tools
4995 (defsubst org-element--cache-active-p ()
4996 "Non-nil when cache is active in current buffer."
4997 (and org-element-use-cache
4998 org-element--cache
4999 (derived-mode-p 'org-mode)))
5001 (defun org-element--cache-find (pos &optional side)
5002 "Find element in cache starting at POS or before.
5004 POS refers to a buffer position.
5006 When optional argument SIDE is non-nil, the function checks for
5007 elements starting at or past POS instead. If SIDE is `both', the
5008 function returns a cons cell where car is the first element
5009 starting at or before POS and cdr the first element starting
5010 after POS.
5012 The function can only find elements in the synchronized part of
5013 the cache."
5014 (let ((limit (and org-element--cache-sync-requests
5015 (aref (car org-element--cache-sync-requests) 0)))
5016 (node (org-element--cache-root))
5017 lower upper)
5018 (while node
5019 (let* ((element (avl-tree--node-data node))
5020 (begin (org-element-property :begin element)))
5021 (cond
5022 ((and limit
5023 (not (org-element--cache-key-less-p
5024 (org-element--cache-key element) limit)))
5025 (setq node (avl-tree--node-left node)))
5026 ((> begin pos)
5027 (setq upper element
5028 node (avl-tree--node-left node)))
5029 ((< begin pos)
5030 (setq lower element
5031 node (avl-tree--node-right node)))
5032 ;; We found an element in cache starting at POS. If `side'
5033 ;; is `both' we also want the next one in order to generate
5034 ;; a key in-between.
5036 ;; If the element is the first row or item in a table or
5037 ;; a plain list, we always return the table or the plain
5038 ;; list.
5040 ;; In any other case, we return the element found.
5041 ((eq side 'both)
5042 (setq lower element)
5043 (setq node (avl-tree--node-right node)))
5044 ((and (memq (org-element-type element) '(item table-row))
5045 (let ((parent (org-element-property :parent element)))
5046 (and (= (org-element-property :begin element)
5047 (org-element-property :contents-begin parent))
5048 (setq node nil
5049 lower parent
5050 upper parent)))))
5052 (setq node nil
5053 lower element
5054 upper element)))))
5055 (pcase side
5056 (`both (cons lower upper))
5057 (`nil lower)
5058 (_ upper))))
5060 (defun org-element--cache-put (element)
5061 "Store ELEMENT in current buffer's cache, if allowed."
5062 (when (org-element--cache-active-p)
5063 (when org-element--cache-sync-requests
5064 ;; During synchronization, first build an appropriate key for
5065 ;; the new element so `avl-tree-enter' can insert it at the
5066 ;; right spot in the cache.
5067 (let ((keys (org-element--cache-find
5068 (org-element-property :begin element) 'both)))
5069 (puthash element
5070 (org-element--cache-generate-key
5071 (and (car keys) (org-element--cache-key (car keys)))
5072 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5073 (org-element--cache-sync-requests
5074 (aref (car org-element--cache-sync-requests) 0))))
5075 org-element--cache-sync-keys)))
5076 (avl-tree-enter org-element--cache element)))
5078 (defsubst org-element--cache-remove (element)
5079 "Remove ELEMENT from cache.
5080 Assume ELEMENT belongs to cache and that a cache is active."
5081 (avl-tree-delete org-element--cache element))
5084 ;;;; Synchronization
5086 (defsubst org-element--cache-set-timer (buffer)
5087 "Set idle timer for cache synchronization in BUFFER."
5088 (when org-element--cache-sync-timer
5089 (cancel-timer org-element--cache-sync-timer))
5090 (setq org-element--cache-sync-timer
5091 (run-with-idle-timer
5092 (let ((idle (current-idle-time)))
5093 (if idle (time-add idle org-element-cache-sync-break)
5094 org-element-cache-sync-idle-time))
5096 #'org-element--cache-sync
5097 buffer)))
5099 (defsubst org-element--cache-interrupt-p (time-limit)
5100 "Non-nil when synchronization process should be interrupted.
5101 TIME-LIMIT is a time value or nil."
5102 (and time-limit
5103 (or (input-pending-p)
5104 (time-less-p time-limit (current-time)))))
5106 (defsubst org-element--cache-shift-positions (element offset &optional props)
5107 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5109 Properties containing buffer positions are `:begin', `:end',
5110 `:contents-begin', `:contents-end' and `:structure'. When
5111 optional argument PROPS is a list of keywords, only shift
5112 properties provided in that list.
5114 Properties are modified by side-effect."
5115 (let ((properties (nth 1 element)))
5116 ;; Shift `:structure' property for the first plain list only: it
5117 ;; is the only one that really matters and it prevents from
5118 ;; shifting it more than once.
5119 (when (and (or (not props) (memq :structure props))
5120 (eq (org-element-type element) 'plain-list)
5121 (not (eq (org-element-type (plist-get properties :parent))
5122 'item)))
5123 (dolist (item (plist-get properties :structure))
5124 (cl-incf (car item) offset)
5125 (cl-incf (nth 6 item) offset)))
5126 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5127 (let ((value (and (or (not props) (memq key props))
5128 (plist-get properties key))))
5129 (and value (plist-put properties key (+ offset value)))))))
5131 (defun org-element--cache-sync (buffer &optional threshold future-change)
5132 "Synchronize cache with recent modification in BUFFER.
5134 When optional argument THRESHOLD is non-nil, do the
5135 synchronization for all elements starting before or at threshold,
5136 then exit. Otherwise, synchronize cache for as long as
5137 `org-element-cache-sync-duration' or until Emacs leaves idle
5138 state.
5140 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5141 not registered yet in the cache are going to happen. It is used
5142 in `org-element--cache-submit-request', where cache is partially
5143 updated before current modification are actually submitted."
5144 (when (buffer-live-p buffer)
5145 (with-current-buffer buffer
5146 (let ((inhibit-quit t) request next)
5147 (when org-element--cache-sync-timer
5148 (cancel-timer org-element--cache-sync-timer))
5149 (catch 'interrupt
5150 (while org-element--cache-sync-requests
5151 (setq request (car org-element--cache-sync-requests)
5152 next (nth 1 org-element--cache-sync-requests))
5153 (org-element--cache-process-request
5154 request
5155 (and next (aref next 0))
5156 threshold
5157 (and (not threshold)
5158 (time-add (current-time)
5159 org-element-cache-sync-duration))
5160 future-change)
5161 ;; Request processed. Merge current and next offsets and
5162 ;; transfer ending position.
5163 (when next
5164 (cl-incf (aref next 3) (aref request 3))
5165 (aset next 2 (aref request 2)))
5166 (setq org-element--cache-sync-requests
5167 (cdr org-element--cache-sync-requests))))
5168 ;; If more requests are awaiting, set idle timer accordingly.
5169 ;; Otherwise, reset keys.
5170 (if org-element--cache-sync-requests
5171 (org-element--cache-set-timer buffer)
5172 (clrhash org-element--cache-sync-keys))))))
5174 (defun org-element--cache-process-request
5175 (request next threshold time-limit future-change)
5176 "Process synchronization REQUEST for all entries before NEXT.
5178 REQUEST is a vector, built by `org-element--cache-submit-request'.
5180 NEXT is a cache key, as returned by `org-element--cache-key'.
5182 When non-nil, THRESHOLD is a buffer position. Synchronization
5183 stops as soon as a shifted element begins after it.
5185 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5186 after this time or when Emacs exits idle state.
5188 When non-nil, FUTURE-CHANGE is a buffer position where changes
5189 not registered yet in the cache are going to happen. See
5190 `org-element--cache-submit-request' for more information.
5192 Throw `interrupt' if the process stops before completing the
5193 request."
5194 (catch 'quit
5195 (when (= (aref request 5) 0)
5196 ;; Phase 0.
5198 ;; Delete all elements starting after BEG, but not after buffer
5199 ;; position END or past element with key NEXT. Also delete
5200 ;; elements contained within a previously removed element
5201 ;; (stored in `last-container').
5203 ;; At each iteration, we start again at tree root since
5204 ;; a deletion modifies structure of the balanced tree.
5205 (catch 'end-phase
5206 (while t
5207 (when (org-element--cache-interrupt-p time-limit)
5208 (throw 'interrupt nil))
5209 ;; Find first element in cache with key BEG or after it.
5210 (let ((beg (aref request 0))
5211 (end (aref request 2))
5212 (node (org-element--cache-root))
5213 data data-key last-container)
5214 (while node
5215 (let* ((element (avl-tree--node-data node))
5216 (key (org-element--cache-key element)))
5217 (cond
5218 ((org-element--cache-key-less-p key beg)
5219 (setq node (avl-tree--node-right node)))
5220 ((org-element--cache-key-less-p beg key)
5221 (setq data element
5222 data-key key
5223 node (avl-tree--node-left node)))
5224 (t (setq data element
5225 data-key key
5226 node nil)))))
5227 (if data
5228 (let ((pos (org-element-property :begin data)))
5229 (if (if (or (not next)
5230 (org-element--cache-key-less-p data-key next))
5231 (<= pos end)
5232 (and last-container
5233 (let ((up data))
5234 (while (and up (not (eq up last-container)))
5235 (setq up (org-element-property :parent up)))
5236 up)))
5237 (progn (when (and (not last-container)
5238 (> (org-element-property :end data)
5239 end))
5240 (setq last-container data))
5241 (org-element--cache-remove data))
5242 (aset request 0 data-key)
5243 (aset request 1 pos)
5244 (aset request 5 1)
5245 (throw 'end-phase nil)))
5246 ;; No element starting after modifications left in
5247 ;; cache: further processing is futile.
5248 (throw 'quit t))))))
5249 (when (= (aref request 5) 1)
5250 ;; Phase 1.
5252 ;; Phase 0 left a hole in the cache. Some elements after it
5253 ;; could have parents within. For example, in the following
5254 ;; buffer:
5256 ;; - item
5259 ;; Paragraph1
5261 ;; Paragraph2
5263 ;; if we remove a blank line between "item" and "Paragraph1",
5264 ;; everything down to "Paragraph2" is removed from cache. But
5265 ;; the paragraph now belongs to the list, and its `:parent'
5266 ;; property no longer is accurate.
5268 ;; Therefore we need to parse again elements in the hole, or at
5269 ;; least in its last section, so that we can re-parent
5270 ;; subsequent elements, during phase 2.
5272 ;; Note that we only need to get the parent from the first
5273 ;; element in cache after the hole.
5275 ;; When next key is lesser or equal to the current one, delegate
5276 ;; phase 1 processing to next request in order to preserve key
5277 ;; order among requests.
5278 (let ((key (aref request 0)))
5279 (when (and next (not (org-element--cache-key-less-p key next)))
5280 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5281 (aset next-request 0 key)
5282 (aset next-request 1 (aref request 1))
5283 (aset next-request 5 1))
5284 (throw 'quit t)))
5285 ;; Next element will start at its beginning position plus
5286 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5287 ;; contains the real beginning position of the first element to
5288 ;; shift and re-parent.
5289 (let ((limit (+ (aref request 1) (aref request 3))))
5290 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5291 ((and future-change (>= limit future-change))
5292 ;; Changes are going to happen around this element and
5293 ;; they will trigger another phase 1 request. Skip the
5294 ;; current one.
5295 (aset request 5 2))
5297 (let ((parent (org-element--parse-to limit t time-limit)))
5298 (aset request 4 parent)
5299 (aset request 5 2))))))
5300 ;; Phase 2.
5302 ;; Shift all elements starting from key START, but before NEXT, by
5303 ;; OFFSET, and re-parent them when appropriate.
5305 ;; Elements are modified by side-effect so the tree structure
5306 ;; remains intact.
5308 ;; Once THRESHOLD, if any, is reached, or once there is an input
5309 ;; pending, exit. Before leaving, the current synchronization
5310 ;; request is updated.
5311 (let ((start (aref request 0))
5312 (offset (aref request 3))
5313 (parent (aref request 4))
5314 (node (org-element--cache-root))
5315 (stack (list nil))
5316 (leftp t)
5317 exit-flag)
5318 ;; No re-parenting nor shifting planned: request is over.
5319 (when (and (not parent) (zerop offset)) (throw 'quit t))
5320 (while node
5321 (let* ((data (avl-tree--node-data node))
5322 (key (org-element--cache-key data)))
5323 (if (and leftp (avl-tree--node-left node)
5324 (not (org-element--cache-key-less-p key start)))
5325 (progn (push node stack)
5326 (setq node (avl-tree--node-left node)))
5327 (unless (org-element--cache-key-less-p key start)
5328 ;; We reached NEXT. Request is complete.
5329 (when (equal key next) (throw 'quit t))
5330 ;; Handle interruption request. Update current request.
5331 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5332 (aset request 0 key)
5333 (aset request 4 parent)
5334 (throw 'interrupt nil))
5335 ;; Shift element.
5336 (unless (zerop offset)
5337 (org-element--cache-shift-positions data offset))
5338 (let ((begin (org-element-property :begin data)))
5339 ;; Update PARENT and re-parent DATA, only when
5340 ;; necessary. Propagate new structures for lists.
5341 (while (and parent
5342 (<= (org-element-property :end parent) begin))
5343 (setq parent (org-element-property :parent parent)))
5344 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5345 ((and parent
5346 (let ((p (org-element-property :parent data)))
5347 (or (not p)
5348 (< (org-element-property :begin p)
5349 (org-element-property :begin parent)))))
5350 (org-element-put-property data :parent parent)
5351 (let ((s (org-element-property :structure parent)))
5352 (when (and s (org-element-property :structure data))
5353 (org-element-put-property data :structure s)))))
5354 ;; Cache is up-to-date past THRESHOLD. Request
5355 ;; interruption.
5356 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5357 (setq node (if (setq leftp (avl-tree--node-right node))
5358 (avl-tree--node-right node)
5359 (pop stack))))))
5360 ;; We reached end of tree: synchronization complete.
5361 t)))
5363 (defun org-element--parse-to (pos &optional syncp time-limit)
5364 "Parse elements in current section, down to POS.
5366 Start parsing from the closest between the last known element in
5367 cache or headline above. Return the smallest element containing
5368 POS.
5370 When optional argument SYNCP is non-nil, return the parent of the
5371 element containing POS instead. In that case, it is also
5372 possible to provide TIME-LIMIT, which is a time value specifying
5373 when the parsing should stop. The function throws `interrupt' if
5374 the process stopped before finding the expected result."
5375 (catch 'exit
5376 (org-with-wide-buffer
5377 (goto-char pos)
5378 (let* ((cached (and (org-element--cache-active-p)
5379 (org-element--cache-find pos nil)))
5380 (begin (org-element-property :begin cached))
5381 element next mode)
5382 (cond
5383 ;; Nothing in cache before point: start parsing from first
5384 ;; element following headline above, or first element in
5385 ;; buffer.
5386 ((not cached)
5387 (when (org-with-limited-levels (outline-previous-heading))
5388 (setq mode 'planning)
5389 (forward-line))
5390 (skip-chars-forward " \r\t\n")
5391 (beginning-of-line))
5392 ;; Cache returned exact match: return it.
5393 ((= pos begin)
5394 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5395 ;; There's a headline between cached value and POS: cached
5396 ;; value is invalid. Start parsing from first element
5397 ;; following the headline.
5398 ((re-search-backward
5399 (org-with-limited-levels org-outline-regexp-bol) begin t)
5400 (forward-line)
5401 (skip-chars-forward " \r\t\n")
5402 (beginning-of-line)
5403 (setq mode 'planning))
5404 ;; Check if CACHED or any of its ancestors contain point.
5406 ;; If there is such an element, we inspect it in order to know
5407 ;; if we return it or if we need to parse its contents.
5408 ;; Otherwise, we just start parsing from current location,
5409 ;; which is right after the top-most element containing
5410 ;; CACHED.
5412 ;; As a special case, if POS is at the end of the buffer, we
5413 ;; want to return the innermost element ending there.
5415 ;; Also, if we find an ancestor and discover that we need to
5416 ;; parse its contents, make sure we don't start from
5417 ;; `:contents-begin', as we would otherwise go past CACHED
5418 ;; again. Instead, in that situation, we will resume parsing
5419 ;; from NEXT, which is located after CACHED or its higher
5420 ;; ancestor not containing point.
5422 (let ((up cached)
5423 (pos (if (= (point-max) pos) (1- pos) pos)))
5424 (goto-char (or (org-element-property :contents-begin cached) begin))
5425 (while (let ((end (org-element-property :end up)))
5426 (and (<= end pos)
5427 (goto-char end)
5428 (setq up (org-element-property :parent up)))))
5429 (cond ((not up))
5430 ((eobp) (setq element up))
5431 (t (setq element up next (point)))))))
5432 ;; Parse successively each element until we reach POS.
5433 (let ((end (or (org-element-property :end element)
5434 (save-excursion
5435 (org-with-limited-levels (outline-next-heading))
5436 (point))))
5437 (parent element))
5438 (while t
5439 (when syncp
5440 (cond ((= (point) pos) (throw 'exit parent))
5441 ((org-element--cache-interrupt-p time-limit)
5442 (throw 'interrupt nil))))
5443 (unless element
5444 (setq element (org-element--current-element
5445 end 'element mode
5446 (org-element-property :structure parent)))
5447 (org-element-put-property element :parent parent)
5448 (org-element--cache-put element))
5449 (let ((elem-end (org-element-property :end element))
5450 (type (org-element-type element)))
5451 (cond
5452 ;; Skip any element ending before point. Also skip
5453 ;; element ending at point (unless it is also the end of
5454 ;; buffer) since we're sure that another element begins
5455 ;; after it.
5456 ((and (<= elem-end pos) (/= (point-max) elem-end))
5457 (goto-char elem-end)
5458 (setq mode (org-element--next-mode type nil)))
5459 ;; A non-greater element contains point: return it.
5460 ((not (memq type org-element-greater-elements))
5461 (throw 'exit element))
5462 ;; Otherwise, we have to decide if ELEMENT really
5463 ;; contains POS. In that case we start parsing from
5464 ;; contents' beginning.
5466 ;; If POS is at contents' beginning but it is also at
5467 ;; the beginning of the first item in a list or a table.
5468 ;; In that case, we need to create an anchor for that
5469 ;; list or table, so return it.
5471 ;; Also, if POS is at the end of the buffer, no element
5472 ;; can start after it, but more than one may end there.
5473 ;; Arbitrarily, we choose to return the innermost of
5474 ;; such elements.
5475 ((let ((cbeg (org-element-property :contents-begin element))
5476 (cend (org-element-property :contents-end element)))
5477 (when (or syncp
5478 (and cbeg cend
5479 (or (< cbeg pos)
5480 (and (= cbeg pos)
5481 (not (memq type '(plain-list table)))))
5482 (or (> cend pos)
5483 (and (= cend pos) (= (point-max) pos)))))
5484 (goto-char (or next cbeg))
5485 (setq next nil
5486 mode (org-element--next-mode type t)
5487 parent element
5488 end cend))))
5489 ;; Otherwise, return ELEMENT as it is the smallest
5490 ;; element containing POS.
5491 (t (throw 'exit element))))
5492 (setq element nil)))))))
5495 ;;;; Staging Buffer Changes
5497 (defconst org-element--cache-sensitive-re
5498 (concat
5499 org-outline-regexp-bol "\\|"
5500 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5501 "^[ \t]*\\(?:"
5502 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5503 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5504 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5505 "\\)")
5506 "Regexp matching a sensitive line, structure wise.
5507 A sensitive line is a headline, inlinetask, block, drawer, or
5508 latex-environment boundary. When such a line is modified,
5509 structure changes in the document may propagate in the whole
5510 section, possibly making cache invalid.")
5512 (defvar org-element--cache-change-warning nil
5513 "Non-nil when a sensitive line is about to be changed.
5514 It is a symbol among nil, t and `headline'.")
5516 (defun org-element--cache-before-change (beg end)
5517 "Request extension of area going to be modified if needed.
5518 BEG and END are the beginning and end of the range of changed
5519 text. See `before-change-functions' for more information."
5520 (when (org-element--cache-active-p)
5521 (org-with-wide-buffer
5522 (goto-char beg)
5523 (beginning-of-line)
5524 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5525 (setq org-element--cache-change-warning
5526 (save-match-data
5527 (if (and (org-with-limited-levels (org-at-heading-p))
5528 (= (line-end-position) bottom))
5529 'headline
5530 (let ((case-fold-search t))
5531 (re-search-forward
5532 org-element--cache-sensitive-re bottom t)))))))))
5534 (defun org-element--cache-after-change (beg end pre)
5535 "Update buffer modifications for current buffer.
5536 BEG and END are the beginning and end of the range of changed
5537 text, and the length in bytes of the pre-change text replaced by
5538 that range. See `after-change-functions' for more information."
5539 (when (org-element--cache-active-p)
5540 (org-with-wide-buffer
5541 (goto-char beg)
5542 (beginning-of-line)
5543 (save-match-data
5544 (let ((top (point))
5545 (bottom (save-excursion (goto-char end) (line-end-position))))
5546 ;; Determine if modified area needs to be extended, according
5547 ;; to both previous and current state. We make a special
5548 ;; case for headline editing: if a headline is modified but
5549 ;; not removed, do not extend.
5550 (when (pcase org-element--cache-change-warning
5551 (`t t)
5552 (`headline
5553 (not (and (org-with-limited-levels (org-at-heading-p))
5554 (= (line-end-position) bottom))))
5556 (let ((case-fold-search t))
5557 (re-search-forward
5558 org-element--cache-sensitive-re bottom t))))
5559 ;; Effectively extend modified area.
5560 (org-with-limited-levels
5561 (setq top (progn (goto-char top)
5562 (when (outline-previous-heading) (forward-line))
5563 (point)))
5564 (setq bottom (progn (goto-char bottom)
5565 (if (outline-next-heading) (1- (point))
5566 (point))))))
5567 ;; Store synchronization request.
5568 (let ((offset (- end beg pre)))
5569 (org-element--cache-submit-request top (- bottom offset) offset)))))
5570 ;; Activate a timer to process the request during idle time.
5571 (org-element--cache-set-timer (current-buffer))))
5573 (defun org-element--cache-for-removal (beg end offset)
5574 "Return first element to remove from cache.
5576 BEG and END are buffer positions delimiting buffer modifications.
5577 OFFSET is the size of the changes.
5579 Returned element is usually the first element in cache containing
5580 any position between BEG and END. As an exception, greater
5581 elements around the changes that are robust to contents
5582 modifications are preserved and updated according to the
5583 changes."
5584 (let* ((elements (org-element--cache-find (1- beg) 'both))
5585 (before (car elements))
5586 (after (cdr elements)))
5587 (if (not before) after
5588 (let ((up before)
5589 (robust-flag t))
5590 (while up
5591 (if (let ((type (org-element-type up)))
5592 (and (or (memq type '(center-block dynamic-block quote-block
5593 special-block))
5594 ;; Drawers named "PROPERTIES" are probably
5595 ;; a properties drawer being edited. Force
5596 ;; parsing to check if editing is over.
5597 (and (eq type 'drawer)
5598 (not (string=
5599 (org-element-property :drawer-name up)
5600 "PROPERTIES"))))
5601 (let ((cbeg (org-element-property :contents-begin up)))
5602 (and cbeg
5603 (<= cbeg beg)
5604 (> (org-element-property :contents-end up) end)))))
5605 ;; UP is a robust greater element containing changes.
5606 ;; We only need to extend its ending boundaries.
5607 (org-element--cache-shift-positions
5608 up offset '(:contents-end :end))
5609 (setq before up)
5610 (when robust-flag (setq robust-flag nil)))
5611 (setq up (org-element-property :parent up)))
5612 ;; We're at top level element containing ELEMENT: if it's
5613 ;; altered by buffer modifications, it is first element in
5614 ;; cache to be removed. Otherwise, that first element is the
5615 ;; following one.
5617 ;; As a special case, do not remove BEFORE if it is a robust
5618 ;; container for current changes.
5619 (if (or (< (org-element-property :end before) beg) robust-flag) after
5620 before)))))
5622 (defun org-element--cache-submit-request (beg end offset)
5623 "Submit a new cache synchronization request for current buffer.
5624 BEG and END are buffer positions delimiting the minimal area
5625 where cache data should be removed. OFFSET is the size of the
5626 change, as an integer."
5627 (let ((next (car org-element--cache-sync-requests))
5628 delete-to delete-from)
5629 (if (and next
5630 (zerop (aref next 5))
5631 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5632 (<= (setq delete-from (aref next 1)) end))
5633 ;; Current changes can be merged with first sync request: we
5634 ;; can save a partial cache synchronization.
5635 (progn
5636 (cl-incf (aref next 3) offset)
5637 ;; If last change happened within area to be removed, extend
5638 ;; boundaries of robust parents, if any. Otherwise, find
5639 ;; first element to remove and update request accordingly.
5640 (if (> beg delete-from)
5641 (let ((up (aref next 4)))
5642 (while up
5643 (org-element--cache-shift-positions
5644 up offset '(:contents-end :end))
5645 (setq up (org-element-property :parent up))))
5646 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5647 (when first
5648 (aset next 0 (org-element--cache-key first))
5649 (aset next 1 (org-element-property :begin first))
5650 (aset next 4 (org-element-property :parent first))))))
5651 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5652 ;; if any, is no longer a 0-phase request, thus ensuring that
5653 ;; phases are properly ordered. We need to provide OFFSET as
5654 ;; optional parameter since current modifications are not known
5655 ;; yet to the otherwise correct part of the cache (i.e, before
5656 ;; the first request).
5657 (when next (org-element--cache-sync (current-buffer) end beg))
5658 (let ((first (org-element--cache-for-removal beg end offset)))
5659 (if first
5660 (push (let ((beg (org-element-property :begin first))
5661 (key (org-element--cache-key first)))
5662 (cond
5663 ;; When changes happen before the first known
5664 ;; element, re-parent and shift the rest of the
5665 ;; cache.
5666 ((> beg end) (vector key beg nil offset nil 1))
5667 ;; Otherwise, we find the first non robust
5668 ;; element containing END. All elements between
5669 ;; FIRST and this one are to be removed.
5670 ((let ((first-end (org-element-property :end first)))
5671 (and (> first-end end)
5672 (vector key beg first-end offset first 0))))
5674 (let* ((element (org-element--cache-find end))
5675 (end (org-element-property :end element))
5676 (up element))
5677 (while (and (setq up (org-element-property :parent up))
5678 (>= (org-element-property :begin up) beg))
5679 (setq end (org-element-property :end up)
5680 element up))
5681 (vector key beg end offset element 0)))))
5682 org-element--cache-sync-requests)
5683 ;; No element to remove. No need to re-parent either.
5684 ;; Simply shift additional elements, if any, by OFFSET.
5685 (when org-element--cache-sync-requests
5686 (cl-incf (aref (car org-element--cache-sync-requests) 3)
5687 offset)))))))
5690 ;;;; Public Functions
5692 ;;;###autoload
5693 (defun org-element-cache-reset (&optional all)
5694 "Reset cache in current buffer.
5695 When optional argument ALL is non-nil, reset cache in all Org
5696 buffers."
5697 (interactive "P")
5698 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5699 (with-current-buffer buffer
5700 (when (and org-element-use-cache (derived-mode-p 'org-mode))
5701 (setq-local org-element--cache
5702 (avl-tree-create #'org-element--cache-compare))
5703 (setq-local org-element--cache-sync-keys
5704 (make-hash-table :weakness 'key :test #'eq))
5705 (setq-local org-element--cache-change-warning nil)
5706 (setq-local org-element--cache-sync-requests nil)
5707 (setq-local org-element--cache-sync-timer nil)
5708 (add-hook 'before-change-functions
5709 #'org-element--cache-before-change nil t)
5710 (add-hook 'after-change-functions
5711 #'org-element--cache-after-change nil t)))))
5713 ;;;###autoload
5714 (defun org-element-cache-refresh (pos)
5715 "Refresh cache at position POS."
5716 (when (org-element--cache-active-p)
5717 (org-element--cache-sync (current-buffer) pos)
5718 (org-element--cache-submit-request pos pos 0)
5719 (org-element--cache-set-timer (current-buffer))))
5723 ;;; The Toolbox
5725 ;; The first move is to implement a way to obtain the smallest element
5726 ;; containing point. This is the job of `org-element-at-point'. It
5727 ;; basically jumps back to the beginning of section containing point
5728 ;; and proceed, one element after the other, with
5729 ;; `org-element--current-element' until the container is found. Note:
5730 ;; When using `org-element-at-point', secondary values are never
5731 ;; parsed since the function focuses on elements, not on objects.
5733 ;; At a deeper level, `org-element-context' lists all elements and
5734 ;; objects containing point.
5736 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5737 ;; internally by navigation and manipulation tools.
5740 ;;;###autoload
5741 (defun org-element-at-point ()
5742 "Determine closest element around point.
5744 Return value is a list like (TYPE PROPS) where TYPE is the type
5745 of the element and PROPS a plist of properties associated to the
5746 element.
5748 Possible types are defined in `org-element-all-elements'.
5749 Properties depend on element or object type, but always include
5750 `:begin', `:end', `:parent' and `:post-blank' properties.
5752 As a special case, if point is at the very beginning of the first
5753 item in a list or sub-list, returned element will be that list
5754 instead of the item. Likewise, if point is at the beginning of
5755 the first row of a table, returned element will be the table
5756 instead of the first row.
5758 When point is at the end of the buffer, return the innermost
5759 element ending there."
5760 (org-with-wide-buffer
5761 (let ((origin (point)))
5762 (end-of-line)
5763 (skip-chars-backward " \r\t\n")
5764 (cond
5765 ;; Within blank lines at the beginning of buffer, return nil.
5766 ((bobp) nil)
5767 ;; Within blank lines right after a headline, return that
5768 ;; headline.
5769 ((org-with-limited-levels (org-at-heading-p))
5770 (beginning-of-line)
5771 (org-element-headline-parser (point-max) t))
5772 ;; Otherwise parse until we find element containing ORIGIN.
5774 (when (org-element--cache-active-p)
5775 (if (not org-element--cache) (org-element-cache-reset)
5776 (org-element--cache-sync (current-buffer) origin)))
5777 (org-element--parse-to origin))))))
5779 ;;;###autoload
5780 (defun org-element-context (&optional element)
5781 "Return smallest element or object around point.
5783 Return value is a list like (TYPE PROPS) where TYPE is the type
5784 of the element or object and PROPS a plist of properties
5785 associated to it.
5787 Possible types are defined in `org-element-all-elements' and
5788 `org-element-all-objects'. Properties depend on element or
5789 object type, but always include `:begin', `:end', `:parent' and
5790 `:post-blank'.
5792 As a special case, if point is right after an object and not at
5793 the beginning of any other object, return that object.
5795 Optional argument ELEMENT, when non-nil, is the closest element
5796 containing point, as returned by `org-element-at-point'.
5797 Providing it allows for quicker computation."
5798 (catch 'objects-forbidden
5799 (org-with-wide-buffer
5800 (let* ((pos (point))
5801 (element (or element (org-element-at-point)))
5802 (type (org-element-type element))
5803 (post (org-element-property :post-affiliated element)))
5804 ;; If point is inside an element containing objects or
5805 ;; a secondary string, narrow buffer to the container and
5806 ;; proceed with parsing. Otherwise, return ELEMENT.
5807 (cond
5808 ;; At a parsed affiliated keyword, check if we're inside main
5809 ;; or dual value.
5810 ((and post (< pos post))
5811 (beginning-of-line)
5812 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5813 (cond
5814 ((not (member-ignore-case (match-string 1)
5815 org-element-parsed-keywords))
5816 (throw 'objects-forbidden element))
5817 ((< (match-end 0) pos)
5818 (narrow-to-region (match-end 0) (line-end-position)))
5819 ((and (match-beginning 2)
5820 (>= pos (match-beginning 2))
5821 (< pos (match-end 2)))
5822 (narrow-to-region (match-beginning 2) (match-end 2)))
5823 (t (throw 'objects-forbidden element)))
5824 ;; Also change type to retrieve correct restrictions.
5825 (setq type 'keyword))
5826 ;; At an item, objects can only be located within tag, if any.
5827 ((eq type 'item)
5828 (let ((tag (org-element-property :tag element)))
5829 (if (or (not tag) (/= (line-beginning-position) post))
5830 (throw 'objects-forbidden element)
5831 (beginning-of-line)
5832 (search-forward tag (line-end-position))
5833 (goto-char (match-beginning 0))
5834 (if (and (>= pos (point)) (< pos (match-end 0)))
5835 (narrow-to-region (point) (match-end 0))
5836 (throw 'objects-forbidden element)))))
5837 ;; At an headline or inlinetask, objects are in title.
5838 ((memq type '(headline inlinetask))
5839 (let ((case-fold-search nil))
5840 (goto-char (org-element-property :begin element))
5841 (looking-at org-complex-heading-regexp)
5842 (let ((end (match-end 4)))
5843 (if (not end) (throw 'objects-forbidden element)
5844 (goto-char (match-beginning 4))
5845 (when (looking-at org-comment-string)
5846 (goto-char (match-end 0)))
5847 (if (>= (point) end) (throw 'objects-forbidden element)
5848 (narrow-to-region (point) end))))))
5849 ;; At a paragraph, a table-row or a verse block, objects are
5850 ;; located within their contents.
5851 ((memq type '(paragraph table-row verse-block))
5852 (let ((cbeg (org-element-property :contents-begin element))
5853 (cend (org-element-property :contents-end element)))
5854 ;; CBEG is nil for table rules.
5855 (if (and cbeg cend (>= pos cbeg)
5856 (or (< pos cend) (and (= pos cend) (eobp))))
5857 (narrow-to-region cbeg cend)
5858 (throw 'objects-forbidden element))))
5859 (t (throw 'objects-forbidden element)))
5860 (goto-char (point-min))
5861 (let ((restriction (org-element-restriction type))
5862 (parent element)
5863 last)
5864 (catch 'exit
5865 (while t
5866 (let ((next (org-element--object-lex restriction)))
5867 (when next (org-element-put-property next :parent parent))
5868 ;; Process NEXT, if any, in order to know if we need to
5869 ;; skip it, return it or move into it.
5870 (if (or (not next) (> (org-element-property :begin next) pos))
5871 (throw 'exit (or last parent))
5872 (let ((end (org-element-property :end next))
5873 (cbeg (org-element-property :contents-begin next))
5874 (cend (org-element-property :contents-end next)))
5875 (cond
5876 ;; Skip objects ending before point. Also skip
5877 ;; objects ending at point unless it is also the
5878 ;; end of buffer, since we want to return the
5879 ;; innermost object.
5880 ((and (<= end pos) (/= (point-max) end))
5881 (goto-char end)
5882 ;; For convenience, when object ends at POS,
5883 ;; without any space, store it in LAST, as we
5884 ;; will return it if no object starts here.
5885 (when (and (= end pos)
5886 (not (memq (char-before) '(?\s ?\t))))
5887 (setq last next)))
5888 ;; If POS is within a container object, move into
5889 ;; that object.
5890 ((and cbeg cend
5891 (>= pos cbeg)
5892 (or (< pos cend)
5893 ;; At contents' end, if there is no
5894 ;; space before point, also move into
5895 ;; object, for consistency with
5896 ;; convenience feature above.
5897 (and (= pos cend)
5898 (or (= (point-max) pos)
5899 (not (memq (char-before pos)
5900 '(?\s ?\t)))))))
5901 (goto-char cbeg)
5902 (narrow-to-region (point) cend)
5903 (setq parent next)
5904 (setq restriction (org-element-restriction next)))
5905 ;; Otherwise, return NEXT.
5906 (t (throw 'exit next)))))))))))))
5908 (defun org-element-lineage (datum &optional types with-self)
5909 "List all ancestors of a given element or object.
5911 DATUM is an object or element.
5913 Return ancestors from the closest to the farthest. When optional
5914 argument TYPES is a list of symbols, return the first element or
5915 object in the lineage whose type belongs to that list instead.
5917 When optional argument WITH-SELF is non-nil, lineage includes
5918 DATUM itself as the first element, and TYPES, if provided, also
5919 apply to it.
5921 When DATUM is obtained through `org-element-context' or
5922 `org-element-at-point', only ancestors from its section can be
5923 found. There is no such limitation when DATUM belongs to a full
5924 parse tree."
5925 (let ((up (if with-self datum (org-element-property :parent datum)))
5926 ancestors)
5927 (while (and up (not (memq (org-element-type up) types)))
5928 (unless types (push up ancestors))
5929 (setq up (org-element-property :parent up)))
5930 (if types up (nreverse ancestors))))
5932 (defun org-element-nested-p (elem-A elem-B)
5933 "Non-nil when elements ELEM-A and ELEM-B are nested."
5934 (let ((beg-A (org-element-property :begin elem-A))
5935 (beg-B (org-element-property :begin elem-B))
5936 (end-A (org-element-property :end elem-A))
5937 (end-B (org-element-property :end elem-B)))
5938 (or (and (>= beg-A beg-B) (<= end-A end-B))
5939 (and (>= beg-B beg-A) (<= end-B end-A)))))
5941 (defun org-element-swap-A-B (elem-A elem-B)
5942 "Swap elements ELEM-A and ELEM-B.
5943 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5944 end of ELEM-A."
5945 (goto-char (org-element-property :begin elem-A))
5946 ;; There are two special cases when an element doesn't start at bol:
5947 ;; the first paragraph in an item or in a footnote definition.
5948 (let ((specialp (not (bolp))))
5949 ;; Only a paragraph without any affiliated keyword can be moved at
5950 ;; ELEM-A position in such a situation. Note that the case of
5951 ;; a footnote definition is impossible: it cannot contain two
5952 ;; paragraphs in a row because it cannot contain a blank line.
5953 (if (and specialp
5954 (or (not (eq (org-element-type elem-B) 'paragraph))
5955 (/= (org-element-property :begin elem-B)
5956 (org-element-property :contents-begin elem-B))))
5957 (error "Cannot swap elements"))
5958 ;; In a special situation, ELEM-A will have no indentation. We'll
5959 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5960 (let* ((ind-B (when specialp
5961 (goto-char (org-element-property :begin elem-B))
5962 (org-get-indentation)))
5963 (beg-A (org-element-property :begin elem-A))
5964 (end-A (save-excursion
5965 (goto-char (org-element-property :end elem-A))
5966 (skip-chars-backward " \r\t\n")
5967 (point-at-eol)))
5968 (beg-B (org-element-property :begin elem-B))
5969 (end-B (save-excursion
5970 (goto-char (org-element-property :end elem-B))
5971 (skip-chars-backward " \r\t\n")
5972 (point-at-eol)))
5973 ;; Store inner overlays responsible for visibility status.
5974 ;; We also need to store their boundaries as they will be
5975 ;; removed from buffer.
5976 (overlays
5977 (cons
5978 (delq nil
5979 (mapcar (lambda (o)
5980 (and (>= (overlay-start o) beg-A)
5981 (<= (overlay-end o) end-A)
5982 (list o (overlay-start o) (overlay-end o))))
5983 (overlays-in beg-A end-A)))
5984 (delq nil
5985 (mapcar (lambda (o)
5986 (and (>= (overlay-start o) beg-B)
5987 (<= (overlay-end o) end-B)
5988 (list o (overlay-start o) (overlay-end o))))
5989 (overlays-in beg-B end-B)))))
5990 ;; Get contents.
5991 (body-A (buffer-substring beg-A end-A))
5992 (body-B (delete-and-extract-region beg-B end-B)))
5993 (goto-char beg-B)
5994 (when specialp
5995 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5996 (indent-to-column ind-B))
5997 (insert body-A)
5998 ;; Restore ex ELEM-A overlays.
5999 (let ((offset (- beg-B beg-A)))
6000 (dolist (o (car overlays))
6001 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
6002 (goto-char beg-A)
6003 (delete-region beg-A end-A)
6004 (insert body-B)
6005 ;; Restore ex ELEM-B overlays.
6006 (dolist (o (cdr overlays))
6007 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
6008 (goto-char (org-element-property :end elem-B)))))
6011 (provide 'org-element)
6013 ;; Local variables:
6014 ;; generated-autoload-file: "org-loaddefs.el"
6015 ;; End:
6017 ;;; org-element.el ends here