Improve Scheme code evaluation
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob1480c05e8a8d6f953a4fee1607cac1214c642b93
1 ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; See <http://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', `:post-blank' and `:post-affiliated' keywords.
817 Assume point is at the beginning of the footnote definition."
818 (save-excursion
819 (let* ((label (progn (looking-at org-footnote-definition-re)
820 (match-string-no-properties 1)))
821 (begin (car affiliated))
822 (post-affiliated (point))
823 (end
824 (save-excursion
825 (end-of-line)
826 (cond
827 ((not
828 (re-search-forward org-element--footnote-separator limit t))
829 limit)
830 ((eq ?\[ (char-after (match-beginning 0)))
831 ;; At a new footnote definition, make sure we end
832 ;; before any affiliated keyword above.
833 (forward-line -1)
834 (while (and (> (point) post-affiliated)
835 (looking-at-p org-element--affiliated-re))
836 (forward-line -1))
837 (line-beginning-position 2))
838 ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
839 (t (skip-chars-forward " \r\t\n" limit)
840 (if (= limit (point)) limit (line-beginning-position))))))
841 (contents-begin
842 (progn (search-forward "]")
843 (skip-chars-forward " \r\t\n" end)
844 (cond ((= (point) end) nil)
845 ((= (line-beginning-position) post-affiliated) (point))
846 (t (line-beginning-position)))))
847 (contents-end
848 (progn (goto-char end)
849 (skip-chars-backward " \r\t\n")
850 (line-beginning-position 2))))
851 (list 'footnote-definition
852 (nconc
853 (list :label label
854 :begin begin
855 :end end
856 :contents-begin contents-begin
857 :contents-end (and contents-begin contents-end)
858 :post-blank (count-lines contents-end end)
859 :post-affiliated post-affiliated)
860 (cdr affiliated))))))
862 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
863 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
864 CONTENTS is the contents of the footnote-definition."
865 (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
867 contents))
870 ;;;; Headline
872 (defun org-element--get-node-properties ()
873 "Return node properties associated to headline at point.
874 Upcase property names. It avoids confusion between properties
875 obtained through property drawer and default properties from the
876 parser (e.g. `:end' and :END:). Return value is a plist."
877 (save-excursion
878 (forward-line)
879 (when (looking-at-p org-planning-line-re) (forward-line))
880 (when (looking-at org-property-drawer-re)
881 (forward-line)
882 (let ((end (match-end 0)) properties)
883 (while (< (line-end-position) end)
884 (looking-at org-property-re)
885 (push (match-string-no-properties 3) properties)
886 (push (intern (concat ":" (upcase (match-string 2)))) properties)
887 (forward-line))
888 properties))))
890 (defun org-element--get-time-properties ()
891 "Return time properties associated to headline at point.
892 Return value is a plist."
893 (save-excursion
894 (when (progn (forward-line) (looking-at org-planning-line-re))
895 (let ((end (line-end-position)) plist)
896 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
897 (goto-char (match-end 1))
898 (skip-chars-forward " \t")
899 (let ((keyword (match-string 1))
900 (time (org-element-timestamp-parser)))
901 (cond ((equal keyword org-scheduled-string)
902 (setq plist (plist-put plist :scheduled time)))
903 ((equal keyword org-deadline-string)
904 (setq plist (plist-put plist :deadline time)))
905 (t (setq plist (plist-put plist :closed time))))))
906 plist))))
908 (defun org-element-headline-parser (limit &optional raw-secondary-p)
909 "Parse a headline.
911 Return a list whose CAR is `headline' and CDR is a plist
912 containing `:raw-value', `:title', `:begin', `:end',
913 `:pre-blank', `:contents-begin' and `:contents-end', `:level',
914 `:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
915 `:deadline', `:closed', `:archivedp', `:commentedp'
916 `:footnote-section-p', `:post-blank' and `:post-affiliated'
917 keywords.
919 The plist also contains any property set in the property drawer,
920 with its name in upper cases and colons added at the
921 beginning (e.g., `:CUSTOM_ID').
923 LIMIT is a buffer position bounding the search.
925 When RAW-SECONDARY-P is non-nil, headline's title will not be
926 parsed as a secondary string, but as a plain string instead.
928 Assume point is at beginning of the headline."
929 (save-excursion
930 (let* ((begin (point))
931 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
932 (skip-chars-forward " \t")))
933 (todo (and org-todo-regexp
934 (let (case-fold-search) (looking-at org-todo-regexp))
935 (progn (goto-char (match-end 0))
936 (skip-chars-forward " \t")
937 (match-string 0))))
938 (todo-type
939 (and todo (if (member todo org-done-keywords) 'done 'todo)))
940 (priority (and (looking-at "\\[#.\\][ \t]*")
941 (progn (goto-char (match-end 0))
942 (aref (match-string 0) 2))))
943 (commentedp
944 (and (let (case-fold-search) (looking-at org-comment-string))
945 (goto-char (match-end 0))))
946 (title-start (point))
947 (tags (when (re-search-forward
948 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
949 (line-end-position)
950 'move)
951 (goto-char (match-beginning 0))
952 (org-split-string (match-string 1) ":")))
953 (title-end (point))
954 (raw-value (org-trim
955 (buffer-substring-no-properties title-start title-end)))
956 (archivedp (member org-archive-tag tags))
957 (footnote-section-p (and org-footnote-section
958 (string= org-footnote-section raw-value)))
959 (standard-props (org-element--get-node-properties))
960 (time-props (org-element--get-time-properties))
961 (end (min (save-excursion (org-end-of-subtree t t)) limit))
962 (contents-begin (save-excursion
963 (forward-line)
964 (skip-chars-forward " \r\t\n" end)
965 (and (/= (point) end) (line-beginning-position))))
966 (contents-end (and contents-begin
967 (progn (goto-char end)
968 (skip-chars-backward " \r\t\n")
969 (line-beginning-position 2)))))
970 (let ((headline
971 (list 'headline
972 (nconc
973 (list :raw-value raw-value
974 :begin begin
975 :end end
976 :pre-blank
977 (if (not contents-begin) 0
978 (1- (count-lines begin contents-begin)))
979 :contents-begin contents-begin
980 :contents-end contents-end
981 :level level
982 :priority priority
983 :tags tags
984 :todo-keyword todo
985 :todo-type todo-type
986 :post-blank
987 (if contents-end
988 (count-lines contents-end end)
989 (1- (count-lines begin end)))
990 :footnote-section-p footnote-section-p
991 :archivedp archivedp
992 :commentedp commentedp
993 :post-affiliated begin)
994 time-props
995 standard-props))))
996 (org-element-put-property
997 headline :title
998 (if raw-secondary-p raw-value
999 (org-element--parse-objects
1000 (progn (goto-char title-start)
1001 (skip-chars-forward " \t")
1002 (point))
1003 (progn (goto-char title-end)
1004 (skip-chars-backward " \t")
1005 (point))
1007 (org-element-restriction 'headline)
1008 headline)))))))
1010 (defun org-element-headline-interpreter (headline contents)
1011 "Interpret HEADLINE element as Org syntax.
1012 CONTENTS is the contents of the element."
1013 (let* ((level (org-element-property :level headline))
1014 (todo (org-element-property :todo-keyword headline))
1015 (priority (org-element-property :priority headline))
1016 (title (org-element-interpret-data
1017 (org-element-property :title headline)))
1018 (tags (let ((tag-list (org-element-property :tags headline)))
1019 (and tag-list
1020 (format ":%s:" (mapconcat #'identity tag-list ":")))))
1021 (commentedp (org-element-property :commentedp headline))
1022 (pre-blank (or (org-element-property :pre-blank headline) 0))
1023 (heading
1024 (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
1026 (and todo (concat " " todo))
1027 (and commentedp (concat " " org-comment-string))
1028 (and priority (format " [#%c]" priority))
1030 (if (and org-footnote-section
1031 (org-element-property :footnote-section-p headline))
1032 org-footnote-section
1033 title))))
1034 (concat
1035 heading
1036 ;; Align tags.
1037 (when tags
1038 (cond
1039 ((zerop org-tags-column) (format " %s" tags))
1040 ((< org-tags-column 0)
1041 (concat
1042 (make-string
1043 (max (- (+ org-tags-column (length heading) (length tags))) 1)
1044 ?\s)
1045 tags))
1047 (concat
1048 (make-string (max (- org-tags-column (length heading)) 1) ?\s)
1049 tags))))
1050 (make-string (1+ pre-blank) ?\n)
1051 contents)))
1054 ;;;; Inlinetask
1056 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
1057 "Parse an inline task.
1059 Return a list whose CAR is `inlinetask' and CDR is a plist
1060 containing `:title', `:begin', `:end', `:pre-blank',
1061 `:contents-begin' and `:contents-end', `:level', `:priority',
1062 `:raw-value', `:tags', `:todo-keyword', `:todo-type',
1063 `:scheduled', `:deadline', `:closed', `:post-blank' and
1064 `:post-affiliated' keywords.
1066 The plist also contains any property set in the property drawer,
1067 with its name in upper cases and colons added at the
1068 beginning (e.g., `:CUSTOM_ID').
1070 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
1071 title will not be parsed as a secondary string, but as a plain
1072 string instead.
1074 Assume point is at beginning of the inline task."
1075 (save-excursion
1076 (let* ((begin (point))
1077 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1078 (skip-chars-forward " \t")))
1079 (todo (and org-todo-regexp
1080 (let (case-fold-search) (looking-at org-todo-regexp))
1081 (progn (goto-char (match-end 0))
1082 (skip-chars-forward " \t")
1083 (match-string 0))))
1084 (todo-type (and todo
1085 (if (member todo org-done-keywords) 'done 'todo)))
1086 (priority (and (looking-at "\\[#.\\][ \t]*")
1087 (progn (goto-char (match-end 0))
1088 (aref (match-string 0) 2))))
1089 (title-start (point))
1090 (tags (when (re-search-forward
1091 "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
1092 (line-end-position)
1093 'move)
1094 (goto-char (match-beginning 0))
1095 (org-split-string (match-string 1) ":")))
1096 (title-end (point))
1097 (raw-value (org-trim
1098 (buffer-substring-no-properties title-start title-end)))
1099 (task-end (save-excursion
1100 (end-of-line)
1101 (and (re-search-forward org-outline-regexp-bol limit t)
1102 (looking-at-p "[ \t]*END[ \t]*$")
1103 (line-beginning-position))))
1104 (standard-props (and task-end (org-element--get-node-properties)))
1105 (time-props (and task-end (org-element--get-time-properties)))
1106 (contents-begin (and task-end
1107 (< (point) task-end)
1108 (progn
1109 (forward-line)
1110 (skip-chars-forward " \t\n")
1111 (line-beginning-position))))
1112 (contents-end (and contents-begin task-end))
1113 (end (progn (when task-end (goto-char task-end))
1114 (forward-line)
1115 (skip-chars-forward " \r\t\n" limit)
1116 (if (eobp) (point) (line-beginning-position))))
1117 (inlinetask
1118 (list 'inlinetask
1119 (nconc
1120 (list :raw-value raw-value
1121 :begin begin
1122 :end end
1123 :pre-blank
1124 (if (not contents-begin) 0
1125 (1- (count-lines begin contents-begin)))
1126 :contents-begin contents-begin
1127 :contents-end contents-end
1128 :level level
1129 :priority priority
1130 :tags tags
1131 :todo-keyword todo
1132 :todo-type todo-type
1133 :post-blank (1- (count-lines (or task-end begin) end))
1134 :post-affiliated begin)
1135 time-props
1136 standard-props))))
1137 (org-element-put-property
1138 inlinetask :title
1139 (if raw-secondary-p raw-value
1140 (org-element--parse-objects
1141 (progn (goto-char title-start)
1142 (skip-chars-forward " \t")
1143 (point))
1144 (progn (goto-char title-end)
1145 (skip-chars-backward " \t")
1146 (point))
1148 (org-element-restriction 'inlinetask)
1149 inlinetask))))))
1151 (defun org-element-inlinetask-interpreter (inlinetask contents)
1152 "Interpret INLINETASK element as Org syntax.
1153 CONTENTS is the contents of inlinetask."
1154 (let* ((level (org-element-property :level inlinetask))
1155 (todo (org-element-property :todo-keyword inlinetask))
1156 (priority (org-element-property :priority inlinetask))
1157 (title (org-element-interpret-data
1158 (org-element-property :title inlinetask)))
1159 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1160 (and tag-list
1161 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1162 (task (concat (make-string level ?*)
1163 (and todo (concat " " todo))
1164 (and priority (format " [#%c]" priority))
1165 (and title (concat " " title)))))
1166 (concat task
1167 ;; Align tags.
1168 (when tags
1169 (cond
1170 ((zerop org-tags-column) (format " %s" tags))
1171 ((< org-tags-column 0)
1172 (concat
1173 (make-string
1174 (max (- (+ org-tags-column (length task) (length tags))) 1)
1176 tags))
1178 (concat
1179 (make-string (max (- org-tags-column (length task)) 1) ? )
1180 tags))))
1181 ;; Prefer degenerate inlinetasks when there are no
1182 ;; contents.
1183 (when contents
1184 (concat "\n"
1185 contents
1186 (make-string level ?*) " END")))))
1189 ;;;; Item
1191 (defun org-element-item-parser (_ struct &optional raw-secondary-p)
1192 "Parse an item.
1194 STRUCT is the structure of the plain list.
1196 Return a list whose CAR is `item' and CDR is a plist containing
1197 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1198 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1199 `:post-affiliated' keywords.
1201 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1202 any, will not be parsed as a secondary string, but as a plain
1203 string instead.
1205 Assume point is at the beginning of the item."
1206 (save-excursion
1207 (beginning-of-line)
1208 (looking-at org-list-full-item-re)
1209 (let* ((begin (point))
1210 (bullet (match-string-no-properties 1))
1211 (checkbox (let ((box (match-string 3)))
1212 (cond ((equal "[ ]" box) 'off)
1213 ((equal "[X]" box) 'on)
1214 ((equal "[-]" box) 'trans))))
1215 (counter (let ((c (match-string 2)))
1216 (save-match-data
1217 (cond
1218 ((not c) nil)
1219 ((string-match "[A-Za-z]" c)
1220 (- (string-to-char (upcase (match-string 0 c)))
1221 64))
1222 ((string-match "[0-9]+" c)
1223 (string-to-number (match-string 0 c)))))))
1224 (end (progn (goto-char (nth 6 (assq (point) struct)))
1225 (if (bolp) (point) (line-beginning-position 2))))
1226 (contents-begin
1227 (progn (goto-char
1228 ;; Ignore tags in un-ordered lists: they are just
1229 ;; a part of item's body.
1230 (if (and (match-beginning 4)
1231 (save-match-data (string-match "[.)]" bullet)))
1232 (match-beginning 4)
1233 (match-end 0)))
1234 (skip-chars-forward " \r\t\n" end)
1235 (cond ((= (point) end) nil)
1236 ;; If first line isn't empty, contents really
1237 ;; start at the text after item's meta-data.
1238 ((= (line-beginning-position) begin) (point))
1239 (t (line-beginning-position)))))
1240 (contents-end (and contents-begin
1241 (progn (goto-char end)
1242 (skip-chars-backward " \r\t\n")
1243 (line-beginning-position 2))))
1244 (item
1245 (list 'item
1246 (list :bullet bullet
1247 :begin begin
1248 :end end
1249 :contents-begin contents-begin
1250 :contents-end contents-end
1251 :checkbox checkbox
1252 :counter counter
1253 :structure struct
1254 :post-blank (count-lines (or contents-end begin) end)
1255 :post-affiliated begin))))
1256 (org-element-put-property
1257 item :tag
1258 (let ((raw (org-list-get-tag begin struct)))
1259 (when raw
1260 (if raw-secondary-p raw
1261 (org-element--parse-objects
1262 (match-beginning 4) (match-end 4) nil
1263 (org-element-restriction 'item)
1264 item))))))))
1266 (defun org-element-item-interpreter (item contents)
1267 "Interpret ITEM element as Org syntax.
1268 CONTENTS is the contents of the element."
1269 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1270 (org-list-bullet-string
1271 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1272 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1273 (t "1.")))))
1274 (checkbox (org-element-property :checkbox item))
1275 (counter (org-element-property :counter item))
1276 (tag (let ((tag (org-element-property :tag item)))
1277 (and tag (org-element-interpret-data tag))))
1278 ;; Compute indentation.
1279 (ind (make-string (length bullet) 32))
1280 (item-starts-with-par-p
1281 (eq (org-element-type (car (org-element-contents item)))
1282 'paragraph)))
1283 ;; Indent contents.
1284 (concat
1285 bullet
1286 (and counter (format "[@%d] " counter))
1287 (pcase checkbox
1288 (`on "[X] ")
1289 (`off "[ ] ")
1290 (`trans "[-] ")
1291 (_ nil))
1292 (and tag (format "%s :: " tag))
1293 (when contents
1294 (let ((contents (replace-regexp-in-string
1295 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1296 (if item-starts-with-par-p (org-trim contents)
1297 (concat "\n" contents)))))))
1300 ;;;; Plain List
1302 (defun org-element--list-struct (limit)
1303 ;; Return structure of list at point. Internal function. See
1304 ;; `org-list-struct' for details.
1305 (let ((case-fold-search t)
1306 (top-ind limit)
1307 (item-re (org-item-re))
1308 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1309 items struct)
1310 (save-excursion
1311 (catch 'exit
1312 (while t
1313 (cond
1314 ;; At limit: end all items.
1315 ((>= (point) limit)
1316 (throw 'exit
1317 (let ((end (progn (skip-chars-backward " \r\t\n")
1318 (forward-line)
1319 (point))))
1320 (dolist (item items (sort (nconc items struct)
1321 'car-less-than-car))
1322 (setcar (nthcdr 6 item) end)))))
1323 ;; At list end: end all items.
1324 ((looking-at org-list-end-re)
1325 (throw 'exit (dolist (item items (sort (nconc items struct)
1326 'car-less-than-car))
1327 (setcar (nthcdr 6 item) (point)))))
1328 ;; At a new item: end previous sibling.
1329 ((looking-at item-re)
1330 (let ((ind (save-excursion (skip-chars-forward " \t")
1331 (current-column))))
1332 (setq top-ind (min top-ind ind))
1333 (while (and items (<= ind (nth 1 (car items))))
1334 (let ((item (pop items)))
1335 (setcar (nthcdr 6 item) (point))
1336 (push item struct)))
1337 (push (progn (looking-at org-list-full-item-re)
1338 (let ((bullet (match-string-no-properties 1)))
1339 (list (point)
1341 bullet
1342 (match-string-no-properties 2) ; counter
1343 (match-string-no-properties 3) ; checkbox
1344 ;; Description tag.
1345 (and (save-match-data
1346 (string-match "[-+*]" bullet))
1347 (match-string-no-properties 4))
1348 ;; Ending position, unknown so far.
1349 nil)))
1350 items))
1351 (forward-line 1))
1352 ;; Skip empty lines.
1353 ((looking-at "^[ \t]*$") (forward-line))
1354 ;; Skip inline tasks and blank lines along the way.
1355 ((and inlinetask-re (looking-at inlinetask-re))
1356 (forward-line)
1357 (let ((origin (point)))
1358 (when (re-search-forward inlinetask-re limit t)
1359 (if (looking-at-p "END[ \t]*$") (forward-line)
1360 (goto-char origin)))))
1361 ;; At some text line. Check if it ends any previous item.
1363 (let ((ind (save-excursion (skip-chars-forward " \t")
1364 (current-column))))
1365 (when (<= ind top-ind)
1366 (skip-chars-backward " \r\t\n")
1367 (forward-line))
1368 (while (<= ind (nth 1 (car items)))
1369 (let ((item (pop items)))
1370 (setcar (nthcdr 6 item) (line-beginning-position))
1371 (push item struct)
1372 (unless items
1373 (throw 'exit (sort struct #'car-less-than-car))))))
1374 ;; Skip blocks (any type) and drawers contents.
1375 (cond
1376 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1377 (re-search-forward
1378 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1379 limit t)))
1380 ((and (looking-at org-drawer-regexp)
1381 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1382 (forward-line))))))))
1384 (defun org-element-plain-list-parser (limit affiliated structure)
1385 "Parse a plain list.
1387 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1388 the buffer position at the beginning of the first affiliated
1389 keyword and CDR is a plist of affiliated keywords along with
1390 their value. STRUCTURE is the structure of the plain list being
1391 parsed.
1393 Return a list whose CAR is `plain-list' and CDR is a plist
1394 containing `:type', `:begin', `:end', `:contents-begin' and
1395 `:contents-end', `:structure', `:post-blank' and
1396 `:post-affiliated' keywords.
1398 Assume point is at the beginning of the list."
1399 (save-excursion
1400 (let* ((struct (or structure (org-element--list-struct limit)))
1401 (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1402 ((nth 5 (assq (point) struct)) 'descriptive)
1403 (t 'unordered)))
1404 (contents-begin (point))
1405 (begin (car affiliated))
1406 (contents-end (let* ((item (assq contents-begin struct))
1407 (ind (nth 1 item))
1408 (pos (nth 6 item)))
1409 (while (and (setq item (assq pos struct))
1410 (= (nth 1 item) ind))
1411 (setq pos (nth 6 item)))
1412 pos))
1413 (end (progn (goto-char contents-end)
1414 (skip-chars-forward " \r\t\n" limit)
1415 (if (= (point) limit) limit (line-beginning-position)))))
1416 ;; Return value.
1417 (list 'plain-list
1418 (nconc
1419 (list :type type
1420 :begin begin
1421 :end end
1422 :contents-begin contents-begin
1423 :contents-end contents-end
1424 :structure struct
1425 :post-blank (count-lines contents-end end)
1426 :post-affiliated contents-begin)
1427 (cdr affiliated))))))
1429 (defun org-element-plain-list-interpreter (_ contents)
1430 "Interpret plain-list element as Org syntax.
1431 CONTENTS is the contents of the element."
1432 (with-temp-buffer
1433 (insert contents)
1434 (goto-char (point-min))
1435 (org-list-repair)
1436 (buffer-string)))
1439 ;;;; Property Drawer
1441 (defun org-element-property-drawer-parser (limit)
1442 "Parse a property drawer.
1444 LIMIT bounds the search.
1446 Return a list whose car is `property-drawer' and cdr is a plist
1447 containing `:begin', `:end', `:contents-begin', `:contents-end',
1448 `:post-blank' and `:post-affiliated' keywords.
1450 Assume point is at the beginning of the property drawer."
1451 (save-excursion
1452 (let ((case-fold-search t)
1453 (begin (point))
1454 (contents-begin (line-beginning-position 2)))
1455 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1456 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1457 (match-beginning 0)))
1458 (before-blank (progn (forward-line) (point)))
1459 (end (progn (skip-chars-forward " \r\t\n" limit)
1460 (if (eobp) (point) (line-beginning-position)))))
1461 (list 'property-drawer
1462 (list :begin begin
1463 :end end
1464 :contents-begin (and contents-end contents-begin)
1465 :contents-end contents-end
1466 :post-blank (count-lines before-blank end)
1467 :post-affiliated begin))))))
1469 (defun org-element-property-drawer-interpreter (_ contents)
1470 "Interpret property-drawer element as Org syntax.
1471 CONTENTS is the properties within the drawer."
1472 (format ":PROPERTIES:\n%s:END:" contents))
1475 ;;;; Quote Block
1477 (defun org-element-quote-block-parser (limit affiliated)
1478 "Parse a quote block.
1480 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1481 the buffer position at the beginning of the first affiliated
1482 keyword and CDR is a plist of affiliated keywords along with
1483 their value.
1485 Return a list whose CAR is `quote-block' and CDR is a plist
1486 containing `:begin', `:end', `:contents-begin', `:contents-end',
1487 `:post-blank' and `:post-affiliated' keywords.
1489 Assume point is at the beginning of the block."
1490 (let ((case-fold-search t))
1491 (if (not (save-excursion
1492 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1493 ;; Incomplete block: parse it as a paragraph.
1494 (org-element-paragraph-parser limit affiliated)
1495 (let ((block-end-line (match-beginning 0)))
1496 (save-excursion
1497 (let* ((begin (car affiliated))
1498 (post-affiliated (point))
1499 ;; Empty blocks have no contents.
1500 (contents-begin (progn (forward-line)
1501 (and (< (point) block-end-line)
1502 (point))))
1503 (contents-end (and contents-begin block-end-line))
1504 (pos-before-blank (progn (goto-char block-end-line)
1505 (forward-line)
1506 (point)))
1507 (end (progn (skip-chars-forward " \r\t\n" limit)
1508 (if (eobp) (point) (line-beginning-position)))))
1509 (list 'quote-block
1510 (nconc
1511 (list :begin begin
1512 :end end
1513 :contents-begin contents-begin
1514 :contents-end contents-end
1515 :post-blank (count-lines pos-before-blank end)
1516 :post-affiliated post-affiliated)
1517 (cdr affiliated)))))))))
1519 (defun org-element-quote-block-interpreter (_ contents)
1520 "Interpret quote-block element as Org syntax.
1521 CONTENTS is the contents of the element."
1522 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1525 ;;;; Section
1527 (defun org-element-section-parser (_)
1528 "Parse a section.
1530 Return a list whose CAR is `section' and CDR is a plist
1531 containing `:begin', `:end', `:contents-begin', `contents-end',
1532 `:post-blank' and `:post-affiliated' keywords."
1533 (save-excursion
1534 ;; Beginning of section is the beginning of the first non-blank
1535 ;; line after previous headline.
1536 (let ((begin (point))
1537 (end (progn (org-with-limited-levels (outline-next-heading))
1538 (point)))
1539 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1540 (line-beginning-position 2))))
1541 (list 'section
1542 (list :begin begin
1543 :end end
1544 :contents-begin begin
1545 :contents-end pos-before-blank
1546 :post-blank (count-lines pos-before-blank end)
1547 :post-affiliated begin)))))
1549 (defun org-element-section-interpreter (_ contents)
1550 "Interpret section element as Org syntax.
1551 CONTENTS is the contents of the element."
1552 contents)
1555 ;;;; Special Block
1557 (defun org-element-special-block-parser (limit affiliated)
1558 "Parse a special block.
1560 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1561 the buffer position at the beginning of the first affiliated
1562 keyword and CDR is a plist of affiliated keywords along with
1563 their value.
1565 Return a list whose CAR is `special-block' and CDR is a plist
1566 containing `:type', `:begin', `:end', `:contents-begin',
1567 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1569 Assume point is at the beginning of the block."
1570 (let* ((case-fold-search t)
1571 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1572 (match-string-no-properties 1))))
1573 (if (not (save-excursion
1574 (re-search-forward
1575 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1576 limit t)))
1577 ;; Incomplete block: parse it as a paragraph.
1578 (org-element-paragraph-parser limit affiliated)
1579 (let ((block-end-line (match-beginning 0)))
1580 (save-excursion
1581 (let* ((begin (car affiliated))
1582 (post-affiliated (point))
1583 ;; Empty blocks have no contents.
1584 (contents-begin (progn (forward-line)
1585 (and (< (point) block-end-line)
1586 (point))))
1587 (contents-end (and contents-begin block-end-line))
1588 (pos-before-blank (progn (goto-char block-end-line)
1589 (forward-line)
1590 (point)))
1591 (end (progn (skip-chars-forward " \r\t\n" limit)
1592 (if (eobp) (point) (line-beginning-position)))))
1593 (list 'special-block
1594 (nconc
1595 (list :type type
1596 :begin begin
1597 :end end
1598 :contents-begin contents-begin
1599 :contents-end contents-end
1600 :post-blank (count-lines pos-before-blank end)
1601 :post-affiliated post-affiliated)
1602 (cdr affiliated)))))))))
1604 (defun org-element-special-block-interpreter (special-block contents)
1605 "Interpret SPECIAL-BLOCK element as Org syntax.
1606 CONTENTS is the contents of the element."
1607 (let ((block-type (org-element-property :type special-block)))
1608 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1612 ;;; Elements
1614 ;; For each element, a parser and an interpreter are also defined.
1615 ;; Both follow the same naming convention used for greater elements.
1617 ;; Also, as for greater elements, adding a new element type is done
1618 ;; through the following steps: implement a parser and an interpreter,
1619 ;; tweak `org-element--current-element' so that it recognizes the new
1620 ;; type and add that new type to `org-element-all-elements'.
1623 ;;;; Babel Call
1625 (defun org-element-babel-call-parser (limit affiliated)
1626 "Parse a babel call.
1628 LIMIT bounds the search. AFFILIATED is a list of which car is
1629 the buffer position at the beginning of the first affiliated
1630 keyword and cdr is a plist of affiliated keywords along with
1631 their value.
1633 Return a list whose car is `babel-call' and cdr is a plist
1634 containing `:call', `:inside-header', `:arguments',
1635 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1636 `:post-affiliated' as keywords."
1637 (save-excursion
1638 (let* ((begin (car affiliated))
1639 (post-affiliated (point))
1640 (before-blank (line-beginning-position 2))
1641 (value (progn (search-forward ":" before-blank t)
1642 (skip-chars-forward " \t")
1643 (org-trim
1644 (buffer-substring-no-properties
1645 (point) (line-end-position)))))
1646 (call
1647 (or (org-string-nw-p
1648 (buffer-substring-no-properties
1649 (point) (progn (skip-chars-forward "^[]()" before-blank)
1650 (point))))))
1651 (inside-header (org-element--parse-paired-brackets ?\[))
1652 (arguments (org-string-nw-p
1653 (org-element--parse-paired-brackets ?\()))
1654 (end-header
1655 (org-string-nw-p
1656 (org-trim
1657 (buffer-substring-no-properties (point) (line-end-position)))))
1658 (end (progn (forward-line)
1659 (skip-chars-forward " \r\t\n" limit)
1660 (if (eobp) (point) (line-beginning-position)))))
1661 (list 'babel-call
1662 (nconc
1663 (list :call call
1664 :inside-header inside-header
1665 :arguments arguments
1666 :end-header end-header
1667 :begin begin
1668 :end end
1669 :value value
1670 :post-blank (count-lines before-blank end)
1671 :post-affiliated post-affiliated)
1672 (cdr affiliated))))))
1674 (defun org-element-babel-call-interpreter (babel-call _)
1675 "Interpret BABEL-CALL element as Org syntax."
1676 (concat "#+CALL: "
1677 (org-element-property :call babel-call)
1678 (let ((h (org-element-property :inside-header babel-call)))
1679 (and h (format "[%s]" h)))
1680 (concat "(" (org-element-property :arguments babel-call) ")")
1681 (let ((h (org-element-property :end-header babel-call)))
1682 (and h (concat " " h)))))
1685 ;;;; Clock
1687 (defun org-element-clock-parser (limit)
1688 "Parse a clock.
1690 LIMIT bounds the search.
1692 Return a list whose CAR is `clock' and CDR is a plist containing
1693 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1694 `:post-affiliated' as keywords."
1695 (save-excursion
1696 (let* ((case-fold-search nil)
1697 (begin (point))
1698 (value (progn (search-forward org-clock-string (line-end-position) t)
1699 (skip-chars-forward " \t")
1700 (org-element-timestamp-parser)))
1701 (duration (and (search-forward " => " (line-end-position) t)
1702 (progn (skip-chars-forward " \t")
1703 (looking-at "\\(\\S-+\\)[ \t]*$"))
1704 (match-string-no-properties 1)))
1705 (status (if duration 'closed 'running))
1706 (post-blank (let ((before-blank (progn (forward-line) (point))))
1707 (skip-chars-forward " \r\t\n" limit)
1708 (skip-chars-backward " \t")
1709 (unless (bolp) (end-of-line))
1710 (count-lines before-blank (point))))
1711 (end (point)))
1712 (list 'clock
1713 (list :status status
1714 :value value
1715 :duration duration
1716 :begin begin
1717 :end end
1718 :post-blank post-blank
1719 :post-affiliated begin)))))
1721 (defun org-element-clock-interpreter (clock _)
1722 "Interpret CLOCK element as Org syntax."
1723 (concat org-clock-string " "
1724 (org-element-timestamp-interpreter
1725 (org-element-property :value clock) nil)
1726 (let ((duration (org-element-property :duration clock)))
1727 (and duration
1728 (concat " => "
1729 (apply 'format
1730 "%2s:%02s"
1731 (org-split-string duration ":")))))))
1734 ;;;; Comment
1736 (defun org-element-comment-parser (limit affiliated)
1737 "Parse a comment.
1739 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1740 the buffer position at the beginning of the first affiliated
1741 keyword and CDR is a plist of affiliated keywords along with
1742 their value.
1744 Return a list whose CAR is `comment' and CDR is a plist
1745 containing `:begin', `:end', `:value', `:post-blank',
1746 `:post-affiliated' keywords.
1748 Assume point is at comment beginning."
1749 (save-excursion
1750 (let* ((begin (car affiliated))
1751 (post-affiliated (point))
1752 (value (prog2 (looking-at "[ \t]*# ?")
1753 (buffer-substring-no-properties
1754 (match-end 0) (line-end-position))
1755 (forward-line)))
1756 (com-end
1757 ;; Get comments ending.
1758 (progn
1759 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1760 ;; Accumulate lines without leading hash and first
1761 ;; whitespace.
1762 (setq value
1763 (concat value
1764 "\n"
1765 (buffer-substring-no-properties
1766 (match-end 0) (line-end-position))))
1767 (forward-line))
1768 (point)))
1769 (end (progn (goto-char com-end)
1770 (skip-chars-forward " \r\t\n" limit)
1771 (if (eobp) (point) (line-beginning-position)))))
1772 (list 'comment
1773 (nconc
1774 (list :begin begin
1775 :end end
1776 :value value
1777 :post-blank (count-lines com-end end)
1778 :post-affiliated post-affiliated)
1779 (cdr affiliated))))))
1781 (defun org-element-comment-interpreter (comment _)
1782 "Interpret COMMENT element as Org syntax.
1783 CONTENTS is nil."
1784 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1787 ;;;; Comment Block
1789 (defun org-element-comment-block-parser (limit affiliated)
1790 "Parse an export block.
1792 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1793 the buffer position at the beginning of the first affiliated
1794 keyword and CDR is a plist of affiliated keywords along with
1795 their value.
1797 Return a list whose CAR is `comment-block' and CDR is a plist
1798 containing `:begin', `:end', `:value', `:post-blank' and
1799 `:post-affiliated' keywords.
1801 Assume point is at comment block beginning."
1802 (let ((case-fold-search t))
1803 (if (not (save-excursion
1804 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1805 ;; Incomplete block: parse it as a paragraph.
1806 (org-element-paragraph-parser limit affiliated)
1807 (let ((contents-end (match-beginning 0)))
1808 (save-excursion
1809 (let* ((begin (car affiliated))
1810 (post-affiliated (point))
1811 (contents-begin (progn (forward-line) (point)))
1812 (pos-before-blank (progn (goto-char contents-end)
1813 (forward-line)
1814 (point)))
1815 (end (progn (skip-chars-forward " \r\t\n" limit)
1816 (if (eobp) (point) (line-beginning-position))))
1817 (value (buffer-substring-no-properties
1818 contents-begin contents-end)))
1819 (list 'comment-block
1820 (nconc
1821 (list :begin begin
1822 :end end
1823 :value value
1824 :post-blank (count-lines pos-before-blank end)
1825 :post-affiliated post-affiliated)
1826 (cdr affiliated)))))))))
1828 (defun org-element-comment-block-interpreter (comment-block _)
1829 "Interpret COMMENT-BLOCK element as Org syntax."
1830 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1831 (org-element-normalize-string
1832 (org-remove-indentation
1833 (org-element-property :value comment-block)))))
1836 ;;;; Diary Sexp
1838 (defun org-element-diary-sexp-parser (limit affiliated)
1839 "Parse a diary sexp.
1841 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1842 the buffer position at the beginning of the first affiliated
1843 keyword and CDR is a plist of affiliated keywords along with
1844 their value.
1846 Return a list whose CAR is `diary-sexp' and CDR is a plist
1847 containing `:begin', `:end', `:value', `:post-blank' and
1848 `:post-affiliated' keywords."
1849 (save-excursion
1850 (let ((begin (car affiliated))
1851 (post-affiliated (point))
1852 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1853 (match-string-no-properties 1)))
1854 (pos-before-blank (progn (forward-line) (point)))
1855 (end (progn (skip-chars-forward " \r\t\n" limit)
1856 (if (eobp) (point) (line-beginning-position)))))
1857 (list 'diary-sexp
1858 (nconc
1859 (list :value value
1860 :begin begin
1861 :end end
1862 :post-blank (count-lines pos-before-blank end)
1863 :post-affiliated post-affiliated)
1864 (cdr affiliated))))))
1866 (defun org-element-diary-sexp-interpreter (diary-sexp _)
1867 "Interpret DIARY-SEXP as Org syntax."
1868 (org-element-property :value diary-sexp))
1871 ;;;; Example Block
1873 (defun org-element-example-block-parser (limit affiliated)
1874 "Parse an example block.
1876 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1877 the buffer position at the beginning of the first affiliated
1878 keyword and CDR is a plist of affiliated keywords along with
1879 their value.
1881 Return a list whose CAR is `example-block' and CDR is a plist
1882 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1883 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1884 `:value', `:post-blank' and `:post-affiliated' keywords."
1885 (let ((case-fold-search t))
1886 (if (not (save-excursion
1887 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1888 ;; Incomplete block: parse it as a paragraph.
1889 (org-element-paragraph-parser limit affiliated)
1890 (let ((contents-end (match-beginning 0)))
1891 (save-excursion
1892 (let* ((switches
1893 (progn
1894 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1895 (match-string-no-properties 1)))
1896 ;; Switches analysis.
1897 (number-lines
1898 (and switches
1899 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
1900 switches)
1901 (cons
1902 (if (equal (match-string 1 switches) "-")
1903 'new
1904 'continued)
1905 (if (not (match-end 2)) 0
1906 ;; Subtract 1 to give number of lines before
1907 ;; first line.
1908 (1- (string-to-number (match-string 2 switches)))))))
1909 (preserve-indent
1910 (and switches (string-match "-i\\>" switches)))
1911 ;; Should labels be retained in (or stripped from) example
1912 ;; blocks?
1913 (retain-labels
1914 (or (not switches)
1915 (not (string-match "-r\\>" switches))
1916 (and number-lines (string-match "-k\\>" switches))))
1917 ;; What should code-references use - labels or
1918 ;; line-numbers?
1919 (use-labels
1920 (or (not switches)
1921 (and retain-labels
1922 (not (string-match "-k\\>" switches)))))
1923 (label-fmt
1924 (and switches
1925 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1926 (match-string 1 switches)))
1927 ;; Standard block parsing.
1928 (begin (car affiliated))
1929 (post-affiliated (point))
1930 (contents-begin (line-beginning-position 2))
1931 (value (org-unescape-code-in-string
1932 (buffer-substring-no-properties
1933 contents-begin contents-end)))
1934 (pos-before-blank (progn (goto-char contents-end)
1935 (forward-line)
1936 (point)))
1937 (end (progn (skip-chars-forward " \r\t\n" limit)
1938 (if (eobp) (point) (line-beginning-position)))))
1939 (list 'example-block
1940 (nconc
1941 (list :begin begin
1942 :end end
1943 :value value
1944 :switches switches
1945 :number-lines number-lines
1946 :preserve-indent preserve-indent
1947 :retain-labels retain-labels
1948 :use-labels use-labels
1949 :label-fmt label-fmt
1950 :post-blank (count-lines pos-before-blank end)
1951 :post-affiliated post-affiliated)
1952 (cdr affiliated)))))))))
1954 (defun org-element-example-block-interpreter (example-block _)
1955 "Interpret EXAMPLE-BLOCK element as Org syntax."
1956 (let ((switches (org-element-property :switches example-block))
1957 (value (org-element-property :value example-block)))
1958 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1959 (org-element-normalize-string
1960 (org-escape-code-in-string
1961 (if (or org-src-preserve-indentation
1962 (org-element-property :preserve-indent example-block))
1963 value
1964 (org-remove-indentation value))))
1965 "#+END_EXAMPLE")))
1968 ;;;; Export Block
1970 (defun org-element-export-block-parser (limit affiliated)
1971 "Parse an export block.
1973 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1974 the buffer position at the beginning of the first affiliated
1975 keyword and CDR is a plist of affiliated keywords along with
1976 their value.
1978 Return a list whose CAR is `export-block' and CDR is a plist
1979 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1980 `:post-affiliated' keywords.
1982 Assume point is at export-block beginning."
1983 (let* ((case-fold-search t))
1984 (if (not (save-excursion
1985 (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
1986 ;; Incomplete block: parse it as a paragraph.
1987 (org-element-paragraph-parser limit affiliated)
1988 (save-excursion
1989 (let* ((contents-end (match-beginning 0))
1990 (backend
1991 (progn
1992 (looking-at
1993 "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
1994 (match-string-no-properties 1)))
1995 (begin (car affiliated))
1996 (post-affiliated (point))
1997 (contents-begin (progn (forward-line) (point)))
1998 (pos-before-blank (progn (goto-char contents-end)
1999 (forward-line)
2000 (point)))
2001 (end (progn (skip-chars-forward " \r\t\n" limit)
2002 (if (eobp) (point) (line-beginning-position))))
2003 (value (org-unescape-code-in-string
2004 (buffer-substring-no-properties contents-begin
2005 contents-end))))
2006 (list 'export-block
2007 (nconc
2008 (list :type (and backend (upcase backend))
2009 :begin begin
2010 :end end
2011 :value value
2012 :post-blank (count-lines pos-before-blank end)
2013 :post-affiliated post-affiliated)
2014 (cdr affiliated))))))))
2016 (defun org-element-export-block-interpreter (export-block _)
2017 "Interpret EXPORT-BLOCK element as Org syntax."
2018 (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT"
2019 (org-element-property :type export-block)
2020 (org-element-property :value export-block)))
2023 ;;;; Fixed-width
2025 (defun org-element-fixed-width-parser (limit affiliated)
2026 "Parse a fixed-width section.
2028 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2029 the buffer position at the beginning of the first affiliated
2030 keyword and CDR is a plist of affiliated keywords along with
2031 their value.
2033 Return a list whose CAR is `fixed-width' and CDR is a plist
2034 containing `:begin', `:end', `:value', `:post-blank' and
2035 `:post-affiliated' keywords.
2037 Assume point is at the beginning of the fixed-width area."
2038 (save-excursion
2039 (let* ((begin (car affiliated))
2040 (post-affiliated (point))
2041 value
2042 (end-area
2043 (progn
2044 (while (and (< (point) limit)
2045 (looking-at "[ \t]*:\\( \\|$\\)"))
2046 ;; Accumulate text without starting colons.
2047 (setq value
2048 (concat value
2049 (buffer-substring-no-properties
2050 (match-end 0) (point-at-eol))
2051 "\n"))
2052 (forward-line))
2053 (point)))
2054 (end (progn (skip-chars-forward " \r\t\n" limit)
2055 (if (eobp) (point) (line-beginning-position)))))
2056 (list 'fixed-width
2057 (nconc
2058 (list :begin begin
2059 :end end
2060 :value value
2061 :post-blank (count-lines end-area end)
2062 :post-affiliated post-affiliated)
2063 (cdr affiliated))))))
2065 (defun org-element-fixed-width-interpreter (fixed-width _)
2066 "Interpret FIXED-WIDTH element as Org syntax."
2067 (let ((value (org-element-property :value fixed-width)))
2068 (and value
2069 (replace-regexp-in-string
2070 "^" ": "
2071 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2074 ;;;; Horizontal Rule
2076 (defun org-element-horizontal-rule-parser (limit affiliated)
2077 "Parse an horizontal rule.
2079 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2080 the buffer position at the beginning of the first affiliated
2081 keyword and CDR is a plist of affiliated keywords along with
2082 their value.
2084 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2085 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2086 keywords."
2087 (save-excursion
2088 (let ((begin (car affiliated))
2089 (post-affiliated (point))
2090 (post-hr (progn (forward-line) (point)))
2091 (end (progn (skip-chars-forward " \r\t\n" limit)
2092 (if (eobp) (point) (line-beginning-position)))))
2093 (list 'horizontal-rule
2094 (nconc
2095 (list :begin begin
2096 :end end
2097 :post-blank (count-lines post-hr end)
2098 :post-affiliated post-affiliated)
2099 (cdr affiliated))))))
2101 (defun org-element-horizontal-rule-interpreter (&rest _)
2102 "Interpret HORIZONTAL-RULE element as Org syntax."
2103 "-----")
2106 ;;;; Keyword
2108 (defun org-element-keyword-parser (limit affiliated)
2109 "Parse a keyword at point.
2111 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2112 the buffer position at the beginning of the first affiliated
2113 keyword and CDR is a plist of affiliated keywords along with
2114 their value.
2116 Return a list whose CAR is `keyword' and CDR is a plist
2117 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2118 `:post-affiliated' keywords."
2119 (save-excursion
2120 ;; An orphaned affiliated keyword is considered as a regular
2121 ;; keyword. In this case AFFILIATED is nil, so we take care of
2122 ;; this corner case.
2123 (let ((begin (or (car affiliated) (point)))
2124 (post-affiliated (point))
2125 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2126 (upcase (match-string-no-properties 1))))
2127 (value (org-trim (buffer-substring-no-properties
2128 (match-end 0) (point-at-eol))))
2129 (pos-before-blank (progn (forward-line) (point)))
2130 (end (progn (skip-chars-forward " \r\t\n" limit)
2131 (if (eobp) (point) (line-beginning-position)))))
2132 (list 'keyword
2133 (nconc
2134 (list :key key
2135 :value value
2136 :begin begin
2137 :end end
2138 :post-blank (count-lines pos-before-blank end)
2139 :post-affiliated post-affiliated)
2140 (cdr affiliated))))))
2142 (defun org-element-keyword-interpreter (keyword _)
2143 "Interpret KEYWORD element as Org syntax."
2144 (format "#+%s: %s"
2145 (org-element-property :key keyword)
2146 (org-element-property :value keyword)))
2149 ;;;; Latex Environment
2151 (defconst org-element--latex-begin-environment
2152 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2153 "Regexp matching the beginning of a LaTeX environment.
2154 The environment is captured by the first group.
2156 See also `org-element--latex-end-environment'.")
2158 (defconst org-element--latex-end-environment
2159 "\\\\end{%s}[ \t]*$"
2160 "Format string matching the ending of a LaTeX environment.
2161 See also `org-element--latex-begin-environment'.")
2163 (defun org-element-latex-environment-parser (limit affiliated)
2164 "Parse a LaTeX environment.
2166 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2167 the buffer position at the beginning of the first affiliated
2168 keyword and CDR is a plist of affiliated keywords along with
2169 their value.
2171 Return a list whose CAR is `latex-environment' and CDR is a plist
2172 containing `:begin', `:end', `:value', `:post-blank' and
2173 `:post-affiliated' keywords.
2175 Assume point is at the beginning of the latex environment."
2176 (save-excursion
2177 (let ((case-fold-search t)
2178 (code-begin (point)))
2179 (looking-at org-element--latex-begin-environment)
2180 (if (not (re-search-forward (format org-element--latex-end-environment
2181 (regexp-quote (match-string 1)))
2182 limit t))
2183 ;; Incomplete latex environment: parse it as a paragraph.
2184 (org-element-paragraph-parser limit affiliated)
2185 (let* ((code-end (progn (forward-line) (point)))
2186 (begin (car affiliated))
2187 (value (buffer-substring-no-properties code-begin code-end))
2188 (end (progn (skip-chars-forward " \r\t\n" limit)
2189 (if (eobp) (point) (line-beginning-position)))))
2190 (list 'latex-environment
2191 (nconc
2192 (list :begin begin
2193 :end end
2194 :value value
2195 :post-blank (count-lines code-end end)
2196 :post-affiliated code-begin)
2197 (cdr affiliated))))))))
2199 (defun org-element-latex-environment-interpreter (latex-environment _)
2200 "Interpret LATEX-ENVIRONMENT element as Org syntax."
2201 (org-element-property :value latex-environment))
2204 ;;;; Node Property
2206 (defun org-element-node-property-parser (limit)
2207 "Parse a node-property at point.
2209 LIMIT bounds the search.
2211 Return a list whose CAR is `node-property' and CDR is a plist
2212 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2213 `:post-affiliated' keywords."
2214 (looking-at org-property-re)
2215 (let ((case-fold-search t)
2216 (begin (point))
2217 (key (match-string-no-properties 2))
2218 (value (match-string-no-properties 3))
2219 (end (save-excursion
2220 (end-of-line)
2221 (if (re-search-forward org-property-re limit t)
2222 (line-beginning-position)
2223 limit))))
2224 (list 'node-property
2225 (list :key key
2226 :value value
2227 :begin begin
2228 :end end
2229 :post-blank 0
2230 :post-affiliated begin))))
2232 (defun org-element-node-property-interpreter (node-property _)
2233 "Interpret NODE-PROPERTY element as Org syntax."
2234 (format org-property-format
2235 (format ":%s:" (org-element-property :key node-property))
2236 (or (org-element-property :value node-property) "")))
2239 ;;;; Paragraph
2241 (defun org-element-paragraph-parser (limit affiliated)
2242 "Parse a paragraph.
2244 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2245 the buffer position at the beginning of the first affiliated
2246 keyword and CDR is a plist of affiliated keywords along with
2247 their value.
2249 Return a list whose CAR is `paragraph' and CDR is a plist
2250 containing `:begin', `:end', `:contents-begin' and
2251 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2253 Assume point is at the beginning of the paragraph."
2254 (save-excursion
2255 (let* ((begin (car affiliated))
2256 (contents-begin (point))
2257 (before-blank
2258 (let ((case-fold-search t))
2259 (end-of-line)
2260 ;; A matching `org-element-paragraph-separate' is not
2261 ;; necessarily the end of the paragraph. In particular,
2262 ;; drawers, blocks or LaTeX environments opening lines
2263 ;; must be closed. Moreover keywords with a secondary
2264 ;; value must belong to "dual keywords".
2265 (while (not
2266 (cond
2267 ((not (and (re-search-forward
2268 org-element-paragraph-separate limit 'move)
2269 (progn (beginning-of-line) t))))
2270 ((looking-at org-drawer-regexp)
2271 (save-excursion
2272 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2273 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2274 (save-excursion
2275 (re-search-forward
2276 (format "^[ \t]*#\\+END_%s[ \t]*$"
2277 (regexp-quote (match-string 1)))
2278 limit t)))
2279 ((looking-at org-element--latex-begin-environment)
2280 (save-excursion
2281 (re-search-forward
2282 (format org-element--latex-end-environment
2283 (regexp-quote (match-string 1)))
2284 limit t)))
2285 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2286 (member-ignore-case (match-string 1)
2287 org-element-dual-keywords))
2288 ;; Everything else is unambiguous.
2289 (t)))
2290 (end-of-line))
2291 (if (= (point) limit) limit
2292 (goto-char (line-beginning-position)))))
2293 (contents-end (save-excursion
2294 (skip-chars-backward " \r\t\n" contents-begin)
2295 (line-beginning-position 2)))
2296 (end (progn (skip-chars-forward " \r\t\n" limit)
2297 (if (eobp) (point) (line-beginning-position)))))
2298 (list 'paragraph
2299 (nconc
2300 (list :begin begin
2301 :end end
2302 :contents-begin contents-begin
2303 :contents-end contents-end
2304 :post-blank (count-lines before-blank end)
2305 :post-affiliated contents-begin)
2306 (cdr affiliated))))))
2308 (defun org-element-paragraph-interpreter (_ contents)
2309 "Interpret paragraph element as Org syntax.
2310 CONTENTS is the contents of the element."
2311 contents)
2314 ;;;; Planning
2316 (defun org-element-planning-parser (limit)
2317 "Parse a planning.
2319 LIMIT bounds the search.
2321 Return a list whose CAR is `planning' and CDR is a plist
2322 containing `:closed', `:deadline', `:scheduled', `:begin',
2323 `:end', `:post-blank' and `:post-affiliated' keywords."
2324 (save-excursion
2325 (let* ((case-fold-search nil)
2326 (begin (point))
2327 (post-blank (let ((before-blank (progn (forward-line) (point))))
2328 (skip-chars-forward " \r\t\n" limit)
2329 (skip-chars-backward " \t")
2330 (unless (bolp) (end-of-line))
2331 (count-lines before-blank (point))))
2332 (end (point))
2333 closed deadline scheduled)
2334 (goto-char begin)
2335 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2336 (goto-char (match-end 1))
2337 (skip-chars-forward " \t" end)
2338 (let ((keyword (match-string 1))
2339 (time (org-element-timestamp-parser)))
2340 (cond ((equal keyword org-closed-string) (setq closed time))
2341 ((equal keyword org-deadline-string) (setq deadline time))
2342 (t (setq scheduled time)))))
2343 (list 'planning
2344 (list :closed closed
2345 :deadline deadline
2346 :scheduled scheduled
2347 :begin begin
2348 :end end
2349 :post-blank post-blank
2350 :post-affiliated begin)))))
2352 (defun org-element-planning-interpreter (planning _)
2353 "Interpret PLANNING element as Org syntax."
2354 (mapconcat
2355 #'identity
2356 (delq nil
2357 (list (let ((deadline (org-element-property :deadline planning)))
2358 (when deadline
2359 (concat org-deadline-string " "
2360 (org-element-timestamp-interpreter deadline nil))))
2361 (let ((scheduled (org-element-property :scheduled planning)))
2362 (when scheduled
2363 (concat org-scheduled-string " "
2364 (org-element-timestamp-interpreter scheduled nil))))
2365 (let ((closed (org-element-property :closed planning)))
2366 (when closed
2367 (concat org-closed-string " "
2368 (org-element-timestamp-interpreter closed nil))))))
2369 " "))
2372 ;;;; Src Block
2374 (defun org-element-src-block-parser (limit affiliated)
2375 "Parse a src block.
2377 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2378 the buffer position at the beginning of the first affiliated
2379 keyword and CDR is a plist of affiliated keywords along with
2380 their value.
2382 Return a list whose CAR is `src-block' and CDR is a plist
2383 containing `:language', `:switches', `:parameters', `:begin',
2384 `:end', `:number-lines', `:retain-labels', `:use-labels',
2385 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2386 `:post-affiliated' keywords.
2388 Assume point is at the beginning of the block."
2389 (let ((case-fold-search t))
2390 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2391 limit t)))
2392 ;; Incomplete block: parse it as a paragraph.
2393 (org-element-paragraph-parser limit affiliated)
2394 (let ((contents-end (match-beginning 0)))
2395 (save-excursion
2396 (let* ((begin (car affiliated))
2397 (post-affiliated (point))
2398 ;; Get language as a string.
2399 (language
2400 (progn
2401 (looking-at
2402 "^[ \t]*#\\+BEGIN_SRC\
2403 \\(?: +\\(\\S-+\\)\\)?\
2404 \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
2405 \\(.*\\)[ \t]*$")
2406 (match-string-no-properties 1)))
2407 ;; Get switches.
2408 (switches (match-string-no-properties 2))
2409 ;; Get parameters.
2410 (parameters (match-string-no-properties 3))
2411 ;; Switches analysis.
2412 (number-lines
2413 (and switches
2414 (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
2415 switches)
2416 (cons
2417 (if (equal (match-string 1 switches) "-")
2418 'new
2419 'continued)
2420 (if (not (match-end 2)) 0
2421 ;; Subtract 1 to give number of lines before
2422 ;; first line.
2423 (1- (string-to-number (match-string 2 switches)))))))
2424 (preserve-indent (and switches
2425 (string-match "-i\\>" switches)))
2426 (label-fmt
2427 (and switches
2428 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2429 (match-string 1 switches)))
2430 ;; Should labels be retained in (or stripped from)
2431 ;; src blocks?
2432 (retain-labels
2433 (or (not switches)
2434 (not (string-match "-r\\>" switches))
2435 (and number-lines (string-match "-k\\>" switches))))
2436 ;; What should code-references use - labels or
2437 ;; line-numbers?
2438 (use-labels
2439 (or (not switches)
2440 (and retain-labels
2441 (not (string-match "-k\\>" switches)))))
2442 ;; Retrieve code.
2443 (value (org-unescape-code-in-string
2444 (buffer-substring-no-properties
2445 (line-beginning-position 2) contents-end)))
2446 (pos-before-blank (progn (goto-char contents-end)
2447 (forward-line)
2448 (point)))
2449 ;; Get position after ending blank lines.
2450 (end (progn (skip-chars-forward " \r\t\n" limit)
2451 (if (eobp) (point) (line-beginning-position)))))
2452 (list 'src-block
2453 (nconc
2454 (list :language language
2455 :switches (and (org-string-nw-p switches)
2456 (org-trim switches))
2457 :parameters (and (org-string-nw-p parameters)
2458 (org-trim parameters))
2459 :begin begin
2460 :end end
2461 :number-lines number-lines
2462 :preserve-indent preserve-indent
2463 :retain-labels retain-labels
2464 :use-labels use-labels
2465 :label-fmt label-fmt
2466 :value value
2467 :post-blank (count-lines pos-before-blank end)
2468 :post-affiliated post-affiliated)
2469 (cdr affiliated)))))))))
2471 (defun org-element-src-block-interpreter (src-block _)
2472 "Interpret SRC-BLOCK element as Org syntax."
2473 (let ((lang (org-element-property :language src-block))
2474 (switches (org-element-property :switches src-block))
2475 (params (org-element-property :parameters src-block))
2476 (value
2477 (let ((val (org-element-property :value src-block)))
2478 (cond
2479 ((or org-src-preserve-indentation
2480 (org-element-property :preserve-indent src-block))
2481 val)
2482 ((zerop org-edit-src-content-indentation)
2483 (org-remove-indentation val))
2485 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2486 (replace-regexp-in-string
2487 "^" ind (org-remove-indentation val))))))))
2488 (concat (format "#+BEGIN_SRC%s\n"
2489 (concat (and lang (concat " " lang))
2490 (and switches (concat " " switches))
2491 (and params (concat " " params))))
2492 (org-element-normalize-string (org-escape-code-in-string value))
2493 "#+END_SRC")))
2496 ;;;; Table
2498 (defun org-element-table-parser (limit affiliated)
2499 "Parse a table at point.
2501 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2502 the buffer position at the beginning of the first affiliated
2503 keyword and CDR is a plist of affiliated keywords along with
2504 their value.
2506 Return a list whose CAR is `table' and CDR is a plist containing
2507 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2508 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2509 keywords.
2511 Assume point is at the beginning of the table."
2512 (save-excursion
2513 (let* ((case-fold-search t)
2514 (table-begin (point))
2515 (type (if (looking-at "[ \t]*|") 'org 'table.el))
2516 (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
2517 (if (eq type 'org) "" "+")))
2518 (begin (car affiliated))
2519 (table-end
2520 (if (re-search-forward end-re limit 'move)
2521 (goto-char (match-beginning 0))
2522 (point)))
2523 (tblfm (let (acc)
2524 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2525 (push (match-string-no-properties 1) acc)
2526 (forward-line))
2527 acc))
2528 (pos-before-blank (point))
2529 (end (progn (skip-chars-forward " \r\t\n" limit)
2530 (if (eobp) (point) (line-beginning-position)))))
2531 (list 'table
2532 (nconc
2533 (list :begin begin
2534 :end end
2535 :type type
2536 :tblfm tblfm
2537 ;; Only `org' tables have contents. `table.el' tables
2538 ;; use a `:value' property to store raw table as
2539 ;; a string.
2540 :contents-begin (and (eq type 'org) table-begin)
2541 :contents-end (and (eq type 'org) table-end)
2542 :value (and (eq type 'table.el)
2543 (buffer-substring-no-properties
2544 table-begin table-end))
2545 :post-blank (count-lines pos-before-blank end)
2546 :post-affiliated table-begin)
2547 (cdr affiliated))))))
2549 (defun org-element-table-interpreter (table contents)
2550 "Interpret TABLE element as Org syntax.
2551 CONTENTS is a string, if table's type is `org', or nil."
2552 (if (eq (org-element-property :type table) 'table.el)
2553 (org-remove-indentation (org-element-property :value table))
2554 (concat (with-temp-buffer (insert contents)
2555 (org-table-align)
2556 (buffer-string))
2557 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2558 (reverse (org-element-property :tblfm table))
2559 "\n"))))
2562 ;;;; Table Row
2564 (defun org-element-table-row-parser (_)
2565 "Parse table row at point.
2567 Return a list whose CAR is `table-row' and CDR is a plist
2568 containing `:begin', `:end', `:contents-begin', `:contents-end',
2569 `:type', `:post-blank' and `:post-affiliated' keywords."
2570 (save-excursion
2571 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2572 (begin (point))
2573 ;; A table rule has no contents. In that case, ensure
2574 ;; CONTENTS-BEGIN matches CONTENTS-END.
2575 (contents-begin (and (eq type 'standard) (search-forward "|")))
2576 (contents-end (and (eq type 'standard)
2577 (progn
2578 (end-of-line)
2579 (skip-chars-backward " \t")
2580 (point))))
2581 (end (line-beginning-position 2)))
2582 (list 'table-row
2583 (list :type type
2584 :begin begin
2585 :end end
2586 :contents-begin contents-begin
2587 :contents-end contents-end
2588 :post-blank 0
2589 :post-affiliated begin)))))
2591 (defun org-element-table-row-interpreter (table-row contents)
2592 "Interpret TABLE-ROW element as Org syntax.
2593 CONTENTS is the contents of the table row."
2594 (if (eq (org-element-property :type table-row) 'rule) "|-"
2595 (concat "|" contents)))
2598 ;;;; Verse Block
2600 (defun org-element-verse-block-parser (limit affiliated)
2601 "Parse a verse block.
2603 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2604 the buffer position at the beginning of the first affiliated
2605 keyword and CDR is a plist of affiliated keywords along with
2606 their value.
2608 Return a list whose CAR is `verse-block' and CDR is a plist
2609 containing `:begin', `:end', `:contents-begin', `:contents-end',
2610 `:post-blank' and `:post-affiliated' keywords.
2612 Assume point is at beginning of the block."
2613 (let ((case-fold-search t))
2614 (if (not (save-excursion
2615 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2616 ;; Incomplete block: parse it as a paragraph.
2617 (org-element-paragraph-parser limit affiliated)
2618 (let ((contents-end (match-beginning 0)))
2619 (save-excursion
2620 (let* ((begin (car affiliated))
2621 (post-affiliated (point))
2622 (contents-begin (progn (forward-line) (point)))
2623 (pos-before-blank (progn (goto-char contents-end)
2624 (forward-line)
2625 (point)))
2626 (end (progn (skip-chars-forward " \r\t\n" limit)
2627 (if (eobp) (point) (line-beginning-position)))))
2628 (list 'verse-block
2629 (nconc
2630 (list :begin begin
2631 :end end
2632 :contents-begin contents-begin
2633 :contents-end contents-end
2634 :post-blank (count-lines pos-before-blank end)
2635 :post-affiliated post-affiliated)
2636 (cdr affiliated)))))))))
2638 (defun org-element-verse-block-interpreter (_ contents)
2639 "Interpret verse-block element as Org syntax.
2640 CONTENTS is verse block contents."
2641 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2645 ;;; Objects
2647 ;; Unlike to elements, raw text can be found between objects. Hence,
2648 ;; `org-element--object-lex' is provided to find the next object in
2649 ;; buffer.
2651 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2652 ;; object types they can contain will be specified in
2653 ;; `org-element-object-restrictions'.
2655 ;; Creating a new type of object requires to alter
2656 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2657 ;; new type in `org-element-all-objects', and possibly add
2658 ;; restrictions in `org-element-object-restrictions'.
2660 ;;;; Bold
2662 (defun org-element-bold-parser ()
2663 "Parse bold object at point, if any.
2665 When at a bold object, return a list whose car is `bold' and cdr
2666 is a plist with `:begin', `:end', `:contents-begin' and
2667 `:contents-end' and `:post-blank' keywords. Otherwise, return
2668 nil.
2670 Assume point is at the first star marker."
2671 (save-excursion
2672 (unless (bolp) (backward-char 1))
2673 (when (looking-at org-emph-re)
2674 (let ((begin (match-beginning 2))
2675 (contents-begin (match-beginning 4))
2676 (contents-end (match-end 4))
2677 (post-blank (progn (goto-char (match-end 2))
2678 (skip-chars-forward " \t")))
2679 (end (point)))
2680 (list 'bold
2681 (list :begin begin
2682 :end end
2683 :contents-begin contents-begin
2684 :contents-end contents-end
2685 :post-blank post-blank))))))
2687 (defun org-element-bold-interpreter (_ contents)
2688 "Interpret bold object as Org syntax.
2689 CONTENTS is the contents of the object."
2690 (format "*%s*" contents))
2693 ;;;; Code
2695 (defun org-element-code-parser ()
2696 "Parse code object at point, if any.
2698 When at a code object, return a list whose car is `code' and cdr
2699 is a plist with `:value', `:begin', `:end' and `:post-blank'
2700 keywords. Otherwise, return nil.
2702 Assume point is at the first tilde marker."
2703 (save-excursion
2704 (unless (bolp) (backward-char 1))
2705 (when (looking-at org-verbatim-re)
2706 (let ((begin (match-beginning 2))
2707 (value (match-string-no-properties 4))
2708 (post-blank (progn (goto-char (match-end 2))
2709 (skip-chars-forward " \t")))
2710 (end (point)))
2711 (list 'code
2712 (list :value value
2713 :begin begin
2714 :end end
2715 :post-blank post-blank))))))
2717 (defun org-element-code-interpreter (code _)
2718 "Interpret CODE object as Org syntax."
2719 (format "~%s~" (org-element-property :value code)))
2722 ;;;; Entity
2724 (defun org-element-entity-parser ()
2725 "Parse entity at point, if any.
2727 When at an entity, return a list whose car is `entity' and cdr
2728 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2729 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2730 `:post-blank' as keywords. Otherwise, return nil.
2732 Assume point is at the beginning of the entity."
2733 (catch 'no-object
2734 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2735 (save-excursion
2736 (let* ((value (or (org-entity-get (match-string 1))
2737 (throw 'no-object nil)))
2738 (begin (match-beginning 0))
2739 (bracketsp (string= (match-string 2) "{}"))
2740 (post-blank (progn (goto-char (match-end 1))
2741 (when bracketsp (forward-char 2))
2742 (skip-chars-forward " \t")))
2743 (end (point)))
2744 (list 'entity
2745 (list :name (car value)
2746 :latex (nth 1 value)
2747 :latex-math-p (nth 2 value)
2748 :html (nth 3 value)
2749 :ascii (nth 4 value)
2750 :latin1 (nth 5 value)
2751 :utf-8 (nth 6 value)
2752 :begin begin
2753 :end end
2754 :use-brackets-p bracketsp
2755 :post-blank post-blank)))))))
2757 (defun org-element-entity-interpreter (entity _)
2758 "Interpret ENTITY object as Org syntax."
2759 (concat "\\"
2760 (org-element-property :name entity)
2761 (when (org-element-property :use-brackets-p entity) "{}")))
2764 ;;;; Export Snippet
2766 (defun org-element-export-snippet-parser ()
2767 "Parse export snippet at point.
2769 When at an export snippet, return a list whose car is
2770 `export-snippet' and cdr a plist with `:begin', `:end',
2771 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2772 return nil.
2774 Assume point is at the beginning of the snippet."
2775 (save-excursion
2776 (let (contents-end)
2777 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2778 (setq contents-end
2779 (save-match-data (goto-char (match-end 0))
2780 (re-search-forward "@@" nil t)
2781 (match-beginning 0))))
2782 (let* ((begin (match-beginning 0))
2783 (back-end (match-string-no-properties 1))
2784 (value (buffer-substring-no-properties
2785 (match-end 0) contents-end))
2786 (post-blank (skip-chars-forward " \t"))
2787 (end (point)))
2788 (list 'export-snippet
2789 (list :back-end back-end
2790 :value value
2791 :begin begin
2792 :end end
2793 :post-blank post-blank)))))))
2795 (defun org-element-export-snippet-interpreter (export-snippet _)
2796 "Interpret EXPORT-SNIPPET object as Org syntax."
2797 (format "@@%s:%s@@"
2798 (org-element-property :back-end export-snippet)
2799 (org-element-property :value export-snippet)))
2802 ;;;; Footnote Reference
2804 (defun org-element-footnote-reference-parser ()
2805 "Parse footnote reference at point, if any.
2807 When at a footnote reference, return a list whose car is
2808 `footnote-reference' and cdr a plist with `:label', `:type',
2809 `:begin', `:end', `:content-begin', `:contents-end' and
2810 `:post-blank' as keywords. Otherwise, return nil."
2811 (when (looking-at org-footnote-re)
2812 (let ((closing (with-syntax-table org-element--pair-square-table
2813 (ignore-errors (scan-lists (point) 1 0)))))
2814 (when closing
2815 (save-excursion
2816 (let* ((begin (point))
2817 (label (match-string-no-properties 1))
2818 (inner-begin (match-end 0))
2819 (inner-end (1- closing))
2820 (type (if (match-end 2) 'inline 'standard))
2821 (post-blank (progn (goto-char closing)
2822 (skip-chars-forward " \t")))
2823 (end (point)))
2824 (list 'footnote-reference
2825 (list :label label
2826 :type type
2827 :begin begin
2828 :end end
2829 :contents-begin (and (eq type 'inline) inner-begin)
2830 :contents-end (and (eq type 'inline) inner-end)
2831 :post-blank post-blank))))))))
2833 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2834 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2835 CONTENTS is its definition, when inline, or nil."
2836 (format "[fn:%s%s]"
2837 (or (org-element-property :label footnote-reference) "")
2838 (if contents (concat ":" contents) "")))
2841 ;;;; Inline Babel Call
2843 (defun org-element-inline-babel-call-parser ()
2844 "Parse inline babel call at point, if any.
2846 When at an inline babel call, return a list whose car is
2847 `inline-babel-call' and cdr a plist with `:call',
2848 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2849 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2851 Assume point is at the beginning of the babel call."
2852 (save-excursion
2853 (catch :no-object
2854 (when (let ((case-fold-search nil))
2855 (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
2856 (goto-char (match-end 1))
2857 (let* ((begin (match-beginning 0))
2858 (call (match-string-no-properties 1))
2859 (inside-header
2860 (let ((p (org-element--parse-paired-brackets ?\[)))
2861 (and (org-string-nw-p p)
2862 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2863 (arguments (org-string-nw-p
2864 (or (org-element--parse-paired-brackets ?\()
2865 ;; Parenthesis are mandatory.
2866 (throw :no-object nil))))
2867 (end-header
2868 (let ((p (org-element--parse-paired-brackets ?\[)))
2869 (and (org-string-nw-p p)
2870 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2871 (value (buffer-substring-no-properties begin (point)))
2872 (post-blank (skip-chars-forward " \t"))
2873 (end (point)))
2874 (list 'inline-babel-call
2875 (list :call call
2876 :inside-header inside-header
2877 :arguments arguments
2878 :end-header end-header
2879 :begin begin
2880 :end end
2881 :value value
2882 :post-blank post-blank)))))))
2884 (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
2885 "Interpret INLINE-BABEL-CALL object as Org syntax."
2886 (concat "call_"
2887 (org-element-property :call inline-babel-call)
2888 (let ((h (org-element-property :inside-header inline-babel-call)))
2889 (and h (format "[%s]" h)))
2890 "(" (org-element-property :arguments inline-babel-call) ")"
2891 (let ((h (org-element-property :end-header inline-babel-call)))
2892 (and h (format "[%s]" h)))))
2895 ;;;; Inline Src Block
2897 (defun org-element-inline-src-block-parser ()
2898 "Parse inline source block at point, if any.
2900 When at an inline source block, return a list whose car is
2901 `inline-src-block' and cdr a plist with `:begin', `:end',
2902 `:language', `:value', `:parameters' and `:post-blank' as
2903 keywords. Otherwise, return nil.
2905 Assume point is at the beginning of the inline src block."
2906 (save-excursion
2907 (catch :no-object
2908 (when (let ((case-fold-search nil))
2909 (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
2910 (goto-char (match-end 1))
2911 (let ((begin (match-beginning 0))
2912 (language (match-string-no-properties 1))
2913 (parameters
2914 (let ((p (org-element--parse-paired-brackets ?\[)))
2915 (and (org-string-nw-p p)
2916 (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
2917 (value (or (org-element--parse-paired-brackets ?\{)
2918 (throw :no-object nil)))
2919 (post-blank (skip-chars-forward " \t")))
2920 (list 'inline-src-block
2921 (list :language language
2922 :value value
2923 :parameters parameters
2924 :begin begin
2925 :end (point)
2926 :post-blank post-blank)))))))
2928 (defun org-element-inline-src-block-interpreter (inline-src-block _)
2929 "Interpret INLINE-SRC-BLOCK object as Org syntax."
2930 (let ((language (org-element-property :language inline-src-block))
2931 (arguments (org-element-property :parameters inline-src-block))
2932 (body (org-element-property :value inline-src-block)))
2933 (format "src_%s%s{%s}"
2934 language
2935 (if arguments (format "[%s]" arguments) "")
2936 body)))
2938 ;;;; Italic
2940 (defun org-element-italic-parser ()
2941 "Parse italic object at point, if any.
2943 When at an italic object, return a list whose car is `italic' and
2944 cdr is a plist with `:begin', `:end', `:contents-begin' and
2945 `:contents-end' and `:post-blank' keywords. Otherwise, return
2946 nil.
2948 Assume point is at the first slash marker."
2949 (save-excursion
2950 (unless (bolp) (backward-char 1))
2951 (when (looking-at org-emph-re)
2952 (let ((begin (match-beginning 2))
2953 (contents-begin (match-beginning 4))
2954 (contents-end (match-end 4))
2955 (post-blank (progn (goto-char (match-end 2))
2956 (skip-chars-forward " \t")))
2957 (end (point)))
2958 (list 'italic
2959 (list :begin begin
2960 :end end
2961 :contents-begin contents-begin
2962 :contents-end contents-end
2963 :post-blank post-blank))))))
2965 (defun org-element-italic-interpreter (_ contents)
2966 "Interpret italic object as Org syntax.
2967 CONTENTS is the contents of the object."
2968 (format "/%s/" contents))
2971 ;;;; Latex Fragment
2973 (defun org-element-latex-fragment-parser ()
2974 "Parse LaTeX fragment at point, if any.
2976 When at a LaTeX fragment, return a list whose car is
2977 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2978 and `:post-blank' as keywords. Otherwise, return nil.
2980 Assume point is at the beginning of the LaTeX fragment."
2981 (catch 'no-object
2982 (save-excursion
2983 (let* ((begin (point))
2984 (after-fragment
2985 (cond
2986 ((not (eq ?$ (char-after)))
2987 (pcase (char-after (1+ (point)))
2988 (?\( (search-forward "\\)" nil t))
2989 (?\[ (search-forward "\\]" nil t))
2991 ;; Macro.
2992 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
2993 \\|\\({[^{}\n]*}\\)\\)*")
2994 (match-end 0)))))
2995 ((eq ?$ (char-after (1+ (point))))
2996 (search-forward "$$" nil t 2))
2998 (and (not (eq ?$ (char-before)))
2999 (not (memq (char-after (1+ (point)))
3000 '(?\s ?\t ?\n ?, ?. ?\;)))
3001 (search-forward "$" nil t 2)
3002 (not (memq (char-before (match-beginning 0))
3003 '(?\s ?\t ?\n ?, ?.)))
3004 (looking-at-p
3005 "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
3006 (point)))))
3007 (post-blank
3008 (if (not after-fragment) (throw 'no-object nil)
3009 (goto-char after-fragment)
3010 (skip-chars-forward " \t")))
3011 (end (point)))
3012 (list 'latex-fragment
3013 (list :value (buffer-substring-no-properties begin after-fragment)
3014 :begin begin
3015 :end end
3016 :post-blank post-blank))))))
3018 (defun org-element-latex-fragment-interpreter (latex-fragment _)
3019 "Interpret LATEX-FRAGMENT object as Org syntax."
3020 (org-element-property :value latex-fragment))
3022 ;;;; Line Break
3024 (defun org-element-line-break-parser ()
3025 "Parse line break at point, if any.
3027 When at a line break, return a list whose car is `line-break',
3028 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3029 Otherwise, return nil.
3031 Assume point is at the beginning of the line break."
3032 (when (and (looking-at-p "\\\\\\\\[ \t]*$")
3033 (not (eq (char-before) ?\\)))
3034 (list 'line-break
3035 (list :begin (point)
3036 :end (line-beginning-position 2)
3037 :post-blank 0))))
3039 (defun org-element-line-break-interpreter (&rest _)
3040 "Interpret LINE-BREAK object as Org syntax."
3041 "\\\\\n")
3044 ;;;; Link
3046 (defun org-element-link-parser ()
3047 "Parse link at point, if any.
3049 When at a link, return a list whose car is `link' and cdr a plist
3050 with `:type', `:path', `:format', `:raw-link', `:application',
3051 `:search-option', `:begin', `:end', `:contents-begin',
3052 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3053 nil.
3055 Assume point is at the beginning of the link."
3056 (catch 'no-object
3057 (let ((begin (point))
3058 end contents-begin contents-end link-end post-blank path type format
3059 raw-link search-option application)
3060 (cond
3061 ;; Type 1: Text targeted from a radio target.
3062 ((and org-target-link-regexp
3063 (save-excursion (or (bolp) (backward-char))
3064 (looking-at org-target-link-regexp)))
3065 (setq type "radio")
3066 (setq format 'plain)
3067 (setq link-end (match-end 1))
3068 (setq path (match-string-no-properties 1))
3069 (setq contents-begin (match-beginning 1))
3070 (setq contents-end (match-end 1)))
3071 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3072 ((looking-at org-bracket-link-regexp)
3073 (setq format 'bracket)
3074 (setq contents-begin (match-beginning 3))
3075 (setq contents-end (match-end 3))
3076 (setq link-end (match-end 0))
3077 ;; RAW-LINK is the original link. Expand any
3078 ;; abbreviation in it.
3080 ;; Also treat any newline character and associated
3081 ;; indentation as a single space character. This is not
3082 ;; compatible with RFC 3986, which requires to ignore
3083 ;; them altogether. However, doing so would require
3084 ;; users to encode spaces on the fly when writing links
3085 ;; (e.g., insert [[shell:ls%20*.org]] instead of
3086 ;; [[shell:ls *.org]], which defeats Org's focus on
3087 ;; simplicity.
3088 (setq raw-link (org-link-expand-abbrev
3089 (replace-regexp-in-string
3090 "[ \t]*\n[ \t]*" " "
3091 (match-string-no-properties 1))))
3092 ;; Determine TYPE of link and set PATH accordingly. According
3093 ;; to RFC 3986, remove whitespaces from URI in external links.
3094 ;; In internal ones, treat indentation as a single space.
3095 (cond
3096 ;; File type.
3097 ((or (file-name-absolute-p raw-link)
3098 (string-match "\\`\\.\\.?/" raw-link))
3099 (setq type "file")
3100 (setq path raw-link))
3101 ;; Explicit type (http, irc, bbdb...).
3102 ((string-match org-link-types-re raw-link)
3103 (setq type (match-string 1 raw-link))
3104 (setq path (substring raw-link (match-end 0))))
3105 ;; Code-ref type: PATH is the name of the reference.
3106 ((and (string-match-p "\\`(" raw-link)
3107 (string-match-p ")\\'" raw-link))
3108 (setq type "coderef")
3109 (setq path (substring raw-link 1 -1)))
3110 ;; Custom-id type: PATH is the name of the custom id.
3111 ((= (string-to-char raw-link) ?#)
3112 (setq type "custom-id")
3113 (setq path (substring raw-link 1)))
3114 ;; Fuzzy type: Internal link either matches a target, an
3115 ;; headline name or nothing. PATH is the target or
3116 ;; headline's name.
3118 (setq type "fuzzy")
3119 (setq path raw-link))))
3120 ;; Type 3: Plain link, e.g., http://orgmode.org
3121 ((looking-at org-plain-link-re)
3122 (setq format 'plain)
3123 (setq raw-link (match-string-no-properties 0))
3124 (setq type (match-string-no-properties 1))
3125 (setq link-end (match-end 0))
3126 (setq path (match-string-no-properties 2)))
3127 ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
3128 ;; bracket links, follow RFC 3986 and remove any extra
3129 ;; whitespace in URI.
3130 ((looking-at org-angle-link-re)
3131 (setq format 'angle)
3132 (setq type (match-string-no-properties 1))
3133 (setq link-end (match-end 0))
3134 (setq raw-link
3135 (buffer-substring-no-properties
3136 (match-beginning 1) (match-end 2)))
3137 (setq path (replace-regexp-in-string
3138 "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
3139 (t (throw 'no-object nil)))
3140 ;; In any case, deduce end point after trailing white space from
3141 ;; LINK-END variable.
3142 (save-excursion
3143 (setq post-blank
3144 (progn (goto-char link-end) (skip-chars-forward " \t")))
3145 (setq end (point)))
3146 ;; Special "file" type link processing. Extract opening
3147 ;; application and search option, if any. Also normalize URI.
3148 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3149 (setq application (match-string 1 type) type "file")
3150 (when (string-match "::\\(.*\\)\\'" path)
3151 (setq search-option (match-string 1 path))
3152 (setq path (replace-match "" nil nil path)))
3153 (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
3154 ;; Translate link, if `org-link-translation-function' is set.
3155 (let ((trans (and (functionp org-link-translation-function)
3156 (funcall org-link-translation-function type path))))
3157 (when trans
3158 (setq type (car trans))
3159 (setq path (cdr trans))))
3160 (list 'link
3161 (list :type type
3162 :path path
3163 :format format
3164 :raw-link (or raw-link path)
3165 :application application
3166 :search-option search-option
3167 :begin begin
3168 :end end
3169 :contents-begin contents-begin
3170 :contents-end contents-end
3171 :post-blank post-blank)))))
3173 (defun org-element-link-interpreter (link contents)
3174 "Interpret LINK object as Org syntax.
3175 CONTENTS is the contents of the object, or nil."
3176 (let ((type (org-element-property :type link))
3177 (path (org-element-property :path link)))
3178 (if (string= type "radio") path
3179 (let ((fmt (pcase (org-element-property :format link)
3180 ;; Links with contents and internal links have to
3181 ;; use bracket syntax. Ignore `:format' in these
3182 ;; cases. This is also the default syntax when the
3183 ;; property is not defined, e.g., when the object
3184 ;; was crafted by the user.
3185 ((guard contents)
3186 (format "[[%%s][%s]]"
3187 ;; Since this is going to be used as
3188 ;; a format string, escape percent signs
3189 ;; in description.
3190 (replace-regexp-in-string "%" "%%" contents)))
3191 ((or `bracket
3192 `nil
3193 (guard (member type '("coderef" "custom-id" "fuzzy"))))
3194 "[[%s]]")
3195 ;; Otherwise, just obey to `:format'.
3196 (`angle "<%s>")
3197 (`plain "%s")
3198 (f (error "Wrong `:format' value: %s" f)))))
3199 (format fmt
3200 (pcase type
3201 ("coderef" (format "(%s)" path))
3202 ("custom-id" (concat "#" path))
3203 ("file"
3204 (let ((app (org-element-property :application link))
3205 (opt (org-element-property :search-option link)))
3206 (concat type (and app (concat "+" app)) ":"
3207 path
3208 (and opt (concat "::" opt)))))
3209 ("fuzzy" path)
3210 (_ (concat type ":" path))))))))
3213 ;;;; Macro
3215 (defun org-element-macro-parser ()
3216 "Parse macro at point, if any.
3218 When at a macro, return a list whose car is `macro' and cdr
3219 a plist with `:key', `:args', `:begin', `:end', `:value' and
3220 `:post-blank' as keywords. Otherwise, return nil.
3222 Assume point is at the macro."
3223 (save-excursion
3224 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3225 (let ((begin (point))
3226 (key (downcase (match-string-no-properties 1)))
3227 (value (match-string-no-properties 0))
3228 (post-blank (progn (goto-char (match-end 0))
3229 (skip-chars-forward " \t")))
3230 (end (point))
3231 (args (let ((args (match-string-no-properties 3)))
3232 (and args (org-macro-extract-arguments args)))))
3233 (list 'macro
3234 (list :key key
3235 :value value
3236 :args args
3237 :begin begin
3238 :end end
3239 :post-blank post-blank))))))
3241 (defun org-element-macro-interpreter (macro _)
3242 "Interpret MACRO object as Org syntax."
3243 (org-element-property :value macro))
3246 ;;;; Radio-target
3248 (defun org-element-radio-target-parser ()
3249 "Parse radio target at point, if any.
3251 When at a radio target, return a list whose car is `radio-target'
3252 and cdr a plist with `:begin', `:end', `:contents-begin',
3253 `:contents-end', `:value' and `:post-blank' as keywords.
3254 Otherwise, return nil.
3256 Assume point is at the radio target."
3257 (save-excursion
3258 (when (looking-at org-radio-target-regexp)
3259 (let ((begin (point))
3260 (contents-begin (match-beginning 1))
3261 (contents-end (match-end 1))
3262 (value (match-string-no-properties 1))
3263 (post-blank (progn (goto-char (match-end 0))
3264 (skip-chars-forward " \t")))
3265 (end (point)))
3266 (list 'radio-target
3267 (list :begin begin
3268 :end end
3269 :contents-begin contents-begin
3270 :contents-end contents-end
3271 :post-blank post-blank
3272 :value value))))))
3274 (defun org-element-radio-target-interpreter (_ contents)
3275 "Interpret target object as Org syntax.
3276 CONTENTS is the contents of the object."
3277 (concat "<<<" contents ">>>"))
3280 ;;;; Statistics Cookie
3282 (defun org-element-statistics-cookie-parser ()
3283 "Parse statistics cookie at point, if any.
3285 When at a statistics cookie, return a list whose car is
3286 `statistics-cookie', and cdr a plist with `:begin', `:end',
3287 `:value' and `:post-blank' keywords. Otherwise, return nil.
3289 Assume point is at the beginning of the statistics-cookie."
3290 (save-excursion
3291 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3292 (let* ((begin (point))
3293 (value (buffer-substring-no-properties
3294 (match-beginning 0) (match-end 0)))
3295 (post-blank (progn (goto-char (match-end 0))
3296 (skip-chars-forward " \t")))
3297 (end (point)))
3298 (list 'statistics-cookie
3299 (list :begin begin
3300 :end end
3301 :value value
3302 :post-blank post-blank))))))
3304 (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
3305 "Interpret STATISTICS-COOKIE object as Org syntax."
3306 (org-element-property :value statistics-cookie))
3309 ;;;; Strike-Through
3311 (defun org-element-strike-through-parser ()
3312 "Parse strike-through object at point, if any.
3314 When at a strike-through object, return a list whose car is
3315 `strike-through' and cdr is a plist with `:begin', `:end',
3316 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3317 Otherwise, return nil.
3319 Assume point is at the first plus sign marker."
3320 (save-excursion
3321 (unless (bolp) (backward-char 1))
3322 (when (looking-at org-emph-re)
3323 (let ((begin (match-beginning 2))
3324 (contents-begin (match-beginning 4))
3325 (contents-end (match-end 4))
3326 (post-blank (progn (goto-char (match-end 2))
3327 (skip-chars-forward " \t")))
3328 (end (point)))
3329 (list 'strike-through
3330 (list :begin begin
3331 :end end
3332 :contents-begin contents-begin
3333 :contents-end contents-end
3334 :post-blank post-blank))))))
3336 (defun org-element-strike-through-interpreter (_ contents)
3337 "Interpret strike-through object as Org syntax.
3338 CONTENTS is the contents of the object."
3339 (format "+%s+" contents))
3342 ;;;; Subscript
3344 (defun org-element-subscript-parser ()
3345 "Parse subscript at point, if any.
3347 When at a subscript object, return a list whose car is
3348 `subscript' and cdr a plist with `:begin', `:end',
3349 `:contents-begin', `:contents-end', `:use-brackets-p' and
3350 `:post-blank' as keywords. Otherwise, return nil.
3352 Assume point is at the underscore."
3353 (save-excursion
3354 (unless (bolp) (backward-char))
3355 (when (looking-at org-match-substring-regexp)
3356 (let ((bracketsp (match-beginning 4))
3357 (begin (match-beginning 2))
3358 (contents-begin (or (match-beginning 4)
3359 (match-beginning 3)))
3360 (contents-end (or (match-end 4) (match-end 3)))
3361 (post-blank (progn (goto-char (match-end 0))
3362 (skip-chars-forward " \t")))
3363 (end (point)))
3364 (list 'subscript
3365 (list :begin begin
3366 :end end
3367 :use-brackets-p bracketsp
3368 :contents-begin contents-begin
3369 :contents-end contents-end
3370 :post-blank post-blank))))))
3372 (defun org-element-subscript-interpreter (subscript contents)
3373 "Interpret SUBSCRIPT object as Org syntax.
3374 CONTENTS is the contents of the object."
3375 (format
3376 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3377 contents))
3380 ;;;; Superscript
3382 (defun org-element-superscript-parser ()
3383 "Parse superscript at point, if any.
3385 When at a superscript object, return a list whose car is
3386 `superscript' and cdr a plist with `:begin', `:end',
3387 `:contents-begin', `:contents-end', `:use-brackets-p' and
3388 `:post-blank' as keywords. Otherwise, return nil.
3390 Assume point is at the caret."
3391 (save-excursion
3392 (unless (bolp) (backward-char))
3393 (when (looking-at org-match-substring-regexp)
3394 (let ((bracketsp (match-beginning 4))
3395 (begin (match-beginning 2))
3396 (contents-begin (or (match-beginning 4)
3397 (match-beginning 3)))
3398 (contents-end (or (match-end 4) (match-end 3)))
3399 (post-blank (progn (goto-char (match-end 0))
3400 (skip-chars-forward " \t")))
3401 (end (point)))
3402 (list 'superscript
3403 (list :begin begin
3404 :end end
3405 :use-brackets-p bracketsp
3406 :contents-begin contents-begin
3407 :contents-end contents-end
3408 :post-blank post-blank))))))
3410 (defun org-element-superscript-interpreter (superscript contents)
3411 "Interpret SUPERSCRIPT object as Org syntax.
3412 CONTENTS is the contents of the object."
3413 (format
3414 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3415 contents))
3418 ;;;; Table Cell
3420 (defun org-element-table-cell-parser ()
3421 "Parse table cell at point.
3422 Return a list whose car is `table-cell' and cdr is a plist
3423 containing `:begin', `:end', `:contents-begin', `:contents-end'
3424 and `:post-blank' keywords."
3425 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3426 (let* ((begin (match-beginning 0))
3427 (end (match-end 0))
3428 (contents-begin (match-beginning 1))
3429 (contents-end (match-end 1)))
3430 (list 'table-cell
3431 (list :begin begin
3432 :end end
3433 :contents-begin contents-begin
3434 :contents-end contents-end
3435 :post-blank 0))))
3437 (defun org-element-table-cell-interpreter (_ contents)
3438 "Interpret table-cell element as Org syntax.
3439 CONTENTS is the contents of the cell, or nil."
3440 (concat " " contents " |"))
3443 ;;;; Target
3445 (defun org-element-target-parser ()
3446 "Parse target at point, if any.
3448 When at a target, return a list whose car is `target' and cdr
3449 a plist with `:begin', `:end', `:value' and `:post-blank' as
3450 keywords. Otherwise, return nil.
3452 Assume point is at the target."
3453 (save-excursion
3454 (when (looking-at org-target-regexp)
3455 (let ((begin (point))
3456 (value (match-string-no-properties 1))
3457 (post-blank (progn (goto-char (match-end 0))
3458 (skip-chars-forward " \t")))
3459 (end (point)))
3460 (list 'target
3461 (list :begin begin
3462 :end end
3463 :value value
3464 :post-blank post-blank))))))
3466 (defun org-element-target-interpreter (target _)
3467 "Interpret TARGET object as Org syntax."
3468 (format "<<%s>>" (org-element-property :value target)))
3471 ;;;; Timestamp
3473 (defconst org-element--timestamp-regexp
3474 (concat org-ts-regexp-both
3475 "\\|"
3476 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3477 "\\|"
3478 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3479 "Regexp matching any timestamp type object.")
3481 (defun org-element-timestamp-parser ()
3482 "Parse time stamp at point, if any.
3484 When at a time stamp, return a list whose car is `timestamp', and
3485 cdr a plist with `:type', `:raw-value', `:year-start',
3486 `:month-start', `:day-start', `:hour-start', `:minute-start',
3487 `:year-end', `:month-end', `:day-end', `:hour-end',
3488 `:minute-end', `:repeater-type', `:repeater-value',
3489 `:repeater-unit', `:warning-type', `:warning-value',
3490 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3491 Otherwise, return nil.
3493 Assume point is at the beginning of the timestamp."
3494 (when (looking-at-p org-element--timestamp-regexp)
3495 (save-excursion
3496 (let* ((begin (point))
3497 (activep (eq (char-after) ?<))
3498 (raw-value
3499 (progn
3500 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3501 (match-string-no-properties 0)))
3502 (date-start (match-string-no-properties 1))
3503 (date-end (match-string 3))
3504 (diaryp (match-beginning 2))
3505 (post-blank (progn (goto-char (match-end 0))
3506 (skip-chars-forward " \t")))
3507 (end (point))
3508 (time-range
3509 (and (not diaryp)
3510 (string-match
3511 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3512 date-start)
3513 (cons (string-to-number (match-string 2 date-start))
3514 (string-to-number (match-string 3 date-start)))))
3515 (type (cond (diaryp 'diary)
3516 ((and activep (or date-end time-range)) 'active-range)
3517 (activep 'active)
3518 ((or date-end time-range) 'inactive-range)
3519 (t 'inactive)))
3520 (repeater-props
3521 (and (not diaryp)
3522 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3523 raw-value)
3524 (list
3525 :repeater-type
3526 (let ((type (match-string 1 raw-value)))
3527 (cond ((equal "++" type) 'catch-up)
3528 ((equal ".+" type) 'restart)
3529 (t 'cumulate)))
3530 :repeater-value (string-to-number (match-string 2 raw-value))
3531 :repeater-unit
3532 (pcase (string-to-char (match-string 3 raw-value))
3533 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3534 (warning-props
3535 (and (not diaryp)
3536 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3537 (list
3538 :warning-type (if (match-string 1 raw-value) 'first 'all)
3539 :warning-value (string-to-number (match-string 2 raw-value))
3540 :warning-unit
3541 (pcase (string-to-char (match-string 3 raw-value))
3542 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
3543 year-start month-start day-start hour-start minute-start year-end
3544 month-end day-end hour-end minute-end)
3545 ;; Parse date-start.
3546 (unless diaryp
3547 (let ((date (org-parse-time-string date-start t)))
3548 (setq year-start (nth 5 date)
3549 month-start (nth 4 date)
3550 day-start (nth 3 date)
3551 hour-start (nth 2 date)
3552 minute-start (nth 1 date))))
3553 ;; Compute date-end. It can be provided directly in time-stamp,
3554 ;; or extracted from time range. Otherwise, it defaults to the
3555 ;; same values as date-start.
3556 (unless diaryp
3557 (let ((date (and date-end (org-parse-time-string date-end t))))
3558 (setq year-end (or (nth 5 date) year-start)
3559 month-end (or (nth 4 date) month-start)
3560 day-end (or (nth 3 date) day-start)
3561 hour-end (or (nth 2 date) (car time-range) hour-start)
3562 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3563 (list 'timestamp
3564 (nconc (list :type type
3565 :raw-value raw-value
3566 :year-start year-start
3567 :month-start month-start
3568 :day-start day-start
3569 :hour-start hour-start
3570 :minute-start minute-start
3571 :year-end year-end
3572 :month-end month-end
3573 :day-end day-end
3574 :hour-end hour-end
3575 :minute-end minute-end
3576 :begin begin
3577 :end end
3578 :post-blank post-blank)
3579 repeater-props
3580 warning-props))))))
3582 (defun org-element-timestamp-interpreter (timestamp _)
3583 "Interpret TIMESTAMP object as Org syntax."
3584 (let* ((repeat-string
3585 (concat
3586 (pcase (org-element-property :repeater-type timestamp)
3587 (`cumulate "+") (`catch-up "++") (`restart ".+"))
3588 (let ((val (org-element-property :repeater-value timestamp)))
3589 (and val (number-to-string val)))
3590 (pcase (org-element-property :repeater-unit timestamp)
3591 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3592 (warning-string
3593 (concat
3594 (pcase (org-element-property :warning-type timestamp)
3595 (`first "--") (`all "-"))
3596 (let ((val (org-element-property :warning-value timestamp)))
3597 (and val (number-to-string val)))
3598 (pcase (org-element-property :warning-unit timestamp)
3599 (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
3600 (build-ts-string
3601 ;; Build an Org timestamp string from TIME. ACTIVEP is
3602 ;; non-nil when time stamp is active. If WITH-TIME-P is
3603 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3604 ;; specify a time range in the timestamp. REPEAT-STRING is
3605 ;; the repeater string, if any.
3606 (lambda (time activep &optional with-time-p hour-end minute-end)
3607 (let ((ts (format-time-string
3608 (funcall (if with-time-p #'cdr #'car)
3609 org-time-stamp-formats)
3610 time)))
3611 (when (and hour-end minute-end)
3612 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3613 (setq ts
3614 (replace-match
3615 (format "\\&-%02d:%02d" hour-end minute-end)
3616 nil nil ts)))
3617 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3618 (dolist (s (list repeat-string warning-string))
3619 (when (org-string-nw-p s)
3620 (setq ts (concat (substring ts 0 -1)
3623 (substring ts -1)))))
3624 ;; Return value.
3625 ts)))
3626 (type (org-element-property :type timestamp)))
3627 (pcase type
3628 ((or `active `inactive)
3629 (let* ((minute-start (org-element-property :minute-start timestamp))
3630 (minute-end (org-element-property :minute-end timestamp))
3631 (hour-start (org-element-property :hour-start timestamp))
3632 (hour-end (org-element-property :hour-end timestamp))
3633 (time-range-p (and hour-start hour-end minute-start minute-end
3634 (or (/= hour-start hour-end)
3635 (/= minute-start minute-end)))))
3636 (funcall
3637 build-ts-string
3638 (encode-time 0
3639 (or minute-start 0)
3640 (or hour-start 0)
3641 (org-element-property :day-start timestamp)
3642 (org-element-property :month-start timestamp)
3643 (org-element-property :year-start timestamp))
3644 (eq type 'active)
3645 (and hour-start minute-start)
3646 (and time-range-p hour-end)
3647 (and time-range-p minute-end))))
3648 ((or `active-range `inactive-range)
3649 (let ((minute-start (org-element-property :minute-start timestamp))
3650 (minute-end (org-element-property :minute-end timestamp))
3651 (hour-start (org-element-property :hour-start timestamp))
3652 (hour-end (org-element-property :hour-end timestamp)))
3653 (concat
3654 (funcall
3655 build-ts-string (encode-time
3657 (or minute-start 0)
3658 (or hour-start 0)
3659 (org-element-property :day-start timestamp)
3660 (org-element-property :month-start timestamp)
3661 (org-element-property :year-start timestamp))
3662 (eq type 'active-range)
3663 (and hour-start minute-start))
3664 "--"
3665 (funcall build-ts-string
3666 (encode-time 0
3667 (or minute-end 0)
3668 (or hour-end 0)
3669 (org-element-property :day-end timestamp)
3670 (org-element-property :month-end timestamp)
3671 (org-element-property :year-end timestamp))
3672 (eq type 'active-range)
3673 (and hour-end minute-end)))))
3674 (_ (org-element-property :raw-value timestamp)))))
3677 ;;;; Underline
3679 (defun org-element-underline-parser ()
3680 "Parse underline object at point, if any.
3682 When at an underline object, return a list whose car is
3683 `underline' and cdr is a plist with `:begin', `:end',
3684 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3685 Otherwise, return nil.
3687 Assume point is at the first underscore marker."
3688 (save-excursion
3689 (unless (bolp) (backward-char 1))
3690 (when (looking-at org-emph-re)
3691 (let ((begin (match-beginning 2))
3692 (contents-begin (match-beginning 4))
3693 (contents-end (match-end 4))
3694 (post-blank (progn (goto-char (match-end 2))
3695 (skip-chars-forward " \t")))
3696 (end (point)))
3697 (list 'underline
3698 (list :begin begin
3699 :end end
3700 :contents-begin contents-begin
3701 :contents-end contents-end
3702 :post-blank post-blank))))))
3704 (defun org-element-underline-interpreter (_ contents)
3705 "Interpret underline object as Org syntax.
3706 CONTENTS is the contents of the object."
3707 (format "_%s_" contents))
3710 ;;;; Verbatim
3712 (defun org-element-verbatim-parser ()
3713 "Parse verbatim object at point, if any.
3715 When at a verbatim object, return a list whose car is `verbatim'
3716 and cdr is a plist with `:value', `:begin', `:end' and
3717 `:post-blank' keywords. Otherwise, return nil.
3719 Assume point is at the first equal sign marker."
3720 (save-excursion
3721 (unless (bolp) (backward-char 1))
3722 (when (looking-at org-verbatim-re)
3723 (let ((begin (match-beginning 2))
3724 (value (match-string-no-properties 4))
3725 (post-blank (progn (goto-char (match-end 2))
3726 (skip-chars-forward " \t")))
3727 (end (point)))
3728 (list 'verbatim
3729 (list :value value
3730 :begin begin
3731 :end end
3732 :post-blank post-blank))))))
3734 (defun org-element-verbatim-interpreter (verbatim _)
3735 "Interpret VERBATIM object as Org syntax."
3736 (format "=%s=" (org-element-property :value verbatim)))
3740 ;;; Parsing Element Starting At Point
3742 ;; `org-element--current-element' is the core function of this section.
3743 ;; It returns the Lisp representation of the element starting at
3744 ;; point.
3746 ;; `org-element--current-element' makes use of special modes. They
3747 ;; are activated for fixed element chaining (e.g., `plain-list' >
3748 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3749 ;; `section'). Special modes are: `first-section', `item',
3750 ;; `node-property', `section' and `table-row'.
3752 (defun org-element--current-element (limit &optional granularity mode structure)
3753 "Parse the element starting at point.
3755 Return value is a list like (TYPE PROPS) where TYPE is the type
3756 of the element and PROPS a plist of properties associated to the
3757 element.
3759 Possible types are defined in `org-element-all-elements'.
3761 LIMIT bounds the search.
3763 Optional argument GRANULARITY determines the depth of the
3764 recursion. Allowed values are `headline', `greater-element',
3765 `element', `object' or nil. When it is broader than `object' (or
3766 nil), secondary values will not be parsed, since they only
3767 contain objects.
3769 Optional argument MODE, when non-nil, can be either
3770 `first-section', `section', `planning', `item', `node-property'
3771 and `table-row'.
3773 If STRUCTURE isn't provided but MODE is set to `item', it will be
3774 computed.
3776 This function assumes point is always at the beginning of the
3777 element it has to parse."
3778 (save-excursion
3779 (let ((case-fold-search t)
3780 ;; Determine if parsing depth allows for secondary strings
3781 ;; parsing. It only applies to elements referenced in
3782 ;; `org-element-secondary-value-alist'.
3783 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3784 (cond
3785 ;; Item.
3786 ((eq mode 'item)
3787 (org-element-item-parser limit structure raw-secondary-p))
3788 ;; Table Row.
3789 ((eq mode 'table-row) (org-element-table-row-parser limit))
3790 ;; Node Property.
3791 ((eq mode 'node-property) (org-element-node-property-parser limit))
3792 ;; Headline.
3793 ((org-with-limited-levels (org-at-heading-p))
3794 (org-element-headline-parser limit raw-secondary-p))
3795 ;; Sections (must be checked after headline).
3796 ((eq mode 'section) (org-element-section-parser limit))
3797 ((eq mode 'first-section)
3798 (org-element-section-parser
3799 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3800 limit)))
3801 ;; Planning.
3802 ((and (eq mode 'planning)
3803 (eq ?* (char-after (line-beginning-position 0)))
3804 (looking-at org-planning-line-re))
3805 (org-element-planning-parser limit))
3806 ;; Property drawer.
3807 ((and (memq mode '(planning property-drawer))
3808 (eq ?* (char-after (line-beginning-position
3809 (if (eq mode 'planning) 0 -1))))
3810 (looking-at org-property-drawer-re))
3811 (org-element-property-drawer-parser limit))
3812 ;; When not at bol, point is at the beginning of an item or
3813 ;; a footnote definition: next item is always a paragraph.
3814 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3815 ;; Clock.
3816 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3817 ;; Inlinetask.
3818 ((org-at-heading-p)
3819 (org-element-inlinetask-parser limit raw-secondary-p))
3820 ;; From there, elements can have affiliated keywords.
3821 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3822 (cond
3823 ;; Jumping over affiliated keywords put point off-limits.
3824 ;; Parse them as regular keywords.
3825 ((and (cdr affiliated) (>= (point) limit))
3826 (goto-char (car affiliated))
3827 (org-element-keyword-parser limit nil))
3828 ;; LaTeX Environment.
3829 ((looking-at org-element--latex-begin-environment)
3830 (org-element-latex-environment-parser limit affiliated))
3831 ;; Drawer and Property Drawer.
3832 ((looking-at org-drawer-regexp)
3833 (org-element-drawer-parser limit affiliated))
3834 ;; Fixed Width
3835 ((looking-at "[ \t]*:\\( \\|$\\)")
3836 (org-element-fixed-width-parser limit affiliated))
3837 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3838 ;; Keywords.
3839 ((looking-at "[ \t]*#")
3840 (goto-char (match-end 0))
3841 (cond
3842 ((looking-at "\\(?: \\|$\\)")
3843 (beginning-of-line)
3844 (org-element-comment-parser limit affiliated))
3845 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3846 (beginning-of-line)
3847 (funcall (pcase (upcase (match-string 1))
3848 ("CENTER" #'org-element-center-block-parser)
3849 ("COMMENT" #'org-element-comment-block-parser)
3850 ("EXAMPLE" #'org-element-example-block-parser)
3851 ("EXPORT" #'org-element-export-block-parser)
3852 ("QUOTE" #'org-element-quote-block-parser)
3853 ("SRC" #'org-element-src-block-parser)
3854 ("VERSE" #'org-element-verse-block-parser)
3855 (_ #'org-element-special-block-parser))
3856 limit
3857 affiliated))
3858 ((looking-at "\\+CALL:")
3859 (beginning-of-line)
3860 (org-element-babel-call-parser limit affiliated))
3861 ((looking-at "\\+BEGIN:? ")
3862 (beginning-of-line)
3863 (org-element-dynamic-block-parser limit affiliated))
3864 ((looking-at "\\+\\S-+:")
3865 (beginning-of-line)
3866 (org-element-keyword-parser limit affiliated))
3868 (beginning-of-line)
3869 (org-element-paragraph-parser limit affiliated))))
3870 ;; Footnote Definition.
3871 ((looking-at org-footnote-definition-re)
3872 (org-element-footnote-definition-parser limit affiliated))
3873 ;; Horizontal Rule.
3874 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3875 (org-element-horizontal-rule-parser limit affiliated))
3876 ;; Diary Sexp.
3877 ((looking-at "%%(")
3878 (org-element-diary-sexp-parser limit affiliated))
3879 ;; Table.
3880 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3881 (org-element-table-parser limit affiliated))
3882 ;; List.
3883 ((looking-at (org-item-re))
3884 (org-element-plain-list-parser
3885 limit affiliated
3886 (or structure (org-element--list-struct limit))))
3887 ;; Default element: Paragraph.
3888 (t (org-element-paragraph-parser limit affiliated)))))))))
3891 ;; Most elements can have affiliated keywords. When looking for an
3892 ;; element beginning, we want to move before them, as they belong to
3893 ;; that element, and, in the meantime, collect information they give
3894 ;; into appropriate properties. Hence the following function.
3896 (defun org-element--collect-affiliated-keywords (limit)
3897 "Collect affiliated keywords from point down to LIMIT.
3899 Return a list whose CAR is the position at the first of them and
3900 CDR a plist of keywords and values and move point to the
3901 beginning of the first line after them.
3903 As a special case, if element doesn't start at the beginning of
3904 the line (e.g., a paragraph starting an item), CAR is current
3905 position of point and CDR is nil."
3906 (if (not (bolp)) (list (point))
3907 (let ((case-fold-search t)
3908 (origin (point))
3909 ;; RESTRICT is the list of objects allowed in parsed
3910 ;; keywords value.
3911 (restrict (org-element-restriction 'keyword))
3912 output)
3913 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3914 (let* ((raw-kwd (upcase (match-string 1)))
3915 ;; Apply translation to RAW-KWD. From there, KWD is
3916 ;; the official keyword.
3917 (kwd (or (cdr (assoc raw-kwd
3918 org-element-keyword-translation-alist))
3919 raw-kwd))
3920 ;; Find main value for any keyword.
3921 (value
3922 (save-match-data
3923 (org-trim
3924 (buffer-substring-no-properties
3925 (match-end 0) (line-end-position)))))
3926 ;; PARSEDP is non-nil when keyword should have its
3927 ;; value parsed.
3928 (parsedp (member kwd org-element-parsed-keywords))
3929 ;; If KWD is a dual keyword, find its secondary
3930 ;; value. Maybe parse it.
3931 (dualp (member kwd org-element-dual-keywords))
3932 (dual-value
3933 (and dualp
3934 (let ((sec (match-string-no-properties 2)))
3935 (if (or (not sec) (not parsedp)) sec
3936 (save-match-data
3937 (org-element--parse-objects
3938 (match-beginning 2) (match-end 2) nil restrict))))))
3939 ;; Attribute a property name to KWD.
3940 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3941 ;; Now set final shape for VALUE.
3942 (when parsedp
3943 (setq value
3944 (org-element--parse-objects
3945 (match-end 0)
3946 (progn (end-of-line) (skip-chars-backward " \t") (point))
3947 nil restrict)))
3948 (when dualp
3949 (setq value (and (or value dual-value) (cons value dual-value))))
3950 (when (or (member kwd org-element-multiple-keywords)
3951 ;; Attributes can always appear on multiple lines.
3952 (string-match "^ATTR_" kwd))
3953 (setq value (cons value (plist-get output kwd-sym))))
3954 ;; Eventually store the new value in OUTPUT.
3955 (setq output (plist-put output kwd-sym value))
3956 ;; Move to next keyword.
3957 (forward-line)))
3958 ;; If affiliated keywords are orphaned: move back to first one.
3959 ;; They will be parsed as a paragraph.
3960 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3961 ;; Return value.
3962 (cons origin output))))
3966 ;;; The Org Parser
3968 ;; The two major functions here are `org-element-parse-buffer', which
3969 ;; parses Org syntax inside the current buffer, taking into account
3970 ;; region, narrowing, or even visibility if specified, and
3971 ;; `org-element-parse-secondary-string', which parses objects within
3972 ;; a given string.
3974 ;; The (almost) almighty `org-element-map' allows applying a function
3975 ;; on elements or objects matching some type, and accumulating the
3976 ;; resulting values. In an export situation, it also skips unneeded
3977 ;; parts of the parse tree.
3979 (defun org-element-parse-buffer (&optional granularity visible-only)
3980 "Recursively parse the buffer and return structure.
3981 If narrowing is in effect, only parse the visible part of the
3982 buffer.
3984 Optional argument GRANULARITY determines the depth of the
3985 recursion. It can be set to the following symbols:
3987 `headline' Only parse headlines.
3988 `greater-element' Don't recurse into greater elements except
3989 headlines and sections. Thus, elements
3990 parsed are the top-level ones.
3991 `element' Parse everything but objects and plain text.
3992 `object' Parse the complete buffer (default).
3994 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3995 elements.
3997 An element or object is represented as a list with the
3998 pattern (TYPE PROPERTIES CONTENTS), where :
4000 TYPE is a symbol describing the element or object. See
4001 `org-element-all-elements' and `org-element-all-objects' for an
4002 exhaustive list of such symbols. One can retrieve it with
4003 `org-element-type' function.
4005 PROPERTIES is the list of attributes attached to the element or
4006 object, as a plist. Although most of them are specific to the
4007 element or object type, all types share `:begin', `:end',
4008 `:post-blank' and `:parent' properties, which respectively
4009 refer to buffer position where the element or object starts,
4010 ends, the number of white spaces or blank lines after it, and
4011 the element or object containing it. Properties values can be
4012 obtained by using `org-element-property' function.
4014 CONTENTS is a list of elements, objects or raw strings
4015 contained in the current element or object, when applicable.
4016 One can access them with `org-element-contents' function.
4018 The Org buffer has `org-data' as type and nil as properties.
4019 `org-element-map' function can be used to find specific elements
4020 or objects within the parse tree.
4022 This function assumes that current major mode is `org-mode'."
4023 (save-excursion
4024 (goto-char (point-min))
4025 (org-skip-whitespace)
4026 (org-element--parse-elements
4027 (point-at-bol) (point-max)
4028 ;; Start in `first-section' mode so text before the first
4029 ;; headline belongs to a section.
4030 'first-section nil granularity visible-only (list 'org-data nil))))
4032 (defun org-element-parse-secondary-string (string restriction &optional parent)
4033 "Recursively parse objects in STRING and return structure.
4035 RESTRICTION is a symbol limiting the object types that will be
4036 looked after.
4038 Optional argument PARENT, when non-nil, is the element or object
4039 containing the secondary string. It is used to set correctly
4040 `:parent' property within the string.
4042 If STRING is the empty string or nil, return nil."
4043 (cond
4044 ((not string) nil)
4045 ((equal string "") nil)
4046 (t (let ((local-variables (buffer-local-variables)))
4047 (with-temp-buffer
4048 (dolist (v local-variables)
4049 (ignore-errors
4050 (if (symbolp v) (makunbound v)
4051 (set (make-local-variable (car v)) (cdr v)))))
4052 (insert string)
4053 (restore-buffer-modified-p nil)
4054 (org-element--parse-objects
4055 (point-min) (point-max) nil restriction parent))))))
4057 (defun org-element-map
4058 (data types fun &optional info first-match no-recursion with-affiliated)
4059 "Map a function on selected elements or objects.
4061 DATA is a parse tree, an element, an object, a string, or a list
4062 of such constructs. TYPES is a symbol or list of symbols of
4063 elements or objects types (see `org-element-all-elements' and
4064 `org-element-all-objects' for a complete list of types). FUN is
4065 the function called on the matching element or object. It has to
4066 accept one argument: the element or object itself.
4068 When optional argument INFO is non-nil, it should be a plist
4069 holding export options. In that case, parts of the parse tree
4070 not exportable according to that property list will be skipped.
4072 When optional argument FIRST-MATCH is non-nil, stop at the first
4073 match for which FUN doesn't return nil, and return that value.
4075 Optional argument NO-RECURSION is a symbol or a list of symbols
4076 representing elements or objects types. `org-element-map' won't
4077 enter any recursive element or object whose type belongs to that
4078 list. Though, FUN can still be applied on them.
4080 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4081 apply to matching objects within parsed affiliated keywords (see
4082 `org-element-parsed-keywords').
4084 Nil values returned from FUN do not appear in the results.
4087 Examples:
4088 ---------
4090 Assuming TREE is a variable containing an Org buffer parse tree,
4091 the following example will return a flat list of all `src-block'
4092 and `example-block' elements in it:
4094 (org-element-map tree \\='(example-block src-block) #\\='identity)
4096 The following snippet will find the first headline with a level
4097 of 1 and a \"phone\" tag, and will return its beginning position:
4099 (org-element-map tree \\='headline
4100 (lambda (hl)
4101 (and (= (org-element-property :level hl) 1)
4102 (member \"phone\" (org-element-property :tags hl))
4103 (org-element-property :begin hl)))
4104 nil t)
4106 The next example will return a flat list of all `plain-list' type
4107 elements in TREE that are not a sub-list themselves:
4109 (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
4111 Eventually, this example will return a flat list of all `bold'
4112 type objects containing a `latex-snippet' type object, even
4113 looking into captions:
4115 (org-element-map tree \\='bold
4116 (lambda (b)
4117 (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
4118 nil nil nil t)"
4119 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4120 (let* ((types (if (listp types) types (list types)))
4121 (no-recursion (if (listp no-recursion) no-recursion
4122 (list no-recursion)))
4123 ;; Recursion depth is determined by --CATEGORY.
4124 (--category
4125 (catch :--found
4126 (let ((category 'greater-elements)
4127 (all-objects (cons 'plain-text org-element-all-objects)))
4128 (dolist (type types category)
4129 (cond ((memq type all-objects)
4130 ;; If one object is found, the function has
4131 ;; to recurse into every object.
4132 (throw :--found 'objects))
4133 ((not (memq type org-element-greater-elements))
4134 ;; If one regular element is found, the
4135 ;; function has to recurse, at least, into
4136 ;; every element it encounters.
4137 (and (not (eq category 'elements))
4138 (setq category 'elements))))))))
4139 --acc)
4140 (letrec ((--walk-tree
4141 (lambda (--data)
4142 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4143 ;; holding contextual information.
4144 (let ((--type (org-element-type --data)))
4145 (cond
4146 ((not --data))
4147 ;; Ignored element in an export context.
4148 ((and info (memq --data (plist-get info :ignore-list))))
4149 ;; List of elements or objects.
4150 ((not --type) (mapc --walk-tree --data))
4151 ;; Unconditionally enter parse trees.
4152 ((eq --type 'org-data)
4153 (mapc --walk-tree (org-element-contents --data)))
4155 ;; Check if TYPE is matching among TYPES. If so,
4156 ;; apply FUN to --DATA and accumulate return value
4157 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4158 (when (memq --type types)
4159 (let ((result (funcall fun --data)))
4160 (cond ((not result))
4161 (first-match (throw :--map-first-match result))
4162 (t (push result --acc)))))
4163 ;; If --DATA has a secondary string that can contain
4164 ;; objects with their type among TYPES, look inside.
4165 (when (and (eq --category 'objects) (not (stringp --data)))
4166 (dolist (p (cdr (assq --type
4167 org-element-secondary-value-alist)))
4168 (funcall --walk-tree (org-element-property p --data))))
4169 ;; If --DATA has any parsed affiliated keywords and
4170 ;; WITH-AFFILIATED is non-nil, look for objects in
4171 ;; them.
4172 (when (and with-affiliated
4173 (eq --category 'objects)
4174 (eq (org-element-class --data) 'element))
4175 (dolist (kwd-pair org-element--parsed-properties-alist)
4176 (let ((kwd (car kwd-pair))
4177 (value (org-element-property (cdr kwd-pair) --data)))
4178 ;; Pay attention to the type of parsed
4179 ;; keyword. In particular, preserve order for
4180 ;; multiple keywords.
4181 (cond
4182 ((not value))
4183 ((member kwd org-element-dual-keywords)
4184 (if (member kwd org-element-multiple-keywords)
4185 (dolist (line (reverse value))
4186 (funcall --walk-tree (cdr line))
4187 (funcall --walk-tree (car line)))
4188 (funcall --walk-tree (cdr value))
4189 (funcall --walk-tree (car value))))
4190 ((member kwd org-element-multiple-keywords)
4191 (mapc --walk-tree (reverse value)))
4192 (t (funcall --walk-tree value))))))
4193 ;; Determine if a recursion into --DATA is possible.
4194 (cond
4195 ;; --TYPE is explicitly removed from recursion.
4196 ((memq --type no-recursion))
4197 ;; --DATA has no contents.
4198 ((not (org-element-contents --data)))
4199 ;; Looking for greater elements but --DATA is
4200 ;; simply an element or an object.
4201 ((and (eq --category 'greater-elements)
4202 (not (memq --type org-element-greater-elements))))
4203 ;; Looking for elements but --DATA is an object.
4204 ((and (eq --category 'elements)
4205 (eq (org-element-class --data) 'object)))
4206 ;; In any other case, map contents.
4207 (t (mapc --walk-tree (org-element-contents --data))))))))))
4208 (catch :--map-first-match
4209 (funcall --walk-tree data)
4210 ;; Return value in a proper order.
4211 (nreverse --acc)))))
4212 (put 'org-element-map 'lisp-indent-function 2)
4214 ;; The following functions are internal parts of the parser.
4216 ;; The first one, `org-element--parse-elements' acts at the element's
4217 ;; level.
4219 ;; The second one, `org-element--parse-objects' applies on all objects
4220 ;; of a paragraph or a secondary string. It calls
4221 ;; `org-element--object-lex' to find the next object in the current
4222 ;; container.
4224 (defsubst org-element--next-mode (type parentp)
4225 "Return next special mode according to TYPE, or nil.
4226 TYPE is a symbol representing the type of an element or object
4227 containing next element if PARENTP is non-nil, or before it
4228 otherwise. Modes can be either `first-section', `item',
4229 `node-property', `planning', `property-drawer', `section',
4230 `table-row' or nil."
4231 (if parentp
4232 (pcase type
4233 (`headline 'section)
4234 (`inlinetask 'planning)
4235 (`plain-list 'item)
4236 (`property-drawer 'node-property)
4237 (`section 'planning)
4238 (`table 'table-row))
4239 (pcase type
4240 (`item 'item)
4241 (`node-property 'node-property)
4242 (`planning 'property-drawer)
4243 (`table-row 'table-row))))
4245 (defun org-element--parse-elements
4246 (beg end mode structure granularity visible-only acc)
4247 "Parse elements between BEG and END positions.
4249 MODE prioritizes some elements over the others. It can be set to
4250 `first-section', `section', `planning', `item', `node-property'
4251 or `table-row'.
4253 When value is `item', STRUCTURE will be used as the current list
4254 structure.
4256 GRANULARITY determines the depth of the recursion. See
4257 `org-element-parse-buffer' for more information.
4259 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4260 elements.
4262 Elements are accumulated into ACC."
4263 (save-excursion
4264 (goto-char beg)
4265 ;; Visible only: skip invisible parts at the beginning of the
4266 ;; element.
4267 (when (and visible-only (org-invisible-p2))
4268 (goto-char (min (1+ (org-find-visible)) end)))
4269 ;; When parsing only headlines, skip any text before first one.
4270 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4271 (org-with-limited-levels (outline-next-heading)))
4272 (let (elements)
4273 (while (< (point) end)
4274 ;; Find current element's type and parse it accordingly to
4275 ;; its category.
4276 (let* ((element (org-element--current-element
4277 end granularity mode structure))
4278 (type (org-element-type element))
4279 (cbeg (org-element-property :contents-begin element)))
4280 (goto-char (org-element-property :end element))
4281 ;; Visible only: skip invisible parts between siblings.
4282 (when (and visible-only (org-invisible-p2))
4283 (goto-char (min (1+ (org-find-visible)) end)))
4284 ;; Fill ELEMENT contents by side-effect.
4285 (cond
4286 ;; If element has no contents, don't modify it.
4287 ((not cbeg))
4288 ;; Greater element: parse it between `contents-begin' and
4289 ;; `contents-end'. Make sure GRANULARITY allows the
4290 ;; recursion, or ELEMENT is a headline, in which case going
4291 ;; inside is mandatory, in order to get sub-level headings.
4292 ((and (memq type org-element-greater-elements)
4293 (or (memq granularity '(element object nil))
4294 (and (eq granularity 'greater-element)
4295 (eq type 'section))
4296 (eq type 'headline)))
4297 (org-element--parse-elements
4298 cbeg (org-element-property :contents-end element)
4299 ;; Possibly switch to a special mode.
4300 (org-element--next-mode type t)
4301 (and (memq type '(item plain-list))
4302 (org-element-property :structure element))
4303 granularity visible-only element))
4304 ;; ELEMENT has contents. Parse objects inside, if
4305 ;; GRANULARITY allows it.
4306 ((memq granularity '(object nil))
4307 (org-element--parse-objects
4308 cbeg (org-element-property :contents-end element) element
4309 (org-element-restriction type))))
4310 (push (org-element-put-property element :parent acc) elements)
4311 ;; Update mode.
4312 (setq mode (org-element--next-mode type nil))))
4313 ;; Return result.
4314 (apply #'org-element-set-contents acc (nreverse elements)))))
4316 (defun org-element--object-lex (restriction)
4317 "Return next object in current buffer or nil.
4318 RESTRICTION is a list of object types, as symbols, that should be
4319 looked after. This function assumes that the buffer is narrowed
4320 to an appropriate container (e.g., a paragraph)."
4321 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4322 (let* ((start (point))
4323 (limit
4324 ;; Object regexp sometimes needs to have a peek at
4325 ;; a character ahead. Therefore, when there is a hard
4326 ;; limit, make it one more than the true beginning of the
4327 ;; radio target.
4328 (save-excursion
4329 (cond ((not org-target-link-regexp) nil)
4330 ((not (memq 'link restriction)) nil)
4331 ((progn
4332 (unless (bolp) (forward-char -1))
4333 (not (re-search-forward org-target-link-regexp nil t)))
4334 nil)
4335 ;; Since we moved backward, we do not want to
4336 ;; match again an hypothetical 1-character long
4337 ;; radio link before us. Realizing that this can
4338 ;; only happen if such a radio link starts at
4339 ;; beginning of line, we prevent this here.
4340 ((and (= start (1+ (line-beginning-position)))
4341 (= start (match-end 1)))
4342 (and (re-search-forward org-target-link-regexp nil t)
4343 (1+ (match-beginning 1))))
4344 (t (1+ (match-beginning 1))))))
4345 found)
4346 (save-excursion
4347 (while (and (not found)
4348 (re-search-forward org-element--object-regexp limit 'move))
4349 (goto-char (match-beginning 0))
4350 (let ((result (match-string 0)))
4351 (setq found
4352 (cond
4353 ((string-prefix-p "call_" result t)
4354 (and (memq 'inline-babel-call restriction)
4355 (org-element-inline-babel-call-parser)))
4356 ((string-prefix-p "src_" result t)
4357 (and (memq 'inline-src-block restriction)
4358 (org-element-inline-src-block-parser)))
4360 (pcase (char-after)
4361 (?^ (and (memq 'superscript restriction)
4362 (org-element-superscript-parser)))
4363 (?_ (or (and (memq 'subscript restriction)
4364 (org-element-subscript-parser))
4365 (and (memq 'underline restriction)
4366 (org-element-underline-parser))))
4367 (?* (and (memq 'bold restriction)
4368 (org-element-bold-parser)))
4369 (?/ (and (memq 'italic restriction)
4370 (org-element-italic-parser)))
4371 (?~ (and (memq 'code restriction)
4372 (org-element-code-parser)))
4373 (?= (and (memq 'verbatim restriction)
4374 (org-element-verbatim-parser)))
4375 (?+ (and (memq 'strike-through restriction)
4376 (org-element-strike-through-parser)))
4377 (?@ (and (memq 'export-snippet restriction)
4378 (org-element-export-snippet-parser)))
4379 (?{ (and (memq 'macro restriction)
4380 (org-element-macro-parser)))
4381 (?$ (and (memq 'latex-fragment restriction)
4382 (org-element-latex-fragment-parser)))
4384 (if (eq (aref result 1) ?<)
4385 (or (and (memq 'radio-target restriction)
4386 (org-element-radio-target-parser))
4387 (and (memq 'target restriction)
4388 (org-element-target-parser)))
4389 (or (and (memq 'timestamp restriction)
4390 (org-element-timestamp-parser))
4391 (and (memq 'link restriction)
4392 (org-element-link-parser)))))
4393 (?\\
4394 (if (eq (aref result 1) ?\\)
4395 (and (memq 'line-break restriction)
4396 (org-element-line-break-parser))
4397 (or (and (memq 'entity restriction)
4398 (org-element-entity-parser))
4399 (and (memq 'latex-fragment restriction)
4400 (org-element-latex-fragment-parser)))))
4401 (?\[
4402 (if (eq (aref result 1) ?\[)
4403 (and (memq 'link restriction)
4404 (org-element-link-parser))
4405 (or (and (memq 'footnote-reference restriction)
4406 (org-element-footnote-reference-parser))
4407 (and (memq 'timestamp restriction)
4408 (org-element-timestamp-parser))
4409 (and (memq 'statistics-cookie restriction)
4410 (org-element-statistics-cookie-parser)))))
4411 ;; This is probably a plain link.
4412 (_ (and (memq 'link restriction)
4413 (org-element-link-parser)))))))
4414 (or (eobp) (forward-char))))
4415 (cond (found)
4416 (limit (forward-char -1)
4417 (org-element-link-parser)) ;radio link
4418 (t nil))))))
4420 (defun org-element--parse-objects (beg end acc restriction &optional parent)
4421 "Parse objects between BEG and END and return recursive structure.
4423 Objects are accumulated in ACC. RESTRICTION is a list of object
4424 successors which are allowed in the current object.
4426 ACC becomes the parent for all parsed objects. However, if ACC
4427 is nil (i.e., a secondary string is being parsed) and optional
4428 argument PARENT is non-nil, use it as the parent for all objects.
4429 Eventually, if both ACC and PARENT are nil, the common parent is
4430 the list of objects itself."
4431 (save-excursion
4432 (save-restriction
4433 (narrow-to-region beg end)
4434 (goto-char (point-min))
4435 (let (next-object contents)
4436 (while (and (not (eobp))
4437 (setq next-object (org-element--object-lex restriction)))
4438 ;; Text before any object.
4439 (let ((obj-beg (org-element-property :begin next-object)))
4440 (unless (= (point) obj-beg)
4441 (let ((text (buffer-substring-no-properties (point) obj-beg)))
4442 (push (if acc (org-element-put-property text :parent acc) text)
4443 contents))))
4444 ;; Object...
4445 (let ((obj-end (org-element-property :end next-object))
4446 (cont-beg (org-element-property :contents-begin next-object)))
4447 (when acc (org-element-put-property next-object :parent acc))
4448 (push (if cont-beg
4449 ;; Fill contents of NEXT-OBJECT if possible.
4450 (org-element--parse-objects
4451 cont-beg
4452 (org-element-property :contents-end next-object)
4453 next-object
4454 (org-element-restriction next-object))
4455 next-object)
4456 contents)
4457 (goto-char obj-end)))
4458 ;; Text after last object.
4459 (unless (eobp)
4460 (let ((text (buffer-substring-no-properties (point) end)))
4461 (push (if acc (org-element-put-property text :parent acc) text)
4462 contents)))
4463 ;; Result. Set appropriate parent.
4464 (if acc (apply #'org-element-set-contents acc (nreverse contents))
4465 (let* ((contents (nreverse contents))
4466 (parent (or parent contents)))
4467 (dolist (datum contents contents)
4468 (org-element-put-property datum :parent parent))))))))
4472 ;;; Towards A Bijective Process
4474 ;; The parse tree obtained with `org-element-parse-buffer' is really
4475 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4476 ;; interpreted and expanded into a string with canonical Org syntax.
4477 ;; Hence `org-element-interpret-data'.
4479 ;; The function relies internally on
4480 ;; `org-element--interpret-affiliated-keywords'.
4482 ;;;###autoload
4483 (defun org-element-interpret-data (data)
4484 "Interpret DATA as Org syntax.
4485 DATA is a parse tree, an element, an object or a secondary string
4486 to interpret. Return Org syntax as a string."
4487 (letrec ((fun
4488 (lambda (data parent)
4489 (let* ((type (org-element-type data))
4490 ;; Find interpreter for current object or
4491 ;; element. If it doesn't exist (e.g. this is
4492 ;; a pseudo object or element), return contents,
4493 ;; if any.
4494 (interpret
4495 (let ((fun (intern
4496 (format "org-element-%s-interpreter" type))))
4497 (if (fboundp fun) fun (lambda (_ contents) contents))))
4498 (results
4499 (cond
4500 ;; Secondary string.
4501 ((not type)
4502 (mapconcat (lambda (obj) (funcall fun obj parent))
4503 data
4504 ""))
4505 ;; Full Org document.
4506 ((eq type 'org-data)
4507 (mapconcat (lambda (obj) (funcall fun obj parent))
4508 (org-element-contents data)
4509 ""))
4510 ;; Plain text: return it.
4511 ((stringp data) data)
4512 ;; Element or object without contents.
4513 ((not (org-element-contents data))
4514 (funcall interpret data nil))
4515 ;; Element or object with contents.
4517 (funcall
4518 interpret
4519 data
4520 ;; Recursively interpret contents.
4521 (mapconcat
4522 (lambda (datum) (funcall fun datum data))
4523 (org-element-contents
4524 (if (not (memq type '(paragraph verse-block)))
4525 data
4526 ;; Fix indentation of elements containing
4527 ;; objects. We ignore `table-row'
4528 ;; elements as they are one line long
4529 ;; anyway.
4530 (org-element-normalize-contents
4531 data
4532 ;; When normalizing first paragraph of
4533 ;; an item or a footnote-definition,
4534 ;; ignore first line's indentation.
4535 (and (eq type 'paragraph)
4536 (memq (org-element-type parent)
4537 '(footnote-definition item))
4538 (eq data
4539 (car (org-element-contents parent)))))))
4540 ""))))))
4541 (if (memq type '(org-data plain-text nil)) results
4542 ;; Build white spaces. If no `:post-blank' property
4543 ;; is specified, assume its value is 0.
4544 (let ((blank (or (org-element-property :post-blank data) 0)))
4545 (if (eq (org-element-class data parent) 'object)
4546 (concat results (make-string blank ?\s))
4547 (concat (org-element--interpret-affiliated-keywords data)
4548 (org-element-normalize-string results)
4549 (make-string blank ?\n)))))))))
4550 (funcall fun data nil)))
4552 (defun org-element--interpret-affiliated-keywords (element)
4553 "Return ELEMENT's affiliated keywords as Org syntax.
4554 If there is no affiliated keyword, return the empty string."
4555 (let ((keyword-to-org
4556 (function
4557 (lambda (key value)
4558 (let (dual)
4559 (when (member key org-element-dual-keywords)
4560 (setq dual (cdr value) value (car value)))
4561 (concat "#+" key
4562 (and dual
4563 (format "[%s]" (org-element-interpret-data dual)))
4564 ": "
4565 (if (member key org-element-parsed-keywords)
4566 (org-element-interpret-data value)
4567 value)
4568 "\n"))))))
4569 (mapconcat
4570 (lambda (prop)
4571 (let ((value (org-element-property prop element))
4572 (keyword (upcase (substring (symbol-name prop) 1))))
4573 (when value
4574 (if (or (member keyword org-element-multiple-keywords)
4575 ;; All attribute keywords can have multiple lines.
4576 (string-match "^ATTR_" keyword))
4577 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4578 (reverse value)
4580 (funcall keyword-to-org keyword value)))))
4581 ;; List all ELEMENT's properties matching an attribute line or an
4582 ;; affiliated keyword, but ignore translated keywords since they
4583 ;; cannot belong to the property list.
4584 (cl-loop for prop in (nth 1 element) by 'cddr
4585 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4586 (or (string-match "^ATTR_" keyword)
4587 (and
4588 (member keyword org-element-affiliated-keywords)
4589 (not (assoc keyword
4590 org-element-keyword-translation-alist)))))
4591 collect prop)
4592 "")))
4594 ;; Because interpretation of the parse tree must return the same
4595 ;; number of blank lines between elements and the same number of white
4596 ;; space after objects, some special care must be given to white
4597 ;; spaces.
4599 ;; The first function, `org-element-normalize-string', ensures any
4600 ;; string different from the empty string will end with a single
4601 ;; newline character.
4603 ;; The second function, `org-element-normalize-contents', removes
4604 ;; global indentation from the contents of the current element.
4606 (defun org-element-normalize-string (s)
4607 "Ensure string S ends with a single newline character.
4609 If S isn't a string return it unchanged. If S is the empty
4610 string, return it. Otherwise, return a new string with a single
4611 newline character at its end."
4612 (cond
4613 ((not (stringp s)) s)
4614 ((string= "" s) "")
4615 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4616 (replace-match "\n" nil nil s)))))
4618 (defun org-element-normalize-contents (element &optional ignore-first)
4619 "Normalize plain text in ELEMENT's contents.
4621 ELEMENT must only contain plain text and objects.
4623 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4624 indentation to compute maximal common indentation.
4626 Return the normalized element that is element with global
4627 indentation removed from its contents."
4628 (letrec ((find-min-ind
4629 ;; Return minimal common indentation within BLOB. This is
4630 ;; done by walking recursively BLOB and updating MIN-IND
4631 ;; along the way. FIRST-FLAG is non-nil when the next
4632 ;; object is expected to be a string that doesn't start
4633 ;; with a newline character. It happens for strings at
4634 ;; the beginnings of the contents or right after a line
4635 ;; break.
4636 (lambda (blob first-flag min-ind)
4637 (dolist (datum (org-element-contents blob) min-ind)
4638 (when first-flag
4639 (setq first-flag nil)
4640 (cond
4641 ;; Objects cannot start with spaces: in this
4642 ;; case, indentation is 0.
4643 ((not (stringp datum)) (throw :zero 0))
4644 ((not (string-match
4645 "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
4646 (throw :zero 0))
4647 ((equal (match-string 2 datum) "\n")
4648 (put-text-property
4649 (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
4651 (let ((i (string-width (match-string 1 datum))))
4652 (put-text-property
4653 (match-beginning 1) (match-end 1) 'org-ind i datum)
4654 (setq min-ind (min i min-ind))))))
4655 (cond
4656 ((stringp datum)
4657 (let ((s 0))
4658 (while (string-match
4659 "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
4660 (setq s (match-end 1))
4661 (cond
4662 ((equal (match-string 1 datum) "")
4663 (unless (member (match-string 2 datum) '("" "\n"))
4664 (throw :zero 0)))
4665 ((equal (match-string 2 datum) "\n")
4666 (put-text-property (match-beginning 1) (match-end 1)
4667 'org-ind 'empty datum))
4669 (let ((i (string-width (match-string 1 datum))))
4670 (put-text-property (match-beginning 1) (match-end 1)
4671 'org-ind i datum)
4672 (setq min-ind (min i min-ind))))))))
4673 ((eq (org-element-type datum) 'line-break)
4674 (setq first-flag t))
4675 ((memq (org-element-type datum) org-element-recursive-objects)
4676 (setq min-ind
4677 (funcall find-min-ind datum first-flag min-ind)))))))
4678 (min-ind
4679 (catch :zero
4680 (funcall find-min-ind
4681 element (not ignore-first) most-positive-fixnum))))
4682 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4683 ;; Build ELEMENT back, replacing each string with the same
4684 ;; string minus common indentation.
4685 (letrec ((build
4686 (lambda (datum)
4687 ;; Return DATUM with all its strings indentation
4688 ;; shortened from MIN-IND white spaces.
4689 (setcdr
4690 (cdr datum)
4691 (mapcar
4692 (lambda (object)
4693 (cond
4694 ((stringp object)
4695 (with-temp-buffer
4696 (insert object)
4697 (let ((s (point-min)))
4698 (while (setq s (text-property-not-all
4699 s (point-max) 'org-ind nil))
4700 (goto-char s)
4701 (let ((i (get-text-property s 'org-ind)))
4702 (delete-region s (progn
4703 (skip-chars-forward " \t")
4704 (point)))
4705 (when (integerp i) (indent-to (- i min-ind))))))
4706 (buffer-string)))
4707 ((memq (org-element-type object)
4708 org-element-recursive-objects)
4709 (funcall build object))
4710 (t object)))
4711 (org-element-contents datum)))
4712 datum)))
4713 (funcall build element)))))
4717 ;;; Cache
4719 ;; Implement a caching mechanism for `org-element-at-point' and
4720 ;; `org-element-context', which see.
4722 ;; A single public function is provided: `org-element-cache-reset'.
4724 ;; Cache is enabled by default, but can be disabled globally with
4725 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4726 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4727 ;; can be tweaked to control caching behaviour.
4729 ;; Internally, parsed elements are stored in an AVL tree,
4730 ;; `org-element--cache'. This tree is updated lazily: whenever
4731 ;; a change happens to the buffer, a synchronization request is
4732 ;; registered in `org-element--cache-sync-requests' (see
4733 ;; `org-element--cache-submit-request'). During idle time, requests
4734 ;; are processed by `org-element--cache-sync'. Synchronization also
4735 ;; happens when an element is required from the cache. In this case,
4736 ;; the process stops as soon as the needed element is up-to-date.
4738 ;; A synchronization request can only apply on a synchronized part of
4739 ;; the cache. Therefore, the cache is updated at least to the
4740 ;; location where the new request applies. Thus, requests are ordered
4741 ;; from left to right and all elements starting before the first
4742 ;; request are correct. This property is used by functions like
4743 ;; `org-element--cache-find' to retrieve elements in the part of the
4744 ;; cache that can be trusted.
4746 ;; A request applies to every element, starting from its original
4747 ;; location (or key, see below). When a request is processed, it
4748 ;; moves forward and may collide the next one. In this case, both
4749 ;; requests are merged into a new one that starts from that element.
4750 ;; As a consequence, the whole synchronization complexity does not
4751 ;; depend on the number of pending requests, but on the number of
4752 ;; elements the very first request will be applied on.
4754 ;; Elements cannot be accessed through their beginning position, which
4755 ;; may or may not be up-to-date. Instead, each element in the tree is
4756 ;; associated to a key, obtained with `org-element--cache-key'. This
4757 ;; mechanism is robust enough to preserve total order among elements
4758 ;; even when the tree is only partially synchronized.
4761 (defvar org-element-use-cache nil
4762 "Non-nil when Org parser should cache its results.
4764 WARNING: for the time being, using cache sometimes triggers
4765 freezes. Therefore, it is disabled by default. Activate it if
4766 you want to help debugging the issue.")
4768 (defvar org-element-cache-sync-idle-time 0.6
4769 "Length, in seconds, of idle time before syncing cache.")
4771 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4772 "Maximum duration, as a time value, for a cache synchronization.
4773 If the synchronization is not over after this delay, the process
4774 pauses and resumes after `org-element-cache-sync-break'
4775 seconds.")
4777 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4778 "Duration, as a time value, of the pause between synchronizations.
4779 See `org-element-cache-sync-duration' for more information.")
4782 ;;;; Data Structure
4784 (defvar org-element--cache nil
4785 "AVL tree used to cache elements.
4786 Each node of the tree contains an element. Comparison is done
4787 with `org-element--cache-compare'. This cache is used in
4788 `org-element-at-point'.")
4790 (defvar org-element--cache-sync-requests nil
4791 "List of pending synchronization requests.
4793 A request is a vector with the following pattern:
4795 \[NEXT BEG END OFFSET PARENT PHASE]
4797 Processing a synchronization request consists of three phases:
4799 0. Delete modified elements,
4800 1. Fill missing area in cache,
4801 2. Shift positions and re-parent elements after the changes.
4803 During phase 0, NEXT is the key of the first element to be
4804 removed, BEG and END is buffer position delimiting the
4805 modifications. Elements starting between them (inclusive) are
4806 removed. So are elements whose parent is removed. PARENT, when
4807 non-nil, is the parent of the first element to be removed.
4809 During phase 1, NEXT is the key of the next known element in
4810 cache and BEG its beginning position. Parse buffer between that
4811 element and the one before it in order to determine the parent of
4812 the next element. Set PARENT to the element containing NEXT.
4814 During phase 2, NEXT is the key of the next element to shift in
4815 the parse tree. All elements starting from this one have their
4816 properties relatives to buffer positions shifted by integer
4817 OFFSET and, if they belong to element PARENT, are adopted by it.
4819 PHASE specifies the phase number, as an integer.")
4821 (defvar org-element--cache-sync-timer nil
4822 "Timer used for cache synchronization.")
4824 (defvar org-element--cache-sync-keys nil
4825 "Hash table used to store keys during synchronization.
4826 See `org-element--cache-key' for more information.")
4828 (defsubst org-element--cache-key (element)
4829 "Return a unique key for ELEMENT in cache tree.
4831 Keys are used to keep a total order among elements in the cache.
4832 Comparison is done with `org-element--cache-key-less-p'.
4834 When no synchronization is taking place, a key is simply the
4835 beginning position of the element, or that position plus one in
4836 the case of an first item (respectively row) in
4837 a list (respectively a table).
4839 During a synchronization, the key is the one the element had when
4840 the cache was synchronized for the last time. Elements added to
4841 cache during the synchronization get a new key generated with
4842 `org-element--cache-generate-key'.
4844 Such keys are stored in `org-element--cache-sync-keys'. The hash
4845 table is cleared once the synchronization is complete."
4846 (or (gethash element org-element--cache-sync-keys)
4847 (let* ((begin (org-element-property :begin element))
4848 ;; Increase beginning position of items (respectively
4849 ;; table rows) by one, so the first item can get
4850 ;; a different key from its parent list (respectively
4851 ;; table).
4852 (key (if (memq (org-element-type element) '(item table-row))
4853 (1+ begin)
4854 begin)))
4855 (if org-element--cache-sync-requests
4856 (puthash element key org-element--cache-sync-keys)
4857 key))))
4859 (defun org-element--cache-generate-key (lower upper)
4860 "Generate a key between LOWER and UPPER.
4862 LOWER and UPPER are integers or lists, possibly empty.
4864 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4865 a unique key, as an integer or a list of integers, according to
4866 the following rules:
4868 - LOWER and UPPER are compared level-wise until values differ.
4870 - If, at a given level, LOWER and UPPER differ from more than
4871 2, the new key shares all the levels above with LOWER and
4872 gets a new level. Its value is the mean between LOWER and
4873 UPPER:
4875 (1 2) + (1 4) --> (1 3)
4877 - If LOWER has no value to compare with, it is assumed that its
4878 value is `most-negative-fixnum'. E.g.,
4880 (1 1) + (1 1 2)
4882 is equivalent to
4884 (1 1 m) + (1 1 2)
4886 where m is `most-negative-fixnum'. Likewise, if UPPER is
4887 short of levels, the current value is `most-positive-fixnum'.
4889 - If they differ from only one, the new key inherits from
4890 current LOWER level and fork it at the next level. E.g.,
4892 (2 1) + (3 3)
4894 is equivalent to
4896 (2 1) + (2 M)
4898 where M is `most-positive-fixnum'.
4900 - If the key is only one level long, it is returned as an
4901 integer:
4903 (1 2) + (3 2) --> 2
4905 When they are not equals, the function assumes that LOWER is
4906 lesser than UPPER, per `org-element--cache-key-less-p'."
4907 (if (equal lower upper) lower
4908 (let ((lower (if (integerp lower) (list lower) lower))
4909 (upper (if (integerp upper) (list upper) upper))
4910 skip-upper key)
4911 (catch 'exit
4912 (while t
4913 (let ((min (or (car lower) most-negative-fixnum))
4914 (max (cond (skip-upper most-positive-fixnum)
4915 ((car upper))
4916 (t most-positive-fixnum))))
4917 (if (< (1+ min) max)
4918 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4919 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4920 (when (and (< min max) (not skip-upper))
4921 ;; When at a given level, LOWER and UPPER differ from
4922 ;; 1, ignore UPPER altogether. Instead create a key
4923 ;; between LOWER and the greatest key with the same
4924 ;; prefix as LOWER so far.
4925 (setq skip-upper t))
4926 (push min key)
4927 (setq lower (cdr lower) upper (cdr upper)))))))))
4929 (defsubst org-element--cache-key-less-p (a b)
4930 "Non-nil if key A is less than key B.
4931 A and B are either integers or lists of integers, as returned by
4932 `org-element--cache-key'."
4933 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4934 (if (integerp b) (< (car a) b)
4935 (catch 'exit
4936 (while (and a b)
4937 (cond ((car-less-than-car a b) (throw 'exit t))
4938 ((car-less-than-car b a) (throw 'exit nil))
4939 (t (setq a (cdr a) b (cdr b)))))
4940 ;; If A is empty, either keys are equal (B is also empty) and
4941 ;; we return nil, or A is lesser than B (B is longer) and we
4942 ;; return a non-nil value.
4944 ;; If A is not empty, B is necessarily empty and A is greater
4945 ;; than B (A is longer). Therefore, return nil.
4946 (and (null a) b)))))
4948 (defun org-element--cache-compare (a b)
4949 "Non-nil when element A is located before element B."
4950 (org-element--cache-key-less-p (org-element--cache-key a)
4951 (org-element--cache-key b)))
4953 (defsubst org-element--cache-root ()
4954 "Return root value in cache.
4955 This function assumes `org-element--cache' is a valid AVL tree."
4956 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4959 ;;;; Tools
4961 (defsubst org-element--cache-active-p ()
4962 "Non-nil when cache is active in current buffer."
4963 (and org-element-use-cache
4964 org-element--cache
4965 (derived-mode-p 'org-mode)))
4967 (defun org-element--cache-find (pos &optional side)
4968 "Find element in cache starting at POS or before.
4970 POS refers to a buffer position.
4972 When optional argument SIDE is non-nil, the function checks for
4973 elements starting at or past POS instead. If SIDE is `both', the
4974 function returns a cons cell where car is the first element
4975 starting at or before POS and cdr the first element starting
4976 after POS.
4978 The function can only find elements in the synchronized part of
4979 the cache."
4980 (let ((limit (and org-element--cache-sync-requests
4981 (aref (car org-element--cache-sync-requests) 0)))
4982 (node (org-element--cache-root))
4983 lower upper)
4984 (while node
4985 (let* ((element (avl-tree--node-data node))
4986 (begin (org-element-property :begin element)))
4987 (cond
4988 ((and limit
4989 (not (org-element--cache-key-less-p
4990 (org-element--cache-key element) limit)))
4991 (setq node (avl-tree--node-left node)))
4992 ((> begin pos)
4993 (setq upper element
4994 node (avl-tree--node-left node)))
4995 ((< begin pos)
4996 (setq lower element
4997 node (avl-tree--node-right node)))
4998 ;; We found an element in cache starting at POS. If `side'
4999 ;; is `both' we also want the next one in order to generate
5000 ;; a key in-between.
5002 ;; If the element is the first row or item in a table or
5003 ;; a plain list, we always return the table or the plain
5004 ;; list.
5006 ;; In any other case, we return the element found.
5007 ((eq side 'both)
5008 (setq lower element)
5009 (setq node (avl-tree--node-right node)))
5010 ((and (memq (org-element-type element) '(item table-row))
5011 (let ((parent (org-element-property :parent element)))
5012 (and (= (org-element-property :begin element)
5013 (org-element-property :contents-begin parent))
5014 (setq node nil
5015 lower parent
5016 upper parent)))))
5018 (setq node nil
5019 lower element
5020 upper element)))))
5021 (pcase side
5022 (`both (cons lower upper))
5023 (`nil lower)
5024 (_ upper))))
5026 (defun org-element--cache-put (element)
5027 "Store ELEMENT in current buffer's cache, if allowed."
5028 (when (org-element--cache-active-p)
5029 (when org-element--cache-sync-requests
5030 ;; During synchronization, first build an appropriate key for
5031 ;; the new element so `avl-tree-enter' can insert it at the
5032 ;; right spot in the cache.
5033 (let ((keys (org-element--cache-find
5034 (org-element-property :begin element) 'both)))
5035 (puthash element
5036 (org-element--cache-generate-key
5037 (and (car keys) (org-element--cache-key (car keys)))
5038 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
5039 (org-element--cache-sync-requests
5040 (aref (car org-element--cache-sync-requests) 0))))
5041 org-element--cache-sync-keys)))
5042 (avl-tree-enter org-element--cache element)))
5044 (defsubst org-element--cache-remove (element)
5045 "Remove ELEMENT from cache.
5046 Assume ELEMENT belongs to cache and that a cache is active."
5047 (avl-tree-delete org-element--cache element))
5050 ;;;; Synchronization
5052 (defsubst org-element--cache-set-timer (buffer)
5053 "Set idle timer for cache synchronization in BUFFER."
5054 (when org-element--cache-sync-timer
5055 (cancel-timer org-element--cache-sync-timer))
5056 (setq org-element--cache-sync-timer
5057 (run-with-idle-timer
5058 (let ((idle (current-idle-time)))
5059 (if idle (time-add idle org-element-cache-sync-break)
5060 org-element-cache-sync-idle-time))
5062 #'org-element--cache-sync
5063 buffer)))
5065 (defsubst org-element--cache-interrupt-p (time-limit)
5066 "Non-nil when synchronization process should be interrupted.
5067 TIME-LIMIT is a time value or nil."
5068 (and time-limit
5069 (or (input-pending-p)
5070 (time-less-p time-limit (current-time)))))
5072 (defsubst org-element--cache-shift-positions (element offset &optional props)
5073 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5075 Properties containing buffer positions are `:begin', `:end',
5076 `:contents-begin', `:contents-end' and `:structure'. When
5077 optional argument PROPS is a list of keywords, only shift
5078 properties provided in that list.
5080 Properties are modified by side-effect."
5081 (let ((properties (nth 1 element)))
5082 ;; Shift `:structure' property for the first plain list only: it
5083 ;; is the only one that really matters and it prevents from
5084 ;; shifting it more than once.
5085 (when (and (or (not props) (memq :structure props))
5086 (eq (org-element-type element) 'plain-list)
5087 (not (eq (org-element-type (plist-get properties :parent))
5088 'item)))
5089 (dolist (item (plist-get properties :structure))
5090 (cl-incf (car item) offset)
5091 (cl-incf (nth 6 item) offset)))
5092 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5093 (let ((value (and (or (not props) (memq key props))
5094 (plist-get properties key))))
5095 (and value (plist-put properties key (+ offset value)))))))
5097 (defun org-element--cache-sync (buffer &optional threshold future-change)
5098 "Synchronize cache with recent modification in BUFFER.
5100 When optional argument THRESHOLD is non-nil, do the
5101 synchronization for all elements starting before or at threshold,
5102 then exit. Otherwise, synchronize cache for as long as
5103 `org-element-cache-sync-duration' or until Emacs leaves idle
5104 state.
5106 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5107 not registered yet in the cache are going to happen. It is used
5108 in `org-element--cache-submit-request', where cache is partially
5109 updated before current modification are actually submitted."
5110 (when (buffer-live-p buffer)
5111 (with-current-buffer buffer
5112 (let ((inhibit-quit t) request next)
5113 (when org-element--cache-sync-timer
5114 (cancel-timer org-element--cache-sync-timer))
5115 (catch 'interrupt
5116 (while org-element--cache-sync-requests
5117 (setq request (car org-element--cache-sync-requests)
5118 next (nth 1 org-element--cache-sync-requests))
5119 (org-element--cache-process-request
5120 request
5121 (and next (aref next 0))
5122 threshold
5123 (and (not threshold)
5124 (time-add (current-time)
5125 org-element-cache-sync-duration))
5126 future-change)
5127 ;; Request processed. Merge current and next offsets and
5128 ;; transfer ending position.
5129 (when next
5130 (cl-incf (aref next 3) (aref request 3))
5131 (aset next 2 (aref request 2)))
5132 (setq org-element--cache-sync-requests
5133 (cdr org-element--cache-sync-requests))))
5134 ;; If more requests are awaiting, set idle timer accordingly.
5135 ;; Otherwise, reset keys.
5136 (if org-element--cache-sync-requests
5137 (org-element--cache-set-timer buffer)
5138 (clrhash org-element--cache-sync-keys))))))
5140 (defun org-element--cache-process-request
5141 (request next threshold time-limit future-change)
5142 "Process synchronization REQUEST for all entries before NEXT.
5144 REQUEST is a vector, built by `org-element--cache-submit-request'.
5146 NEXT is a cache key, as returned by `org-element--cache-key'.
5148 When non-nil, THRESHOLD is a buffer position. Synchronization
5149 stops as soon as a shifted element begins after it.
5151 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5152 after this time or when Emacs exits idle state.
5154 When non-nil, FUTURE-CHANGE is a buffer position where changes
5155 not registered yet in the cache are going to happen. See
5156 `org-element--cache-submit-request' for more information.
5158 Throw `interrupt' if the process stops before completing the
5159 request."
5160 (catch 'quit
5161 (when (= (aref request 5) 0)
5162 ;; Phase 0.
5164 ;; Delete all elements starting after BEG, but not after buffer
5165 ;; position END or past element with key NEXT. Also delete
5166 ;; elements contained within a previously removed element
5167 ;; (stored in `last-container').
5169 ;; At each iteration, we start again at tree root since
5170 ;; a deletion modifies structure of the balanced tree.
5171 (catch 'end-phase
5172 (while t
5173 (when (org-element--cache-interrupt-p time-limit)
5174 (throw 'interrupt nil))
5175 ;; Find first element in cache with key BEG or after it.
5176 (let ((beg (aref request 0))
5177 (end (aref request 2))
5178 (node (org-element--cache-root))
5179 data data-key last-container)
5180 (while node
5181 (let* ((element (avl-tree--node-data node))
5182 (key (org-element--cache-key element)))
5183 (cond
5184 ((org-element--cache-key-less-p key beg)
5185 (setq node (avl-tree--node-right node)))
5186 ((org-element--cache-key-less-p beg key)
5187 (setq data element
5188 data-key key
5189 node (avl-tree--node-left node)))
5190 (t (setq data element
5191 data-key key
5192 node nil)))))
5193 (if data
5194 (let ((pos (org-element-property :begin data)))
5195 (if (if (or (not next)
5196 (org-element--cache-key-less-p data-key next))
5197 (<= pos end)
5198 (and last-container
5199 (let ((up data))
5200 (while (and up (not (eq up last-container)))
5201 (setq up (org-element-property :parent up)))
5202 up)))
5203 (progn (when (and (not last-container)
5204 (> (org-element-property :end data)
5205 end))
5206 (setq last-container data))
5207 (org-element--cache-remove data))
5208 (aset request 0 data-key)
5209 (aset request 1 pos)
5210 (aset request 5 1)
5211 (throw 'end-phase nil)))
5212 ;; No element starting after modifications left in
5213 ;; cache: further processing is futile.
5214 (throw 'quit t))))))
5215 (when (= (aref request 5) 1)
5216 ;; Phase 1.
5218 ;; Phase 0 left a hole in the cache. Some elements after it
5219 ;; could have parents within. For example, in the following
5220 ;; buffer:
5222 ;; - item
5225 ;; Paragraph1
5227 ;; Paragraph2
5229 ;; if we remove a blank line between "item" and "Paragraph1",
5230 ;; everything down to "Paragraph2" is removed from cache. But
5231 ;; the paragraph now belongs to the list, and its `:parent'
5232 ;; property no longer is accurate.
5234 ;; Therefore we need to parse again elements in the hole, or at
5235 ;; least in its last section, so that we can re-parent
5236 ;; subsequent elements, during phase 2.
5238 ;; Note that we only need to get the parent from the first
5239 ;; element in cache after the hole.
5241 ;; When next key is lesser or equal to the current one, delegate
5242 ;; phase 1 processing to next request in order to preserve key
5243 ;; order among requests.
5244 (let ((key (aref request 0)))
5245 (when (and next (not (org-element--cache-key-less-p key next)))
5246 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5247 (aset next-request 0 key)
5248 (aset next-request 1 (aref request 1))
5249 (aset next-request 5 1))
5250 (throw 'quit t)))
5251 ;; Next element will start at its beginning position plus
5252 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5253 ;; contains the real beginning position of the first element to
5254 ;; shift and re-parent.
5255 (let ((limit (+ (aref request 1) (aref request 3))))
5256 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5257 ((and future-change (>= limit future-change))
5258 ;; Changes are going to happen around this element and
5259 ;; they will trigger another phase 1 request. Skip the
5260 ;; current one.
5261 (aset request 5 2))
5263 (let ((parent (org-element--parse-to limit t time-limit)))
5264 (aset request 4 parent)
5265 (aset request 5 2))))))
5266 ;; Phase 2.
5268 ;; Shift all elements starting from key START, but before NEXT, by
5269 ;; OFFSET, and re-parent them when appropriate.
5271 ;; Elements are modified by side-effect so the tree structure
5272 ;; remains intact.
5274 ;; Once THRESHOLD, if any, is reached, or once there is an input
5275 ;; pending, exit. Before leaving, the current synchronization
5276 ;; request is updated.
5277 (let ((start (aref request 0))
5278 (offset (aref request 3))
5279 (parent (aref request 4))
5280 (node (org-element--cache-root))
5281 (stack (list nil))
5282 (leftp t)
5283 exit-flag)
5284 ;; No re-parenting nor shifting planned: request is over.
5285 (when (and (not parent) (zerop offset)) (throw 'quit t))
5286 (while node
5287 (let* ((data (avl-tree--node-data node))
5288 (key (org-element--cache-key data)))
5289 (if (and leftp (avl-tree--node-left node)
5290 (not (org-element--cache-key-less-p key start)))
5291 (progn (push node stack)
5292 (setq node (avl-tree--node-left node)))
5293 (unless (org-element--cache-key-less-p key start)
5294 ;; We reached NEXT. Request is complete.
5295 (when (equal key next) (throw 'quit t))
5296 ;; Handle interruption request. Update current request.
5297 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5298 (aset request 0 key)
5299 (aset request 4 parent)
5300 (throw 'interrupt nil))
5301 ;; Shift element.
5302 (unless (zerop offset)
5303 (org-element--cache-shift-positions data offset))
5304 (let ((begin (org-element-property :begin data)))
5305 ;; Update PARENT and re-parent DATA, only when
5306 ;; necessary. Propagate new structures for lists.
5307 (while (and parent
5308 (<= (org-element-property :end parent) begin))
5309 (setq parent (org-element-property :parent parent)))
5310 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5311 ((and parent
5312 (let ((p (org-element-property :parent data)))
5313 (or (not p)
5314 (< (org-element-property :begin p)
5315 (org-element-property :begin parent)))))
5316 (org-element-put-property data :parent parent)
5317 (let ((s (org-element-property :structure parent)))
5318 (when (and s (org-element-property :structure data))
5319 (org-element-put-property data :structure s)))))
5320 ;; Cache is up-to-date past THRESHOLD. Request
5321 ;; interruption.
5322 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5323 (setq node (if (setq leftp (avl-tree--node-right node))
5324 (avl-tree--node-right node)
5325 (pop stack))))))
5326 ;; We reached end of tree: synchronization complete.
5327 t)))
5329 (defun org-element--parse-to (pos &optional syncp time-limit)
5330 "Parse elements in current section, down to POS.
5332 Start parsing from the closest between the last known element in
5333 cache or headline above. Return the smallest element containing
5334 POS.
5336 When optional argument SYNCP is non-nil, return the parent of the
5337 element containing POS instead. In that case, it is also
5338 possible to provide TIME-LIMIT, which is a time value specifying
5339 when the parsing should stop. The function throws `interrupt' if
5340 the process stopped before finding the expected result."
5341 (catch 'exit
5342 (org-with-wide-buffer
5343 (goto-char pos)
5344 (let* ((cached (and (org-element--cache-active-p)
5345 (org-element--cache-find pos nil)))
5346 (begin (org-element-property :begin cached))
5347 element next mode)
5348 (cond
5349 ;; Nothing in cache before point: start parsing from first
5350 ;; element following headline above, or first element in
5351 ;; buffer.
5352 ((not cached)
5353 (when (org-with-limited-levels (outline-previous-heading))
5354 (setq mode 'planning)
5355 (forward-line))
5356 (skip-chars-forward " \r\t\n")
5357 (beginning-of-line))
5358 ;; Cache returned exact match: return it.
5359 ((= pos begin)
5360 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5361 ;; There's a headline between cached value and POS: cached
5362 ;; value is invalid. Start parsing from first element
5363 ;; following the headline.
5364 ((re-search-backward
5365 (org-with-limited-levels org-outline-regexp-bol) begin t)
5366 (forward-line)
5367 (skip-chars-forward " \r\t\n")
5368 (beginning-of-line)
5369 (setq mode 'planning))
5370 ;; Check if CACHED or any of its ancestors contain point.
5372 ;; If there is such an element, we inspect it in order to know
5373 ;; if we return it or if we need to parse its contents.
5374 ;; Otherwise, we just start parsing from current location,
5375 ;; which is right after the top-most element containing
5376 ;; CACHED.
5378 ;; As a special case, if POS is at the end of the buffer, we
5379 ;; want to return the innermost element ending there.
5381 ;; Also, if we find an ancestor and discover that we need to
5382 ;; parse its contents, make sure we don't start from
5383 ;; `:contents-begin', as we would otherwise go past CACHED
5384 ;; again. Instead, in that situation, we will resume parsing
5385 ;; from NEXT, which is located after CACHED or its higher
5386 ;; ancestor not containing point.
5388 (let ((up cached)
5389 (pos (if (= (point-max) pos) (1- pos) pos)))
5390 (goto-char (or (org-element-property :contents-begin cached) begin))
5391 (while (let ((end (org-element-property :end up)))
5392 (and (<= end pos)
5393 (goto-char end)
5394 (setq up (org-element-property :parent up)))))
5395 (cond ((not up))
5396 ((eobp) (setq element up))
5397 (t (setq element up next (point)))))))
5398 ;; Parse successively each element until we reach POS.
5399 (let ((end (or (org-element-property :end element)
5400 (save-excursion
5401 (org-with-limited-levels (outline-next-heading))
5402 (point))))
5403 (parent element))
5404 (while t
5405 (when syncp
5406 (cond ((= (point) pos) (throw 'exit parent))
5407 ((org-element--cache-interrupt-p time-limit)
5408 (throw 'interrupt nil))))
5409 (unless element
5410 (setq element (org-element--current-element
5411 end 'element mode
5412 (org-element-property :structure parent)))
5413 (org-element-put-property element :parent parent)
5414 (org-element--cache-put element))
5415 (let ((elem-end (org-element-property :end element))
5416 (type (org-element-type element)))
5417 (cond
5418 ;; Skip any element ending before point. Also skip
5419 ;; element ending at point (unless it is also the end of
5420 ;; buffer) since we're sure that another element begins
5421 ;; after it.
5422 ((and (<= elem-end pos) (/= (point-max) elem-end))
5423 (goto-char elem-end)
5424 (setq mode (org-element--next-mode type nil)))
5425 ;; A non-greater element contains point: return it.
5426 ((not (memq type org-element-greater-elements))
5427 (throw 'exit element))
5428 ;; Otherwise, we have to decide if ELEMENT really
5429 ;; contains POS. In that case we start parsing from
5430 ;; contents' beginning.
5432 ;; If POS is at contents' beginning but it is also at
5433 ;; the beginning of the first item in a list or a table.
5434 ;; In that case, we need to create an anchor for that
5435 ;; list or table, so return it.
5437 ;; Also, if POS is at the end of the buffer, no element
5438 ;; can start after it, but more than one may end there.
5439 ;; Arbitrarily, we choose to return the innermost of
5440 ;; such elements.
5441 ((let ((cbeg (org-element-property :contents-begin element))
5442 (cend (org-element-property :contents-end element)))
5443 (when (or syncp
5444 (and cbeg cend
5445 (or (< cbeg pos)
5446 (and (= cbeg pos)
5447 (not (memq type '(plain-list table)))))
5448 (or (> cend pos)
5449 (and (= cend pos) (= (point-max) pos)))))
5450 (goto-char (or next cbeg))
5451 (setq next nil
5452 mode (org-element--next-mode type t)
5453 parent element
5454 end cend))))
5455 ;; Otherwise, return ELEMENT as it is the smallest
5456 ;; element containing POS.
5457 (t (throw 'exit element))))
5458 (setq element nil)))))))
5461 ;;;; Staging Buffer Changes
5463 (defconst org-element--cache-sensitive-re
5464 (concat
5465 org-outline-regexp-bol "\\|"
5466 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5467 "^[ \t]*\\(?:"
5468 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5469 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5470 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5471 "\\)")
5472 "Regexp matching a sensitive line, structure wise.
5473 A sensitive line is a headline, inlinetask, block, drawer, or
5474 latex-environment boundary. When such a line is modified,
5475 structure changes in the document may propagate in the whole
5476 section, possibly making cache invalid.")
5478 (defvar org-element--cache-change-warning nil
5479 "Non-nil when a sensitive line is about to be changed.
5480 It is a symbol among nil, t and `headline'.")
5482 (defun org-element--cache-before-change (beg end)
5483 "Request extension of area going to be modified if needed.
5484 BEG and END are the beginning and end of the range of changed
5485 text. See `before-change-functions' for more information."
5486 (when (org-element--cache-active-p)
5487 (org-with-wide-buffer
5488 (goto-char beg)
5489 (beginning-of-line)
5490 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5491 (setq org-element--cache-change-warning
5492 (save-match-data
5493 (if (and (org-with-limited-levels (org-at-heading-p))
5494 (= (line-end-position) bottom))
5495 'headline
5496 (let ((case-fold-search t))
5497 (re-search-forward
5498 org-element--cache-sensitive-re bottom t)))))))))
5500 (defun org-element--cache-after-change (beg end pre)
5501 "Update buffer modifications for current buffer.
5502 BEG and END are the beginning and end of the range of changed
5503 text, and the length in bytes of the pre-change text replaced by
5504 that range. See `after-change-functions' for more information."
5505 (when (org-element--cache-active-p)
5506 (org-with-wide-buffer
5507 (goto-char beg)
5508 (beginning-of-line)
5509 (save-match-data
5510 (let ((top (point))
5511 (bottom (save-excursion (goto-char end) (line-end-position))))
5512 ;; Determine if modified area needs to be extended, according
5513 ;; to both previous and current state. We make a special
5514 ;; case for headline editing: if a headline is modified but
5515 ;; not removed, do not extend.
5516 (when (pcase org-element--cache-change-warning
5517 (`t t)
5518 (`headline
5519 (not (and (org-with-limited-levels (org-at-heading-p))
5520 (= (line-end-position) bottom))))
5522 (let ((case-fold-search t))
5523 (re-search-forward
5524 org-element--cache-sensitive-re bottom t))))
5525 ;; Effectively extend modified area.
5526 (org-with-limited-levels
5527 (setq top (progn (goto-char top)
5528 (when (outline-previous-heading) (forward-line))
5529 (point)))
5530 (setq bottom (progn (goto-char bottom)
5531 (if (outline-next-heading) (1- (point))
5532 (point))))))
5533 ;; Store synchronization request.
5534 (let ((offset (- end beg pre)))
5535 (org-element--cache-submit-request top (- bottom offset) offset)))))
5536 ;; Activate a timer to process the request during idle time.
5537 (org-element--cache-set-timer (current-buffer))))
5539 (defun org-element--cache-for-removal (beg end offset)
5540 "Return first element to remove from cache.
5542 BEG and END are buffer positions delimiting buffer modifications.
5543 OFFSET is the size of the changes.
5545 Returned element is usually the first element in cache containing
5546 any position between BEG and END. As an exception, greater
5547 elements around the changes that are robust to contents
5548 modifications are preserved and updated according to the
5549 changes."
5550 (let* ((elements (org-element--cache-find (1- beg) 'both))
5551 (before (car elements))
5552 (after (cdr elements)))
5553 (if (not before) after
5554 (let ((up before)
5555 (robust-flag t))
5556 (while up
5557 (if (let ((type (org-element-type up)))
5558 (and (or (memq type '(center-block dynamic-block quote-block
5559 special-block))
5560 ;; Drawers named "PROPERTIES" are probably
5561 ;; a properties drawer being edited. Force
5562 ;; parsing to check if editing is over.
5563 (and (eq type 'drawer)
5564 (not (string=
5565 (org-element-property :drawer-name up)
5566 "PROPERTIES"))))
5567 (let ((cbeg (org-element-property :contents-begin up)))
5568 (and cbeg
5569 (<= cbeg beg)
5570 (> (org-element-property :contents-end up) end)))))
5571 ;; UP is a robust greater element containing changes.
5572 ;; We only need to extend its ending boundaries.
5573 (org-element--cache-shift-positions
5574 up offset '(:contents-end :end))
5575 (setq before up)
5576 (when robust-flag (setq robust-flag nil)))
5577 (setq up (org-element-property :parent up)))
5578 ;; We're at top level element containing ELEMENT: if it's
5579 ;; altered by buffer modifications, it is first element in
5580 ;; cache to be removed. Otherwise, that first element is the
5581 ;; following one.
5583 ;; As a special case, do not remove BEFORE if it is a robust
5584 ;; container for current changes.
5585 (if (or (< (org-element-property :end before) beg) robust-flag) after
5586 before)))))
5588 (defun org-element--cache-submit-request (beg end offset)
5589 "Submit a new cache synchronization request for current buffer.
5590 BEG and END are buffer positions delimiting the minimal area
5591 where cache data should be removed. OFFSET is the size of the
5592 change, as an integer."
5593 (let ((next (car org-element--cache-sync-requests))
5594 delete-to delete-from)
5595 (if (and next
5596 (zerop (aref next 5))
5597 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5598 (<= (setq delete-from (aref next 1)) end))
5599 ;; Current changes can be merged with first sync request: we
5600 ;; can save a partial cache synchronization.
5601 (progn
5602 (cl-incf (aref next 3) offset)
5603 ;; If last change happened within area to be removed, extend
5604 ;; boundaries of robust parents, if any. Otherwise, find
5605 ;; first element to remove and update request accordingly.
5606 (if (> beg delete-from)
5607 (let ((up (aref next 4)))
5608 (while up
5609 (org-element--cache-shift-positions
5610 up offset '(:contents-end :end))
5611 (setq up (org-element-property :parent up))))
5612 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5613 (when first
5614 (aset next 0 (org-element--cache-key first))
5615 (aset next 1 (org-element-property :begin first))
5616 (aset next 4 (org-element-property :parent first))))))
5617 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5618 ;; if any, is no longer a 0-phase request, thus ensuring that
5619 ;; phases are properly ordered. We need to provide OFFSET as
5620 ;; optional parameter since current modifications are not known
5621 ;; yet to the otherwise correct part of the cache (i.e, before
5622 ;; the first request).
5623 (when next (org-element--cache-sync (current-buffer) end beg))
5624 (let ((first (org-element--cache-for-removal beg end offset)))
5625 (if first
5626 (push (let ((beg (org-element-property :begin first))
5627 (key (org-element--cache-key first)))
5628 (cond
5629 ;; When changes happen before the first known
5630 ;; element, re-parent and shift the rest of the
5631 ;; cache.
5632 ((> beg end) (vector key beg nil offset nil 1))
5633 ;; Otherwise, we find the first non robust
5634 ;; element containing END. All elements between
5635 ;; FIRST and this one are to be removed.
5636 ((let ((first-end (org-element-property :end first)))
5637 (and (> first-end end)
5638 (vector key beg first-end offset first 0))))
5640 (let* ((element (org-element--cache-find end))
5641 (end (org-element-property :end element))
5642 (up element))
5643 (while (and (setq up (org-element-property :parent up))
5644 (>= (org-element-property :begin up) beg))
5645 (setq end (org-element-property :end up)
5646 element up))
5647 (vector key beg end offset element 0)))))
5648 org-element--cache-sync-requests)
5649 ;; No element to remove. No need to re-parent either.
5650 ;; Simply shift additional elements, if any, by OFFSET.
5651 (when org-element--cache-sync-requests
5652 (cl-incf (aref (car org-element--cache-sync-requests) 3)
5653 offset)))))))
5656 ;;;; Public Functions
5658 ;;;###autoload
5659 (defun org-element-cache-reset (&optional all)
5660 "Reset cache in current buffer.
5661 When optional argument ALL is non-nil, reset cache in all Org
5662 buffers."
5663 (interactive "P")
5664 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5665 (with-current-buffer buffer
5666 (when (and org-element-use-cache (derived-mode-p 'org-mode))
5667 (setq-local org-element--cache
5668 (avl-tree-create #'org-element--cache-compare))
5669 (setq-local org-element--cache-sync-keys
5670 (make-hash-table :weakness 'key :test #'eq))
5671 (setq-local org-element--cache-change-warning nil)
5672 (setq-local org-element--cache-sync-requests nil)
5673 (setq-local org-element--cache-sync-timer nil)
5674 (add-hook 'before-change-functions
5675 #'org-element--cache-before-change nil t)
5676 (add-hook 'after-change-functions
5677 #'org-element--cache-after-change nil t)))))
5679 ;;;###autoload
5680 (defun org-element-cache-refresh (pos)
5681 "Refresh cache at position POS."
5682 (when (org-element--cache-active-p)
5683 (org-element--cache-sync (current-buffer) pos)
5684 (org-element--cache-submit-request pos pos 0)
5685 (org-element--cache-set-timer (current-buffer))))
5689 ;;; The Toolbox
5691 ;; The first move is to implement a way to obtain the smallest element
5692 ;; containing point. This is the job of `org-element-at-point'. It
5693 ;; basically jumps back to the beginning of section containing point
5694 ;; and proceed, one element after the other, with
5695 ;; `org-element--current-element' until the container is found. Note:
5696 ;; When using `org-element-at-point', secondary values are never
5697 ;; parsed since the function focuses on elements, not on objects.
5699 ;; At a deeper level, `org-element-context' lists all elements and
5700 ;; objects containing point.
5702 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5703 ;; internally by navigation and manipulation tools.
5706 ;;;###autoload
5707 (defun org-element-at-point ()
5708 "Determine closest element around point.
5710 Return value is a list like (TYPE PROPS) where TYPE is the type
5711 of the element and PROPS a plist of properties associated to the
5712 element.
5714 Possible types are defined in `org-element-all-elements'.
5715 Properties depend on element or object type, but always include
5716 `:begin', `:end', `:parent' and `:post-blank' properties.
5718 As a special case, if point is at the very beginning of the first
5719 item in a list or sub-list, returned element will be that list
5720 instead of the item. Likewise, if point is at the beginning of
5721 the first row of a table, returned element will be the table
5722 instead of the first row.
5724 When point is at the end of the buffer, return the innermost
5725 element ending there."
5726 (org-with-wide-buffer
5727 (let ((origin (point)))
5728 (end-of-line)
5729 (skip-chars-backward " \r\t\n")
5730 (cond
5731 ;; Within blank lines at the beginning of buffer, return nil.
5732 ((bobp) nil)
5733 ;; Within blank lines right after a headline, return that
5734 ;; headline.
5735 ((org-with-limited-levels (org-at-heading-p))
5736 (beginning-of-line)
5737 (org-element-headline-parser (point-max) t))
5738 ;; Otherwise parse until we find element containing ORIGIN.
5740 (when (org-element--cache-active-p)
5741 (if (not org-element--cache) (org-element-cache-reset)
5742 (org-element--cache-sync (current-buffer) origin)))
5743 (org-element--parse-to origin))))))
5745 ;;;###autoload
5746 (defun org-element-context (&optional element)
5747 "Return smallest element or object around point.
5749 Return value is a list like (TYPE PROPS) where TYPE is the type
5750 of the element or object and PROPS a plist of properties
5751 associated to it.
5753 Possible types are defined in `org-element-all-elements' and
5754 `org-element-all-objects'. Properties depend on element or
5755 object type, but always include `:begin', `:end', `:parent' and
5756 `:post-blank'.
5758 As a special case, if point is right after an object and not at
5759 the beginning of any other object, return that object.
5761 Optional argument ELEMENT, when non-nil, is the closest element
5762 containing point, as returned by `org-element-at-point'.
5763 Providing it allows for quicker computation."
5764 (catch 'objects-forbidden
5765 (org-with-wide-buffer
5766 (let* ((pos (point))
5767 (element (or element (org-element-at-point)))
5768 (type (org-element-type element))
5769 (post (org-element-property :post-affiliated element)))
5770 ;; If point is inside an element containing objects or
5771 ;; a secondary string, narrow buffer to the container and
5772 ;; proceed with parsing. Otherwise, return ELEMENT.
5773 (cond
5774 ;; At a parsed affiliated keyword, check if we're inside main
5775 ;; or dual value.
5776 ((and post (< pos post))
5777 (beginning-of-line)
5778 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5779 (cond
5780 ((not (member-ignore-case (match-string 1)
5781 org-element-parsed-keywords))
5782 (throw 'objects-forbidden element))
5783 ((< (match-end 0) pos)
5784 (narrow-to-region (match-end 0) (line-end-position)))
5785 ((and (match-beginning 2)
5786 (>= pos (match-beginning 2))
5787 (< pos (match-end 2)))
5788 (narrow-to-region (match-beginning 2) (match-end 2)))
5789 (t (throw 'objects-forbidden element)))
5790 ;; Also change type to retrieve correct restrictions.
5791 (setq type 'keyword))
5792 ;; At an item, objects can only be located within tag, if any.
5793 ((eq type 'item)
5794 (let ((tag (org-element-property :tag element)))
5795 (if (or (not tag) (/= (line-beginning-position) post))
5796 (throw 'objects-forbidden element)
5797 (beginning-of-line)
5798 (search-forward tag (line-end-position))
5799 (goto-char (match-beginning 0))
5800 (if (and (>= pos (point)) (< pos (match-end 0)))
5801 (narrow-to-region (point) (match-end 0))
5802 (throw 'objects-forbidden element)))))
5803 ;; At an headline or inlinetask, objects are in title.
5804 ((memq type '(headline inlinetask))
5805 (let ((case-fold-search nil))
5806 (goto-char (org-element-property :begin element))
5807 (looking-at org-complex-heading-regexp)
5808 (let ((end (match-end 4)))
5809 (if (not end) (throw 'objects-forbidden element)
5810 (goto-char (match-beginning 4))
5811 (when (looking-at org-comment-string)
5812 (goto-char (match-end 0)))
5813 (if (>= (point) end) (throw 'objects-forbidden element)
5814 (narrow-to-region (point) end))))))
5815 ;; At a paragraph, a table-row or a verse block, objects are
5816 ;; located within their contents.
5817 ((memq type '(paragraph table-row verse-block))
5818 (let ((cbeg (org-element-property :contents-begin element))
5819 (cend (org-element-property :contents-end element)))
5820 ;; CBEG is nil for table rules.
5821 (if (and cbeg cend (>= pos cbeg)
5822 (or (< pos cend) (and (= pos cend) (eobp))))
5823 (narrow-to-region cbeg cend)
5824 (throw 'objects-forbidden element))))
5825 (t (throw 'objects-forbidden element)))
5826 (goto-char (point-min))
5827 (let ((restriction (org-element-restriction type))
5828 (parent element)
5829 last)
5830 (catch 'exit
5831 (while t
5832 (let ((next (org-element--object-lex restriction)))
5833 (when next (org-element-put-property next :parent parent))
5834 ;; Process NEXT, if any, in order to know if we need to
5835 ;; skip it, return it or move into it.
5836 (if (or (not next) (> (org-element-property :begin next) pos))
5837 (throw 'exit (or last parent))
5838 (let ((end (org-element-property :end next))
5839 (cbeg (org-element-property :contents-begin next))
5840 (cend (org-element-property :contents-end next)))
5841 (cond
5842 ;; Skip objects ending before point. Also skip
5843 ;; objects ending at point unless it is also the
5844 ;; end of buffer, since we want to return the
5845 ;; innermost object.
5846 ((and (<= end pos) (/= (point-max) end))
5847 (goto-char end)
5848 ;; For convenience, when object ends at POS,
5849 ;; without any space, store it in LAST, as we
5850 ;; will return it if no object starts here.
5851 (when (and (= end pos)
5852 (not (memq (char-before) '(?\s ?\t))))
5853 (setq last next)))
5854 ;; If POS is within a container object, move into
5855 ;; that object.
5856 ((and cbeg cend
5857 (>= pos cbeg)
5858 (or (< pos cend)
5859 ;; At contents' end, if there is no
5860 ;; space before point, also move into
5861 ;; object, for consistency with
5862 ;; convenience feature above.
5863 (and (= pos cend)
5864 (or (= (point-max) pos)
5865 (not (memq (char-before pos)
5866 '(?\s ?\t)))))))
5867 (goto-char cbeg)
5868 (narrow-to-region (point) cend)
5869 (setq parent next)
5870 (setq restriction (org-element-restriction next)))
5871 ;; Otherwise, return NEXT.
5872 (t (throw 'exit next)))))))))))))
5874 (defun org-element-lineage (blob &optional types with-self)
5875 "List all ancestors of a given element or object.
5877 BLOB is an object or element.
5879 When optional argument TYPES is a list of symbols, return the
5880 first element or object in the lineage whose type belongs to that
5881 list.
5883 When optional argument WITH-SELF is non-nil, lineage includes
5884 BLOB itself as the first element, and TYPES, if provided, also
5885 apply to it.
5887 When BLOB is obtained through `org-element-context' or
5888 `org-element-at-point', only ancestors from its section can be
5889 found. There is no such limitation when BLOB belongs to a full
5890 parse tree."
5891 (let ((up (if with-self blob (org-element-property :parent blob)))
5892 ancestors)
5893 (while (and up (not (memq (org-element-type up) types)))
5894 (unless types (push up ancestors))
5895 (setq up (org-element-property :parent up)))
5896 (if types up (nreverse ancestors))))
5898 (defun org-element-nested-p (elem-A elem-B)
5899 "Non-nil when elements ELEM-A and ELEM-B are nested."
5900 (let ((beg-A (org-element-property :begin elem-A))
5901 (beg-B (org-element-property :begin elem-B))
5902 (end-A (org-element-property :end elem-A))
5903 (end-B (org-element-property :end elem-B)))
5904 (or (and (>= beg-A beg-B) (<= end-A end-B))
5905 (and (>= beg-B beg-A) (<= end-B end-A)))))
5907 (defun org-element-swap-A-B (elem-A elem-B)
5908 "Swap elements ELEM-A and ELEM-B.
5909 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5910 end of ELEM-A."
5911 (goto-char (org-element-property :begin elem-A))
5912 ;; There are two special cases when an element doesn't start at bol:
5913 ;; the first paragraph in an item or in a footnote definition.
5914 (let ((specialp (not (bolp))))
5915 ;; Only a paragraph without any affiliated keyword can be moved at
5916 ;; ELEM-A position in such a situation. Note that the case of
5917 ;; a footnote definition is impossible: it cannot contain two
5918 ;; paragraphs in a row because it cannot contain a blank line.
5919 (if (and specialp
5920 (or (not (eq (org-element-type elem-B) 'paragraph))
5921 (/= (org-element-property :begin elem-B)
5922 (org-element-property :contents-begin elem-B))))
5923 (error "Cannot swap elements"))
5924 ;; In a special situation, ELEM-A will have no indentation. We'll
5925 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5926 (let* ((ind-B (when specialp
5927 (goto-char (org-element-property :begin elem-B))
5928 (org-get-indentation)))
5929 (beg-A (org-element-property :begin elem-A))
5930 (end-A (save-excursion
5931 (goto-char (org-element-property :end elem-A))
5932 (skip-chars-backward " \r\t\n")
5933 (point-at-eol)))
5934 (beg-B (org-element-property :begin elem-B))
5935 (end-B (save-excursion
5936 (goto-char (org-element-property :end elem-B))
5937 (skip-chars-backward " \r\t\n")
5938 (point-at-eol)))
5939 ;; Store inner overlays responsible for visibility status.
5940 ;; We also need to store their boundaries as they will be
5941 ;; removed from buffer.
5942 (overlays
5943 (cons
5944 (delq nil
5945 (mapcar (lambda (o)
5946 (and (>= (overlay-start o) beg-A)
5947 (<= (overlay-end o) end-A)
5948 (list o (overlay-start o) (overlay-end o))))
5949 (overlays-in beg-A end-A)))
5950 (delq nil
5951 (mapcar (lambda (o)
5952 (and (>= (overlay-start o) beg-B)
5953 (<= (overlay-end o) end-B)
5954 (list o (overlay-start o) (overlay-end o))))
5955 (overlays-in beg-B end-B)))))
5956 ;; Get contents.
5957 (body-A (buffer-substring beg-A end-A))
5958 (body-B (delete-and-extract-region beg-B end-B)))
5959 (goto-char beg-B)
5960 (when specialp
5961 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5962 (indent-to-column ind-B))
5963 (insert body-A)
5964 ;; Restore ex ELEM-A overlays.
5965 (let ((offset (- beg-B beg-A)))
5966 (dolist (o (car overlays))
5967 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
5968 (goto-char beg-A)
5969 (delete-region beg-A end-A)
5970 (insert body-B)
5971 ;; Restore ex ELEM-B overlays.
5972 (dolist (o (cdr overlays))
5973 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
5974 (goto-char (org-element-property :end elem-B)))))
5977 (provide 'org-element)
5979 ;; Local variables:
5980 ;; generated-autoload-file: "org-loaddefs.el"
5981 ;; End:
5983 ;;; org-element.el ends here