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