org-capture: Fix "org-find-olp: Wrong type argument: stringp, nil"
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob64d2123b4e3a0635031f1c5a12c8ddd2f0164232
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 (progn (skip-chars-forward " \t") (current-column))))
1337 (when (<= ind top-ind)
1338 (skip-chars-backward " \r\t\n")
1339 (forward-line))
1340 (while (<= ind (nth 1 (car items)))
1341 (let ((item (pop items)))
1342 (setcar (nthcdr 6 item) (line-beginning-position))
1343 (push item struct)
1344 (unless items
1345 (throw 'exit (sort struct 'car-less-than-car))))))
1346 ;; Skip blocks (any type) and drawers contents.
1347 (cond
1348 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1349 (re-search-forward
1350 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1351 limit t)))
1352 ((and (looking-at org-drawer-regexp)
1353 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1354 (forward-line))))))))
1356 (defun org-element-plain-list-parser (limit affiliated structure)
1357 "Parse a plain list.
1359 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1360 the buffer position at the beginning of the first affiliated
1361 keyword and CDR is a plist of affiliated keywords along with
1362 their value. STRUCTURE is the structure of the plain list being
1363 parsed.
1365 Return a list whose CAR is `plain-list' and CDR is a plist
1366 containing `:type', `:begin', `:end', `:contents-begin' and
1367 `:contents-end', `:structure', `:post-blank' and
1368 `:post-affiliated' keywords.
1370 Assume point is at the beginning of the list."
1371 (save-excursion
1372 (let* ((struct (or structure (org-element--list-struct limit)))
1373 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1374 ((nth 5 (assq (point) struct)) 'descriptive)
1375 (t 'unordered)))
1376 (contents-begin (point))
1377 (begin (car affiliated))
1378 (contents-end (let* ((item (assq contents-begin struct))
1379 (ind (nth 1 item))
1380 (pos (nth 6 item)))
1381 (while (and (setq item (assq pos struct))
1382 (= (nth 1 item) ind))
1383 (setq pos (nth 6 item)))
1384 pos))
1385 (end (progn (goto-char contents-end)
1386 (skip-chars-forward " \r\t\n" limit)
1387 (if (= (point) limit) limit (line-beginning-position)))))
1388 ;; Return value.
1389 (list 'plain-list
1390 (nconc
1391 (list :type type
1392 :begin begin
1393 :end end
1394 :contents-begin contents-begin
1395 :contents-end contents-end
1396 :structure struct
1397 :post-blank (count-lines contents-end end)
1398 :post-affiliated contents-begin)
1399 (cdr affiliated))))))
1401 (defun org-element-plain-list-interpreter (plain-list contents)
1402 "Interpret PLAIN-LIST element as Org syntax.
1403 CONTENTS is the contents of the element."
1404 (with-temp-buffer
1405 (insert contents)
1406 (goto-char (point-min))
1407 (org-list-repair)
1408 (buffer-string)))
1411 ;;;; Property Drawer
1413 (defun org-element-property-drawer-parser (limit)
1414 "Parse a property drawer.
1416 LIMIT bounds the search.
1418 Return a list whose car is `property-drawer' and cdr is a plist
1419 containing `:begin', `:end', `:contents-begin', `:contents-end',
1420 `:post-blank' and `:post-affiliated' keywords.
1422 Assume point is at the beginning of the property drawer."
1423 (save-excursion
1424 (let ((case-fold-search t)
1425 (begin (point))
1426 (contents-begin (line-beginning-position 2)))
1427 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1428 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1429 (match-beginning 0)))
1430 (before-blank (progn (forward-line) (point)))
1431 (end (progn (skip-chars-forward " \r\t\n" limit)
1432 (if (eobp) (point) (line-beginning-position)))))
1433 (list 'property-drawer
1434 (list :begin begin
1435 :end end
1436 :contents-begin (and contents-end contents-begin)
1437 :contents-end contents-end
1438 :post-blank (count-lines before-blank end)
1439 :post-affiliated begin))))))
1441 (defun org-element-property-drawer-interpreter (property-drawer contents)
1442 "Interpret PROPERTY-DRAWER element as Org syntax.
1443 CONTENTS is the properties within the drawer."
1444 (format ":PROPERTIES:\n%s:END:" contents))
1447 ;;;; Quote Block
1449 (defun org-element-quote-block-parser (limit affiliated)
1450 "Parse a quote block.
1452 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1453 the buffer position at the beginning of the first affiliated
1454 keyword and CDR is a plist of affiliated keywords along with
1455 their value.
1457 Return a list whose CAR is `quote-block' and CDR is a plist
1458 containing `:begin', `:end', `:contents-begin', `:contents-end',
1459 `:post-blank' and `:post-affiliated' keywords.
1461 Assume point is at the beginning of the block."
1462 (let ((case-fold-search t))
1463 (if (not (save-excursion
1464 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1465 ;; Incomplete block: parse it as a paragraph.
1466 (org-element-paragraph-parser limit affiliated)
1467 (let ((block-end-line (match-beginning 0)))
1468 (save-excursion
1469 (let* ((begin (car affiliated))
1470 (post-affiliated (point))
1471 ;; Empty blocks have no contents.
1472 (contents-begin (progn (forward-line)
1473 (and (< (point) block-end-line)
1474 (point))))
1475 (contents-end (and contents-begin block-end-line))
1476 (pos-before-blank (progn (goto-char block-end-line)
1477 (forward-line)
1478 (point)))
1479 (end (progn (skip-chars-forward " \r\t\n" limit)
1480 (if (eobp) (point) (line-beginning-position)))))
1481 (list 'quote-block
1482 (nconc
1483 (list :begin begin
1484 :end end
1485 :contents-begin contents-begin
1486 :contents-end contents-end
1487 :post-blank (count-lines pos-before-blank end)
1488 :post-affiliated post-affiliated)
1489 (cdr affiliated)))))))))
1491 (defun org-element-quote-block-interpreter (quote-block contents)
1492 "Interpret QUOTE-BLOCK element as Org syntax.
1493 CONTENTS is the contents of the element."
1494 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1497 ;;;; Section
1499 (defun org-element-section-parser (limit)
1500 "Parse a section.
1502 LIMIT bounds the search.
1504 Return a list whose CAR is `section' and CDR is a plist
1505 containing `:begin', `:end', `:contents-begin', `contents-end',
1506 `:post-blank' and `:post-affiliated' keywords."
1507 (save-excursion
1508 ;; Beginning of section is the beginning of the first non-blank
1509 ;; line after previous headline.
1510 (let ((begin (point))
1511 (end (progn (org-with-limited-levels (outline-next-heading))
1512 (point)))
1513 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1514 (forward-line)
1515 (point))))
1516 (list 'section
1517 (list :begin begin
1518 :end end
1519 :contents-begin begin
1520 :contents-end pos-before-blank
1521 :post-blank (count-lines pos-before-blank end)
1522 :post-affiliated begin)))))
1524 (defun org-element-section-interpreter (section contents)
1525 "Interpret SECTION element as Org syntax.
1526 CONTENTS is the contents of the element."
1527 contents)
1530 ;;;; Special Block
1532 (defun org-element-special-block-parser (limit affiliated)
1533 "Parse a special block.
1535 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1536 the buffer position at the beginning of the first affiliated
1537 keyword and CDR is a plist of affiliated keywords along with
1538 their value.
1540 Return a list whose CAR is `special-block' and CDR is a plist
1541 containing `:type', `:begin', `:end', `:contents-begin',
1542 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1544 Assume point is at the beginning of the block."
1545 (let* ((case-fold-search t)
1546 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1547 (match-string-no-properties 1))))
1548 (if (not (save-excursion
1549 (re-search-forward
1550 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1551 limit t)))
1552 ;; Incomplete block: parse it as a paragraph.
1553 (org-element-paragraph-parser limit affiliated)
1554 (let ((block-end-line (match-beginning 0)))
1555 (save-excursion
1556 (let* ((begin (car affiliated))
1557 (post-affiliated (point))
1558 ;; Empty blocks have no contents.
1559 (contents-begin (progn (forward-line)
1560 (and (< (point) block-end-line)
1561 (point))))
1562 (contents-end (and contents-begin block-end-line))
1563 (pos-before-blank (progn (goto-char block-end-line)
1564 (forward-line)
1565 (point)))
1566 (end (progn (skip-chars-forward " \r\t\n" limit)
1567 (if (eobp) (point) (line-beginning-position)))))
1568 (list 'special-block
1569 (nconc
1570 (list :type type
1571 :begin begin
1572 :end end
1573 :contents-begin contents-begin
1574 :contents-end contents-end
1575 :post-blank (count-lines pos-before-blank end)
1576 :post-affiliated post-affiliated)
1577 (cdr affiliated)))))))))
1579 (defun org-element-special-block-interpreter (special-block contents)
1580 "Interpret SPECIAL-BLOCK element as Org syntax.
1581 CONTENTS is the contents of the element."
1582 (let ((block-type (org-element-property :type special-block)))
1583 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1587 ;;; Elements
1589 ;; For each element, a parser and an interpreter are also defined.
1590 ;; Both follow the same naming convention used for greater elements.
1592 ;; Also, as for greater elements, adding a new element type is done
1593 ;; through the following steps: implement a parser and an interpreter,
1594 ;; tweak `org-element--current-element' so that it recognizes the new
1595 ;; type and add that new type to `org-element-all-elements'.
1597 ;; As a special case, when the newly defined type is a block type,
1598 ;; `org-element-block-name-alist' has to be modified accordingly.
1601 ;;;; Babel Call
1603 (defun org-element-babel-call-parser (limit affiliated)
1604 "Parse a babel call.
1606 LIMIT bounds the search. AFFILIATED is a list of which car is
1607 the buffer position at the beginning of the first affiliated
1608 keyword and cdr is a plist of affiliated keywords along with
1609 their value.
1611 Return a list whose car is `babel-call' and cdr is a plist
1612 containing `:call', `:inside-header', `:arguments',
1613 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1614 `:post-affiliated' as keywords."
1615 (save-excursion
1616 (let* ((begin (car affiliated))
1617 (post-affiliated (point))
1618 (value (progn (search-forward ":" nil t)
1619 (org-trim
1620 (buffer-substring-no-properties
1621 (point) (line-end-position)))))
1622 (pos-before-blank (progn (forward-line) (point)))
1623 (end (progn (skip-chars-forward " \r\t\n" limit)
1624 (if (eobp) (point) (line-beginning-position))))
1625 (valid-value
1626 (string-match
1627 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*?\\))[ \t]*\\(.*\\)"
1628 value)))
1629 (list 'babel-call
1630 (nconc
1631 (list :call (and valid-value (match-string 1 value))
1632 :inside-header (and valid-value
1633 (org-string-nw-p (match-string 2 value)))
1634 :arguments (and valid-value
1635 (org-string-nw-p (match-string 3 value)))
1636 :end-header (and valid-value
1637 (org-string-nw-p (match-string 4 value)))
1638 :begin begin
1639 :end end
1640 :value value
1641 :post-blank (count-lines pos-before-blank end)
1642 :post-affiliated post-affiliated)
1643 (cdr affiliated))))))
1645 (defun org-element-babel-call-interpreter (babel-call contents)
1646 "Interpret BABEL-CALL element as Org syntax.
1647 CONTENTS is nil."
1648 (concat "#+CALL: "
1649 (org-element-property :call babel-call)
1650 (let ((h (org-element-property :inside-header babel-call)))
1651 (and h (format "[%s]" h)))
1652 (concat "(" (org-element-property :arguments babel-call) ")")
1653 (let ((h (org-element-property :end-header babel-call)))
1654 (and h (concat " " h)))))
1657 ;;;; Clock
1659 (defun org-element-clock-parser (limit)
1660 "Parse a clock.
1662 LIMIT bounds the search.
1664 Return a list whose CAR is `clock' and CDR is a plist containing
1665 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1666 `:post-affiliated' as keywords."
1667 (save-excursion
1668 (let* ((case-fold-search nil)
1669 (begin (point))
1670 (value (progn (search-forward org-clock-string (line-end-position) t)
1671 (skip-chars-forward " \t")
1672 (org-element-timestamp-parser)))
1673 (duration (and (search-forward " => " (line-end-position) t)
1674 (progn (skip-chars-forward " \t")
1675 (looking-at "\\(\\S-+\\)[ \t]*$"))
1676 (org-match-string-no-properties 1)))
1677 (status (if duration 'closed 'running))
1678 (post-blank (let ((before-blank (progn (forward-line) (point))))
1679 (skip-chars-forward " \r\t\n" limit)
1680 (skip-chars-backward " \t")
1681 (unless (bolp) (end-of-line))
1682 (count-lines before-blank (point))))
1683 (end (point)))
1684 (list 'clock
1685 (list :status status
1686 :value value
1687 :duration duration
1688 :begin begin
1689 :end end
1690 :post-blank post-blank
1691 :post-affiliated begin)))))
1693 (defun org-element-clock-interpreter (clock contents)
1694 "Interpret CLOCK element as Org syntax.
1695 CONTENTS is nil."
1696 (concat org-clock-string " "
1697 (org-element-timestamp-interpreter
1698 (org-element-property :value clock) nil)
1699 (let ((duration (org-element-property :duration clock)))
1700 (and duration
1701 (concat " => "
1702 (apply 'format
1703 "%2s:%02s"
1704 (org-split-string duration ":")))))))
1707 ;;;; Comment
1709 (defun org-element-comment-parser (limit affiliated)
1710 "Parse a comment.
1712 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1713 the buffer position at the beginning of the first affiliated
1714 keyword and CDR is a plist of affiliated keywords along with
1715 their value.
1717 Return a list whose CAR is `comment' and CDR is a plist
1718 containing `:begin', `:end', `:value', `:post-blank',
1719 `:post-affiliated' keywords.
1721 Assume point is at comment beginning."
1722 (save-excursion
1723 (let* ((begin (car affiliated))
1724 (post-affiliated (point))
1725 (value (prog2 (looking-at "[ \t]*# ?")
1726 (buffer-substring-no-properties
1727 (match-end 0) (line-end-position))
1728 (forward-line)))
1729 (com-end
1730 ;; Get comments ending.
1731 (progn
1732 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1733 ;; Accumulate lines without leading hash and first
1734 ;; whitespace.
1735 (setq value
1736 (concat value
1737 "\n"
1738 (buffer-substring-no-properties
1739 (match-end 0) (line-end-position))))
1740 (forward-line))
1741 (point)))
1742 (end (progn (goto-char com-end)
1743 (skip-chars-forward " \r\t\n" limit)
1744 (if (eobp) (point) (line-beginning-position)))))
1745 (list 'comment
1746 (nconc
1747 (list :begin begin
1748 :end end
1749 :value value
1750 :post-blank (count-lines com-end end)
1751 :post-affiliated post-affiliated)
1752 (cdr affiliated))))))
1754 (defun org-element-comment-interpreter (comment contents)
1755 "Interpret COMMENT element as Org syntax.
1756 CONTENTS is nil."
1757 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1760 ;;;; Comment Block
1762 (defun org-element-comment-block-parser (limit affiliated)
1763 "Parse an export block.
1765 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1766 the buffer position at the beginning of the first affiliated
1767 keyword and CDR is a plist of affiliated keywords along with
1768 their value.
1770 Return a list whose CAR is `comment-block' and CDR is a plist
1771 containing `:begin', `:end', `:value', `:post-blank' and
1772 `:post-affiliated' keywords.
1774 Assume point is at comment block beginning."
1775 (let ((case-fold-search t))
1776 (if (not (save-excursion
1777 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1778 ;; Incomplete block: parse it as a paragraph.
1779 (org-element-paragraph-parser limit affiliated)
1780 (let ((contents-end (match-beginning 0)))
1781 (save-excursion
1782 (let* ((begin (car affiliated))
1783 (post-affiliated (point))
1784 (contents-begin (progn (forward-line) (point)))
1785 (pos-before-blank (progn (goto-char contents-end)
1786 (forward-line)
1787 (point)))
1788 (end (progn (skip-chars-forward " \r\t\n" limit)
1789 (if (eobp) (point) (line-beginning-position))))
1790 (value (buffer-substring-no-properties
1791 contents-begin contents-end)))
1792 (list 'comment-block
1793 (nconc
1794 (list :begin begin
1795 :end end
1796 :value value
1797 :post-blank (count-lines pos-before-blank end)
1798 :post-affiliated post-affiliated)
1799 (cdr affiliated)))))))))
1801 (defun org-element-comment-block-interpreter (comment-block contents)
1802 "Interpret COMMENT-BLOCK element as Org syntax.
1803 CONTENTS is nil."
1804 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1805 (org-element-normalize-string
1806 (org-remove-indentation
1807 (org-element-property :value comment-block)))))
1810 ;;;; Diary Sexp
1812 (defun org-element-diary-sexp-parser (limit affiliated)
1813 "Parse a diary sexp.
1815 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1816 the buffer position at the beginning of the first affiliated
1817 keyword and CDR is a plist of affiliated keywords along with
1818 their value.
1820 Return a list whose CAR is `diary-sexp' and CDR is a plist
1821 containing `:begin', `:end', `:value', `:post-blank' and
1822 `:post-affiliated' keywords."
1823 (save-excursion
1824 (let ((begin (car affiliated))
1825 (post-affiliated (point))
1826 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1827 (org-match-string-no-properties 1)))
1828 (pos-before-blank (progn (forward-line) (point)))
1829 (end (progn (skip-chars-forward " \r\t\n" limit)
1830 (if (eobp) (point) (line-beginning-position)))))
1831 (list 'diary-sexp
1832 (nconc
1833 (list :value value
1834 :begin begin
1835 :end end
1836 :post-blank (count-lines pos-before-blank end)
1837 :post-affiliated post-affiliated)
1838 (cdr affiliated))))))
1840 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1841 "Interpret DIARY-SEXP as Org syntax.
1842 CONTENTS is nil."
1843 (org-element-property :value diary-sexp))
1846 ;;;; Example Block
1848 (defun org-element-example-block-parser (limit affiliated)
1849 "Parse an example block.
1851 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1852 the buffer position at the beginning of the first affiliated
1853 keyword and CDR is a plist of affiliated keywords along with
1854 their value.
1856 Return a list whose CAR is `example-block' and CDR is a plist
1857 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1858 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1859 `:value', `:post-blank' and `:post-affiliated' keywords."
1860 (let ((case-fold-search t))
1861 (if (not (save-excursion
1862 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1863 ;; Incomplete block: parse it as a paragraph.
1864 (org-element-paragraph-parser limit affiliated)
1865 (let ((contents-end (match-beginning 0)))
1866 (save-excursion
1867 (let* ((switches
1868 (progn
1869 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1870 (org-match-string-no-properties 1)))
1871 ;; Switches analysis
1872 (number-lines
1873 (cond ((not switches) nil)
1874 ((string-match "-n\\>" switches) 'new)
1875 ((string-match "+n\\>" switches) 'continued)))
1876 (preserve-indent
1877 (and switches (string-match "-i\\>" switches)))
1878 ;; Should labels be retained in (or stripped from) example
1879 ;; blocks?
1880 (retain-labels
1881 (or (not switches)
1882 (not (string-match "-r\\>" switches))
1883 (and number-lines (string-match "-k\\>" switches))))
1884 ;; What should code-references use - labels or
1885 ;; line-numbers?
1886 (use-labels
1887 (or (not switches)
1888 (and retain-labels
1889 (not (string-match "-k\\>" switches)))))
1890 (label-fmt
1891 (and switches
1892 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1893 (match-string 1 switches)))
1894 ;; Standard block parsing.
1895 (begin (car affiliated))
1896 (post-affiliated (point))
1897 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1898 (contents-begin (progn (forward-line) (point)))
1899 (value (org-element-remove-indentation
1900 (org-unescape-code-in-string
1901 (buffer-substring-no-properties
1902 contents-begin contents-end))
1903 block-ind))
1904 (pos-before-blank (progn (goto-char contents-end)
1905 (forward-line)
1906 (point)))
1907 (end (progn (skip-chars-forward " \r\t\n" limit)
1908 (if (eobp) (point) (line-beginning-position)))))
1909 (list 'example-block
1910 (nconc
1911 (list :begin begin
1912 :end end
1913 :value value
1914 :switches switches
1915 :number-lines number-lines
1916 :preserve-indent preserve-indent
1917 :retain-labels retain-labels
1918 :use-labels use-labels
1919 :label-fmt label-fmt
1920 :post-blank (count-lines pos-before-blank end)
1921 :post-affiliated post-affiliated)
1922 (cdr affiliated)))))))))
1924 (defun org-element-example-block-interpreter (example-block contents)
1925 "Interpret EXAMPLE-BLOCK element as Org syntax.
1926 CONTENTS is nil."
1927 (let ((switches (org-element-property :switches example-block))
1928 (value (org-element-property :value example-block)))
1929 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1930 (org-element-normalize-string
1931 (org-escape-code-in-string
1932 (if (or org-src-preserve-indentation
1933 (org-element-property :preserve-indent example-block))
1934 value
1935 (org-element-remove-indentation value))))
1936 "#+END_EXAMPLE")))
1939 ;;;; Export Block
1941 (defun org-element-export-block-parser (limit affiliated)
1942 "Parse an export block.
1944 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1945 the buffer position at the beginning of the first affiliated
1946 keyword and CDR is a plist of affiliated keywords along with
1947 their value.
1949 Return a list whose CAR is `export-block' and CDR is a plist
1950 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1951 `:post-affiliated' keywords.
1953 Assume point is at export-block beginning."
1954 (let* ((case-fold-search t)
1955 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1956 (upcase (org-match-string-no-properties 1)))))
1957 (if (not (save-excursion
1958 (re-search-forward
1959 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1960 ;; Incomplete block: parse it as a paragraph.
1961 (org-element-paragraph-parser limit affiliated)
1962 (let ((contents-end (match-beginning 0)))
1963 (save-excursion
1964 (let* ((begin (car affiliated))
1965 (post-affiliated (point))
1966 (contents-begin (progn (forward-line) (point)))
1967 (pos-before-blank (progn (goto-char contents-end)
1968 (forward-line)
1969 (point)))
1970 (end (progn (skip-chars-forward " \r\t\n" limit)
1971 (if (eobp) (point) (line-beginning-position))))
1972 (value (buffer-substring-no-properties contents-begin
1973 contents-end)))
1974 (list 'export-block
1975 (nconc
1976 (list :begin begin
1977 :end end
1978 :type type
1979 :value value
1980 :post-blank (count-lines pos-before-blank end)
1981 :post-affiliated post-affiliated)
1982 (cdr affiliated)))))))))
1984 (defun org-element-export-block-interpreter (export-block contents)
1985 "Interpret EXPORT-BLOCK element as Org syntax.
1986 CONTENTS is nil."
1987 (let ((type (org-element-property :type export-block)))
1988 (concat (format "#+BEGIN_%s\n" type)
1989 (org-element-property :value export-block)
1990 (format "#+END_%s" type))))
1993 ;;;; Fixed-width
1995 (defun org-element-fixed-width-parser (limit affiliated)
1996 "Parse a fixed-width section.
1998 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1999 the buffer position at the beginning of the first affiliated
2000 keyword and CDR is a plist of affiliated keywords along with
2001 their value.
2003 Return a list whose CAR is `fixed-width' and CDR is a plist
2004 containing `:begin', `:end', `:value', `:post-blank' and
2005 `:post-affiliated' keywords.
2007 Assume point is at the beginning of the fixed-width area."
2008 (save-excursion
2009 (let* ((begin (car affiliated))
2010 (post-affiliated (point))
2011 value
2012 (end-area
2013 (progn
2014 (while (and (< (point) limit)
2015 (looking-at "[ \t]*:\\( \\|$\\)"))
2016 ;; Accumulate text without starting colons.
2017 (setq value
2018 (concat value
2019 (buffer-substring-no-properties
2020 (match-end 0) (point-at-eol))
2021 "\n"))
2022 (forward-line))
2023 (point)))
2024 (end (progn (skip-chars-forward " \r\t\n" limit)
2025 (if (eobp) (point) (line-beginning-position)))))
2026 (list 'fixed-width
2027 (nconc
2028 (list :begin begin
2029 :end end
2030 :value value
2031 :post-blank (count-lines end-area end)
2032 :post-affiliated post-affiliated)
2033 (cdr affiliated))))))
2035 (defun org-element-fixed-width-interpreter (fixed-width contents)
2036 "Interpret FIXED-WIDTH element as Org syntax.
2037 CONTENTS is nil."
2038 (let ((value (org-element-property :value fixed-width)))
2039 (and value
2040 (replace-regexp-in-string
2041 "^" ": "
2042 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2045 ;;;; Horizontal Rule
2047 (defun org-element-horizontal-rule-parser (limit affiliated)
2048 "Parse an horizontal rule.
2050 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2051 the buffer position at the beginning of the first affiliated
2052 keyword and CDR is a plist of affiliated keywords along with
2053 their value.
2055 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2056 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2057 keywords."
2058 (save-excursion
2059 (let ((begin (car affiliated))
2060 (post-affiliated (point))
2061 (post-hr (progn (forward-line) (point)))
2062 (end (progn (skip-chars-forward " \r\t\n" limit)
2063 (if (eobp) (point) (line-beginning-position)))))
2064 (list 'horizontal-rule
2065 (nconc
2066 (list :begin begin
2067 :end end
2068 :post-blank (count-lines post-hr end)
2069 :post-affiliated post-affiliated)
2070 (cdr affiliated))))))
2072 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
2073 "Interpret HORIZONTAL-RULE element as Org syntax.
2074 CONTENTS is nil."
2075 "-----")
2078 ;;;; Keyword
2080 (defun org-element-keyword-parser (limit affiliated)
2081 "Parse a keyword at point.
2083 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2084 the buffer position at the beginning of the first affiliated
2085 keyword and CDR is a plist of affiliated keywords along with
2086 their value.
2088 Return a list whose CAR is `keyword' and CDR is a plist
2089 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2090 `:post-affiliated' keywords."
2091 (save-excursion
2092 ;; An orphaned affiliated keyword is considered as a regular
2093 ;; keyword. In this case AFFILIATED is nil, so we take care of
2094 ;; this corner case.
2095 (let ((begin (or (car affiliated) (point)))
2096 (post-affiliated (point))
2097 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2098 (upcase (org-match-string-no-properties 1))))
2099 (value (org-trim (buffer-substring-no-properties
2100 (match-end 0) (point-at-eol))))
2101 (pos-before-blank (progn (forward-line) (point)))
2102 (end (progn (skip-chars-forward " \r\t\n" limit)
2103 (if (eobp) (point) (line-beginning-position)))))
2104 (list 'keyword
2105 (nconc
2106 (list :key key
2107 :value value
2108 :begin begin
2109 :end end
2110 :post-blank (count-lines pos-before-blank end)
2111 :post-affiliated post-affiliated)
2112 (cdr affiliated))))))
2114 (defun org-element-keyword-interpreter (keyword contents)
2115 "Interpret KEYWORD element as Org syntax.
2116 CONTENTS is nil."
2117 (format "#+%s: %s"
2118 (org-element-property :key keyword)
2119 (org-element-property :value keyword)))
2122 ;;;; Latex Environment
2124 (defconst org-element--latex-begin-environment
2125 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2126 "Regexp matching the beginning of a LaTeX environment.
2127 The environment is captured by the first group.
2129 See also `org-element--latex-end-environment'.")
2131 (defconst org-element--latex-end-environment
2132 "\\\\end{%s}[ \t]*$"
2133 "Format string matching the ending of a LaTeX environment.
2134 See also `org-element--latex-begin-environment'.")
2136 (defun org-element-latex-environment-parser (limit affiliated)
2137 "Parse a LaTeX environment.
2139 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2140 the buffer position at the beginning of the first affiliated
2141 keyword and CDR is a plist of affiliated keywords along with
2142 their value.
2144 Return a list whose CAR is `latex-environment' and CDR is a plist
2145 containing `:begin', `:end', `:value', `:post-blank' and
2146 `:post-affiliated' keywords.
2148 Assume point is at the beginning of the latex environment."
2149 (save-excursion
2150 (let ((case-fold-search t)
2151 (code-begin (point)))
2152 (looking-at org-element--latex-begin-environment)
2153 (if (not (re-search-forward (format org-element--latex-end-environment
2154 (regexp-quote (match-string 1)))
2155 limit t))
2156 ;; Incomplete latex environment: parse it as a paragraph.
2157 (org-element-paragraph-parser limit affiliated)
2158 (let* ((code-end (progn (forward-line) (point)))
2159 (begin (car affiliated))
2160 (value (buffer-substring-no-properties code-begin code-end))
2161 (end (progn (skip-chars-forward " \r\t\n" limit)
2162 (if (eobp) (point) (line-beginning-position)))))
2163 (list 'latex-environment
2164 (nconc
2165 (list :begin begin
2166 :end end
2167 :value value
2168 :post-blank (count-lines code-end end)
2169 :post-affiliated code-begin)
2170 (cdr affiliated))))))))
2172 (defun org-element-latex-environment-interpreter (latex-environment contents)
2173 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2174 CONTENTS is nil."
2175 (org-element-property :value latex-environment))
2178 ;;;; Node Property
2180 (defun org-element-node-property-parser (limit)
2181 "Parse a node-property at point.
2183 LIMIT bounds the search.
2185 Return a list whose CAR is `node-property' and CDR is a plist
2186 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2187 `:post-affiliated' keywords."
2188 (looking-at org-property-re)
2189 (let ((case-fold-search t)
2190 (begin (point))
2191 (key (org-match-string-no-properties 2))
2192 (value (org-match-string-no-properties 3))
2193 (end (save-excursion
2194 (end-of-line)
2195 (if (re-search-forward org-property-re limit t)
2196 (line-beginning-position)
2197 limit))))
2198 (list 'node-property
2199 (list :key key
2200 :value value
2201 :begin begin
2202 :end end
2203 :post-blank 0
2204 :post-affiliated begin))))
2206 (defun org-element-node-property-interpreter (node-property contents)
2207 "Interpret NODE-PROPERTY element as Org syntax.
2208 CONTENTS is nil."
2209 (format org-property-format
2210 (format ":%s:" (org-element-property :key node-property))
2211 (or (org-element-property :value node-property) "")))
2214 ;;;; Paragraph
2216 (defun org-element-paragraph-parser (limit affiliated)
2217 "Parse a paragraph.
2219 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2220 the buffer position at the beginning of the first affiliated
2221 keyword and CDR is a plist of affiliated keywords along with
2222 their value.
2224 Return a list whose CAR is `paragraph' and CDR is a plist
2225 containing `:begin', `:end', `:contents-begin' and
2226 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2228 Assume point is at the beginning of the paragraph."
2229 (save-excursion
2230 (let* ((begin (car affiliated))
2231 (contents-begin (point))
2232 (before-blank
2233 (let ((case-fold-search t))
2234 (end-of-line)
2235 ;; A matching `org-element-paragraph-separate' is not
2236 ;; necessarily the end of the paragraph. In particular,
2237 ;; drawers, blocks or LaTeX environments opening lines
2238 ;; must be closed. Moreover keywords with a secondary
2239 ;; value must belong to "dual keywords".
2240 (while (not
2241 (cond
2242 ((not (and (re-search-forward
2243 org-element-paragraph-separate limit 'move)
2244 (progn (beginning-of-line) t))))
2245 ((looking-at org-drawer-regexp)
2246 (save-excursion
2247 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2248 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2249 (save-excursion
2250 (re-search-forward
2251 (format "^[ \t]*#\\+END_%s[ \t]*$"
2252 (regexp-quote (match-string 1)))
2253 limit t)))
2254 ((looking-at org-element--latex-begin-environment)
2255 (save-excursion
2256 (re-search-forward
2257 (format org-element--latex-end-environment
2258 (regexp-quote (match-string 1)))
2259 limit t)))
2260 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2261 (member-ignore-case (match-string 1)
2262 org-element-dual-keywords))
2263 ;; Everything else is unambiguous.
2264 (t)))
2265 (end-of-line))
2266 (if (= (point) limit) limit
2267 (goto-char (line-beginning-position)))))
2268 (contents-end (save-excursion
2269 (skip-chars-backward " \r\t\n" contents-begin)
2270 (line-beginning-position 2)))
2271 (end (progn (skip-chars-forward " \r\t\n" limit)
2272 (if (eobp) (point) (line-beginning-position)))))
2273 (list 'paragraph
2274 (nconc
2275 (list :begin begin
2276 :end end
2277 :contents-begin contents-begin
2278 :contents-end contents-end
2279 :post-blank (count-lines before-blank end)
2280 :post-affiliated contents-begin)
2281 (cdr affiliated))))))
2283 (defun org-element-paragraph-interpreter (paragraph contents)
2284 "Interpret PARAGRAPH element as Org syntax.
2285 CONTENTS is the contents of the element."
2286 contents)
2289 ;;;; Planning
2291 (defun org-element-planning-parser (limit)
2292 "Parse a planning.
2294 LIMIT bounds the search.
2296 Return a list whose CAR is `planning' and CDR is a plist
2297 containing `:closed', `:deadline', `:scheduled', `:begin',
2298 `:end', `:post-blank' and `:post-affiliated' keywords."
2299 (save-excursion
2300 (let* ((case-fold-search nil)
2301 (begin (point))
2302 (post-blank (let ((before-blank (progn (forward-line) (point))))
2303 (skip-chars-forward " \r\t\n" limit)
2304 (skip-chars-backward " \t")
2305 (unless (bolp) (end-of-line))
2306 (count-lines before-blank (point))))
2307 (end (point))
2308 closed deadline scheduled)
2309 (goto-char begin)
2310 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2311 (goto-char (match-end 1))
2312 (skip-chars-forward " \t" end)
2313 (let ((keyword (match-string 1))
2314 (time (org-element-timestamp-parser)))
2315 (cond ((equal keyword org-closed-string) (setq closed time))
2316 ((equal keyword org-deadline-string) (setq deadline time))
2317 (t (setq scheduled time)))))
2318 (list 'planning
2319 (list :closed closed
2320 :deadline deadline
2321 :scheduled scheduled
2322 :begin begin
2323 :end end
2324 :post-blank post-blank
2325 :post-affiliated begin)))))
2327 (defun org-element-planning-interpreter (planning contents)
2328 "Interpret PLANNING element as Org syntax.
2329 CONTENTS is nil."
2330 (mapconcat
2331 'identity
2332 (delq nil
2333 (list (let ((deadline (org-element-property :deadline planning)))
2334 (when deadline
2335 (concat org-deadline-string " "
2336 (org-element-timestamp-interpreter deadline nil))))
2337 (let ((scheduled (org-element-property :scheduled planning)))
2338 (when scheduled
2339 (concat org-scheduled-string " "
2340 (org-element-timestamp-interpreter scheduled nil))))
2341 (let ((closed (org-element-property :closed planning)))
2342 (when closed
2343 (concat org-closed-string " "
2344 (org-element-timestamp-interpreter closed nil))))))
2345 " "))
2348 ;;;; Src Block
2350 (defun org-element-src-block-parser (limit affiliated)
2351 "Parse a src block.
2353 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2354 the buffer position at the beginning of the first affiliated
2355 keyword and CDR is a plist of affiliated keywords along with
2356 their value.
2358 Return a list whose CAR is `src-block' and CDR is a plist
2359 containing `:language', `:switches', `:parameters', `:begin',
2360 `:end', `:number-lines', `:retain-labels', `:use-labels',
2361 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2362 `:post-affiliated' keywords.
2364 Assume point is at the beginning of the block."
2365 (let ((case-fold-search t))
2366 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2367 limit t)))
2368 ;; Incomplete block: parse it as a paragraph.
2369 (org-element-paragraph-parser limit affiliated)
2370 (let ((contents-end (match-beginning 0)))
2371 (save-excursion
2372 (let* ((begin (car affiliated))
2373 (post-affiliated (point))
2374 ;; Get language as a string.
2375 (language
2376 (progn
2377 (looking-at
2378 (concat "^[ \t]*#\\+BEGIN_SRC"
2379 "\\(?: +\\(\\S-+\\)\\)?"
2380 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2381 "\\(.*\\)[ \t]*$"))
2382 (org-match-string-no-properties 1)))
2383 ;; Get switches.
2384 (switches (org-match-string-no-properties 2))
2385 ;; Get parameters.
2386 (parameters (org-match-string-no-properties 3))
2387 ;; Switches analysis
2388 (number-lines
2389 (cond ((not switches) nil)
2390 ((string-match "-n\\>" switches) 'new)
2391 ((string-match "+n\\>" switches) 'continued)))
2392 (preserve-indent (and switches
2393 (string-match "-i\\>" switches)))
2394 (label-fmt
2395 (and switches
2396 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2397 (match-string 1 switches)))
2398 ;; Should labels be retained in (or stripped from)
2399 ;; src blocks?
2400 (retain-labels
2401 (or (not switches)
2402 (not (string-match "-r\\>" switches))
2403 (and number-lines (string-match "-k\\>" switches))))
2404 ;; What should code-references use - labels or
2405 ;; line-numbers?
2406 (use-labels
2407 (or (not switches)
2408 (and retain-labels
2409 (not (string-match "-k\\>" switches)))))
2410 ;; Indentation.
2411 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2412 ;; Retrieve code.
2413 (value (org-element-remove-indentation
2414 (org-unescape-code-in-string
2415 (buffer-substring-no-properties
2416 (progn (forward-line) (point)) contents-end))
2417 block-ind))
2418 (pos-before-blank (progn (goto-char contents-end)
2419 (forward-line)
2420 (point)))
2421 ;; Get position after ending blank lines.
2422 (end (progn (skip-chars-forward " \r\t\n" limit)
2423 (if (eobp) (point) (line-beginning-position)))))
2424 (list 'src-block
2425 (nconc
2426 (list :language language
2427 :switches (and (org-string-nw-p switches)
2428 (org-trim switches))
2429 :parameters (and (org-string-nw-p parameters)
2430 (org-trim parameters))
2431 :begin begin
2432 :end end
2433 :number-lines number-lines
2434 :preserve-indent preserve-indent
2435 :retain-labels retain-labels
2436 :use-labels use-labels
2437 :label-fmt label-fmt
2438 :value value
2439 :post-blank (count-lines pos-before-blank end)
2440 :post-affiliated post-affiliated)
2441 (cdr affiliated)))))))))
2443 (defun org-element-src-block-interpreter (src-block contents)
2444 "Interpret SRC-BLOCK element as Org syntax.
2445 CONTENTS is nil."
2446 (let ((lang (org-element-property :language src-block))
2447 (switches (org-element-property :switches src-block))
2448 (params (org-element-property :parameters src-block))
2449 (value
2450 (let ((val (org-element-property :value src-block)))
2451 (cond
2452 ((or org-src-preserve-indentation
2453 (org-element-property :preserve-indent src-block))
2454 val)
2455 ((zerop org-edit-src-content-indentation) val)
2457 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2458 (replace-regexp-in-string
2459 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2460 (concat (format "#+BEGIN_SRC%s\n"
2461 (concat (and lang (concat " " lang))
2462 (and switches (concat " " switches))
2463 (and params (concat " " params))))
2464 (org-element-normalize-string (org-escape-code-in-string value))
2465 "#+END_SRC")))
2468 ;;;; Table
2470 (defun org-element-table-parser (limit affiliated)
2471 "Parse a table at point.
2473 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2474 the buffer position at the beginning of the first affiliated
2475 keyword and CDR is a plist of affiliated keywords along with
2476 their value.
2478 Return a list whose CAR is `table' and CDR is a plist containing
2479 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2480 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2481 keywords.
2483 Assume point is at the beginning of the table."
2484 (save-excursion
2485 (let* ((case-fold-search t)
2486 (table-begin (point))
2487 (type (if (org-at-table.el-p) 'table.el 'org))
2488 (begin (car affiliated))
2489 (table-end
2490 (if (re-search-forward org-table-any-border-regexp limit 'm)
2491 (goto-char (match-beginning 0))
2492 (point)))
2493 (tblfm (let (acc)
2494 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2495 (push (org-match-string-no-properties 1) acc)
2496 (forward-line))
2497 acc))
2498 (pos-before-blank (point))
2499 (end (progn (skip-chars-forward " \r\t\n" limit)
2500 (if (eobp) (point) (line-beginning-position)))))
2501 (list 'table
2502 (nconc
2503 (list :begin begin
2504 :end end
2505 :type type
2506 :tblfm tblfm
2507 ;; Only `org' tables have contents. `table.el' tables
2508 ;; use a `:value' property to store raw table as
2509 ;; a string.
2510 :contents-begin (and (eq type 'org) table-begin)
2511 :contents-end (and (eq type 'org) table-end)
2512 :value (and (eq type 'table.el)
2513 (buffer-substring-no-properties
2514 table-begin table-end))
2515 :post-blank (count-lines pos-before-blank end)
2516 :post-affiliated table-begin)
2517 (cdr affiliated))))))
2519 (defun org-element-table-interpreter (table contents)
2520 "Interpret TABLE element as Org syntax.
2521 CONTENTS is a string, if table's type is `org', or nil."
2522 (if (eq (org-element-property :type table) 'table.el)
2523 (org-remove-indentation (org-element-property :value table))
2524 (concat (with-temp-buffer (insert contents)
2525 (org-table-align)
2526 (buffer-string))
2527 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2528 (reverse (org-element-property :tblfm table))
2529 "\n"))))
2532 ;;;; Table Row
2534 (defun org-element-table-row-parser (limit)
2535 "Parse table row at point.
2537 LIMIT bounds the search.
2539 Return a list whose CAR is `table-row' and CDR is a plist
2540 containing `:begin', `:end', `:contents-begin', `:contents-end',
2541 `:type', `:post-blank' and `:post-affiliated' keywords."
2542 (save-excursion
2543 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2544 (begin (point))
2545 ;; A table rule has no contents. In that case, ensure
2546 ;; CONTENTS-BEGIN matches CONTENTS-END.
2547 (contents-begin (and (eq type 'standard)
2548 (search-forward "|")
2549 (point)))
2550 (contents-end (and (eq type 'standard)
2551 (progn
2552 (end-of-line)
2553 (skip-chars-backward " \t")
2554 (point))))
2555 (end (progn (forward-line) (point))))
2556 (list 'table-row
2557 (list :type type
2558 :begin begin
2559 :end end
2560 :contents-begin contents-begin
2561 :contents-end contents-end
2562 :post-blank 0
2563 :post-affiliated begin)))))
2565 (defun org-element-table-row-interpreter (table-row contents)
2566 "Interpret TABLE-ROW element as Org syntax.
2567 CONTENTS is the contents of the table row."
2568 (if (eq (org-element-property :type table-row) 'rule) "|-"
2569 (concat "| " contents)))
2572 ;;;; Verse Block
2574 (defun org-element-verse-block-parser (limit affiliated)
2575 "Parse a verse block.
2577 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2578 the buffer position at the beginning of the first affiliated
2579 keyword and CDR is a plist of affiliated keywords along with
2580 their value.
2582 Return a list whose CAR is `verse-block' and CDR is a plist
2583 containing `:begin', `:end', `:contents-begin', `:contents-end',
2584 `:post-blank' and `:post-affiliated' keywords.
2586 Assume point is at beginning of the block."
2587 (let ((case-fold-search t))
2588 (if (not (save-excursion
2589 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2590 ;; Incomplete block: parse it as a paragraph.
2591 (org-element-paragraph-parser limit affiliated)
2592 (let ((contents-end (match-beginning 0)))
2593 (save-excursion
2594 (let* ((begin (car affiliated))
2595 (post-affiliated (point))
2596 (contents-begin (progn (forward-line) (point)))
2597 (pos-before-blank (progn (goto-char contents-end)
2598 (forward-line)
2599 (point)))
2600 (end (progn (skip-chars-forward " \r\t\n" limit)
2601 (if (eobp) (point) (line-beginning-position)))))
2602 (list 'verse-block
2603 (nconc
2604 (list :begin begin
2605 :end end
2606 :contents-begin contents-begin
2607 :contents-end contents-end
2608 :post-blank (count-lines pos-before-blank end)
2609 :post-affiliated post-affiliated)
2610 (cdr affiliated)))))))))
2612 (defun org-element-verse-block-interpreter (verse-block contents)
2613 "Interpret VERSE-BLOCK element as Org syntax.
2614 CONTENTS is verse block contents."
2615 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2619 ;;; Objects
2621 ;; Unlike to elements, raw text can be found between objects. Hence,
2622 ;; `org-element--object-lex' is provided to find the next object in
2623 ;; buffer.
2625 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2626 ;; object types they can contain will be specified in
2627 ;; `org-element-object-restrictions'.
2629 ;; Creating a new type of object requires to alter
2630 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2631 ;; new type in `org-element-all-objects', and possibly add
2632 ;; restrictions in `org-element-object-restrictions'.
2634 ;;;; Bold
2636 (defun org-element-bold-parser ()
2637 "Parse bold object at point, if any.
2639 When at a bold object, return a list whose car is `bold' and cdr
2640 is a plist with `:begin', `:end', `:contents-begin' and
2641 `:contents-end' and `:post-blank' keywords. Otherwise, return
2642 nil.
2644 Assume point is at the first star marker."
2645 (save-excursion
2646 (unless (bolp) (backward-char 1))
2647 (when (looking-at org-emph-re)
2648 (let ((begin (match-beginning 2))
2649 (contents-begin (match-beginning 4))
2650 (contents-end (match-end 4))
2651 (post-blank (progn (goto-char (match-end 2))
2652 (skip-chars-forward " \t")))
2653 (end (point)))
2654 (list 'bold
2655 (list :begin begin
2656 :end end
2657 :contents-begin contents-begin
2658 :contents-end contents-end
2659 :post-blank post-blank))))))
2661 (defun org-element-bold-interpreter (bold contents)
2662 "Interpret BOLD object as Org syntax.
2663 CONTENTS is the contents of the object."
2664 (format "*%s*" contents))
2667 ;;;; Code
2669 (defun org-element-code-parser ()
2670 "Parse code object at point, if any.
2672 When at a code object, return a list whose car is `code' and cdr
2673 is a plist with `:value', `:begin', `:end' and `:post-blank'
2674 keywords. Otherwise, return nil.
2676 Assume point is at the first tilde marker."
2677 (save-excursion
2678 (unless (bolp) (backward-char 1))
2679 (when (looking-at org-emph-re)
2680 (let ((begin (match-beginning 2))
2681 (value (org-match-string-no-properties 4))
2682 (post-blank (progn (goto-char (match-end 2))
2683 (skip-chars-forward " \t")))
2684 (end (point)))
2685 (list 'code
2686 (list :value value
2687 :begin begin
2688 :end end
2689 :post-blank post-blank))))))
2691 (defun org-element-code-interpreter (code contents)
2692 "Interpret CODE object as Org syntax.
2693 CONTENTS is nil."
2694 (format "~%s~" (org-element-property :value code)))
2697 ;;;; Entity
2699 (defun org-element-entity-parser ()
2700 "Parse entity at point, if any.
2702 When at an entity, return a list whose car is `entity' and cdr
2703 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2704 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2705 `:post-blank' as keywords. Otherwise, return nil.
2707 Assume point is at the beginning of the entity."
2708 (catch 'no-object
2709 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2710 (save-excursion
2711 (let* ((value (or (org-entity-get (match-string 1))
2712 (throw 'no-object nil)))
2713 (begin (match-beginning 0))
2714 (bracketsp (string= (match-string 2) "{}"))
2715 (post-blank (progn (goto-char (match-end 1))
2716 (when bracketsp (forward-char 2))
2717 (skip-chars-forward " \t")))
2718 (end (point)))
2719 (list 'entity
2720 (list :name (car value)
2721 :latex (nth 1 value)
2722 :latex-math-p (nth 2 value)
2723 :html (nth 3 value)
2724 :ascii (nth 4 value)
2725 :latin1 (nth 5 value)
2726 :utf-8 (nth 6 value)
2727 :begin begin
2728 :end end
2729 :use-brackets-p bracketsp
2730 :post-blank post-blank)))))))
2732 (defun org-element-entity-interpreter (entity contents)
2733 "Interpret ENTITY object as Org syntax.
2734 CONTENTS is nil."
2735 (concat "\\"
2736 (org-element-property :name entity)
2737 (when (org-element-property :use-brackets-p entity) "{}")))
2740 ;;;; Export Snippet
2742 (defun org-element-export-snippet-parser ()
2743 "Parse export snippet at point.
2745 When at an export snippet, return a list whose car is
2746 `export-snippet' and cdr a plist with `:begin', `:end',
2747 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2748 return nil.
2750 Assume point is at the beginning of the snippet."
2751 (save-excursion
2752 (let (contents-end)
2753 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2754 (setq contents-end
2755 (save-match-data (goto-char (match-end 0))
2756 (re-search-forward "@@" nil t)
2757 (match-beginning 0))))
2758 (let* ((begin (match-beginning 0))
2759 (back-end (org-match-string-no-properties 1))
2760 (value (buffer-substring-no-properties
2761 (match-end 0) contents-end))
2762 (post-blank (skip-chars-forward " \t"))
2763 (end (point)))
2764 (list 'export-snippet
2765 (list :back-end back-end
2766 :value value
2767 :begin begin
2768 :end end
2769 :post-blank post-blank)))))))
2771 (defun org-element-export-snippet-interpreter (export-snippet contents)
2772 "Interpret EXPORT-SNIPPET object as Org syntax.
2773 CONTENTS is nil."
2774 (format "@@%s:%s@@"
2775 (org-element-property :back-end export-snippet)
2776 (org-element-property :value export-snippet)))
2779 ;;;; Footnote Reference
2781 (defun org-element-footnote-reference-parser ()
2782 "Parse footnote reference at point, if any.
2784 When at a footnote reference, return a list whose car is
2785 `footnote-reference' and cdr a plist with `:label', `:type',
2786 `:begin', `:end', `:content-begin', `:contents-end' and
2787 `:post-blank' as keywords. Otherwise, return nil."
2788 (when (looking-at org-footnote-re)
2789 (let ((closing (with-syntax-table org-element--pair-square-table
2790 (ignore-errors (scan-lists (point) 1 0)))))
2791 (when closing
2792 (save-excursion
2793 (let* ((begin (point))
2794 (label
2795 (or (org-match-string-no-properties 2)
2796 (org-match-string-no-properties 3)
2797 (and (match-string 1)
2798 (concat "fn:" (org-match-string-no-properties 1)))))
2799 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2800 (inner-begin (match-end 0))
2801 (inner-end (1- closing))
2802 (post-blank (progn (goto-char closing)
2803 (skip-chars-forward " \t")))
2804 (end (point)))
2805 (list 'footnote-reference
2806 (list :label label
2807 :type type
2808 :begin begin
2809 :end end
2810 :contents-begin (and (eq type 'inline) inner-begin)
2811 :contents-end (and (eq type 'inline) inner-end)
2812 :post-blank post-blank))))))))
2814 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2815 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2816 CONTENTS is its definition, when inline, or nil."
2817 (format "[%s]"
2818 (concat (or (org-element-property :label footnote-reference) "fn:")
2819 (and contents (concat ":" contents)))))
2822 ;;;; Inline Babel Call
2824 (defun org-element-inline-babel-call-parser ()
2825 "Parse inline babel call at point, if any.
2827 When at an inline babel call, return a list whose car is
2828 `inline-babel-call' and cdr a plist with `:call',
2829 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2830 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2832 Assume point is at the beginning of the babel call."
2833 (save-excursion
2834 (unless (bolp) (backward-char))
2835 (when (let ((case-fold-search t))
2836 (looking-at org-babel-inline-lob-one-liner-regexp))
2837 (let ((begin (match-end 1))
2838 (call (org-match-string-no-properties 2))
2839 (inside-header (org-string-nw-p (org-match-string-no-properties 4)))
2840 (arguments (org-string-nw-p (org-match-string-no-properties 6)))
2841 (end-header (org-string-nw-p (org-match-string-no-properties 8)))
2842 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2843 (post-blank (progn (goto-char (match-end 0))
2844 (skip-chars-forward " \t")))
2845 (end (point)))
2846 (list 'inline-babel-call
2847 (list :call call
2848 :inside-header inside-header
2849 :arguments arguments
2850 :end-header end-header
2851 :begin begin
2852 :end end
2853 :value value
2854 :post-blank post-blank))))))
2856 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2857 "Interpret INLINE-BABEL-CALL object as Org syntax.
2858 CONTENTS is nil."
2859 (concat "call_"
2860 (org-element-property :call inline-babel-call)
2861 (let ((h (org-element-property :inside-header inline-babel-call)))
2862 (and h (format "[%s]" h)))
2863 "(" (org-element-property :arguments inline-babel-call) ")"
2864 (let ((h (org-element-property :end-header inline-babel-call)))
2865 (and h (format "[%s]" h)))))
2868 ;;;; Inline Src Block
2870 (defun org-element-inline-src-block-parser ()
2871 "Parse inline source block at point, if any.
2873 When at an inline source block, return a list whose car is
2874 `inline-src-block' and cdr a plist with `:begin', `:end',
2875 `:language', `:value', `:parameters' and `:post-blank' as
2876 keywords. Otherwise, return nil.
2878 Assume point is at the beginning of the inline src block."
2879 (save-excursion
2880 (unless (bolp) (backward-char))
2881 (when (looking-at org-babel-inline-src-block-regexp)
2882 (let ((begin (match-beginning 1))
2883 (language (org-match-string-no-properties 2))
2884 (parameters (org-match-string-no-properties 4))
2885 (value (org-match-string-no-properties 5))
2886 (post-blank (progn (goto-char (match-end 0))
2887 (skip-chars-forward " \t")))
2888 (end (point)))
2889 (list 'inline-src-block
2890 (list :language language
2891 :value value
2892 :parameters parameters
2893 :begin begin
2894 :end end
2895 :post-blank post-blank))))))
2897 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2898 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2899 CONTENTS is nil."
2900 (let ((language (org-element-property :language inline-src-block))
2901 (arguments (org-element-property :parameters inline-src-block))
2902 (body (org-element-property :value inline-src-block)))
2903 (format "src_%s%s{%s}"
2904 language
2905 (if arguments (format "[%s]" arguments) "")
2906 body)))
2908 ;;;; Italic
2910 (defun org-element-italic-parser ()
2911 "Parse italic object at point, if any.
2913 When at an italic object, return a list whose car is `italic' and
2914 cdr is a plist with `:begin', `:end', `:contents-begin' and
2915 `:contents-end' and `:post-blank' keywords. Otherwise, return
2916 nil.
2918 Assume point is at the first slash marker."
2919 (save-excursion
2920 (unless (bolp) (backward-char 1))
2921 (when (looking-at org-emph-re)
2922 (let ((begin (match-beginning 2))
2923 (contents-begin (match-beginning 4))
2924 (contents-end (match-end 4))
2925 (post-blank (progn (goto-char (match-end 2))
2926 (skip-chars-forward " \t")))
2927 (end (point)))
2928 (list 'italic
2929 (list :begin begin
2930 :end end
2931 :contents-begin contents-begin
2932 :contents-end contents-end
2933 :post-blank post-blank))))))
2935 (defun org-element-italic-interpreter (italic contents)
2936 "Interpret ITALIC object as Org syntax.
2937 CONTENTS is the contents of the object."
2938 (format "/%s/" contents))
2941 ;;;; Latex Fragment
2943 (defun org-element-latex-fragment-parser ()
2944 "Parse LaTeX fragment at point, if any.
2946 When at a LaTeX fragment, return a list whose car is
2947 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2948 and `:post-blank' as keywords. Otherwise, return nil.
2950 Assume point is at the beginning of the LaTeX fragment."
2951 (catch 'no-object
2952 (save-excursion
2953 (let* ((begin (point))
2954 (after-fragment
2955 (if (eq (char-after) ?$)
2956 (if (eq (char-after (1+ (point))) ?$)
2957 (search-forward "$$" nil t 2)
2958 (and (not (eq (char-before) ?$))
2959 (search-forward "$" nil t 2)
2960 (not (memq (char-before (match-beginning 0))
2961 '(?\s ?\t ?\n ?, ?.)))
2962 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2963 (point)))
2964 (case (char-after (1+ (point)))
2965 (?\( (search-forward "\\)" nil t))
2966 (?\[ (search-forward "\\]" nil t))
2967 (otherwise
2968 ;; Macro.
2969 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2970 (match-end 0))))))
2971 (post-blank (if (not after-fragment) (throw 'no-object nil)
2972 (goto-char after-fragment)
2973 (skip-chars-forward " \t")))
2974 (end (point)))
2975 (list 'latex-fragment
2976 (list :value (buffer-substring-no-properties begin after-fragment)
2977 :begin begin
2978 :end end
2979 :post-blank post-blank))))))
2981 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2982 "Interpret LATEX-FRAGMENT object as Org syntax.
2983 CONTENTS is nil."
2984 (org-element-property :value latex-fragment))
2986 ;;;; Line Break
2988 (defun org-element-line-break-parser ()
2989 "Parse line break at point, if any.
2991 When at a line break, return a list whose car is `line-break',
2992 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2993 Otherwise, return nil.
2995 Assume point is at the beginning of the line break."
2996 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2997 (not (eq (char-before) ?\\)))
2998 (list 'line-break
2999 (list :begin (point)
3000 :end (line-beginning-position 2)
3001 :post-blank 0))))
3003 (defun org-element-line-break-interpreter (line-break contents)
3004 "Interpret LINE-BREAK object as Org syntax.
3005 CONTENTS is nil."
3006 "\\\\\n")
3009 ;;;; Link
3011 (defun org-element-link-parser ()
3012 "Parse link at point, if any.
3014 When at a link, return a list whose car is `link' and cdr a plist
3015 with `:type', `:path', `:raw-link', `:application',
3016 `:search-option', `:begin', `:end', `:contents-begin',
3017 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3018 nil.
3020 Assume point is at the beginning of the link."
3021 (catch 'no-object
3022 (let ((begin (point))
3023 end contents-begin contents-end link-end post-blank path type
3024 raw-link link search-option application)
3025 (cond
3026 ;; Type 1: Text targeted from a radio target.
3027 ((and org-target-link-regexp
3028 (save-excursion (or (bolp) (backward-char))
3029 (looking-at org-target-link-regexp)))
3030 (setq type "radio"
3031 link-end (match-end 1)
3032 path (org-match-string-no-properties 1)
3033 contents-begin (match-beginning 1)
3034 contents-end (match-end 1)))
3035 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3036 ((looking-at org-bracket-link-regexp)
3037 (setq contents-begin (match-beginning 3)
3038 contents-end (match-end 3)
3039 link-end (match-end 0)
3040 ;; RAW-LINK is the original link. Expand any
3041 ;; abbreviation in it.
3042 raw-link (org-translate-link
3043 (org-link-expand-abbrev
3044 (org-match-string-no-properties 1))))
3045 ;; Determine TYPE of link and set PATH accordingly.
3046 (cond
3047 ;; File type.
3048 ((or (file-name-absolute-p raw-link)
3049 (string-match "\\`\\.\\.?/" raw-link))
3050 (setq type "file" path raw-link))
3051 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3052 ((string-match org-link-types-re raw-link)
3053 (setq type (match-string 1 raw-link)
3054 ;; According to RFC 3986, extra whitespace should be
3055 ;; ignored when a URI is extracted.
3056 path (replace-regexp-in-string
3057 "[ \t]*\n[ \t]*" "" (substring raw-link (match-end 0)))))
3058 ;; Id type: PATH is the id.
3059 ((string-match "\\`id:\\([-a-f0-9]+\\)" raw-link)
3060 (setq type "id" path (match-string 1 raw-link)))
3061 ;; Code-ref type: PATH is the name of the reference.
3062 ((string-match "\\`(\\(.*\\))\\'" raw-link)
3063 (setq type "coderef" path (match-string 1 raw-link)))
3064 ;; Custom-id type: PATH is the name of the custom id.
3065 ((= (aref raw-link 0) ?#)
3066 (setq type "custom-id" path (substring raw-link 1)))
3067 ;; Fuzzy type: Internal link either matches a target, an
3068 ;; headline name or nothing. PATH is the target or
3069 ;; headline's name.
3070 (t (setq type "fuzzy" path raw-link))))
3071 ;; Type 3: Plain link, e.g., http://orgmode.org
3072 ((looking-at org-plain-link-re)
3073 (setq raw-link (org-match-string-no-properties 0)
3074 type (org-match-string-no-properties 1)
3075 link-end (match-end 0)
3076 path (org-match-string-no-properties 2)))
3077 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3078 ((looking-at org-angle-link-re)
3079 (setq raw-link (buffer-substring-no-properties
3080 (match-beginning 1) (match-end 2))
3081 type (org-match-string-no-properties 1)
3082 link-end (match-end 0)
3083 path (org-match-string-no-properties 2)))
3084 (t (throw 'no-object nil)))
3085 ;; In any case, deduce end point after trailing white space from
3086 ;; LINK-END variable.
3087 (save-excursion
3088 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3089 end (point))
3090 ;; Special "file" type link processing. Extract opening
3091 ;; application and search option, if any. Also normalize URI.
3092 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3093 (setq application (match-string 1 type) type "file")
3094 (when (string-match "::\\(.*\\)\\'" path)
3095 (setq search-option (match-string 1 path)
3096 path (replace-match "" nil nil path)))
3097 (setq path (replace-regexp-in-string "\\`/+" "/" path)))
3098 (list 'link
3099 (list :type type
3100 :path path
3101 :raw-link (or raw-link path)
3102 :application application
3103 :search-option search-option
3104 :begin begin
3105 :end end
3106 :contents-begin contents-begin
3107 :contents-end contents-end
3108 :post-blank post-blank))))))
3110 (defun org-element-link-interpreter (link contents)
3111 "Interpret LINK object as Org syntax.
3112 CONTENTS is the contents of the object, or nil."
3113 (let ((type (org-element-property :type link))
3114 (raw-link (org-element-property :raw-link link)))
3115 (if (string= type "radio") raw-link
3116 (format "[[%s]%s]"
3117 raw-link
3118 (if contents (format "[%s]" contents) "")))))
3121 ;;;; Macro
3123 (defun org-element-macro-parser ()
3124 "Parse macro at point, if any.
3126 When at a macro, return a list whose car is `macro' and cdr
3127 a plist with `:key', `:args', `:begin', `:end', `:value' and
3128 `:post-blank' as keywords. Otherwise, return nil.
3130 Assume point is at the macro."
3131 (save-excursion
3132 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3133 (let ((begin (point))
3134 (key (downcase (org-match-string-no-properties 1)))
3135 (value (org-match-string-no-properties 0))
3136 (post-blank (progn (goto-char (match-end 0))
3137 (skip-chars-forward " \t")))
3138 (end (point))
3139 (args (let ((args (org-match-string-no-properties 3)))
3140 (and args (org-macro-extract-arguments args)))))
3141 (list 'macro
3142 (list :key key
3143 :value value
3144 :args args
3145 :begin begin
3146 :end end
3147 :post-blank post-blank))))))
3149 (defun org-element-macro-interpreter (macro contents)
3150 "Interpret MACRO object as Org syntax.
3151 CONTENTS is nil."
3152 (org-element-property :value macro))
3155 ;;;; Radio-target
3157 (defun org-element-radio-target-parser ()
3158 "Parse radio target at point, if any.
3160 When at a radio target, return a list whose car is `radio-target'
3161 and cdr a plist with `:begin', `:end', `:contents-begin',
3162 `:contents-end', `:value' and `:post-blank' as keywords.
3163 Otherwise, return nil.
3165 Assume point is at the radio target."
3166 (save-excursion
3167 (when (looking-at org-radio-target-regexp)
3168 (let ((begin (point))
3169 (contents-begin (match-beginning 1))
3170 (contents-end (match-end 1))
3171 (value (org-match-string-no-properties 1))
3172 (post-blank (progn (goto-char (match-end 0))
3173 (skip-chars-forward " \t")))
3174 (end (point)))
3175 (list 'radio-target
3176 (list :begin begin
3177 :end end
3178 :contents-begin contents-begin
3179 :contents-end contents-end
3180 :post-blank post-blank
3181 :value value))))))
3183 (defun org-element-radio-target-interpreter (target contents)
3184 "Interpret TARGET object as Org syntax.
3185 CONTENTS is the contents of the object."
3186 (concat "<<<" contents ">>>"))
3189 ;;;; Statistics Cookie
3191 (defun org-element-statistics-cookie-parser ()
3192 "Parse statistics cookie at point, if any.
3194 When at a statistics cookie, return a list whose car is
3195 `statistics-cookie', and cdr a plist with `:begin', `:end',
3196 `:value' and `:post-blank' keywords. Otherwise, return nil.
3198 Assume point is at the beginning of the statistics-cookie."
3199 (save-excursion
3200 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3201 (let* ((begin (point))
3202 (value (buffer-substring-no-properties
3203 (match-beginning 0) (match-end 0)))
3204 (post-blank (progn (goto-char (match-end 0))
3205 (skip-chars-forward " \t")))
3206 (end (point)))
3207 (list 'statistics-cookie
3208 (list :begin begin
3209 :end end
3210 :value value
3211 :post-blank post-blank))))))
3213 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3214 "Interpret STATISTICS-COOKIE object as Org syntax.
3215 CONTENTS is nil."
3216 (org-element-property :value statistics-cookie))
3219 ;;;; Strike-Through
3221 (defun org-element-strike-through-parser ()
3222 "Parse strike-through object at point, if any.
3224 When at a strike-through object, return a list whose car is
3225 `strike-through' and cdr is a plist with `:begin', `:end',
3226 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3227 Otherwise, return nil.
3229 Assume point is at the first plus sign marker."
3230 (save-excursion
3231 (unless (bolp) (backward-char 1))
3232 (when (looking-at org-emph-re)
3233 (let ((begin (match-beginning 2))
3234 (contents-begin (match-beginning 4))
3235 (contents-end (match-end 4))
3236 (post-blank (progn (goto-char (match-end 2))
3237 (skip-chars-forward " \t")))
3238 (end (point)))
3239 (list 'strike-through
3240 (list :begin begin
3241 :end end
3242 :contents-begin contents-begin
3243 :contents-end contents-end
3244 :post-blank post-blank))))))
3246 (defun org-element-strike-through-interpreter (strike-through contents)
3247 "Interpret STRIKE-THROUGH object as Org syntax.
3248 CONTENTS is the contents of the object."
3249 (format "+%s+" contents))
3252 ;;;; Subscript
3254 (defun org-element-subscript-parser ()
3255 "Parse subscript at point, if any.
3257 When at a subscript object, return a list whose car is
3258 `subscript' and cdr a plist with `:begin', `:end',
3259 `:contents-begin', `:contents-end', `:use-brackets-p' and
3260 `:post-blank' as keywords. Otherwise, return nil.
3262 Assume point is at the underscore."
3263 (save-excursion
3264 (unless (bolp) (backward-char))
3265 (when (looking-at org-match-substring-regexp)
3266 (let ((bracketsp (match-beginning 4))
3267 (begin (match-beginning 2))
3268 (contents-begin (or (match-beginning 4)
3269 (match-beginning 3)))
3270 (contents-end (or (match-end 4) (match-end 3)))
3271 (post-blank (progn (goto-char (match-end 0))
3272 (skip-chars-forward " \t")))
3273 (end (point)))
3274 (list 'subscript
3275 (list :begin begin
3276 :end end
3277 :use-brackets-p bracketsp
3278 :contents-begin contents-begin
3279 :contents-end contents-end
3280 :post-blank post-blank))))))
3282 (defun org-element-subscript-interpreter (subscript contents)
3283 "Interpret SUBSCRIPT object as Org syntax.
3284 CONTENTS is the contents of the object."
3285 (format
3286 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3287 contents))
3290 ;;;; Superscript
3292 (defun org-element-superscript-parser ()
3293 "Parse superscript at point, if any.
3295 When at a superscript object, return a list whose car is
3296 `superscript' and cdr a plist with `:begin', `:end',
3297 `:contents-begin', `:contents-end', `:use-brackets-p' and
3298 `:post-blank' as keywords. Otherwise, return nil.
3300 Assume point is at the caret."
3301 (save-excursion
3302 (unless (bolp) (backward-char))
3303 (when (looking-at org-match-substring-regexp)
3304 (let ((bracketsp (match-beginning 4))
3305 (begin (match-beginning 2))
3306 (contents-begin (or (match-beginning 4)
3307 (match-beginning 3)))
3308 (contents-end (or (match-end 4) (match-end 3)))
3309 (post-blank (progn (goto-char (match-end 0))
3310 (skip-chars-forward " \t")))
3311 (end (point)))
3312 (list 'superscript
3313 (list :begin begin
3314 :end end
3315 :use-brackets-p bracketsp
3316 :contents-begin contents-begin
3317 :contents-end contents-end
3318 :post-blank post-blank))))))
3320 (defun org-element-superscript-interpreter (superscript contents)
3321 "Interpret SUPERSCRIPT object as Org syntax.
3322 CONTENTS is the contents of the object."
3323 (format
3324 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3325 contents))
3328 ;;;; Table Cell
3330 (defun org-element-table-cell-parser ()
3331 "Parse table cell at point.
3332 Return a list whose car is `table-cell' and cdr is a plist
3333 containing `:begin', `:end', `:contents-begin', `:contents-end'
3334 and `:post-blank' keywords."
3335 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3336 (let* ((begin (match-beginning 0))
3337 (end (match-end 0))
3338 (contents-begin (match-beginning 1))
3339 (contents-end (match-end 1)))
3340 (list 'table-cell
3341 (list :begin begin
3342 :end end
3343 :contents-begin contents-begin
3344 :contents-end contents-end
3345 :post-blank 0))))
3347 (defun org-element-table-cell-interpreter (table-cell contents)
3348 "Interpret TABLE-CELL element as Org syntax.
3349 CONTENTS is the contents of the cell, or nil."
3350 (concat " " contents " |"))
3353 ;;;; Target
3355 (defun org-element-target-parser ()
3356 "Parse target at point, if any.
3358 When at a target, return a list whose car is `target' and cdr
3359 a plist with `:begin', `:end', `:value' and `:post-blank' as
3360 keywords. Otherwise, return nil.
3362 Assume point is at the target."
3363 (save-excursion
3364 (when (looking-at org-target-regexp)
3365 (let ((begin (point))
3366 (value (org-match-string-no-properties 1))
3367 (post-blank (progn (goto-char (match-end 0))
3368 (skip-chars-forward " \t")))
3369 (end (point)))
3370 (list 'target
3371 (list :begin begin
3372 :end end
3373 :value value
3374 :post-blank post-blank))))))
3376 (defun org-element-target-interpreter (target contents)
3377 "Interpret TARGET object as Org syntax.
3378 CONTENTS is nil."
3379 (format "<<%s>>" (org-element-property :value target)))
3382 ;;;; Timestamp
3384 (defconst org-element--timestamp-regexp
3385 (concat org-ts-regexp-both
3386 "\\|"
3387 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3388 "\\|"
3389 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3390 "Regexp matching any timestamp type object.")
3392 (defun org-element-timestamp-parser ()
3393 "Parse time stamp at point, if any.
3395 When at a time stamp, return a list whose car is `timestamp', and
3396 cdr a plist with `:type', `:raw-value', `:year-start',
3397 `:month-start', `:day-start', `:hour-start', `:minute-start',
3398 `:year-end', `:month-end', `:day-end', `:hour-end',
3399 `:minute-end', `:repeater-type', `:repeater-value',
3400 `:repeater-unit', `:warning-type', `:warning-value',
3401 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3402 Otherwise, return nil.
3404 Assume point is at the beginning of the timestamp."
3405 (when (org-looking-at-p org-element--timestamp-regexp)
3406 (save-excursion
3407 (let* ((begin (point))
3408 (activep (eq (char-after) ?<))
3409 (raw-value
3410 (progn
3411 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3412 (match-string-no-properties 0)))
3413 (date-start (match-string-no-properties 1))
3414 (date-end (match-string 3))
3415 (diaryp (match-beginning 2))
3416 (post-blank (progn (goto-char (match-end 0))
3417 (skip-chars-forward " \t")))
3418 (end (point))
3419 (time-range
3420 (and (not diaryp)
3421 (string-match
3422 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3423 date-start)
3424 (cons (string-to-number (match-string 2 date-start))
3425 (string-to-number (match-string 3 date-start)))))
3426 (type (cond (diaryp 'diary)
3427 ((and activep (or date-end time-range)) 'active-range)
3428 (activep 'active)
3429 ((or date-end time-range) 'inactive-range)
3430 (t 'inactive)))
3431 (repeater-props
3432 (and (not diaryp)
3433 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3434 raw-value)
3435 (list
3436 :repeater-type
3437 (let ((type (match-string 1 raw-value)))
3438 (cond ((equal "++" type) 'catch-up)
3439 ((equal ".+" type) 'restart)
3440 (t 'cumulate)))
3441 :repeater-value (string-to-number (match-string 2 raw-value))
3442 :repeater-unit
3443 (case (string-to-char (match-string 3 raw-value))
3444 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3445 (warning-props
3446 (and (not diaryp)
3447 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3448 (list
3449 :warning-type (if (match-string 1 raw-value) 'first 'all)
3450 :warning-value (string-to-number (match-string 2 raw-value))
3451 :warning-unit
3452 (case (string-to-char (match-string 3 raw-value))
3453 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3454 year-start month-start day-start hour-start minute-start year-end
3455 month-end day-end hour-end minute-end)
3456 ;; Parse date-start.
3457 (unless diaryp
3458 (let ((date (org-parse-time-string date-start t)))
3459 (setq year-start (nth 5 date)
3460 month-start (nth 4 date)
3461 day-start (nth 3 date)
3462 hour-start (nth 2 date)
3463 minute-start (nth 1 date))))
3464 ;; Compute date-end. It can be provided directly in time-stamp,
3465 ;; or extracted from time range. Otherwise, it defaults to the
3466 ;; same values as date-start.
3467 (unless diaryp
3468 (let ((date (and date-end (org-parse-time-string date-end t))))
3469 (setq year-end (or (nth 5 date) year-start)
3470 month-end (or (nth 4 date) month-start)
3471 day-end (or (nth 3 date) day-start)
3472 hour-end (or (nth 2 date) (car time-range) hour-start)
3473 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3474 (list 'timestamp
3475 (nconc (list :type type
3476 :raw-value raw-value
3477 :year-start year-start
3478 :month-start month-start
3479 :day-start day-start
3480 :hour-start hour-start
3481 :minute-start minute-start
3482 :year-end year-end
3483 :month-end month-end
3484 :day-end day-end
3485 :hour-end hour-end
3486 :minute-end minute-end
3487 :begin begin
3488 :end end
3489 :post-blank post-blank)
3490 repeater-props
3491 warning-props))))))
3493 (defun org-element-timestamp-interpreter (timestamp contents)
3494 "Interpret TIMESTAMP object as Org syntax.
3495 CONTENTS is nil."
3496 (let* ((repeat-string
3497 (concat
3498 (case (org-element-property :repeater-type timestamp)
3499 (cumulate "+") (catch-up "++") (restart ".+"))
3500 (let ((val (org-element-property :repeater-value timestamp)))
3501 (and val (number-to-string val)))
3502 (case (org-element-property :repeater-unit timestamp)
3503 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3504 (warning-string
3505 (concat
3506 (case (org-element-property :warning-type timestamp)
3507 (first "--")
3508 (all "-"))
3509 (let ((val (org-element-property :warning-value timestamp)))
3510 (and val (number-to-string val)))
3511 (case (org-element-property :warning-unit timestamp)
3512 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3513 (build-ts-string
3514 ;; Build an Org timestamp string from TIME. ACTIVEP is
3515 ;; non-nil when time stamp is active. If WITH-TIME-P is
3516 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3517 ;; specify a time range in the timestamp. REPEAT-STRING is
3518 ;; the repeater string, if any.
3519 (lambda (time activep &optional with-time-p hour-end minute-end)
3520 (let ((ts (format-time-string
3521 (funcall (if with-time-p 'cdr 'car)
3522 org-time-stamp-formats)
3523 time)))
3524 (when (and hour-end minute-end)
3525 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3526 (setq ts
3527 (replace-match
3528 (format "\\&-%02d:%02d" hour-end minute-end)
3529 nil nil ts)))
3530 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3531 (dolist (s (list repeat-string warning-string))
3532 (when (org-string-nw-p s)
3533 (setq ts (concat (substring ts 0 -1)
3536 (substring ts -1)))))
3537 ;; Return value.
3538 ts)))
3539 (type (org-element-property :type timestamp)))
3540 (case type
3541 ((active inactive)
3542 (let* ((minute-start (org-element-property :minute-start timestamp))
3543 (minute-end (org-element-property :minute-end timestamp))
3544 (hour-start (org-element-property :hour-start timestamp))
3545 (hour-end (org-element-property :hour-end timestamp))
3546 (time-range-p (and hour-start hour-end minute-start minute-end
3547 (or (/= hour-start hour-end)
3548 (/= minute-start minute-end)))))
3549 (funcall
3550 build-ts-string
3551 (encode-time 0
3552 (or minute-start 0)
3553 (or hour-start 0)
3554 (org-element-property :day-start timestamp)
3555 (org-element-property :month-start timestamp)
3556 (org-element-property :year-start timestamp))
3557 (eq type 'active)
3558 (and hour-start minute-start)
3559 (and time-range-p hour-end)
3560 (and time-range-p minute-end))))
3561 ((active-range inactive-range)
3562 (let ((minute-start (org-element-property :minute-start timestamp))
3563 (minute-end (org-element-property :minute-end timestamp))
3564 (hour-start (org-element-property :hour-start timestamp))
3565 (hour-end (org-element-property :hour-end timestamp)))
3566 (concat
3567 (funcall
3568 build-ts-string (encode-time
3570 (or minute-start 0)
3571 (or hour-start 0)
3572 (org-element-property :day-start timestamp)
3573 (org-element-property :month-start timestamp)
3574 (org-element-property :year-start timestamp))
3575 (eq type 'active-range)
3576 (and hour-start minute-start))
3577 "--"
3578 (funcall build-ts-string
3579 (encode-time 0
3580 (or minute-end 0)
3581 (or hour-end 0)
3582 (org-element-property :day-end timestamp)
3583 (org-element-property :month-end timestamp)
3584 (org-element-property :year-end timestamp))
3585 (eq type 'active-range)
3586 (and hour-end minute-end)))))
3587 (otherwise (org-element-property :raw-value timestamp)))))
3590 ;;;; Underline
3592 (defun org-element-underline-parser ()
3593 "Parse underline object at point, if any.
3595 When at an underline object, return a list whose car is
3596 `underline' and cdr is a plist with `:begin', `:end',
3597 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3598 Otherwise, return nil.
3600 Assume point is at the first underscore marker."
3601 (save-excursion
3602 (unless (bolp) (backward-char 1))
3603 (when (looking-at org-emph-re)
3604 (let ((begin (match-beginning 2))
3605 (contents-begin (match-beginning 4))
3606 (contents-end (match-end 4))
3607 (post-blank (progn (goto-char (match-end 2))
3608 (skip-chars-forward " \t")))
3609 (end (point)))
3610 (list 'underline
3611 (list :begin begin
3612 :end end
3613 :contents-begin contents-begin
3614 :contents-end contents-end
3615 :post-blank post-blank))))))
3617 (defun org-element-underline-interpreter (underline contents)
3618 "Interpret UNDERLINE object as Org syntax.
3619 CONTENTS is the contents of the object."
3620 (format "_%s_" contents))
3623 ;;;; Verbatim
3625 (defun org-element-verbatim-parser ()
3626 "Parse verbatim object at point, if any.
3628 When at a verbatim object, return a list whose car is `verbatim'
3629 and cdr is a plist with `:value', `:begin', `:end' and
3630 `:post-blank' keywords. Otherwise, return nil.
3632 Assume point is at the first equal sign marker."
3633 (save-excursion
3634 (unless (bolp) (backward-char 1))
3635 (when (looking-at org-emph-re)
3636 (let ((begin (match-beginning 2))
3637 (value (org-match-string-no-properties 4))
3638 (post-blank (progn (goto-char (match-end 2))
3639 (skip-chars-forward " \t")))
3640 (end (point)))
3641 (list 'verbatim
3642 (list :value value
3643 :begin begin
3644 :end end
3645 :post-blank post-blank))))))
3647 (defun org-element-verbatim-interpreter (verbatim contents)
3648 "Interpret VERBATIM object as Org syntax.
3649 CONTENTS is nil."
3650 (format "=%s=" (org-element-property :value verbatim)))
3654 ;;; Parsing Element Starting At Point
3656 ;; `org-element--current-element' is the core function of this section.
3657 ;; It returns the Lisp representation of the element starting at
3658 ;; point.
3660 ;; `org-element--current-element' makes use of special modes. They
3661 ;; are activated for fixed element chaining (e.g., `plain-list' >
3662 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3663 ;; `section'). Special modes are: `first-section', `item',
3664 ;; `node-property', `section' and `table-row'.
3666 (defun org-element--current-element (limit &optional granularity mode structure)
3667 "Parse the element starting at point.
3669 Return value is a list like (TYPE PROPS) where TYPE is the type
3670 of the element and PROPS a plist of properties associated to the
3671 element.
3673 Possible types are defined in `org-element-all-elements'.
3675 LIMIT bounds the search.
3677 Optional argument GRANULARITY determines the depth of the
3678 recursion. Allowed values are `headline', `greater-element',
3679 `element', `object' or nil. When it is broader than `object' (or
3680 nil), secondary values will not be parsed, since they only
3681 contain objects.
3683 Optional argument MODE, when non-nil, can be either
3684 `first-section', `section', `planning', `item', `node-property'
3685 and `table-row'.
3687 If STRUCTURE isn't provided but MODE is set to `item', it will be
3688 computed.
3690 This function assumes point is always at the beginning of the
3691 element it has to parse."
3692 (save-excursion
3693 (let ((case-fold-search t)
3694 ;; Determine if parsing depth allows for secondary strings
3695 ;; parsing. It only applies to elements referenced in
3696 ;; `org-element-secondary-value-alist'.
3697 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3698 (cond
3699 ;; Item.
3700 ((eq mode 'item)
3701 (org-element-item-parser limit structure raw-secondary-p))
3702 ;; Table Row.
3703 ((eq mode 'table-row) (org-element-table-row-parser limit))
3704 ;; Node Property.
3705 ((eq mode 'node-property) (org-element-node-property-parser limit))
3706 ;; Headline.
3707 ((org-with-limited-levels (org-at-heading-p))
3708 (org-element-headline-parser limit raw-secondary-p))
3709 ;; Sections (must be checked after headline).
3710 ((eq mode 'section) (org-element-section-parser limit))
3711 ((eq mode 'first-section)
3712 (org-element-section-parser
3713 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3714 limit)))
3715 ;; Planning.
3716 ((and (eq mode 'planning) (looking-at org-planning-line-re))
3717 (org-element-planning-parser limit))
3718 ;; Property drawer.
3719 ((and (memq mode '(planning property-drawer))
3720 (looking-at org-property-drawer-re))
3721 (org-element-property-drawer-parser limit))
3722 ;; When not at bol, point is at the beginning of an item or
3723 ;; a footnote definition: next item is always a paragraph.
3724 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3725 ;; Clock.
3726 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3727 ;; Inlinetask.
3728 ((org-at-heading-p)
3729 (org-element-inlinetask-parser limit raw-secondary-p))
3730 ;; From there, elements can have affiliated keywords.
3731 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3732 (cond
3733 ;; Jumping over affiliated keywords put point off-limits.
3734 ;; Parse them as regular keywords.
3735 ((and (cdr affiliated) (>= (point) limit))
3736 (goto-char (car affiliated))
3737 (org-element-keyword-parser limit nil))
3738 ;; LaTeX Environment.
3739 ((looking-at org-element--latex-begin-environment)
3740 (org-element-latex-environment-parser limit affiliated))
3741 ;; Drawer and Property Drawer.
3742 ((looking-at org-drawer-regexp)
3743 (org-element-drawer-parser limit affiliated))
3744 ;; Fixed Width
3745 ((looking-at "[ \t]*:\\( \\|$\\)")
3746 (org-element-fixed-width-parser limit affiliated))
3747 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3748 ;; Keywords.
3749 ((looking-at "[ \t]*#")
3750 (goto-char (match-end 0))
3751 (cond ((looking-at "\\(?: \\|$\\)")
3752 (beginning-of-line)
3753 (org-element-comment-parser limit affiliated))
3754 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3755 (beginning-of-line)
3756 (let ((parser (assoc (upcase (match-string 1))
3757 org-element-block-name-alist)))
3758 (if parser (funcall (cdr parser) limit affiliated)
3759 (org-element-special-block-parser limit affiliated))))
3760 ((looking-at "\\+CALL:")
3761 (beginning-of-line)
3762 (org-element-babel-call-parser limit affiliated))
3763 ((looking-at "\\+BEGIN:? ")
3764 (beginning-of-line)
3765 (org-element-dynamic-block-parser limit affiliated))
3766 ((looking-at "\\+\\S-+:")
3767 (beginning-of-line)
3768 (org-element-keyword-parser limit affiliated))
3770 (beginning-of-line)
3771 (org-element-paragraph-parser limit affiliated))))
3772 ;; Footnote Definition.
3773 ((looking-at org-footnote-definition-re)
3774 (org-element-footnote-definition-parser limit affiliated))
3775 ;; Horizontal Rule.
3776 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3777 (org-element-horizontal-rule-parser limit affiliated))
3778 ;; Diary Sexp.
3779 ((looking-at "%%(")
3780 (org-element-diary-sexp-parser limit affiliated))
3781 ;; Table.
3782 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3783 ;; List.
3784 ((looking-at (org-item-re))
3785 (org-element-plain-list-parser
3786 limit affiliated
3787 (or structure (org-element--list-struct limit))))
3788 ;; Default element: Paragraph.
3789 (t (org-element-paragraph-parser limit affiliated)))))))))
3792 ;; Most elements can have affiliated keywords. When looking for an
3793 ;; element beginning, we want to move before them, as they belong to
3794 ;; that element, and, in the meantime, collect information they give
3795 ;; into appropriate properties. Hence the following function.
3797 (defun org-element--collect-affiliated-keywords (limit)
3798 "Collect affiliated keywords from point down to LIMIT.
3800 Return a list whose CAR is the position at the first of them and
3801 CDR a plist of keywords and values and move point to the
3802 beginning of the first line after them.
3804 As a special case, if element doesn't start at the beginning of
3805 the line (e.g., a paragraph starting an item), CAR is current
3806 position of point and CDR is nil."
3807 (if (not (bolp)) (list (point))
3808 (let ((case-fold-search t)
3809 (origin (point))
3810 ;; RESTRICT is the list of objects allowed in parsed
3811 ;; keywords value.
3812 (restrict (org-element-restriction 'keyword))
3813 output)
3814 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3815 (let* ((raw-kwd (upcase (match-string 1)))
3816 ;; Apply translation to RAW-KWD. From there, KWD is
3817 ;; the official keyword.
3818 (kwd (or (cdr (assoc raw-kwd
3819 org-element-keyword-translation-alist))
3820 raw-kwd))
3821 ;; Find main value for any keyword.
3822 (value
3823 (save-match-data
3824 (org-trim
3825 (buffer-substring-no-properties
3826 (match-end 0) (line-end-position)))))
3827 ;; PARSEDP is non-nil when keyword should have its
3828 ;; value parsed.
3829 (parsedp (member kwd org-element-parsed-keywords))
3830 ;; If KWD is a dual keyword, find its secondary
3831 ;; value. Maybe parse it.
3832 (dualp (member kwd org-element-dual-keywords))
3833 (dual-value
3834 (and dualp
3835 (let ((sec (org-match-string-no-properties 2)))
3836 (if (or (not sec) (not parsedp)) sec
3837 (org-element--parse-objects
3838 (match-beginning 2) (match-end 2) nil restrict)))))
3839 ;; Attribute a property name to KWD.
3840 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3841 ;; Now set final shape for VALUE.
3842 (when parsedp
3843 (setq value
3844 (org-element--parse-objects
3845 (match-end 0)
3846 (progn (end-of-line) (skip-chars-backward " \t") (point))
3847 nil restrict)))
3848 (when dualp
3849 (setq value (and (or value dual-value) (cons value dual-value))))
3850 (when (or (member kwd org-element-multiple-keywords)
3851 ;; Attributes can always appear on multiple lines.
3852 (string-match "^ATTR_" kwd))
3853 (setq value (cons value (plist-get output kwd-sym))))
3854 ;; Eventually store the new value in OUTPUT.
3855 (setq output (plist-put output kwd-sym value))
3856 ;; Move to next keyword.
3857 (forward-line)))
3858 ;; If affiliated keywords are orphaned: move back to first one.
3859 ;; They will be parsed as a paragraph.
3860 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3861 ;; Return value.
3862 (cons origin output))))
3866 ;;; The Org Parser
3868 ;; The two major functions here are `org-element-parse-buffer', which
3869 ;; parses Org syntax inside the current buffer, taking into account
3870 ;; region, narrowing, or even visibility if specified, and
3871 ;; `org-element-parse-secondary-string', which parses objects within
3872 ;; a given string.
3874 ;; The (almost) almighty `org-element-map' allows to apply a function
3875 ;; on elements or objects matching some type, and accumulate the
3876 ;; resulting values. In an export situation, it also skips unneeded
3877 ;; parts of the parse tree.
3879 (defun org-element-parse-buffer (&optional granularity visible-only)
3880 "Recursively parse the buffer and return structure.
3881 If narrowing is in effect, only parse the visible part of the
3882 buffer.
3884 Optional argument GRANULARITY determines the depth of the
3885 recursion. It can be set to the following symbols:
3887 `headline' Only parse headlines.
3888 `greater-element' Don't recurse into greater elements excepted
3889 headlines and sections. Thus, elements
3890 parsed are the top-level ones.
3891 `element' Parse everything but objects and plain text.
3892 `object' Parse the complete buffer (default).
3894 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3895 elements.
3897 An element or an objects is represented as a list with the
3898 pattern (TYPE PROPERTIES CONTENTS), where :
3900 TYPE is a symbol describing the element or object. See
3901 `org-element-all-elements' and `org-element-all-objects' for an
3902 exhaustive list of such symbols. One can retrieve it with
3903 `org-element-type' function.
3905 PROPERTIES is the list of attributes attached to the element or
3906 object, as a plist. Although most of them are specific to the
3907 element or object type, all types share `:begin', `:end',
3908 `:post-blank' and `:parent' properties, which respectively
3909 refer to buffer position where the element or object starts,
3910 ends, the number of white spaces or blank lines after it, and
3911 the element or object containing it. Properties values can be
3912 obtained by using `org-element-property' function.
3914 CONTENTS is a list of elements, objects or raw strings
3915 contained in the current element or object, when applicable.
3916 One can access them with `org-element-contents' function.
3918 The Org buffer has `org-data' as type and nil as properties.
3919 `org-element-map' function can be used to find specific elements
3920 or objects within the parse tree.
3922 This function assumes that current major mode is `org-mode'."
3923 (save-excursion
3924 (goto-char (point-min))
3925 (org-skip-whitespace)
3926 (org-element--parse-elements
3927 (point-at-bol) (point-max)
3928 ;; Start in `first-section' mode so text before the first
3929 ;; headline belongs to a section.
3930 'first-section nil granularity visible-only (list 'org-data nil))))
3932 (defun org-element-parse-secondary-string (string restriction &optional parent)
3933 "Recursively parse objects in STRING and return structure.
3935 RESTRICTION is a symbol limiting the object types that will be
3936 looked after.
3938 Optional argument PARENT, when non-nil, is the element or object
3939 containing the secondary string. It is used to set correctly
3940 `:parent' property within the string.
3942 If STRING is the empty string or nil, return nil."
3943 (cond
3944 ((not string) nil)
3945 ((equal string "") nil)
3946 (t (let ((local-variables (buffer-local-variables)))
3947 (with-temp-buffer
3948 (dolist (v local-variables)
3949 (ignore-errors
3950 (if (symbolp v) (makunbound v)
3951 (org-set-local (car v) (cdr v)))))
3952 (insert string)
3953 (restore-buffer-modified-p nil)
3954 (let ((data (org-element--parse-objects
3955 (point-min) (point-max) nil restriction)))
3956 (when parent
3957 (dolist (o data) (org-element-put-property o :parent parent)))
3958 data))))))
3960 (defun org-element-map
3961 (data types fun &optional info first-match no-recursion with-affiliated)
3962 "Map a function on selected elements or objects.
3964 DATA is a parse tree, an element, an object, a string, or a list
3965 of such constructs. TYPES is a symbol or list of symbols of
3966 elements or objects types (see `org-element-all-elements' and
3967 `org-element-all-objects' for a complete list of types). FUN is
3968 the function called on the matching element or object. It has to
3969 accept one argument: the element or object itself.
3971 When optional argument INFO is non-nil, it should be a plist
3972 holding export options. In that case, parts of the parse tree
3973 not exportable according to that property list will be skipped.
3975 When optional argument FIRST-MATCH is non-nil, stop at the first
3976 match for which FUN doesn't return nil, and return that value.
3978 Optional argument NO-RECURSION is a symbol or a list of symbols
3979 representing elements or objects types. `org-element-map' won't
3980 enter any recursive element or object whose type belongs to that
3981 list. Though, FUN can still be applied on them.
3983 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3984 apply to matching objects within parsed affiliated keywords (see
3985 `org-element-parsed-keywords').
3987 Nil values returned from FUN do not appear in the results.
3990 Examples:
3991 ---------
3993 Assuming TREE is a variable containing an Org buffer parse tree,
3994 the following example will return a flat list of all `src-block'
3995 and `example-block' elements in it:
3997 \(org-element-map tree '(example-block src-block) #'identity)
3999 The following snippet will find the first headline with a level
4000 of 1 and a \"phone\" tag, and will return its beginning position:
4002 \(org-element-map tree 'headline
4003 \(lambda (hl)
4004 \(and (= (org-element-property :level hl) 1)
4005 \(member \"phone\" (org-element-property :tags hl))
4006 \(org-element-property :begin hl)))
4007 nil t)
4009 The next example will return a flat list of all `plain-list' type
4010 elements in TREE that are not a sub-list themselves:
4012 \(org-element-map tree 'plain-list #'identity nil nil 'plain-list)
4014 Eventually, this example will return a flat list of all `bold'
4015 type objects containing a `latex-snippet' type object, even
4016 looking into captions:
4018 \(org-element-map tree 'bold
4019 \(lambda (b)
4020 \(and (org-element-map b 'latex-snippet #'identity nil t) b))
4021 nil nil nil t)"
4022 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4023 (let* ((types (if (listp types) types (list types)))
4024 (no-recursion (if (listp no-recursion) no-recursion
4025 (list no-recursion)))
4026 ;; Recursion depth is determined by --CATEGORY.
4027 (--category
4028 (catch 'found
4029 (let ((category 'greater-elements)
4030 (all-objects (cons 'plain-text org-element-all-objects)))
4031 (dolist (type types category)
4032 (cond ((memq type all-objects)
4033 ;; If one object is found, the function has to
4034 ;; recurse into every object.
4035 (throw 'found 'objects))
4036 ((not (memq type org-element-greater-elements))
4037 ;; If one regular element is found, the
4038 ;; function has to recurse, at least, into
4039 ;; every element it encounters.
4040 (and (not (eq category 'elements))
4041 (setq category 'elements))))))))
4042 --acc
4043 --walk-tree
4044 (--walk-tree
4045 (lambda (--data)
4046 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4047 ;; holding contextual information.
4048 (let ((--type (org-element-type --data)))
4049 (cond
4050 ((not --data))
4051 ;; Ignored element in an export context.
4052 ((and info (memq --data (plist-get info :ignore-list))))
4053 ;; List of elements or objects.
4054 ((not --type) (mapc --walk-tree --data))
4055 ;; Unconditionally enter parse trees.
4056 ((eq --type 'org-data)
4057 (mapc --walk-tree (org-element-contents --data)))
4059 ;; Check if TYPE is matching among TYPES. If so,
4060 ;; apply FUN to --DATA and accumulate return value
4061 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4062 (when (memq --type types)
4063 (let ((result (funcall fun --data)))
4064 (cond ((not result))
4065 (first-match (throw '--map-first-match result))
4066 (t (push result --acc)))))
4067 ;; If --DATA has a secondary string that can contain
4068 ;; objects with their type among TYPES, look into it.
4069 (when (and (eq --category 'objects) (not (stringp --data)))
4070 (dolist (p (cdr (assq --type
4071 org-element-secondary-value-alist)))
4072 (funcall --walk-tree (org-element-property p --data))))
4073 ;; If --DATA has any parsed affiliated keywords and
4074 ;; WITH-AFFILIATED is non-nil, look for objects in
4075 ;; them.
4076 (when (and with-affiliated
4077 (eq --category 'objects)
4078 (memq --type org-element-all-elements))
4079 (dolist (kwd-pair org-element--parsed-properties-alist)
4080 (let ((kwd (car kwd-pair))
4081 (value (org-element-property (cdr kwd-pair) --data)))
4082 ;; Pay attention to the type of parsed keyword.
4083 ;; In particular, preserve order for multiple
4084 ;; keywords.
4085 (cond
4086 ((not value))
4087 ((member kwd org-element-dual-keywords)
4088 (if (member kwd org-element-multiple-keywords)
4089 (dolist (line (reverse value))
4090 (funcall --walk-tree (cdr line))
4091 (funcall --walk-tree (car line)))
4092 (funcall --walk-tree (cdr value))
4093 (funcall --walk-tree (car value))))
4094 ((member kwd org-element-multiple-keywords)
4095 (mapc --walk-tree (reverse value)))
4096 (t (funcall --walk-tree value))))))
4097 ;; Determine if a recursion into --DATA is possible.
4098 (cond
4099 ;; --TYPE is explicitly removed from recursion.
4100 ((memq --type no-recursion))
4101 ;; --DATA has no contents.
4102 ((not (org-element-contents --data)))
4103 ;; Looking for greater elements but --DATA is simply
4104 ;; an element or an object.
4105 ((and (eq --category 'greater-elements)
4106 (not (memq --type org-element-greater-elements))))
4107 ;; Looking for elements but --DATA is an object.
4108 ((and (eq --category 'elements)
4109 (memq --type org-element-all-objects)))
4110 ;; In any other case, map contents.
4111 (t (mapc --walk-tree (org-element-contents --data))))))))))
4112 (catch '--map-first-match
4113 (funcall --walk-tree data)
4114 ;; Return value in a proper order.
4115 (nreverse --acc))))
4116 (put 'org-element-map 'lisp-indent-function 2)
4118 ;; The following functions are internal parts of the parser.
4120 ;; The first one, `org-element--parse-elements' acts at the element's
4121 ;; level.
4123 ;; The second one, `org-element--parse-objects' applies on all objects
4124 ;; of a paragraph or a secondary string. It calls
4125 ;; `org-element--object-lex' to find the next object in the current
4126 ;; container.
4128 (defsubst org-element--next-mode (type parentp)
4129 "Return next special mode according to TYPE, or nil.
4130 TYPE is a symbol representing the type of an element or object
4131 containing next element if PARENTP is non-nil, or before it
4132 otherwise. Modes can be either `first-section', `item',
4133 `node-property', `planning', `property-drawer', `section',
4134 `table-row' or nil."
4135 (if parentp
4136 (case type
4137 (headline 'section)
4138 (plain-list 'item)
4139 (property-drawer 'node-property)
4140 (section 'planning)
4141 (table 'table-row))
4142 (case type
4143 (item 'item)
4144 (node-property 'node-property)
4145 (planning 'property-drawer)
4146 (table-row 'table-row))))
4148 (defun org-element--parse-elements
4149 (beg end mode structure granularity visible-only acc)
4150 "Parse elements between BEG and END positions.
4152 MODE prioritizes some elements over the others. It can be set to
4153 `first-section', `section', `planning', `item', `node-property'
4154 or `table-row'.
4156 When value is `item', STRUCTURE will be used as the current list
4157 structure.
4159 GRANULARITY determines the depth of the recursion. See
4160 `org-element-parse-buffer' for more information.
4162 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4163 elements.
4165 Elements are accumulated into ACC."
4166 (save-excursion
4167 (goto-char beg)
4168 ;; Visible only: skip invisible parts at the beginning of the
4169 ;; element.
4170 (when (and visible-only (org-invisible-p2))
4171 (goto-char (min (1+ (org-find-visible)) end)))
4172 ;; When parsing only headlines, skip any text before first one.
4173 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4174 (org-with-limited-levels (outline-next-heading)))
4175 ;; Main loop start.
4176 (while (< (point) end)
4177 ;; Find current element's type and parse it accordingly to
4178 ;; its category.
4179 (let* ((element (org-element--current-element
4180 end granularity mode structure))
4181 (type (org-element-type element))
4182 (cbeg (org-element-property :contents-begin element)))
4183 (goto-char (org-element-property :end element))
4184 ;; Visible only: skip invisible parts between siblings.
4185 (when (and visible-only (org-invisible-p2))
4186 (goto-char (min (1+ (org-find-visible)) end)))
4187 ;; Fill ELEMENT contents by side-effect.
4188 (cond
4189 ;; If element has no contents, don't modify it.
4190 ((not cbeg))
4191 ;; Greater element: parse it between `contents-begin' and
4192 ;; `contents-end'. Make sure GRANULARITY allows the
4193 ;; recursion, or ELEMENT is a headline, in which case going
4194 ;; inside is mandatory, in order to get sub-level headings.
4195 ((and (memq type org-element-greater-elements)
4196 (or (memq granularity '(element object nil))
4197 (and (eq granularity 'greater-element)
4198 (eq type 'section))
4199 (eq type 'headline)))
4200 (org-element--parse-elements
4201 cbeg (org-element-property :contents-end element)
4202 ;; Possibly switch to a special mode.
4203 (org-element--next-mode type t)
4204 (and (memq type '(item plain-list))
4205 (org-element-property :structure element))
4206 granularity visible-only element))
4207 ;; ELEMENT has contents. Parse objects inside, if
4208 ;; GRANULARITY allows it.
4209 ((memq granularity '(object nil))
4210 (org-element--parse-objects
4211 cbeg (org-element-property :contents-end element) element
4212 (org-element-restriction type))))
4213 (org-element-adopt-elements acc element)
4214 ;; Update mode.
4215 (setq mode (org-element--next-mode type nil))))
4216 ;; Return result.
4217 acc))
4219 (defun org-element--object-lex (restriction)
4220 "Return next object in current buffer or nil.
4221 RESTRICTION is a list of object types, as symbols, that should be
4222 looked after. This function assumes that the buffer is narrowed
4223 to an appropriate container (e.g., a paragraph)."
4224 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4225 (save-excursion
4226 (let ((limit (and org-target-link-regexp
4227 (save-excursion
4228 (or (bolp) (backward-char))
4229 (re-search-forward org-target-link-regexp nil t))
4230 (match-beginning 1)))
4231 found)
4232 (while (and (not found)
4233 (re-search-forward org-element--object-regexp limit t))
4234 (goto-char (match-beginning 0))
4235 (let ((result (match-string 0)))
4236 (setq found
4237 (cond
4238 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4239 (and (memq 'inline-babel-call restriction)
4240 (org-element-inline-babel-call-parser)))
4241 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4242 (and (memq 'inline-src-block restriction)
4243 (org-element-inline-src-block-parser)))
4245 (case (char-after)
4246 (?^ (and (memq 'superscript restriction)
4247 (org-element-superscript-parser)))
4248 (?_ (or (and (memq 'subscript restriction)
4249 (org-element-subscript-parser))
4250 (and (memq 'underline restriction)
4251 (org-element-underline-parser))))
4252 (?* (and (memq 'bold restriction)
4253 (org-element-bold-parser)))
4254 (?/ (and (memq 'italic restriction)
4255 (org-element-italic-parser)))
4256 (?~ (and (memq 'code restriction)
4257 (org-element-code-parser)))
4258 (?= (and (memq 'verbatim restriction)
4259 (org-element-verbatim-parser)))
4260 (?+ (and (memq 'strike-through restriction)
4261 (org-element-strike-through-parser)))
4262 (?@ (and (memq 'export-snippet restriction)
4263 (org-element-export-snippet-parser)))
4264 (?{ (and (memq 'macro restriction)
4265 (org-element-macro-parser)))
4266 (?$ (and (memq 'latex-fragment restriction)
4267 (org-element-latex-fragment-parser)))
4269 (if (eq (aref result 1) ?<)
4270 (or (and (memq 'radio-target restriction)
4271 (org-element-radio-target-parser))
4272 (and (memq 'target restriction)
4273 (org-element-target-parser)))
4274 (or (and (memq 'timestamp restriction)
4275 (org-element-timestamp-parser))
4276 (and (memq 'link restriction)
4277 (org-element-link-parser)))))
4278 (?\\
4279 (if (eq (aref result 1) ?\\)
4280 (and (memq 'line-break restriction)
4281 (org-element-line-break-parser))
4282 (or (and (memq 'entity restriction)
4283 (org-element-entity-parser))
4284 (and (memq 'latex-fragment restriction)
4285 (org-element-latex-fragment-parser)))))
4286 (?\[
4287 (if (eq (aref result 1) ?\[)
4288 (and (memq 'link restriction)
4289 (org-element-link-parser))
4290 (or (and (memq 'footnote-reference restriction)
4291 (org-element-footnote-reference-parser))
4292 (and (memq 'timestamp restriction)
4293 (org-element-timestamp-parser))
4294 (and (memq 'statistics-cookie restriction)
4295 (org-element-statistics-cookie-parser)))))
4296 ;; This is probably a plain link.
4297 (otherwise (and (or (memq 'link restriction)
4298 (memq 'plain-link restriction))
4299 (org-element-link-parser)))))))
4300 (or (eobp) (forward-char))))
4301 (cond (found)
4302 ;; Radio link.
4303 ((and limit (memq 'link restriction))
4304 (goto-char limit) (org-element-link-parser)))))))
4306 (defun org-element--parse-objects (beg end acc restriction)
4307 "Parse objects between BEG and END and return recursive structure.
4309 Objects are accumulated in ACC.
4311 RESTRICTION is a list of object successors which are allowed in
4312 the current object."
4313 (save-excursion
4314 (save-restriction
4315 (narrow-to-region beg end)
4316 (goto-char (point-min))
4317 (let (next-object)
4318 (while (and (not (eobp))
4319 (setq next-object (org-element--object-lex restriction)))
4320 ;; 1. Text before any object. Untabify it.
4321 (let ((obj-beg (org-element-property :begin next-object)))
4322 (unless (= (point) obj-beg)
4323 (setq acc
4324 (org-element-adopt-elements
4326 (replace-regexp-in-string
4327 "\t" (make-string tab-width ? )
4328 (buffer-substring-no-properties (point) obj-beg))))))
4329 ;; 2. Object...
4330 (let ((obj-end (org-element-property :end next-object))
4331 (cont-beg (org-element-property :contents-begin next-object)))
4332 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4333 ;; a recursive type.
4334 (when (and cont-beg
4335 (memq (car next-object) org-element-recursive-objects))
4336 (org-element--parse-objects
4337 cont-beg (org-element-property :contents-end next-object)
4338 next-object (org-element-restriction next-object)))
4339 (setq acc (org-element-adopt-elements acc next-object))
4340 (goto-char obj-end))))
4341 ;; 3. Text after last object. Untabify it.
4342 (unless (eobp)
4343 (setq acc
4344 (org-element-adopt-elements
4346 (replace-regexp-in-string
4347 "\t" (make-string tab-width ? )
4348 (buffer-substring-no-properties (point) end)))))
4349 ;; Result.
4350 acc)))
4354 ;;; Towards A Bijective Process
4356 ;; The parse tree obtained with `org-element-parse-buffer' is really
4357 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4358 ;; interpreted and expanded into a string with canonical Org syntax.
4359 ;; Hence `org-element-interpret-data'.
4361 ;; The function relies internally on
4362 ;; `org-element--interpret-affiliated-keywords'.
4364 ;;;###autoload
4365 (defun org-element-interpret-data (data)
4366 "Interpret DATA as Org syntax.
4367 DATA is a parse tree, an element, an object or a secondary string
4368 to interpret. Return Org syntax as a string."
4369 (org-element--interpret-data-1 data nil))
4371 (defun org-element--interpret-data-1 (data parent)
4372 "Interpret DATA as Org syntax.
4374 DATA is a parse tree, an element, an object or a secondary string
4375 to interpret. PARENT is used for recursive calls. It contains
4376 the element or object containing data, or nil.
4378 Return Org syntax as a string."
4379 (let* ((type (org-element-type data))
4380 ;; Find interpreter for current object or element. If it
4381 ;; doesn't exist (e.g. this is a pseudo object or element),
4382 ;; return contents, if any.
4383 (interpret
4384 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4385 (if (fboundp fun) fun (lambda (data contents) contents))))
4386 (results
4387 (cond
4388 ;; Secondary string.
4389 ((not type)
4390 (mapconcat
4391 (lambda (obj) (org-element--interpret-data-1 obj parent)) data ""))
4392 ;; Full Org document.
4393 ((eq type 'org-data)
4394 (mapconcat (lambda (obj) (org-element--interpret-data-1 obj parent))
4395 (org-element-contents data) ""))
4396 ;; Plain text: return it.
4397 ((stringp data) data)
4398 ;; Element or object without contents.
4399 ((not (org-element-contents data)) (funcall interpret data nil))
4400 ;; Element or object with contents.
4402 (funcall interpret data
4403 ;; Recursively interpret contents.
4404 (mapconcat
4405 (lambda (obj) (org-element--interpret-data-1 obj data))
4406 (org-element-contents
4407 (if (not (memq type '(paragraph verse-block)))
4408 data
4409 ;; Fix indentation of elements containing
4410 ;; objects. We ignore `table-row' elements
4411 ;; as they are one line long anyway.
4412 (org-element-normalize-contents
4413 data
4414 ;; When normalizing first paragraph of an
4415 ;; item or a footnote-definition, ignore
4416 ;; first line's indentation.
4417 (and (eq type 'paragraph)
4418 (equal data (car (org-element-contents parent)))
4419 (memq (org-element-type parent)
4420 '(footnote-definition item))))))
4421 ""))))))
4422 (if (memq type '(org-data plain-text nil)) results
4423 ;; Build white spaces. If no `:post-blank' property is
4424 ;; specified, assume its value is 0.
4425 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4426 (if (or (memq type org-element-all-objects)
4427 (and parent
4428 (let ((type (org-element-type parent)))
4429 (or (not type)
4430 (memq type org-element-object-containers)))))
4431 (concat results (make-string post-blank ?\s))
4432 (concat
4433 (org-element--interpret-affiliated-keywords data)
4434 (org-element-normalize-string results)
4435 (make-string post-blank ?\n)))))))
4437 (defun org-element--interpret-affiliated-keywords (element)
4438 "Return ELEMENT's affiliated keywords as Org syntax.
4439 If there is no affiliated keyword, return the empty string."
4440 (let ((keyword-to-org
4441 (function
4442 (lambda (key value)
4443 (let (dual)
4444 (when (member key org-element-dual-keywords)
4445 (setq dual (cdr value) value (car value)))
4446 (concat "#+" key
4447 (and dual
4448 (format "[%s]" (org-element-interpret-data dual)))
4449 ": "
4450 (if (member key org-element-parsed-keywords)
4451 (org-element-interpret-data value)
4452 value)
4453 "\n"))))))
4454 (mapconcat
4455 (lambda (prop)
4456 (let ((value (org-element-property prop element))
4457 (keyword (upcase (substring (symbol-name prop) 1))))
4458 (when value
4459 (if (or (member keyword org-element-multiple-keywords)
4460 ;; All attribute keywords can have multiple lines.
4461 (string-match "^ATTR_" keyword))
4462 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4463 (reverse value)
4465 (funcall keyword-to-org keyword value)))))
4466 ;; List all ELEMENT's properties matching an attribute line or an
4467 ;; affiliated keyword, but ignore translated keywords since they
4468 ;; cannot belong to the property list.
4469 (loop for prop in (nth 1 element) by 'cddr
4470 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4471 (or (string-match "^ATTR_" keyword)
4472 (and
4473 (member keyword org-element-affiliated-keywords)
4474 (not (assoc keyword
4475 org-element-keyword-translation-alist)))))
4476 collect prop)
4477 "")))
4479 ;; Because interpretation of the parse tree must return the same
4480 ;; number of blank lines between elements and the same number of white
4481 ;; space after objects, some special care must be given to white
4482 ;; spaces.
4484 ;; The first function, `org-element-normalize-string', ensures any
4485 ;; string different from the empty string will end with a single
4486 ;; newline character.
4488 ;; The second function, `org-element-normalize-contents', removes
4489 ;; global indentation from the contents of the current element.
4491 (defun org-element-normalize-string (s)
4492 "Ensure string S ends with a single newline character.
4494 If S isn't a string return it unchanged. If S is the empty
4495 string, return it. Otherwise, return a new string with a single
4496 newline character at its end."
4497 (cond
4498 ((not (stringp s)) s)
4499 ((string= "" s) "")
4500 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4501 (replace-match "\n" nil nil s)))))
4503 (defun org-element-normalize-contents (element &optional ignore-first)
4504 "Normalize plain text in ELEMENT's contents.
4506 ELEMENT must only contain plain text and objects.
4508 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4509 indentation to compute maximal common indentation.
4511 Return the normalized element that is element with global
4512 indentation removed from its contents. The function assumes that
4513 indentation is not done with TAB characters."
4514 (let* ((min-ind most-positive-fixnum)
4515 find-min-ind ; For byte-compiler.
4516 (find-min-ind
4517 ;; Return minimal common indentation within BLOB. This is
4518 ;; done by walking recursively BLOB and updating MIN-IND
4519 ;; along the way. FIRST-FLAG is non-nil when the next
4520 ;; object is expected to be a string that doesn't start with
4521 ;; a newline character. It happens for strings at the
4522 ;; beginnings of the contents or right after a line break.
4523 (lambda (blob first-flag)
4524 (dolist (object (org-element-contents blob))
4525 (when first-flag
4526 (setq first-flag nil)
4527 ;; Objects cannot start with spaces: in this case,
4528 ;; indentation is 0.
4529 (if (not (stringp object)) (throw 'zero (setq min-ind 0))
4530 (string-match "\\` *" object)
4531 (let ((len (match-end 0)))
4532 ;; An indentation of zero means no string will be
4533 ;; modified. Quit the process.
4534 (if (zerop len) (throw 'zero (setq min-ind 0))
4535 (setq min-ind (min len min-ind))))))
4536 (cond
4537 ((stringp object)
4538 (dolist (line (cdr (org-split-string object " *\n")))
4539 (unless (string= line "")
4540 (setq min-ind (min (org-get-indentation line) min-ind)))))
4541 ((eq (org-element-type object) 'line-break) (setq first-flag t))
4542 ((memq (org-element-type object) org-element-recursive-objects)
4543 (funcall find-min-ind object first-flag)))))))
4544 ;; Find minimal indentation in ELEMENT.
4545 (catch 'zero (funcall find-min-ind element (not ignore-first)))
4546 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4547 ;; Build ELEMENT back, replacing each string with the same
4548 ;; string minus common indentation.
4549 (let* (build ; For byte compiler.
4550 (build
4551 (lambda (blob first-flag)
4552 ;; Return BLOB with all its strings indentation
4553 ;; shortened from MIN-IND white spaces. FIRST-FLAG is
4554 ;; non-nil when the next object is expected to be
4555 ;; a string that doesn't start with a newline
4556 ;; character.
4557 (setcdr (cdr blob)
4558 (mapcar
4559 (lambda (object)
4560 (when first-flag
4561 (setq first-flag nil)
4562 (when (stringp object)
4563 (setq object
4564 (replace-regexp-in-string
4565 (format "\\` \\{%d\\}" min-ind)
4566 "" object))))
4567 (cond
4568 ((stringp object)
4569 (replace-regexp-in-string
4570 (format "\n \\{%d\\}" min-ind) "\n" object))
4571 ((memq (org-element-type object)
4572 org-element-recursive-objects)
4573 (funcall build object first-flag))
4574 ((eq (org-element-type object) 'line-break)
4575 (setq first-flag t)
4576 object)
4577 (t object)))
4578 (org-element-contents blob)))
4579 blob)))
4580 (funcall build element (not ignore-first))))))
4584 ;;; Cache
4586 ;; Implement a caching mechanism for `org-element-at-point' and
4587 ;; `org-element-context', which see.
4589 ;; A single public function is provided: `org-element-cache-reset'.
4591 ;; Cache is enabled by default, but can be disabled globally with
4592 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4593 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4594 ;; can be tweaked to control caching behaviour.
4596 ;; Internally, parsed elements are stored in an AVL tree,
4597 ;; `org-element--cache'. This tree is updated lazily: whenever
4598 ;; a change happens to the buffer, a synchronization request is
4599 ;; registered in `org-element--cache-sync-requests' (see
4600 ;; `org-element--cache-submit-request'). During idle time, requests
4601 ;; are processed by `org-element--cache-sync'. Synchronization also
4602 ;; happens when an element is required from the cache. In this case,
4603 ;; the process stops as soon as the needed element is up-to-date.
4605 ;; A synchronization request can only apply on a synchronized part of
4606 ;; the cache. Therefore, the cache is updated at least to the
4607 ;; location where the new request applies. Thus, requests are ordered
4608 ;; from left to right and all elements starting before the first
4609 ;; request are correct. This property is used by functions like
4610 ;; `org-element--cache-find' to retrieve elements in the part of the
4611 ;; cache that can be trusted.
4613 ;; A request applies to every element, starting from its original
4614 ;; location (or key, see below). When a request is processed, it
4615 ;; moves forward and may collide the next one. In this case, both
4616 ;; requests are merged into a new one that starts from that element.
4617 ;; As a consequence, the whole synchronization complexity does not
4618 ;; depend on the number of pending requests, but on the number of
4619 ;; elements the very first request will be applied on.
4621 ;; Elements cannot be accessed through their beginning position, which
4622 ;; may or may not be up-to-date. Instead, each element in the tree is
4623 ;; associated to a key, obtained with `org-element--cache-key'. This
4624 ;; mechanism is robust enough to preserve total order among elements
4625 ;; even when the tree is only partially synchronized.
4627 ;; Objects contained in an element are stored in a hash table,
4628 ;; `org-element--cache-objects'.
4631 (defvar org-element-use-cache t
4632 "Non nil when Org parser should cache its results.
4633 This is mostly for debugging purpose.")
4635 (defvar org-element-cache-sync-idle-time 0.6
4636 "Length, in seconds, of idle time before syncing cache.")
4638 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4639 "Maximum duration, as a time value, for a cache synchronization.
4640 If the synchronization is not over after this delay, the process
4641 pauses and resumes after `org-element-cache-sync-break'
4642 seconds.")
4644 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4645 "Duration, as a time value, of the pause between synchronizations.
4646 See `org-element-cache-sync-duration' for more information.")
4649 ;;;; Data Structure
4651 (defvar org-element--cache nil
4652 "AVL tree used to cache elements.
4653 Each node of the tree contains an element. Comparison is done
4654 with `org-element--cache-compare'. This cache is used in
4655 `org-element-at-point'.")
4657 (defvar org-element--cache-objects nil
4658 "Hash table used as to cache objects.
4659 Key is an element, as returned by `org-element-at-point', and
4660 value is an alist where each association is:
4662 \(PARENT COMPLETEP . OBJECTS)
4664 where PARENT is an element or object, COMPLETEP is a boolean,
4665 non-nil when all direct children of parent are already cached and
4666 OBJECTS is a list of such children, as objects, from farthest to
4667 closest.
4669 In the following example, \\alpha, bold object and \\beta are
4670 contained within a paragraph
4672 \\alpha *\\beta*
4674 If the paragraph is completely parsed, OBJECTS-DATA will be
4676 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4677 \(BOLD-OBJECT t ENTITY-OBJECT))
4679 whereas in a partially parsed paragraph, it could be
4681 \((PARAGRAPH nil ENTITY-OBJECT))
4683 This cache is used in `org-element-context'.")
4685 (defvar org-element--cache-sync-requests nil
4686 "List of pending synchronization requests.
4688 A request is a vector with the following pattern:
4690 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4692 Processing a synchronization request consists of three phases:
4694 0. Delete modified elements,
4695 1. Fill missing area in cache,
4696 2. Shift positions and re-parent elements after the changes.
4698 During phase 0, NEXT is the key of the first element to be
4699 removed, BEG and END is buffer position delimiting the
4700 modifications. Elements starting between them (inclusive) are
4701 removed and so are those contained within OUTREACH. PARENT, when
4702 non-nil, is the parent of the first element to be removed.
4704 During phase 1, NEXT is the key of the next known element in
4705 cache and BEG its beginning position. Parse buffer between that
4706 element and the one before it in order to determine the parent of
4707 the next element. Set PARENT to the element containing NEXT.
4709 During phase 2, NEXT is the key of the next element to shift in
4710 the parse tree. All elements starting from this one have their
4711 properties relatives to buffer positions shifted by integer
4712 OFFSET and, if they belong to element PARENT, are adopted by it.
4714 PHASE specifies the phase number, as an integer.")
4716 (defvar org-element--cache-sync-timer nil
4717 "Timer used for cache synchronization.")
4719 (defvar org-element--cache-sync-keys nil
4720 "Hash table used to store keys during synchronization.
4721 See `org-element--cache-key' for more information.")
4723 (defsubst org-element--cache-key (element)
4724 "Return a unique key for ELEMENT in cache tree.
4726 Keys are used to keep a total order among elements in the cache.
4727 Comparison is done with `org-element--cache-key-less-p'.
4729 When no synchronization is taking place, a key is simply the
4730 beginning position of the element, or that position plus one in
4731 the case of an first item (respectively row) in
4732 a list (respectively a table).
4734 During a synchronization, the key is the one the element had when
4735 the cache was synchronized for the last time. Elements added to
4736 cache during the synchronization get a new key generated with
4737 `org-element--cache-generate-key'.
4739 Such keys are stored in `org-element--cache-sync-keys'. The hash
4740 table is cleared once the synchronization is complete."
4741 (or (gethash element org-element--cache-sync-keys)
4742 (let* ((begin (org-element-property :begin element))
4743 ;; Increase beginning position of items (respectively
4744 ;; table rows) by one, so the first item can get
4745 ;; a different key from its parent list (respectively
4746 ;; table).
4747 (key (if (memq (org-element-type element) '(item table-row))
4748 (1+ begin)
4749 begin)))
4750 (if org-element--cache-sync-requests
4751 (puthash element key org-element--cache-sync-keys)
4752 key))))
4754 (defun org-element--cache-generate-key (lower upper)
4755 "Generate a key between LOWER and UPPER.
4757 LOWER and UPPER are integers or lists, possibly empty.
4759 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4760 a unique key, as an integer or a list of integers, according to
4761 the following rules:
4763 - LOWER and UPPER are compared level-wise until values differ.
4765 - If, at a given level, LOWER and UPPER differ from more than
4766 2, the new key shares all the levels above with LOWER and
4767 gets a new level. Its value is the mean between LOWER and
4768 UPPER:
4770 \(1 2) + (1 4) --> (1 3)
4772 - If LOWER has no value to compare with, it is assumed that its
4773 value is `most-negative-fixnum'. E.g.,
4775 \(1 1) + (1 1 2)
4777 is equivalent to
4779 \(1 1 m) + (1 1 2)
4781 where m is `most-negative-fixnum'. Likewise, if UPPER is
4782 short of levels, the current value is `most-positive-fixnum'.
4784 - If they differ from only one, the new key inherits from
4785 current LOWER level and fork it at the next level. E.g.,
4787 \(2 1) + (3 3)
4789 is equivalent to
4791 \(2 1) + (2 M)
4793 where M is `most-positive-fixnum'.
4795 - If the key is only one level long, it is returned as an
4796 integer:
4798 \(1 2) + (3 2) --> 2
4800 When they are not equals, the function assumes that LOWER is
4801 lesser than UPPER, per `org-element--cache-key-less-p'."
4802 (if (equal lower upper) lower
4803 (let ((lower (if (integerp lower) (list lower) lower))
4804 (upper (if (integerp upper) (list upper) upper))
4805 skip-upper key)
4806 (catch 'exit
4807 (while t
4808 (let ((min (or (car lower) most-negative-fixnum))
4809 (max (cond (skip-upper most-positive-fixnum)
4810 ((car upper))
4811 (t most-positive-fixnum))))
4812 (if (< (1+ min) max)
4813 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4814 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4815 (when (and (< min max) (not skip-upper))
4816 ;; When at a given level, LOWER and UPPER differ from
4817 ;; 1, ignore UPPER altogether. Instead create a key
4818 ;; between LOWER and the greatest key with the same
4819 ;; prefix as LOWER so far.
4820 (setq skip-upper t))
4821 (push min key)
4822 (setq lower (cdr lower) upper (cdr upper)))))))))
4824 (defsubst org-element--cache-key-less-p (a b)
4825 "Non-nil if key A is less than key B.
4826 A and B are either integers or lists of integers, as returned by
4827 `org-element--cache-key'."
4828 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4829 (if (integerp b) (< (car a) b)
4830 (catch 'exit
4831 (while (and a b)
4832 (cond ((car-less-than-car a b) (throw 'exit t))
4833 ((car-less-than-car b a) (throw 'exit nil))
4834 (t (setq a (cdr a) b (cdr b)))))
4835 ;; If A is empty, either keys are equal (B is also empty) and
4836 ;; we return nil, or A is lesser than B (B is longer) and we
4837 ;; return a non-nil value.
4839 ;; If A is not empty, B is necessarily empty and A is greater
4840 ;; than B (A is longer). Therefore, return nil.
4841 (and (null a) b)))))
4843 (defun org-element--cache-compare (a b)
4844 "Non-nil when element A is located before element B."
4845 (org-element--cache-key-less-p (org-element--cache-key a)
4846 (org-element--cache-key b)))
4848 (defsubst org-element--cache-root ()
4849 "Return root value in cache.
4850 This function assumes `org-element--cache' is a valid AVL tree."
4851 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4854 ;;;; Tools
4856 (defsubst org-element--cache-active-p ()
4857 "Non-nil when cache is active in current buffer."
4858 (and org-element-use-cache
4859 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4861 (defun org-element--cache-find (pos &optional side)
4862 "Find element in cache starting at POS or before.
4864 POS refers to a buffer position.
4866 When optional argument SIDE is non-nil, the function checks for
4867 elements starting at or past POS instead. If SIDE is `both', the
4868 function returns a cons cell where car is the first element
4869 starting at or before POS and cdr the first element starting
4870 after POS.
4872 The function can only find elements in the synchronized part of
4873 the cache."
4874 (let ((limit (and org-element--cache-sync-requests
4875 (aref (car org-element--cache-sync-requests) 0)))
4876 (node (org-element--cache-root))
4877 lower upper)
4878 (while node
4879 (let* ((element (avl-tree--node-data node))
4880 (begin (org-element-property :begin element)))
4881 (cond
4882 ((and limit
4883 (not (org-element--cache-key-less-p
4884 (org-element--cache-key element) limit)))
4885 (setq node (avl-tree--node-left node)))
4886 ((> begin pos)
4887 (setq upper element
4888 node (avl-tree--node-left node)))
4889 ((< begin pos)
4890 (setq lower element
4891 node (avl-tree--node-right node)))
4892 ;; We found an element in cache starting at POS. If `side'
4893 ;; is `both' we also want the next one in order to generate
4894 ;; a key in-between.
4896 ;; If the element is the first row or item in a table or
4897 ;; a plain list, we always return the table or the plain
4898 ;; list.
4900 ;; In any other case, we return the element found.
4901 ((eq side 'both)
4902 (setq lower element)
4903 (setq node (avl-tree--node-right node)))
4904 ((and (memq (org-element-type element) '(item table-row))
4905 (let ((parent (org-element-property :parent element)))
4906 (and (= (org-element-property :begin element)
4907 (org-element-property :contents-begin parent))
4908 (setq node nil
4909 lower parent
4910 upper parent)))))
4912 (setq node nil
4913 lower element
4914 upper element)))))
4915 (case side
4916 (both (cons lower upper))
4917 ((nil) lower)
4918 (otherwise upper))))
4920 (defun org-element--cache-put (element &optional data)
4921 "Store ELEMENT in current buffer's cache, if allowed.
4922 When optional argument DATA is non-nil, assume is it object data
4923 relative to ELEMENT and store it in the objects cache."
4924 (cond ((not (org-element--cache-active-p)) nil)
4925 ((not data)
4926 (when org-element--cache-sync-requests
4927 ;; During synchronization, first build an appropriate key
4928 ;; for the new element so `avl-tree-enter' can insert it at
4929 ;; the right spot in the cache.
4930 (let ((keys (org-element--cache-find
4931 (org-element-property :begin element) 'both)))
4932 (puthash element
4933 (org-element--cache-generate-key
4934 (and (car keys) (org-element--cache-key (car keys)))
4935 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4936 (org-element--cache-sync-requests
4937 (aref (car org-element--cache-sync-requests) 0))))
4938 org-element--cache-sync-keys)))
4939 (avl-tree-enter org-element--cache element))
4940 ;; Headlines are not stored in cache, so objects in titles are
4941 ;; not stored either.
4942 ((eq (org-element-type element) 'headline) nil)
4943 (t (puthash element data org-element--cache-objects))))
4945 (defsubst org-element--cache-remove (element)
4946 "Remove ELEMENT from cache.
4947 Assume ELEMENT belongs to cache and that a cache is active."
4948 (avl-tree-delete org-element--cache element)
4949 (remhash element org-element--cache-objects))
4952 ;;;; Synchronization
4954 (defsubst org-element--cache-set-timer (buffer)
4955 "Set idle timer for cache synchronization in BUFFER."
4956 (when org-element--cache-sync-timer
4957 (cancel-timer org-element--cache-sync-timer))
4958 (setq org-element--cache-sync-timer
4959 (run-with-idle-timer
4960 (let ((idle (current-idle-time)))
4961 (if idle (time-add idle org-element-cache-sync-break)
4962 org-element-cache-sync-idle-time))
4964 #'org-element--cache-sync
4965 buffer)))
4967 (defsubst org-element--cache-interrupt-p (time-limit)
4968 "Non-nil when synchronization process should be interrupted.
4969 TIME-LIMIT is a time value or nil."
4970 (and time-limit
4971 (or (input-pending-p)
4972 (time-less-p time-limit (current-time)))))
4974 (defsubst org-element--cache-shift-positions (element offset &optional props)
4975 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4977 Properties containing buffer positions are `:begin', `:end',
4978 `:contents-begin', `:contents-end' and `:structure'. When
4979 optional argument PROPS is a list of keywords, only shift
4980 properties provided in that list.
4982 Properties are modified by side-effect."
4983 (let ((properties (nth 1 element)))
4984 ;; Shift `:structure' property for the first plain list only: it
4985 ;; is the only one that really matters and it prevents from
4986 ;; shifting it more than once.
4987 (when (and (or (not props) (memq :structure props))
4988 (eq (org-element-type element) 'plain-list)
4989 (not (eq (org-element-type (plist-get properties :parent))
4990 'item)))
4991 (dolist (item (plist-get properties :structure))
4992 (incf (car item) offset)
4993 (incf (nth 6 item) offset)))
4994 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
4995 (let ((value (and (or (not props) (memq key props))
4996 (plist-get properties key))))
4997 (and value (plist-put properties key (+ offset value)))))))
4999 (defun org-element--cache-sync (buffer &optional threshold future-change)
5000 "Synchronize cache with recent modification in BUFFER.
5002 When optional argument THRESHOLD is non-nil, do the
5003 synchronization for all elements starting before or at threshold,
5004 then exit. Otherwise, synchronize cache for as long as
5005 `org-element-cache-sync-duration' or until Emacs leaves idle
5006 state.
5008 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5009 not registered yet in the cache are going to happen. It is used
5010 in `org-element--cache-submit-request', where cache is partially
5011 updated before current modification are actually submitted."
5012 (when (buffer-live-p buffer)
5013 (with-current-buffer buffer
5014 (let ((inhibit-quit t) request next)
5015 (when org-element--cache-sync-timer
5016 (cancel-timer org-element--cache-sync-timer))
5017 (catch 'interrupt
5018 (while org-element--cache-sync-requests
5019 (setq request (car org-element--cache-sync-requests)
5020 next (nth 1 org-element--cache-sync-requests))
5021 (org-element--cache-process-request
5022 request
5023 (and next (aref next 0))
5024 threshold
5025 (and (not threshold)
5026 (time-add (current-time)
5027 org-element-cache-sync-duration))
5028 future-change)
5029 ;; Request processed. Merge current and next offsets and
5030 ;; transfer ending position.
5031 (when next
5032 (incf (aref next 3) (aref request 3))
5033 (aset next 2 (aref request 2)))
5034 (setq org-element--cache-sync-requests
5035 (cdr org-element--cache-sync-requests))))
5036 ;; If more requests are awaiting, set idle timer accordingly.
5037 ;; Otherwise, reset keys.
5038 (if org-element--cache-sync-requests
5039 (org-element--cache-set-timer buffer)
5040 (clrhash org-element--cache-sync-keys))))))
5042 (defun org-element--cache-process-request
5043 (request next threshold time-limit future-change)
5044 "Process synchronization REQUEST for all entries before NEXT.
5046 REQUEST is a vector, built by `org-element--cache-submit-request'.
5048 NEXT is a cache key, as returned by `org-element--cache-key'.
5050 When non-nil, THRESHOLD is a buffer position. Synchronization
5051 stops as soon as a shifted element begins after it.
5053 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5054 after this time or when Emacs exits idle state.
5056 When non-nil, FUTURE-CHANGE is a buffer position where changes
5057 not registered yet in the cache are going to happen. See
5058 `org-element--cache-submit-request' for more information.
5060 Throw `interrupt' if the process stops before completing the
5061 request."
5062 (catch 'quit
5063 (when (= (aref request 6) 0)
5064 ;; Phase 0.
5066 ;; Delete all elements starting after BEG, but not after buffer
5067 ;; position END or past element with key NEXT.
5069 ;; At each iteration, we start again at tree root since
5070 ;; a deletion modifies structure of the balanced tree.
5071 (catch 'end-phase
5072 (let ((beg (aref request 0))
5073 (end (aref request 2))
5074 (outreach (aref request 4)))
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 ((node (org-element--cache-root)) data data-key)
5080 (while node
5081 (let* ((element (avl-tree--node-data node))
5082 (key (org-element--cache-key element)))
5083 (cond
5084 ((org-element--cache-key-less-p key beg)
5085 (setq node (avl-tree--node-right node)))
5086 ((org-element--cache-key-less-p beg key)
5087 (setq data element
5088 data-key key
5089 node (avl-tree--node-left node)))
5090 (t (setq data element
5091 data-key key
5092 node nil)))))
5093 (if data
5094 (let ((pos (org-element-property :begin data)))
5095 (if (if (or (not next)
5096 (org-element--cache-key-less-p data-key next))
5097 (<= pos end)
5098 (let ((up data))
5099 (while (and up (not (eq up outreach)))
5100 (setq up (org-element-property :parent up)))
5101 up))
5102 (org-element--cache-remove data)
5103 (aset request 0 data-key)
5104 (aset request 1 pos)
5105 (aset request 6 1)
5106 (throw 'end-phase nil)))
5107 ;; No element starting after modifications left in
5108 ;; cache: further processing is futile.
5109 (throw 'quit t)))))))
5110 (when (= (aref request 6) 1)
5111 ;; Phase 1.
5113 ;; Phase 0 left a hole in the cache. Some elements after it
5114 ;; could have parents within. For example, in the following
5115 ;; buffer:
5117 ;; - item
5120 ;; Paragraph1
5122 ;; Paragraph2
5124 ;; if we remove a blank line between "item" and "Paragraph1",
5125 ;; everything down to "Paragraph2" is removed from cache. But
5126 ;; the paragraph now belongs to the list, and its `:parent'
5127 ;; property no longer is accurate.
5129 ;; Therefore we need to parse again elements in the hole, or at
5130 ;; least in its last section, so that we can re-parent
5131 ;; subsequent elements, during phase 2.
5133 ;; Note that we only need to get the parent from the first
5134 ;; element in cache after the hole.
5136 ;; When next key is lesser or equal to the current one, delegate
5137 ;; phase 1 processing to next request in order to preserve key
5138 ;; order among requests.
5139 (let ((key (aref request 0)))
5140 (when (and next (not (org-element--cache-key-less-p key next)))
5141 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5142 (aset next-request 0 key)
5143 (aset next-request 1 (aref request 1))
5144 (aset next-request 6 1))
5145 (throw 'quit t)))
5146 ;; Next element will start at its beginning position plus
5147 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5148 ;; contains the real beginning position of the first element to
5149 ;; shift and re-parent.
5150 (let ((limit (+ (aref request 1) (aref request 3))))
5151 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5152 ((and future-change (>= limit future-change))
5153 ;; Changes are going to happen around this element and
5154 ;; they will trigger another phase 1 request. Skip the
5155 ;; current one.
5156 (aset request 6 2))
5158 (let ((parent (org-element--parse-to limit t time-limit)))
5159 (aset request 5 parent)
5160 (aset request 6 2))))))
5161 ;; Phase 2.
5163 ;; Shift all elements starting from key START, but before NEXT, by
5164 ;; OFFSET, and re-parent them when appropriate.
5166 ;; Elements are modified by side-effect so the tree structure
5167 ;; remains intact.
5169 ;; Once THRESHOLD, if any, is reached, or once there is an input
5170 ;; pending, exit. Before leaving, the current synchronization
5171 ;; request is updated.
5172 (let ((start (aref request 0))
5173 (offset (aref request 3))
5174 (parent (aref request 5))
5175 (node (org-element--cache-root))
5176 (stack (list nil))
5177 (leftp t)
5178 exit-flag)
5179 ;; No re-parenting nor shifting planned: request is over.
5180 (when (and (not parent) (zerop offset)) (throw 'quit t))
5181 (while node
5182 (let* ((data (avl-tree--node-data node))
5183 (key (org-element--cache-key data)))
5184 (if (and leftp (avl-tree--node-left node)
5185 (not (org-element--cache-key-less-p key start)))
5186 (progn (push node stack)
5187 (setq node (avl-tree--node-left node)))
5188 (unless (org-element--cache-key-less-p key start)
5189 ;; We reached NEXT. Request is complete.
5190 (when (equal key next) (throw 'quit t))
5191 ;; Handle interruption request. Update current request.
5192 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5193 (aset request 0 key)
5194 (aset request 5 parent)
5195 (throw 'interrupt nil))
5196 ;; Shift element.
5197 (unless (zerop offset)
5198 (org-element--cache-shift-positions data offset)
5199 ;; Shift associated objects data, if any.
5200 (dolist (object-data (gethash data org-element--cache-objects))
5201 (dolist (object (cddr object-data))
5202 (org-element--cache-shift-positions object offset))))
5203 (let ((begin (org-element-property :begin data)))
5204 ;; Update PARENT and re-parent DATA, only when
5205 ;; necessary. Propagate new structures for lists.
5206 (while (and parent
5207 (<= (org-element-property :end parent) begin))
5208 (setq parent (org-element-property :parent parent)))
5209 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5210 ((and parent
5211 (let ((p (org-element-property :parent data)))
5212 (or (not p)
5213 (< (org-element-property :begin p)
5214 (org-element-property :begin parent)))))
5215 (org-element-put-property data :parent parent)
5216 (let ((s (org-element-property :structure parent)))
5217 (when (and s (org-element-property :structure data))
5218 (org-element-put-property data :structure s)))))
5219 ;; Cache is up-to-date past THRESHOLD. Request
5220 ;; interruption.
5221 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5222 (setq node (if (setq leftp (avl-tree--node-right node))
5223 (avl-tree--node-right node)
5224 (pop stack))))))
5225 ;; We reached end of tree: synchronization complete.
5226 t)))
5228 (defun org-element--parse-to (pos &optional syncp time-limit)
5229 "Parse elements in current section, down to POS.
5231 Start parsing from the closest between the last known element in
5232 cache or headline above. Return the smallest element containing
5233 POS.
5235 When optional argument SYNCP is non-nil, return the parent of the
5236 element containing POS instead. In that case, it is also
5237 possible to provide TIME-LIMIT, which is a time value specifying
5238 when the parsing should stop. The function throws `interrupt' if
5239 the process stopped before finding the expected result."
5240 (catch 'exit
5241 (org-with-wide-buffer
5242 (goto-char pos)
5243 (let* ((cached (and (org-element--cache-active-p)
5244 (org-element--cache-find pos nil)))
5245 (begin (org-element-property :begin cached))
5246 element next mode)
5247 (cond
5248 ;; Nothing in cache before point: start parsing from first
5249 ;; element following headline above, or first element in
5250 ;; buffer.
5251 ((not cached)
5252 (when (org-with-limited-levels (outline-previous-heading))
5253 (setq mode 'planning)
5254 (forward-line))
5255 (skip-chars-forward " \r\t\n")
5256 (beginning-of-line))
5257 ;; Cache returned exact match: return it.
5258 ((= pos begin)
5259 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5260 ;; There's a headline between cached value and POS: cached
5261 ;; value is invalid. Start parsing from first element
5262 ;; following the headline.
5263 ((re-search-backward
5264 (org-with-limited-levels org-outline-regexp-bol) begin t)
5265 (forward-line)
5266 (skip-chars-forward " \r\t\n")
5267 (beginning-of-line)
5268 (setq mode 'planning))
5269 ;; Check if CACHED or any of its ancestors contain point.
5271 ;; If there is such an element, we inspect it in order to know
5272 ;; if we return it or if we need to parse its contents.
5273 ;; Otherwise, we just start parsing from current location,
5274 ;; which is right after the top-most element containing
5275 ;; CACHED.
5277 ;; As a special case, if POS is at the end of the buffer, we
5278 ;; want to return the innermost element ending there.
5280 ;; Also, if we find an ancestor and discover that we need to
5281 ;; parse its contents, make sure we don't start from
5282 ;; `:contents-begin', as we would otherwise go past CACHED
5283 ;; again. Instead, in that situation, we will resume parsing
5284 ;; from NEXT, which is located after CACHED or its higher
5285 ;; ancestor not containing point.
5287 (let ((up cached)
5288 (pos (if (= (point-max) pos) (1- pos) pos)))
5289 (goto-char (or (org-element-property :contents-begin cached) begin))
5290 (while (let ((end (org-element-property :end up)))
5291 (and (<= end pos)
5292 (goto-char end)
5293 (setq up (org-element-property :parent up)))))
5294 (cond ((not up))
5295 ((eobp) (setq element up))
5296 (t (setq element up next (point)))))))
5297 ;; Parse successively each element until we reach POS.
5298 (let ((end (or (org-element-property :end element)
5299 (save-excursion
5300 (org-with-limited-levels (outline-next-heading))
5301 (point))))
5302 (parent element))
5303 (while t
5304 (when syncp
5305 (cond ((= (point) pos) (throw 'exit parent))
5306 ((org-element--cache-interrupt-p time-limit)
5307 (throw 'interrupt nil))))
5308 (unless element
5309 (setq element (org-element--current-element
5310 end 'element mode
5311 (org-element-property :structure parent)))
5312 (org-element-put-property element :parent parent)
5313 (org-element--cache-put element))
5314 (let ((elem-end (org-element-property :end element))
5315 (type (org-element-type element)))
5316 (cond
5317 ;; Skip any element ending before point. Also skip
5318 ;; element ending at point (unless it is also the end of
5319 ;; buffer) since we're sure that another element begins
5320 ;; after it.
5321 ((and (<= elem-end pos) (/= (point-max) elem-end))
5322 (goto-char elem-end)
5323 (setq mode (org-element--next-mode type nil)))
5324 ;; A non-greater element contains point: return it.
5325 ((not (memq type org-element-greater-elements))
5326 (throw 'exit element))
5327 ;; Otherwise, we have to decide if ELEMENT really
5328 ;; contains POS. In that case we start parsing from
5329 ;; contents' beginning.
5331 ;; If POS is at contents' beginning but it is also at
5332 ;; the beginning of the first item in a list or a table.
5333 ;; In that case, we need to create an anchor for that
5334 ;; list or table, so return it.
5336 ;; Also, if POS is at the end of the buffer, no element
5337 ;; can start after it, but more than one may end there.
5338 ;; Arbitrarily, we choose to return the innermost of
5339 ;; such elements.
5340 ((let ((cbeg (org-element-property :contents-begin element))
5341 (cend (org-element-property :contents-end element)))
5342 (when (or syncp
5343 (and cbeg cend
5344 (or (< cbeg pos)
5345 (and (= cbeg pos)
5346 (not (memq type '(plain-list table)))))
5347 (or (> cend pos)
5348 (and (= cend pos) (= (point-max) pos)))))
5349 (goto-char (or next cbeg))
5350 (setq next nil
5351 mode (org-element--next-mode type t)
5352 parent element
5353 end cend))))
5354 ;; Otherwise, return ELEMENT as it is the smallest
5355 ;; element containing POS.
5356 (t (throw 'exit element))))
5357 (setq element nil)))))))
5360 ;;;; Staging Buffer Changes
5362 (defconst org-element--cache-sensitive-re
5363 (concat
5364 org-outline-regexp-bol "\\|"
5365 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5366 "^[ \t]*\\(?:"
5367 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5368 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5369 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5370 "\\)")
5371 "Regexp matching a sensitive line, structure wise.
5372 A sensitive line is a headline, inlinetask, block, drawer, or
5373 latex-environment boundary. When such a line is modified,
5374 structure changes in the document may propagate in the whole
5375 section, possibly making cache invalid.")
5377 (defvar org-element--cache-change-warning nil
5378 "Non-nil when a sensitive line is about to be changed.
5379 It is a symbol among nil, t and `headline'.")
5381 (defun org-element--cache-before-change (beg end)
5382 "Request extension of area going to be modified if needed.
5383 BEG and END are the beginning and end of the range of changed
5384 text. See `before-change-functions' for more information."
5385 (when (org-element--cache-active-p)
5386 (org-with-wide-buffer
5387 (goto-char beg)
5388 (beginning-of-line)
5389 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5390 (setq org-element--cache-change-warning
5391 (save-match-data
5392 (if (and (org-with-limited-levels (org-at-heading-p))
5393 (= (line-end-position) bottom))
5394 'headline
5395 (let ((case-fold-search t))
5396 (re-search-forward
5397 org-element--cache-sensitive-re bottom t)))))))))
5399 (defun org-element--cache-after-change (beg end pre)
5400 "Update buffer modifications for current buffer.
5401 BEG and END are the beginning and end of the range of changed
5402 text, and the length in bytes of the pre-change text replaced by
5403 that range. See `after-change-functions' for more information."
5404 (when (org-element--cache-active-p)
5405 (org-with-wide-buffer
5406 (goto-char beg)
5407 (beginning-of-line)
5408 (save-match-data
5409 (let ((top (point))
5410 (bottom (save-excursion (goto-char end) (line-end-position))))
5411 ;; Determine if modified area needs to be extended, according
5412 ;; to both previous and current state. We make a special
5413 ;; case for headline editing: if a headline is modified but
5414 ;; not removed, do not extend.
5415 (when (case org-element--cache-change-warning
5416 ((t) t)
5417 (headline
5418 (not (and (org-with-limited-levels (org-at-heading-p))
5419 (= (line-end-position) bottom))))
5420 (otherwise
5421 (let ((case-fold-search t))
5422 (re-search-forward
5423 org-element--cache-sensitive-re bottom t))))
5424 ;; Effectively extend modified area.
5425 (org-with-limited-levels
5426 (setq top (progn (goto-char top)
5427 (when (outline-previous-heading) (forward-line))
5428 (point)))
5429 (setq bottom (progn (goto-char bottom)
5430 (if (outline-next-heading) (1- (point))
5431 (point))))))
5432 ;; Store synchronization request.
5433 (let ((offset (- end beg pre)))
5434 (org-element--cache-submit-request top (- bottom offset) offset)))))
5435 ;; Activate a timer to process the request during idle time.
5436 (org-element--cache-set-timer (current-buffer))))
5438 (defun org-element--cache-for-removal (beg end offset)
5439 "Return first element to remove from cache.
5441 BEG and END are buffer positions delimiting buffer modifications.
5442 OFFSET is the size of the changes.
5444 Returned element is usually the first element in cache containing
5445 any position between BEG and END. As an exception, greater
5446 elements around the changes that are robust to contents
5447 modifications are preserved and updated according to the
5448 changes."
5449 (let* ((elements (org-element--cache-find (1- beg) 'both))
5450 (before (car elements))
5451 (after (cdr elements)))
5452 (if (not before) after
5453 (let ((up before)
5454 (robust-flag t))
5455 (while up
5456 (if (let ((type (org-element-type up)))
5457 (and (or (memq type '(center-block dynamic-block quote-block
5458 special-block))
5459 ;; Drawers named "PROPERTIES" are probably
5460 ;; a properties drawer being edited. Force
5461 ;; parsing to check if editing is over.
5462 (and (eq type 'drawer)
5463 (not (string=
5464 (org-element-property :drawer-name up)
5465 "PROPERTIES"))))
5466 (let ((cbeg (org-element-property :contents-begin up)))
5467 (and cbeg
5468 (<= cbeg beg)
5469 (> (org-element-property :contents-end up) end)))))
5470 ;; UP is a robust greater element containing changes.
5471 ;; We only need to extend its ending boundaries.
5472 (org-element--cache-shift-positions
5473 up offset '(:contents-end :end))
5474 (setq before up)
5475 (when robust-flag (setq robust-flag nil)))
5476 (setq up (org-element-property :parent up)))
5477 ;; We're at top level element containing ELEMENT: if it's
5478 ;; altered by buffer modifications, it is first element in
5479 ;; cache to be removed. Otherwise, that first element is the
5480 ;; following one.
5482 ;; As a special case, do not remove BEFORE if it is a robust
5483 ;; container for current changes.
5484 (if (or (< (org-element-property :end before) beg) robust-flag) after
5485 before)))))
5487 (defun org-element--cache-submit-request (beg end offset)
5488 "Submit a new cache synchronization request for current buffer.
5489 BEG and END are buffer positions delimiting the minimal area
5490 where cache data should be removed. OFFSET is the size of the
5491 change, as an integer."
5492 (let ((next (car org-element--cache-sync-requests))
5493 delete-to delete-from)
5494 (if (and next
5495 (zerop (aref next 6))
5496 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5497 (<= (setq delete-from (aref next 1)) end))
5498 ;; Current changes can be merged with first sync request: we
5499 ;; can save a partial cache synchronization.
5500 (progn
5501 (incf (aref next 3) offset)
5502 ;; If last change happened within area to be removed, extend
5503 ;; boundaries of robust parents, if any. Otherwise, find
5504 ;; first element to remove and update request accordingly.
5505 (if (> beg delete-from)
5506 (let ((up (aref next 5)))
5507 (while up
5508 (org-element--cache-shift-positions
5509 up offset '(:contents-end :end))
5510 (setq up (org-element-property :parent up))))
5511 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5512 (when first
5513 (aset next 0 (org-element--cache-key first))
5514 (aset next 1 (org-element-property :begin first))
5515 (aset next 5 (org-element-property :parent first))))))
5516 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5517 ;; if any, is no longer a 0-phase request, thus ensuring that
5518 ;; phases are properly ordered. We need to provide OFFSET as
5519 ;; optional parameter since current modifications are not known
5520 ;; yet to the otherwise correct part of the cache (i.e, before
5521 ;; the first request).
5522 (when next (org-element--cache-sync (current-buffer) end beg))
5523 (let ((first (org-element--cache-for-removal beg end offset)))
5524 (if first
5525 (push (let ((beg (org-element-property :begin first))
5526 (key (org-element--cache-key first)))
5527 (cond
5528 ;; When changes happen before the first known
5529 ;; element, re-parent and shift the rest of the
5530 ;; cache.
5531 ((> beg end) (vector key beg nil offset nil nil 1))
5532 ;; Otherwise, we find the first non robust
5533 ;; element containing END. All elements between
5534 ;; FIRST and this one are to be removed.
5536 ;; Among them, some could be located outside the
5537 ;; synchronized part of the cache, in which case
5538 ;; comparing buffer positions to find them is
5539 ;; useless. Instead, we store the element
5540 ;; containing them in the request itself. All
5541 ;; its children will be removed.
5542 ((let ((first-end (org-element-property :end first)))
5543 (and (> first-end end)
5544 (vector key beg first-end offset first
5545 (org-element-property :parent 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
5555 (org-element-property :parent first) 0)))))
5556 org-element--cache-sync-requests)
5557 ;; No element to remove. No need to re-parent either.
5558 ;; Simply shift additional elements, if any, by OFFSET.
5559 (when org-element--cache-sync-requests
5560 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5563 ;;;; Public Functions
5565 ;;;###autoload
5566 (defun org-element-cache-reset (&optional all)
5567 "Reset cache in current buffer.
5568 When optional argument ALL is non-nil, reset cache in all Org
5569 buffers."
5570 (interactive "P")
5571 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5572 (with-current-buffer buffer
5573 (when (org-element--cache-active-p)
5574 (org-set-local 'org-element--cache
5575 (avl-tree-create #'org-element--cache-compare))
5576 (org-set-local 'org-element--cache-objects (make-hash-table :test #'eq))
5577 (org-set-local 'org-element--cache-sync-keys
5578 (make-hash-table :weakness 'key :test #'eq))
5579 (org-set-local 'org-element--cache-change-warning nil)
5580 (org-set-local 'org-element--cache-sync-requests nil)
5581 (org-set-local 'org-element--cache-sync-timer nil)
5582 (add-hook 'before-change-functions
5583 #'org-element--cache-before-change nil t)
5584 (add-hook 'after-change-functions
5585 #'org-element--cache-after-change nil t)))))
5587 ;;;###autoload
5588 (defun org-element-cache-refresh (pos)
5589 "Refresh cache at position POS."
5590 (when (org-element--cache-active-p)
5591 (org-element--cache-sync (current-buffer) pos)
5592 (org-element--cache-submit-request pos pos 0)
5593 (org-element--cache-set-timer (current-buffer))))
5597 ;;; The Toolbox
5599 ;; The first move is to implement a way to obtain the smallest element
5600 ;; containing point. This is the job of `org-element-at-point'. It
5601 ;; basically jumps back to the beginning of section containing point
5602 ;; and proceed, one element after the other, with
5603 ;; `org-element--current-element' until the container is found. Note:
5604 ;; When using `org-element-at-point', secondary values are never
5605 ;; parsed since the function focuses on elements, not on objects.
5607 ;; At a deeper level, `org-element-context' lists all elements and
5608 ;; objects containing point.
5610 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5611 ;; internally by navigation and manipulation tools.
5614 ;;;###autoload
5615 (defun org-element-at-point ()
5616 "Determine closest element around point.
5618 Return value is a list like (TYPE PROPS) where TYPE is the type
5619 of the element and PROPS a plist of properties associated to the
5620 element.
5622 Possible types are defined in `org-element-all-elements'.
5623 Properties depend on element or object type, but always include
5624 `:begin', `:end', `:parent' and `:post-blank' properties.
5626 As a special case, if point is at the very beginning of the first
5627 item in a list or sub-list, returned element will be that list
5628 instead of the item. Likewise, if point is at the beginning of
5629 the first row of a table, returned element will be the table
5630 instead of the first row.
5632 When point is at the end of the buffer, return the innermost
5633 element ending there."
5634 (org-with-wide-buffer
5635 (let ((origin (point)))
5636 (end-of-line)
5637 (skip-chars-backward " \r\t\n")
5638 (cond
5639 ;; Within blank lines at the beginning of buffer, return nil.
5640 ((bobp) nil)
5641 ;; Within blank lines right after a headline, return that
5642 ;; headline.
5643 ((org-with-limited-levels (org-at-heading-p))
5644 (beginning-of-line)
5645 (org-element-headline-parser (point-max) t))
5646 ;; Otherwise parse until we find element containing ORIGIN.
5648 (when (org-element--cache-active-p)
5649 (if (not org-element--cache) (org-element-cache-reset)
5650 (org-element--cache-sync (current-buffer) origin)))
5651 (org-element--parse-to origin))))))
5653 ;;;###autoload
5654 (defun org-element-context (&optional element)
5655 "Return smallest element or object around point.
5657 Return value is a list like (TYPE PROPS) where TYPE is the type
5658 of the element or object and PROPS a plist of properties
5659 associated to it.
5661 Possible types are defined in `org-element-all-elements' and
5662 `org-element-all-objects'. Properties depend on element or
5663 object type, but always include `:begin', `:end', `:parent' and
5664 `:post-blank'.
5666 As a special case, if point is right after an object and not at
5667 the beginning of any other object, return that object.
5669 Optional argument ELEMENT, when non-nil, is the closest element
5670 containing point, as returned by `org-element-at-point'.
5671 Providing it allows for quicker computation."
5672 (catch 'objects-forbidden
5673 (org-with-wide-buffer
5674 (let* ((pos (point))
5675 (element (or element (org-element-at-point)))
5676 (type (org-element-type element)))
5677 ;; If point is inside an element containing objects or
5678 ;; a secondary string, narrow buffer to the container and
5679 ;; proceed with parsing. Otherwise, return ELEMENT.
5680 (cond
5681 ;; At a parsed affiliated keyword, check if we're inside main
5682 ;; or dual value.
5683 ((let ((post (org-element-property :post-affiliated element)))
5684 (and post (< pos post)))
5685 (beginning-of-line)
5686 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5687 (cond
5688 ((not (member-ignore-case (match-string 1)
5689 org-element-parsed-keywords))
5690 (throw 'objects-forbidden element))
5691 ((< (match-end 0) pos)
5692 (narrow-to-region (match-end 0) (line-end-position)))
5693 ((and (match-beginning 2)
5694 (>= pos (match-beginning 2))
5695 (< pos (match-end 2)))
5696 (narrow-to-region (match-beginning 2) (match-end 2)))
5697 (t (throw 'objects-forbidden element)))
5698 ;; Also change type to retrieve correct restrictions.
5699 (setq type 'keyword))
5700 ;; At an item, objects can only be located within tag, if any.
5701 ((eq type 'item)
5702 (let ((tag (org-element-property :tag element)))
5703 (if (not tag) (throw 'objects-forbidden element)
5704 (beginning-of-line)
5705 (search-forward tag (line-end-position))
5706 (goto-char (match-beginning 0))
5707 (if (and (>= pos (point)) (< pos (match-end 0)))
5708 (narrow-to-region (point) (match-end 0))
5709 (throw 'objects-forbidden element)))))
5710 ;; At an headline or inlinetask, objects are in title.
5711 ((memq type '(headline inlinetask))
5712 (goto-char (org-element-property :begin element))
5713 (skip-chars-forward "*")
5714 (if (and (> pos (point)) (< pos (line-end-position)))
5715 (narrow-to-region (point) (line-end-position))
5716 (throw 'objects-forbidden element)))
5717 ;; At a paragraph, a table-row or a verse block, objects are
5718 ;; located within their contents.
5719 ((memq type '(paragraph table-row verse-block))
5720 (let ((cbeg (org-element-property :contents-begin element))
5721 (cend (org-element-property :contents-end element)))
5722 ;; CBEG is nil for table rules.
5723 (if (and cbeg cend (>= pos cbeg)
5724 (or (< pos cend) (and (= pos cend) (eobp))))
5725 (narrow-to-region cbeg cend)
5726 (throw 'objects-forbidden element))))
5727 ;; At a planning line, if point is at a timestamp, return it,
5728 ;; otherwise, return element.
5729 ((eq type 'planning)
5730 (dolist (p '(:closed :deadline :scheduled))
5731 (let ((timestamp (org-element-property p element)))
5732 (when (and timestamp
5733 (<= (org-element-property :begin timestamp) pos)
5734 (> (org-element-property :end timestamp) pos))
5735 (throw 'objects-forbidden timestamp))))
5736 ;; All other locations cannot contain objects: bail out.
5737 (throw 'objects-forbidden element))
5738 (t (throw 'objects-forbidden element)))
5739 (goto-char (point-min))
5740 (let ((restriction (org-element-restriction type))
5741 (parent element)
5742 (cache (cond ((not (org-element--cache-active-p)) nil)
5743 (org-element--cache-objects
5744 (gethash element org-element--cache-objects))
5745 (t (org-element-cache-reset) nil)))
5746 next object-data last)
5747 (prog1
5748 (catch 'exit
5749 (while t
5750 ;; When entering PARENT for the first time, get list
5751 ;; of objects within known so far. Store it in
5752 ;; OBJECT-DATA.
5753 (unless next
5754 (let ((data (assq parent cache)))
5755 (if data (setq object-data data)
5756 (push (setq object-data (list parent nil)) cache))))
5757 ;; Find NEXT object for analysis.
5758 (catch 'found
5759 ;; If NEXT is non-nil, we already exhausted the
5760 ;; cache so we can parse buffer to find the object
5761 ;; after it.
5762 (if next (setq next (org-element--object-lex restriction))
5763 ;; Otherwise, check if cache can help us.
5764 (let ((objects (cddr object-data))
5765 (completep (nth 1 object-data)))
5766 (cond
5767 ((and (not objects) completep) (throw 'exit parent))
5768 ((not objects)
5769 (setq next (org-element--object-lex restriction)))
5771 (let ((cache-limit
5772 (org-element-property :end (car objects))))
5773 (if (>= cache-limit pos)
5774 ;; Cache contains the information needed.
5775 (dolist (object objects (throw 'exit parent))
5776 (when (<= (org-element-property :begin object)
5777 pos)
5778 (if (>= (org-element-property :end object)
5779 pos)
5780 (throw 'found (setq next object))
5781 (throw 'exit parent))))
5782 (goto-char cache-limit)
5783 (setq next
5784 (org-element--object-lex restriction))))))))
5785 ;; If we have a new object to analyze, store it in
5786 ;; cache. Otherwise record that there is nothing
5787 ;; more to parse in this element at this depth.
5788 (if next
5789 (progn (org-element-put-property next :parent parent)
5790 (push next (cddr object-data)))
5791 (setcar (cdr object-data) t)))
5792 ;; Process NEXT, if any, in order to know if we need
5793 ;; to skip it, return it or move into it.
5794 (if (or (not next) (> (org-element-property :begin next) pos))
5795 (throw 'exit (or last parent))
5796 (let ((end (org-element-property :end next))
5797 (cbeg (org-element-property :contents-begin next))
5798 (cend (org-element-property :contents-end next)))
5799 (cond
5800 ;; Skip objects ending before point. Also skip
5801 ;; objects ending at point unless it is also the
5802 ;; end of buffer, since we want to return the
5803 ;; innermost object.
5804 ((and (<= end pos) (/= (point-max) end))
5805 (goto-char end)
5806 ;; For convenience, when object ends at POS,
5807 ;; without any space, store it in LAST, as we
5808 ;; will return it if no object starts here.
5809 (when (and (= end pos)
5810 (not (memq (char-before) '(?\s ?\t))))
5811 (setq last next)))
5812 ;; If POS is within a container object, move
5813 ;; into that object.
5814 ((and cbeg cend
5815 (>= pos cbeg)
5816 (or (< pos cend)
5817 ;; At contents' end, if there is no
5818 ;; space before point, also move into
5819 ;; object, for consistency with
5820 ;; convenience feature above.
5821 (and (= pos cend)
5822 (or (= (point-max) pos)
5823 (not (memq (char-before pos)
5824 '(?\s ?\t)))))))
5825 (goto-char cbeg)
5826 (narrow-to-region (point) cend)
5827 (setq parent next
5828 restriction (org-element-restriction next)
5829 next nil
5830 object-data nil))
5831 ;; Otherwise, return NEXT.
5832 (t (throw 'exit next)))))))
5833 ;; Store results in cache, if applicable.
5834 (org-element--cache-put element cache)))))))
5836 (defun org-element-lineage (blob &optional types with-self)
5837 "List all ancestors of a given element or object.
5839 BLOB is an object or element.
5841 When optional argument TYPES is a list of symbols, return the
5842 first element or object in the lineage whose type belongs to that
5843 list.
5845 When optional argument WITH-SELF is non-nil, lineage includes
5846 BLOB itself as the first element, and TYPES, if provided, also
5847 apply to it.
5849 When BLOB is obtained through `org-element-context' or
5850 `org-element-at-point', only ancestors from its section can be
5851 found. There is no such limitation when BLOB belongs to a full
5852 parse tree."
5853 (let ((up (if with-self blob (org-element-property :parent blob)))
5854 ancestors)
5855 (while (and up (not (memq (org-element-type up) types)))
5856 (unless types (push up ancestors))
5857 (setq up (org-element-property :parent up)))
5858 (if types up (nreverse ancestors))))
5860 (defun org-element-nested-p (elem-A elem-B)
5861 "Non-nil when elements ELEM-A and ELEM-B are nested."
5862 (let ((beg-A (org-element-property :begin elem-A))
5863 (beg-B (org-element-property :begin elem-B))
5864 (end-A (org-element-property :end elem-A))
5865 (end-B (org-element-property :end elem-B)))
5866 (or (and (>= beg-A beg-B) (<= end-A end-B))
5867 (and (>= beg-B beg-A) (<= end-B end-A)))))
5869 (defun org-element-swap-A-B (elem-A elem-B)
5870 "Swap elements ELEM-A and ELEM-B.
5871 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5872 end of ELEM-A."
5873 (goto-char (org-element-property :begin elem-A))
5874 ;; There are two special cases when an element doesn't start at bol:
5875 ;; the first paragraph in an item or in a footnote definition.
5876 (let ((specialp (not (bolp))))
5877 ;; Only a paragraph without any affiliated keyword can be moved at
5878 ;; ELEM-A position in such a situation. Note that the case of
5879 ;; a footnote definition is impossible: it cannot contain two
5880 ;; paragraphs in a row because it cannot contain a blank line.
5881 (if (and specialp
5882 (or (not (eq (org-element-type elem-B) 'paragraph))
5883 (/= (org-element-property :begin elem-B)
5884 (org-element-property :contents-begin elem-B))))
5885 (error "Cannot swap elements"))
5886 ;; In a special situation, ELEM-A will have no indentation. We'll
5887 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5888 (let* ((ind-B (when specialp
5889 (goto-char (org-element-property :begin elem-B))
5890 (org-get-indentation)))
5891 (beg-A (org-element-property :begin elem-A))
5892 (end-A (save-excursion
5893 (goto-char (org-element-property :end elem-A))
5894 (skip-chars-backward " \r\t\n")
5895 (point-at-eol)))
5896 (beg-B (org-element-property :begin elem-B))
5897 (end-B (save-excursion
5898 (goto-char (org-element-property :end elem-B))
5899 (skip-chars-backward " \r\t\n")
5900 (point-at-eol)))
5901 ;; Store inner overlays responsible for visibility status.
5902 ;; We also need to store their boundaries as they will be
5903 ;; removed from buffer.
5904 (overlays
5905 (cons
5906 (delq nil
5907 (mapcar (lambda (o)
5908 (and (>= (overlay-start o) beg-A)
5909 (<= (overlay-end o) end-A)
5910 (list o (overlay-start o) (overlay-end o))))
5911 (overlays-in beg-A end-A)))
5912 (delq nil
5913 (mapcar (lambda (o)
5914 (and (>= (overlay-start o) beg-B)
5915 (<= (overlay-end o) end-B)
5916 (list o (overlay-start o) (overlay-end o))))
5917 (overlays-in beg-B end-B)))))
5918 ;; Get contents.
5919 (body-A (buffer-substring beg-A end-A))
5920 (body-B (delete-and-extract-region beg-B end-B)))
5921 (goto-char beg-B)
5922 (when specialp
5923 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5924 (org-indent-to-column ind-B))
5925 (insert body-A)
5926 ;; Restore ex ELEM-A overlays.
5927 (let ((offset (- beg-B beg-A)))
5928 (dolist (o (car overlays))
5929 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
5930 (goto-char beg-A)
5931 (delete-region beg-A end-A)
5932 (insert body-B)
5933 ;; Restore ex ELEM-B overlays.
5934 (dolist (o (cdr overlays))
5935 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
5936 (goto-char (org-element-property :end elem-B)))))
5938 (defun org-element-remove-indentation (s &optional n)
5939 "Remove maximum common indentation in string S and return it.
5940 When optional argument N is a positive integer, remove exactly
5941 that much characters from indentation, if possible, or return
5942 S as-is otherwise. Unlike to `org-remove-indentation', this
5943 function doesn't call `untabify' on S."
5944 (catch 'exit
5945 (with-temp-buffer
5946 (insert s)
5947 (goto-char (point-min))
5948 ;; Find maximum common indentation, if not specified.
5949 (setq n (or n
5950 (let ((min-ind (point-max)))
5951 (save-excursion
5952 (while (re-search-forward "^[ \t]*\\S-" nil t)
5953 (let ((ind (1- (current-column))))
5954 (if (zerop ind) (throw 'exit s)
5955 (setq min-ind (min min-ind ind))))))
5956 min-ind)))
5957 (if (zerop n) s
5958 ;; Remove exactly N indentation, but give up if not possible.
5959 (while (not (eobp))
5960 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5961 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5962 ((< ind n) (throw 'exit s))
5963 (t (org-indent-line-to (- ind n))))
5964 (forward-line)))
5965 (buffer-string)))))
5969 (provide 'org-element)
5971 ;; Local variables:
5972 ;; generated-autoload-file: "org-loaddefs.el"
5973 ;; End:
5975 ;;; org-element.el ends here