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