Use parser for `org-at-table-p' and al.
[org-mode.git] / lisp / org-element.el
blobff0fa75d10a38ebb9c4a319c335dd0ddc7e6abed
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 (if (not children) parent
493 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
494 ;; string: parent is the list itself.
495 (dolist (child children)
496 (org-element-put-property child :parent (or parent 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-create (type &optional props &rest children)
577 "Create a new element of type TYPE.
578 Optional argument PROPS, when non-nil, is a plist defining the
579 properties of the element. CHILDREN can be elements, objects or
580 strings."
581 (apply #'org-element-adopt-elements (list type props) children))
583 (defun org-element-copy (datum)
584 "Return a copy of DATUM.
585 DATUM is an element, object, string or nil. `:parent' property
586 is cleared and contents are removed in the process."
587 (when datum
588 (let ((type (org-element-type datum)))
589 (case type
590 (org-data (list 'org-data nil))
591 (plain-text (substring-no-properties datum))
592 ((nil) (copy-sequence datum))
593 (otherwise
594 (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
598 ;;; Greater elements
600 ;; For each greater element type, we define a parser and an
601 ;; interpreter.
603 ;; A parser returns the element or object as the list described above.
604 ;; Most of them accepts no argument. Though, exceptions exist. Hence
605 ;; every element containing a secondary string (see
606 ;; `org-element-secondary-value-alist') will accept an optional
607 ;; argument to toggle parsing of these secondary strings. Moreover,
608 ;; `item' parser requires current list's structure as its first
609 ;; element.
611 ;; An interpreter accepts two arguments: the list representation of
612 ;; the element or object, and its contents. The latter may be nil,
613 ;; depending on the element or object considered. It returns the
614 ;; appropriate Org syntax, as a string.
616 ;; Parsing functions must follow the naming convention:
617 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
618 ;; defined in `org-element-greater-elements'.
620 ;; Similarly, interpreting functions must follow the naming
621 ;; convention: org-element-TYPE-interpreter.
623 ;; With the exception of `headline' and `item' types, greater elements
624 ;; cannot contain other greater elements of their own type.
626 ;; Beside implementing a parser and an interpreter, adding a new
627 ;; greater element requires to tweak `org-element--current-element'.
628 ;; Moreover, the newly defined type must be added to both
629 ;; `org-element-all-elements' and `org-element-greater-elements'.
632 ;;;; Center Block
634 (defun org-element-center-block-parser (limit affiliated)
635 "Parse a center block.
637 LIMIT bounds the search. AFFILIATED is a list of which CAR is
638 the buffer position at the beginning of the first affiliated
639 keyword and CDR is a plist of affiliated keywords along with
640 their value.
642 Return a list whose CAR is `center-block' and CDR is a plist
643 containing `:begin', `:end', `:contents-begin', `:contents-end',
644 `:post-blank' and `:post-affiliated' keywords.
646 Assume point is at the beginning of the block."
647 (let ((case-fold-search t))
648 (if (not (save-excursion
649 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
650 ;; Incomplete block: parse it as a paragraph.
651 (org-element-paragraph-parser limit affiliated)
652 (let ((block-end-line (match-beginning 0)))
653 (let* ((begin (car affiliated))
654 (post-affiliated (point))
655 ;; Empty blocks have no contents.
656 (contents-begin (progn (forward-line)
657 (and (< (point) block-end-line)
658 (point))))
659 (contents-end (and contents-begin block-end-line))
660 (pos-before-blank (progn (goto-char block-end-line)
661 (forward-line)
662 (point)))
663 (end (save-excursion
664 (skip-chars-forward " \r\t\n" limit)
665 (if (eobp) (point) (line-beginning-position)))))
666 (list 'center-block
667 (nconc
668 (list :begin begin
669 :end end
670 :contents-begin contents-begin
671 :contents-end contents-end
672 :post-blank (count-lines pos-before-blank end)
673 :post-affiliated post-affiliated)
674 (cdr affiliated))))))))
676 (defun org-element-center-block-interpreter (center-block contents)
677 "Interpret CENTER-BLOCK element as Org syntax.
678 CONTENTS is the contents of the element."
679 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
682 ;;;; Drawer
684 (defun org-element-drawer-parser (limit affiliated)
685 "Parse a drawer.
687 LIMIT bounds the search. AFFILIATED is a list of which CAR is
688 the buffer position at the beginning of the first affiliated
689 keyword and CDR is a plist of affiliated keywords along with
690 their value.
692 Return a list whose CAR is `drawer' and CDR is a plist containing
693 `:drawer-name', `:begin', `:end', `:contents-begin',
694 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
696 Assume point is at beginning of drawer."
697 (let ((case-fold-search t))
698 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
699 ;; Incomplete drawer: parse it as a paragraph.
700 (org-element-paragraph-parser limit affiliated)
701 (save-excursion
702 (let* ((drawer-end-line (match-beginning 0))
703 (name (progn (looking-at org-drawer-regexp)
704 (org-match-string-no-properties 1)))
705 (begin (car affiliated))
706 (post-affiliated (point))
707 ;; Empty drawers have no contents.
708 (contents-begin (progn (forward-line)
709 (and (< (point) drawer-end-line)
710 (point))))
711 (contents-end (and contents-begin drawer-end-line))
712 (pos-before-blank (progn (goto-char drawer-end-line)
713 (forward-line)
714 (point)))
715 (end (progn (skip-chars-forward " \r\t\n" limit)
716 (if (eobp) (point) (line-beginning-position)))))
717 (list 'drawer
718 (nconc
719 (list :begin begin
720 :end end
721 :drawer-name name
722 :contents-begin contents-begin
723 :contents-end contents-end
724 :post-blank (count-lines pos-before-blank end)
725 :post-affiliated post-affiliated)
726 (cdr affiliated))))))))
728 (defun org-element-drawer-interpreter (drawer contents)
729 "Interpret DRAWER element as Org syntax.
730 CONTENTS is the contents of the element."
731 (format ":%s:\n%s:END:"
732 (org-element-property :drawer-name drawer)
733 contents))
736 ;;;; Dynamic Block
738 (defun org-element-dynamic-block-parser (limit affiliated)
739 "Parse a dynamic block.
741 LIMIT bounds the search. AFFILIATED is a list of which CAR is
742 the buffer position at the beginning of the first affiliated
743 keyword and CDR is a plist of affiliated keywords along with
744 their value.
746 Return a list whose CAR is `dynamic-block' and CDR is a plist
747 containing `:block-name', `:begin', `:end', `:contents-begin',
748 `:contents-end', `:arguments', `:post-blank' and
749 `:post-affiliated' keywords.
751 Assume point is at beginning of dynamic block."
752 (let ((case-fold-search t))
753 (if (not (save-excursion
754 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
755 ;; Incomplete block: parse it as a paragraph.
756 (org-element-paragraph-parser limit affiliated)
757 (let ((block-end-line (match-beginning 0)))
758 (save-excursion
759 (let* ((name (progn (looking-at org-dblock-start-re)
760 (org-match-string-no-properties 1)))
761 (arguments (org-match-string-no-properties 3))
762 (begin (car affiliated))
763 (post-affiliated (point))
764 ;; Empty blocks have no contents.
765 (contents-begin (progn (forward-line)
766 (and (< (point) block-end-line)
767 (point))))
768 (contents-end (and contents-begin block-end-line))
769 (pos-before-blank (progn (goto-char block-end-line)
770 (forward-line)
771 (point)))
772 (end (progn (skip-chars-forward " \r\t\n" limit)
773 (if (eobp) (point) (line-beginning-position)))))
774 (list 'dynamic-block
775 (nconc
776 (list :begin begin
777 :end end
778 :block-name name
779 :arguments arguments
780 :contents-begin contents-begin
781 :contents-end contents-end
782 :post-blank (count-lines pos-before-blank end)
783 :post-affiliated post-affiliated)
784 (cdr affiliated)))))))))
786 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
787 "Interpret DYNAMIC-BLOCK element as Org syntax.
788 CONTENTS is the contents of the element."
789 (format "#+BEGIN: %s%s\n%s#+END:"
790 (org-element-property :block-name dynamic-block)
791 (let ((args (org-element-property :arguments dynamic-block)))
792 (and args (concat " " args)))
793 contents))
796 ;;;; Footnote Definition
798 (defun org-element-footnote-definition-parser (limit affiliated)
799 "Parse a footnote definition.
801 LIMIT bounds the search. AFFILIATED is a list of which CAR is
802 the buffer position at the beginning of the first affiliated
803 keyword and CDR is a plist of affiliated keywords along with
804 their value.
806 Return a list whose CAR is `footnote-definition' and CDR is
807 a plist containing `:label', `:begin' `:end', `:contents-begin',
808 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
810 Assume point is at the beginning of the footnote definition."
811 (save-excursion
812 (let* ((label (progn (looking-at org-footnote-definition-re)
813 (org-match-string-no-properties 1)))
814 (begin (car affiliated))
815 (post-affiliated (point))
816 (ending (save-excursion
817 (if (progn
818 (end-of-line)
819 (re-search-forward
820 (concat org-outline-regexp-bol "\\|"
821 org-footnote-definition-re "\\|"
822 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
823 (match-beginning 0)
824 (point))))
825 (contents-begin (progn
826 (search-forward "]")
827 (skip-chars-forward " \r\t\n" ending)
828 (cond ((= (point) ending) nil)
829 ((= (line-beginning-position) begin) (point))
830 (t (line-beginning-position)))))
831 (contents-end (and contents-begin ending))
832 (end (progn (goto-char ending)
833 (skip-chars-forward " \r\t\n" limit)
834 (if (eobp) (point) (line-beginning-position)))))
835 (list 'footnote-definition
836 (nconc
837 (list :label label
838 :begin begin
839 :end end
840 :contents-begin contents-begin
841 :contents-end contents-end
842 :post-blank (count-lines ending end)
843 :post-affiliated post-affiliated)
844 (cdr affiliated))))))
846 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
847 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
848 CONTENTS is the contents of the footnote-definition."
849 (concat (format "[%s]" (org-element-property :label footnote-definition))
851 contents))
854 ;;;; Headline
856 (defun org-element--get-node-properties ()
857 "Return node properties associated to headline at point.
858 Upcase property names. It avoids confusion between properties
859 obtained through property drawer and default properties from the
860 parser (e.g. `:end' and :END:). Return value is a plist."
861 (save-excursion
862 (forward-line)
863 (when (org-looking-at-p org-planning-line-re) (forward-line))
864 (when (looking-at org-property-drawer-re)
865 (forward-line)
866 (let ((end (match-end 0)) properties)
867 (while (< (line-end-position) end)
868 (looking-at org-property-re)
869 (push (org-match-string-no-properties 3) properties)
870 (push (intern (concat ":" (upcase (match-string 2)))) properties)
871 (forward-line))
872 properties))))
874 (defun org-element--get-time-properties ()
875 "Return time properties associated to headline at point.
876 Return value is a plist."
877 (save-excursion
878 (when (progn (forward-line) (looking-at org-planning-line-re))
879 (let ((end (line-end-position)) plist)
880 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
881 (goto-char (match-end 1))
882 (skip-chars-forward " \t")
883 (let ((keyword (match-string 1))
884 (time (org-element-timestamp-parser)))
885 (cond ((equal keyword org-scheduled-string)
886 (setq plist (plist-put plist :scheduled time)))
887 ((equal keyword org-deadline-string)
888 (setq plist (plist-put plist :deadline time)))
889 (t (setq plist (plist-put plist :closed time))))))
890 plist))))
892 (defun org-element-headline-parser (limit &optional raw-secondary-p)
893 "Parse a headline.
895 Return a list whose CAR is `headline' and CDR is a plist
896 containing `:raw-value', `:title', `:begin', `:end',
897 `:pre-blank', `:contents-begin' and `:contents-end', `:level',
898 `:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
899 `:deadline', `:closed', `:archivedp', `:commentedp'
900 `:footnote-section-p', `:post-blank' and `:post-affiliated'
901 keywords.
903 The plist also contains any property set in the property drawer,
904 with its name in upper cases and colons added at the
905 beginning (e.g., `:CUSTOM_ID').
907 LIMIT is a buffer position bounding the search.
909 When RAW-SECONDARY-P is non-nil, headline's title will not be
910 parsed as a secondary string, but as a plain string instead.
912 Assume point is at beginning of the headline."
913 (save-excursion
914 (let* ((begin (point))
915 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
916 (skip-chars-forward " \t")))
917 (todo (and org-todo-regexp
918 (let (case-fold-search) (looking-at org-todo-regexp))
919 (progn (goto-char (match-end 0))
920 (skip-chars-forward " \t")
921 (match-string 0))))
922 (todo-type
923 (and todo (if (member todo org-done-keywords) 'done 'todo)))
924 (priority (and (looking-at "\\[#.\\][ \t]*")
925 (progn (goto-char (match-end 0))
926 (aref (match-string 0) 2))))
927 (commentedp
928 (and (let (case-fold-search) (looking-at org-comment-string))
929 (goto-char (match-end 0))))
930 (title-start (point))
931 (tags (when (re-search-forward
932 (org-re "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
933 (line-end-position)
934 'move)
935 (goto-char (match-beginning 0))
936 (org-split-string (match-string 1) ":")))
937 (title-end (point))
938 (raw-value (org-trim
939 (buffer-substring-no-properties title-start title-end)))
940 (archivedp (member org-archive-tag tags))
941 (footnote-section-p (and org-footnote-section
942 (string= org-footnote-section raw-value)))
943 (standard-props (org-element--get-node-properties))
944 (time-props (org-element--get-time-properties))
945 (end (min (save-excursion (org-end-of-subtree t t)) limit))
946 (pos-after-head (progn (forward-line) (point)))
947 (contents-begin (save-excursion
948 (skip-chars-forward " \r\t\n" end)
949 (and (/= (point) end) (line-beginning-position))))
950 (contents-end (and contents-begin
951 (progn (goto-char end)
952 (skip-chars-backward " \r\t\n")
953 (forward-line)
954 (point)))))
955 (let ((headline
956 (list 'headline
957 (nconc
958 (list :raw-value raw-value
959 :begin begin
960 :end end
961 :pre-blank
962 (if (not contents-begin) 0
963 (count-lines pos-after-head contents-begin))
964 :contents-begin contents-begin
965 :contents-end contents-end
966 :level level
967 :priority priority
968 :tags tags
969 :todo-keyword todo
970 :todo-type todo-type
971 :post-blank (count-lines
972 (or contents-end pos-after-head)
973 end)
974 :footnote-section-p footnote-section-p
975 :archivedp archivedp
976 :commentedp commentedp
977 :post-affiliated begin)
978 time-props
979 standard-props))))
980 (org-element-put-property
981 headline :title
982 (if raw-secondary-p raw-value
983 (let ((title (org-element--parse-objects
984 (progn (goto-char title-start)
985 (skip-chars-forward " \t")
986 (point))
987 (progn (goto-char title-end)
988 (skip-chars-backward " \t")
989 (point))
991 (org-element-restriction 'headline))))
992 (dolist (datum title title)
993 (org-element-put-property datum :parent headline)))))))))
995 (defun org-element-headline-interpreter (headline contents)
996 "Interpret HEADLINE element as Org syntax.
997 CONTENTS is the contents of the element."
998 (let* ((level (org-element-property :level headline))
999 (todo (org-element-property :todo-keyword headline))
1000 (priority (org-element-property :priority headline))
1001 (title (org-element-interpret-data
1002 (org-element-property :title headline)))
1003 (tags (let ((tag-list (org-element-property :tags headline)))
1004 (and tag-list
1005 (format ":%s:" (mapconcat #'identity tag-list ":")))))
1006 (commentedp (org-element-property :commentedp headline))
1007 (pre-blank (or (org-element-property :pre-blank headline) 0))
1008 (heading
1009 (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
1011 (and todo (concat " " todo))
1012 (and commentedp (concat " " org-comment-string))
1013 (and priority (format " [#%c]" priority))
1015 (if (and org-footnote-section
1016 (org-element-property :footnote-section-p headline))
1017 org-footnote-section
1018 title))))
1019 (concat
1020 heading
1021 ;; Align tags.
1022 (when tags
1023 (cond
1024 ((zerop org-tags-column) (format " %s" tags))
1025 ((< org-tags-column 0)
1026 (concat
1027 (make-string
1028 (max (- (+ org-tags-column (length heading) (length tags))) 1)
1029 ?\s)
1030 tags))
1032 (concat
1033 (make-string (max (- org-tags-column (length heading)) 1) ?\s)
1034 tags))))
1035 (make-string (1+ pre-blank) ?\n)
1036 contents)))
1039 ;;;; Inlinetask
1041 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
1042 "Parse an inline task.
1044 Return a list whose CAR is `inlinetask' and CDR is a plist
1045 containing `:title', `:begin', `:end', `:contents-begin' and
1046 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
1047 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
1048 `:closed', `:post-blank' and `:post-affiliated' keywords.
1050 The plist also contains any property set in the property drawer,
1051 with its name in upper cases and colons added at the
1052 beginning (e.g., `:CUSTOM_ID').
1054 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
1055 title will not be parsed as a secondary string, but as a plain
1056 string instead.
1058 Assume point is at beginning of the inline task."
1059 (save-excursion
1060 (let* ((begin (point))
1061 (level (prog1 (org-reduced-level (skip-chars-forward "*"))
1062 (skip-chars-forward " \t")))
1063 (todo (and org-todo-regexp
1064 (let (case-fold-search) (looking-at org-todo-regexp))
1065 (progn (goto-char (match-end 0))
1066 (skip-chars-forward " \t")
1067 (match-string 0))))
1068 (todo-type (and todo
1069 (if (member todo org-done-keywords) 'done 'todo)))
1070 (priority (and (looking-at "\\[#.\\][ \t]*")
1071 (progn (goto-char (match-end 0))
1072 (aref (match-string 0) 2))))
1073 (title-start (point))
1074 (tags (when (re-search-forward
1075 (org-re "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
1076 (line-end-position)
1077 'move)
1078 (goto-char (match-beginning 0))
1079 (org-split-string (match-string 1) ":")))
1080 (title-end (point))
1081 (raw-value (org-trim
1082 (buffer-substring-no-properties title-start title-end)))
1083 (task-end (save-excursion
1084 (end-of-line)
1085 (and (re-search-forward org-outline-regexp-bol limit t)
1086 (org-looking-at-p "END[ \t]*$")
1087 (line-beginning-position))))
1088 (standard-props (and task-end (org-element--get-node-properties)))
1089 (time-props (and task-end (org-element--get-time-properties)))
1090 (contents-begin (progn (forward-line)
1091 (and task-end (< (point) task-end) (point))))
1092 (contents-end (and contents-begin task-end))
1093 (before-blank (if (not task-end) (point)
1094 (goto-char task-end)
1095 (forward-line)
1096 (point)))
1097 (end (progn (skip-chars-forward " \r\t\n" limit)
1098 (if (eobp) (point) (line-beginning-position))))
1099 (inlinetask
1100 (list 'inlinetask
1101 (nconc
1102 (list :raw-value raw-value
1103 :begin begin
1104 :end end
1105 :contents-begin contents-begin
1106 :contents-end contents-end
1107 :level level
1108 :priority priority
1109 :tags tags
1110 :todo-keyword todo
1111 :todo-type todo-type
1112 :post-blank (count-lines before-blank end)
1113 :post-affiliated begin)
1114 time-props
1115 standard-props))))
1116 (org-element-put-property
1117 inlinetask :title
1118 (if raw-secondary-p raw-value
1119 (let ((title (org-element--parse-objects
1120 (progn (goto-char title-start)
1121 (skip-chars-forward " \t")
1122 (point))
1123 (progn (goto-char title-end)
1124 (skip-chars-backward " \t")
1125 (point))
1127 (org-element-restriction 'inlinetask))))
1128 (dolist (datum title title)
1129 (org-element-put-property datum :parent inlinetask))))))))
1131 (defun org-element-inlinetask-interpreter (inlinetask contents)
1132 "Interpret INLINETASK element as Org syntax.
1133 CONTENTS is the contents of inlinetask."
1134 (let* ((level (org-element-property :level inlinetask))
1135 (todo (org-element-property :todo-keyword inlinetask))
1136 (priority (org-element-property :priority inlinetask))
1137 (title (org-element-interpret-data
1138 (org-element-property :title inlinetask)))
1139 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1140 (and tag-list
1141 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1142 (task (concat (make-string level ?*)
1143 (and todo (concat " " todo))
1144 (and priority (format " [#%c]" priority))
1145 (and title (concat " " title)))))
1146 (concat task
1147 ;; Align tags.
1148 (when tags
1149 (cond
1150 ((zerop org-tags-column) (format " %s" tags))
1151 ((< org-tags-column 0)
1152 (concat
1153 (make-string
1154 (max (- (+ org-tags-column (length task) (length tags))) 1)
1156 tags))
1158 (concat
1159 (make-string (max (- org-tags-column (length task)) 1) ? )
1160 tags))))
1161 ;; Prefer degenerate inlinetasks when there are no
1162 ;; contents.
1163 (when contents
1164 (concat "\n"
1165 contents
1166 (make-string level ?*) " END")))))
1169 ;;;; Item
1171 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1172 "Parse an item.
1174 STRUCT is the structure of the plain list.
1176 Return a list whose CAR is `item' and CDR is a plist containing
1177 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1178 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1179 `:post-affiliated' keywords.
1181 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1182 any, will not be parsed as a secondary string, but as a plain
1183 string instead.
1185 Assume point is at the beginning of the item."
1186 (save-excursion
1187 (beginning-of-line)
1188 (looking-at org-list-full-item-re)
1189 (let* ((begin (point))
1190 (bullet (org-match-string-no-properties 1))
1191 (checkbox (let ((box (match-string 3)))
1192 (cond ((equal "[ ]" box) 'off)
1193 ((equal "[X]" box) 'on)
1194 ((equal "[-]" box) 'trans))))
1195 (counter (let ((c (match-string 2)))
1196 (save-match-data
1197 (cond
1198 ((not c) nil)
1199 ((string-match "[A-Za-z]" c)
1200 (- (string-to-char (upcase (match-string 0 c)))
1201 64))
1202 ((string-match "[0-9]+" c)
1203 (string-to-number (match-string 0 c)))))))
1204 (end (progn (goto-char (nth 6 (assq (point) struct)))
1205 (if (bolp) (point) (line-beginning-position 2))))
1206 (contents-begin
1207 (progn (goto-char
1208 ;; Ignore tags in un-ordered lists: they are just
1209 ;; a part of item's body.
1210 (if (and (match-beginning 4)
1211 (save-match-data (string-match "[.)]" bullet)))
1212 (match-beginning 4)
1213 (match-end 0)))
1214 (skip-chars-forward " \r\t\n" end)
1215 (cond ((= (point) end) nil)
1216 ;; If first line isn't empty, contents really
1217 ;; start at the text after item's meta-data.
1218 ((= (line-beginning-position) begin) (point))
1219 (t (line-beginning-position)))))
1220 (contents-end (and contents-begin
1221 (progn (goto-char end)
1222 (skip-chars-backward " \r\t\n")
1223 (line-beginning-position 2))))
1224 (item
1225 (list 'item
1226 (list :bullet bullet
1227 :begin begin
1228 :end end
1229 :contents-begin contents-begin
1230 :contents-end contents-end
1231 :checkbox checkbox
1232 :counter counter
1233 :structure struct
1234 :post-blank (count-lines (or contents-end begin) end)
1235 :post-affiliated begin))))
1236 (org-element-put-property
1237 item :tag
1238 (let ((raw (org-list-get-tag begin struct)))
1239 (when raw
1240 (if raw-secondary-p raw
1241 (let ((tag (org-element--parse-objects
1242 (match-beginning 4) (match-end 4) nil
1243 (org-element-restriction 'item))))
1244 (dolist (datum tag tag)
1245 (org-element-put-property datum :parent item))))))))))
1247 (defun org-element-item-interpreter (item contents)
1248 "Interpret ITEM element as Org syntax.
1249 CONTENTS is the contents of the element."
1250 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1251 (org-list-bullet-string
1252 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1253 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1254 (t "1.")))))
1255 (checkbox (org-element-property :checkbox item))
1256 (counter (org-element-property :counter item))
1257 (tag (let ((tag (org-element-property :tag item)))
1258 (and tag (org-element-interpret-data tag))))
1259 ;; Compute indentation.
1260 (ind (make-string (length bullet) 32))
1261 (item-starts-with-par-p
1262 (eq (org-element-type (car (org-element-contents item)))
1263 'paragraph)))
1264 ;; Indent contents.
1265 (concat
1266 bullet
1267 (and counter (format "[@%d] " counter))
1268 (case checkbox
1269 (on "[X] ")
1270 (off "[ ] ")
1271 (trans "[-] "))
1272 (and tag (format "%s :: " tag))
1273 (when contents
1274 (let ((contents (replace-regexp-in-string
1275 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1276 (if item-starts-with-par-p (org-trim contents)
1277 (concat "\n" contents)))))))
1280 ;;;; Plain List
1282 (defun org-element--list-struct (limit)
1283 ;; Return structure of list at point. Internal function. See
1284 ;; `org-list-struct' for details.
1285 (let ((case-fold-search t)
1286 (top-ind limit)
1287 (item-re (org-item-re))
1288 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1289 items struct)
1290 (save-excursion
1291 (catch 'exit
1292 (while t
1293 (cond
1294 ;; At limit: end all items.
1295 ((>= (point) limit)
1296 (throw 'exit
1297 (let ((end (progn (skip-chars-backward " \r\t\n")
1298 (forward-line)
1299 (point))))
1300 (dolist (item items (sort (nconc items struct)
1301 'car-less-than-car))
1302 (setcar (nthcdr 6 item) end)))))
1303 ;; At list end: end all items.
1304 ((looking-at org-list-end-re)
1305 (throw 'exit (dolist (item items (sort (nconc items struct)
1306 'car-less-than-car))
1307 (setcar (nthcdr 6 item) (point)))))
1308 ;; At a new item: end previous sibling.
1309 ((looking-at item-re)
1310 (let ((ind (save-excursion (skip-chars-forward " \t")
1311 (current-column))))
1312 (setq top-ind (min top-ind ind))
1313 (while (and items (<= ind (nth 1 (car items))))
1314 (let ((item (pop items)))
1315 (setcar (nthcdr 6 item) (point))
1316 (push item struct)))
1317 (push (progn (looking-at org-list-full-item-re)
1318 (let ((bullet (match-string-no-properties 1)))
1319 (list (point)
1321 bullet
1322 (match-string-no-properties 2) ; counter
1323 (match-string-no-properties 3) ; checkbox
1324 ;; Description tag.
1325 (and (save-match-data
1326 (string-match "[-+*]" bullet))
1327 (match-string-no-properties 4))
1328 ;; Ending position, unknown so far.
1329 nil)))
1330 items))
1331 (forward-line 1))
1332 ;; Skip empty lines.
1333 ((looking-at "^[ \t]*$") (forward-line))
1334 ;; Skip inline tasks and blank lines along the way.
1335 ((and inlinetask-re (looking-at inlinetask-re))
1336 (forward-line)
1337 (let ((origin (point)))
1338 (when (re-search-forward inlinetask-re limit t)
1339 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1340 (goto-char origin)))))
1341 ;; At some text line. Check if it ends any previous item.
1343 (let ((ind (save-excursion (skip-chars-forward " \t")
1344 (current-column))))
1345 (when (<= ind top-ind)
1346 (skip-chars-backward " \r\t\n")
1347 (forward-line))
1348 (while (<= ind (nth 1 (car items)))
1349 (let ((item (pop items)))
1350 (setcar (nthcdr 6 item) (line-beginning-position))
1351 (push item struct)
1352 (unless items
1353 (throw 'exit (sort struct #'car-less-than-car))))))
1354 ;; Skip blocks (any type) and drawers contents.
1355 (cond
1356 ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
1357 (re-search-forward
1358 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1359 limit t)))
1360 ((and (looking-at org-drawer-regexp)
1361 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1362 (forward-line))))))))
1364 (defun org-element-plain-list-parser (limit affiliated structure)
1365 "Parse a plain list.
1367 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1368 the buffer position at the beginning of the first affiliated
1369 keyword and CDR is a plist of affiliated keywords along with
1370 their value. STRUCTURE is the structure of the plain list being
1371 parsed.
1373 Return a list whose CAR is `plain-list' and CDR is a plist
1374 containing `:type', `:begin', `:end', `:contents-begin' and
1375 `:contents-end', `:structure', `:post-blank' and
1376 `:post-affiliated' keywords.
1378 Assume point is at the beginning of the list."
1379 (save-excursion
1380 (let* ((struct (or structure (org-element--list-struct limit)))
1381 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1382 ((nth 5 (assq (point) struct)) 'descriptive)
1383 (t 'unordered)))
1384 (contents-begin (point))
1385 (begin (car affiliated))
1386 (contents-end (let* ((item (assq contents-begin struct))
1387 (ind (nth 1 item))
1388 (pos (nth 6 item)))
1389 (while (and (setq item (assq pos struct))
1390 (= (nth 1 item) ind))
1391 (setq pos (nth 6 item)))
1392 pos))
1393 (end (progn (goto-char contents-end)
1394 (skip-chars-forward " \r\t\n" limit)
1395 (if (= (point) limit) limit (line-beginning-position)))))
1396 ;; Return value.
1397 (list 'plain-list
1398 (nconc
1399 (list :type type
1400 :begin begin
1401 :end end
1402 :contents-begin contents-begin
1403 :contents-end contents-end
1404 :structure struct
1405 :post-blank (count-lines contents-end end)
1406 :post-affiliated contents-begin)
1407 (cdr affiliated))))))
1409 (defun org-element-plain-list-interpreter (plain-list contents)
1410 "Interpret PLAIN-LIST element as Org syntax.
1411 CONTENTS is the contents of the element."
1412 (with-temp-buffer
1413 (insert contents)
1414 (goto-char (point-min))
1415 (org-list-repair)
1416 (buffer-string)))
1419 ;;;; Property Drawer
1421 (defun org-element-property-drawer-parser (limit)
1422 "Parse a property drawer.
1424 LIMIT bounds the search.
1426 Return a list whose car is `property-drawer' and cdr is a plist
1427 containing `:begin', `:end', `:contents-begin', `:contents-end',
1428 `:post-blank' and `:post-affiliated' keywords.
1430 Assume point is at the beginning of the property drawer."
1431 (save-excursion
1432 (let ((case-fold-search t)
1433 (begin (point))
1434 (contents-begin (line-beginning-position 2)))
1435 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1436 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1437 (match-beginning 0)))
1438 (before-blank (progn (forward-line) (point)))
1439 (end (progn (skip-chars-forward " \r\t\n" limit)
1440 (if (eobp) (point) (line-beginning-position)))))
1441 (list 'property-drawer
1442 (list :begin begin
1443 :end end
1444 :contents-begin (and contents-end contents-begin)
1445 :contents-end contents-end
1446 :post-blank (count-lines before-blank end)
1447 :post-affiliated begin))))))
1449 (defun org-element-property-drawer-interpreter (property-drawer contents)
1450 "Interpret PROPERTY-DRAWER element as Org syntax.
1451 CONTENTS is the properties within the drawer."
1452 (format ":PROPERTIES:\n%s:END:" contents))
1455 ;;;; Quote Block
1457 (defun org-element-quote-block-parser (limit affiliated)
1458 "Parse a quote block.
1460 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1461 the buffer position at the beginning of the first affiliated
1462 keyword and CDR is a plist of affiliated keywords along with
1463 their value.
1465 Return a list whose CAR is `quote-block' and CDR is a plist
1466 containing `:begin', `:end', `:contents-begin', `:contents-end',
1467 `:post-blank' and `:post-affiliated' keywords.
1469 Assume point is at the beginning of the block."
1470 (let ((case-fold-search t))
1471 (if (not (save-excursion
1472 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1473 ;; Incomplete block: parse it as a paragraph.
1474 (org-element-paragraph-parser limit affiliated)
1475 (let ((block-end-line (match-beginning 0)))
1476 (save-excursion
1477 (let* ((begin (car affiliated))
1478 (post-affiliated (point))
1479 ;; Empty blocks have no contents.
1480 (contents-begin (progn (forward-line)
1481 (and (< (point) block-end-line)
1482 (point))))
1483 (contents-end (and contents-begin block-end-line))
1484 (pos-before-blank (progn (goto-char block-end-line)
1485 (forward-line)
1486 (point)))
1487 (end (progn (skip-chars-forward " \r\t\n" limit)
1488 (if (eobp) (point) (line-beginning-position)))))
1489 (list 'quote-block
1490 (nconc
1491 (list :begin begin
1492 :end end
1493 :contents-begin contents-begin
1494 :contents-end contents-end
1495 :post-blank (count-lines pos-before-blank end)
1496 :post-affiliated post-affiliated)
1497 (cdr affiliated)))))))))
1499 (defun org-element-quote-block-interpreter (quote-block contents)
1500 "Interpret QUOTE-BLOCK element as Org syntax.
1501 CONTENTS is the contents of the element."
1502 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1505 ;;;; Section
1507 (defun org-element-section-parser (limit)
1508 "Parse a section.
1510 LIMIT bounds the search.
1512 Return a list whose CAR is `section' and CDR is a plist
1513 containing `:begin', `:end', `:contents-begin', `contents-end',
1514 `:post-blank' and `:post-affiliated' keywords."
1515 (save-excursion
1516 ;; Beginning of section is the beginning of the first non-blank
1517 ;; line after previous headline.
1518 (let ((begin (point))
1519 (end (progn (org-with-limited-levels (outline-next-heading))
1520 (point)))
1521 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1522 (forward-line)
1523 (point))))
1524 (list 'section
1525 (list :begin begin
1526 :end end
1527 :contents-begin begin
1528 :contents-end pos-before-blank
1529 :post-blank (count-lines pos-before-blank end)
1530 :post-affiliated begin)))))
1532 (defun org-element-section-interpreter (section contents)
1533 "Interpret SECTION element as Org syntax.
1534 CONTENTS is the contents of the element."
1535 contents)
1538 ;;;; Special Block
1540 (defun org-element-special-block-parser (limit affiliated)
1541 "Parse a special block.
1543 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1544 the buffer position at the beginning of the first affiliated
1545 keyword and CDR is a plist of affiliated keywords along with
1546 their value.
1548 Return a list whose CAR is `special-block' and CDR is a plist
1549 containing `:type', `:begin', `:end', `:contents-begin',
1550 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1552 Assume point is at the beginning of the block."
1553 (let* ((case-fold-search t)
1554 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1555 (match-string-no-properties 1))))
1556 (if (not (save-excursion
1557 (re-search-forward
1558 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1559 limit t)))
1560 ;; Incomplete block: parse it as a paragraph.
1561 (org-element-paragraph-parser limit affiliated)
1562 (let ((block-end-line (match-beginning 0)))
1563 (save-excursion
1564 (let* ((begin (car affiliated))
1565 (post-affiliated (point))
1566 ;; Empty blocks have no contents.
1567 (contents-begin (progn (forward-line)
1568 (and (< (point) block-end-line)
1569 (point))))
1570 (contents-end (and contents-begin block-end-line))
1571 (pos-before-blank (progn (goto-char block-end-line)
1572 (forward-line)
1573 (point)))
1574 (end (progn (skip-chars-forward " \r\t\n" limit)
1575 (if (eobp) (point) (line-beginning-position)))))
1576 (list 'special-block
1577 (nconc
1578 (list :type type
1579 :begin begin
1580 :end end
1581 :contents-begin contents-begin
1582 :contents-end contents-end
1583 :post-blank (count-lines pos-before-blank end)
1584 :post-affiliated post-affiliated)
1585 (cdr affiliated)))))))))
1587 (defun org-element-special-block-interpreter (special-block contents)
1588 "Interpret SPECIAL-BLOCK element as Org syntax.
1589 CONTENTS is the contents of the element."
1590 (let ((block-type (org-element-property :type special-block)))
1591 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1595 ;;; Elements
1597 ;; For each element, a parser and an interpreter are also defined.
1598 ;; Both follow the same naming convention used for greater elements.
1600 ;; Also, as for greater elements, adding a new element type is done
1601 ;; through the following steps: implement a parser and an interpreter,
1602 ;; tweak `org-element--current-element' so that it recognizes the new
1603 ;; type and add that new type to `org-element-all-elements'.
1605 ;; As a special case, when the newly defined type is a block type,
1606 ;; `org-element-block-name-alist' has to be modified accordingly.
1609 ;;;; Babel Call
1611 (defun org-element-babel-call-parser (limit affiliated)
1612 "Parse a babel call.
1614 LIMIT bounds the search. AFFILIATED is a list of which car is
1615 the buffer position at the beginning of the first affiliated
1616 keyword and cdr is a plist of affiliated keywords along with
1617 their value.
1619 Return a list whose car is `babel-call' and cdr is a plist
1620 containing `:call', `:inside-header', `:arguments',
1621 `:end-header', `:begin', `:end', `:value', `:post-blank' and
1622 `:post-affiliated' as keywords."
1623 (save-excursion
1624 (let* ((begin (car affiliated))
1625 (post-affiliated (point))
1626 (value (progn (search-forward ":" nil t)
1627 (org-trim
1628 (buffer-substring-no-properties
1629 (point) (line-end-position)))))
1630 (pos-before-blank (progn (forward-line) (point)))
1631 (end (progn (skip-chars-forward " \r\t\n" limit)
1632 (if (eobp) (point) (line-beginning-position))))
1633 (valid-value
1634 (string-match
1635 "\\([^()\n]+?\\)\\(?:\\[\\(.*?\\)\\]\\)?(\\(.*?\\))[ \t]*\\(.*\\)"
1636 value)))
1637 (list 'babel-call
1638 (nconc
1639 (list :call (and valid-value (match-string 1 value))
1640 :inside-header (and valid-value
1641 (org-string-nw-p (match-string 2 value)))
1642 :arguments (and valid-value
1643 (org-string-nw-p (match-string 3 value)))
1644 :end-header (and valid-value
1645 (org-string-nw-p (match-string 4 value)))
1646 :begin begin
1647 :end end
1648 :value value
1649 :post-blank (count-lines pos-before-blank end)
1650 :post-affiliated post-affiliated)
1651 (cdr affiliated))))))
1653 (defun org-element-babel-call-interpreter (babel-call contents)
1654 "Interpret BABEL-CALL element as Org syntax.
1655 CONTENTS is nil."
1656 (concat "#+CALL: "
1657 (org-element-property :call babel-call)
1658 (let ((h (org-element-property :inside-header babel-call)))
1659 (and h (format "[%s]" h)))
1660 (concat "(" (org-element-property :arguments babel-call) ")")
1661 (let ((h (org-element-property :end-header babel-call)))
1662 (and h (concat " " h)))))
1665 ;;;; Clock
1667 (defun org-element-clock-parser (limit)
1668 "Parse a clock.
1670 LIMIT bounds the search.
1672 Return a list whose CAR is `clock' and CDR is a plist containing
1673 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1674 `:post-affiliated' as keywords."
1675 (save-excursion
1676 (let* ((case-fold-search nil)
1677 (begin (point))
1678 (value (progn (search-forward org-clock-string (line-end-position) t)
1679 (skip-chars-forward " \t")
1680 (org-element-timestamp-parser)))
1681 (duration (and (search-forward " => " (line-end-position) t)
1682 (progn (skip-chars-forward " \t")
1683 (looking-at "\\(\\S-+\\)[ \t]*$"))
1684 (org-match-string-no-properties 1)))
1685 (status (if duration 'closed 'running))
1686 (post-blank (let ((before-blank (progn (forward-line) (point))))
1687 (skip-chars-forward " \r\t\n" limit)
1688 (skip-chars-backward " \t")
1689 (unless (bolp) (end-of-line))
1690 (count-lines before-blank (point))))
1691 (end (point)))
1692 (list 'clock
1693 (list :status status
1694 :value value
1695 :duration duration
1696 :begin begin
1697 :end end
1698 :post-blank post-blank
1699 :post-affiliated begin)))))
1701 (defun org-element-clock-interpreter (clock contents)
1702 "Interpret CLOCK element as Org syntax.
1703 CONTENTS is nil."
1704 (concat org-clock-string " "
1705 (org-element-timestamp-interpreter
1706 (org-element-property :value clock) nil)
1707 (let ((duration (org-element-property :duration clock)))
1708 (and duration
1709 (concat " => "
1710 (apply 'format
1711 "%2s:%02s"
1712 (org-split-string duration ":")))))))
1715 ;;;; Comment
1717 (defun org-element-comment-parser (limit affiliated)
1718 "Parse a comment.
1720 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1721 the buffer position at the beginning of the first affiliated
1722 keyword and CDR is a plist of affiliated keywords along with
1723 their value.
1725 Return a list whose CAR is `comment' and CDR is a plist
1726 containing `:begin', `:end', `:value', `:post-blank',
1727 `:post-affiliated' keywords.
1729 Assume point is at comment beginning."
1730 (save-excursion
1731 (let* ((begin (car affiliated))
1732 (post-affiliated (point))
1733 (value (prog2 (looking-at "[ \t]*# ?")
1734 (buffer-substring-no-properties
1735 (match-end 0) (line-end-position))
1736 (forward-line)))
1737 (com-end
1738 ;; Get comments ending.
1739 (progn
1740 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1741 ;; Accumulate lines without leading hash and first
1742 ;; whitespace.
1743 (setq value
1744 (concat value
1745 "\n"
1746 (buffer-substring-no-properties
1747 (match-end 0) (line-end-position))))
1748 (forward-line))
1749 (point)))
1750 (end (progn (goto-char com-end)
1751 (skip-chars-forward " \r\t\n" limit)
1752 (if (eobp) (point) (line-beginning-position)))))
1753 (list 'comment
1754 (nconc
1755 (list :begin begin
1756 :end end
1757 :value value
1758 :post-blank (count-lines com-end end)
1759 :post-affiliated post-affiliated)
1760 (cdr affiliated))))))
1762 (defun org-element-comment-interpreter (comment contents)
1763 "Interpret COMMENT element as Org syntax.
1764 CONTENTS is nil."
1765 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1768 ;;;; Comment Block
1770 (defun org-element-comment-block-parser (limit affiliated)
1771 "Parse an export block.
1773 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1774 the buffer position at the beginning of the first affiliated
1775 keyword and CDR is a plist of affiliated keywords along with
1776 their value.
1778 Return a list whose CAR is `comment-block' and CDR is a plist
1779 containing `:begin', `:end', `:value', `:post-blank' and
1780 `:post-affiliated' keywords.
1782 Assume point is at comment block beginning."
1783 (let ((case-fold-search t))
1784 (if (not (save-excursion
1785 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1786 ;; Incomplete block: parse it as a paragraph.
1787 (org-element-paragraph-parser limit affiliated)
1788 (let ((contents-end (match-beginning 0)))
1789 (save-excursion
1790 (let* ((begin (car affiliated))
1791 (post-affiliated (point))
1792 (contents-begin (progn (forward-line) (point)))
1793 (pos-before-blank (progn (goto-char contents-end)
1794 (forward-line)
1795 (point)))
1796 (end (progn (skip-chars-forward " \r\t\n" limit)
1797 (if (eobp) (point) (line-beginning-position))))
1798 (value (buffer-substring-no-properties
1799 contents-begin contents-end)))
1800 (list 'comment-block
1801 (nconc
1802 (list :begin begin
1803 :end end
1804 :value value
1805 :post-blank (count-lines pos-before-blank end)
1806 :post-affiliated post-affiliated)
1807 (cdr affiliated)))))))))
1809 (defun org-element-comment-block-interpreter (comment-block contents)
1810 "Interpret COMMENT-BLOCK element as Org syntax.
1811 CONTENTS is nil."
1812 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1813 (org-element-normalize-string
1814 (org-remove-indentation
1815 (org-element-property :value comment-block)))))
1818 ;;;; Diary Sexp
1820 (defun org-element-diary-sexp-parser (limit affiliated)
1821 "Parse a diary sexp.
1823 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1824 the buffer position at the beginning of the first affiliated
1825 keyword and CDR is a plist of affiliated keywords along with
1826 their value.
1828 Return a list whose CAR is `diary-sexp' and CDR is a plist
1829 containing `:begin', `:end', `:value', `:post-blank' and
1830 `:post-affiliated' keywords."
1831 (save-excursion
1832 (let ((begin (car affiliated))
1833 (post-affiliated (point))
1834 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1835 (org-match-string-no-properties 1)))
1836 (pos-before-blank (progn (forward-line) (point)))
1837 (end (progn (skip-chars-forward " \r\t\n" limit)
1838 (if (eobp) (point) (line-beginning-position)))))
1839 (list 'diary-sexp
1840 (nconc
1841 (list :value value
1842 :begin begin
1843 :end end
1844 :post-blank (count-lines pos-before-blank end)
1845 :post-affiliated post-affiliated)
1846 (cdr affiliated))))))
1848 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1849 "Interpret DIARY-SEXP as Org syntax.
1850 CONTENTS is nil."
1851 (org-element-property :value diary-sexp))
1854 ;;;; Example Block
1856 (defun org-element-example-block-parser (limit affiliated)
1857 "Parse an example block.
1859 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1860 the buffer position at the beginning of the first affiliated
1861 keyword and CDR is a plist of affiliated keywords along with
1862 their value.
1864 Return a list whose CAR is `example-block' and CDR is a plist
1865 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1866 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1867 `:value', `:post-blank' and `:post-affiliated' keywords."
1868 (let ((case-fold-search t))
1869 (if (not (save-excursion
1870 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1871 ;; Incomplete block: parse it as a paragraph.
1872 (org-element-paragraph-parser limit affiliated)
1873 (let ((contents-end (match-beginning 0)))
1874 (save-excursion
1875 (let* ((switches
1876 (progn
1877 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1878 (org-match-string-no-properties 1)))
1879 ;; Switches analysis
1880 (number-lines
1881 (cond ((not switches) nil)
1882 ((string-match "-n\\>" switches) 'new)
1883 ((string-match "+n\\>" switches) 'continued)))
1884 (preserve-indent
1885 (and switches (string-match "-i\\>" switches)))
1886 ;; Should labels be retained in (or stripped from) example
1887 ;; blocks?
1888 (retain-labels
1889 (or (not switches)
1890 (not (string-match "-r\\>" switches))
1891 (and number-lines (string-match "-k\\>" switches))))
1892 ;; What should code-references use - labels or
1893 ;; line-numbers?
1894 (use-labels
1895 (or (not switches)
1896 (and retain-labels
1897 (not (string-match "-k\\>" switches)))))
1898 (label-fmt
1899 (and switches
1900 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1901 (match-string 1 switches)))
1902 ;; Standard block parsing.
1903 (begin (car affiliated))
1904 (post-affiliated (point))
1905 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1906 (contents-begin (progn (forward-line) (point)))
1907 (value (org-element-remove-indentation
1908 (org-unescape-code-in-string
1909 (buffer-substring-no-properties
1910 contents-begin contents-end))
1911 block-ind))
1912 (pos-before-blank (progn (goto-char contents-end)
1913 (forward-line)
1914 (point)))
1915 (end (progn (skip-chars-forward " \r\t\n" limit)
1916 (if (eobp) (point) (line-beginning-position)))))
1917 (list 'example-block
1918 (nconc
1919 (list :begin begin
1920 :end end
1921 :value value
1922 :switches switches
1923 :number-lines number-lines
1924 :preserve-indent preserve-indent
1925 :retain-labels retain-labels
1926 :use-labels use-labels
1927 :label-fmt label-fmt
1928 :post-blank (count-lines pos-before-blank end)
1929 :post-affiliated post-affiliated)
1930 (cdr affiliated)))))))))
1932 (defun org-element-example-block-interpreter (example-block contents)
1933 "Interpret EXAMPLE-BLOCK element as Org syntax.
1934 CONTENTS is nil."
1935 (let ((switches (org-element-property :switches example-block))
1936 (value (org-element-property :value example-block)))
1937 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1938 (org-element-normalize-string
1939 (org-escape-code-in-string
1940 (if (or org-src-preserve-indentation
1941 (org-element-property :preserve-indent example-block))
1942 value
1943 (org-element-remove-indentation value))))
1944 "#+END_EXAMPLE")))
1947 ;;;; Export Block
1949 (defun org-element-export-block-parser (limit affiliated)
1950 "Parse an export block.
1952 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1953 the buffer position at the beginning of the first affiliated
1954 keyword and CDR is a plist of affiliated keywords along with
1955 their value.
1957 Return a list whose CAR is `export-block' and CDR is a plist
1958 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1959 `:post-affiliated' keywords.
1961 Assume point is at export-block beginning."
1962 (let* ((case-fold-search t)
1963 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1964 (upcase (org-match-string-no-properties 1)))))
1965 (if (not (save-excursion
1966 (re-search-forward
1967 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1968 ;; Incomplete block: parse it as a paragraph.
1969 (org-element-paragraph-parser limit affiliated)
1970 (let ((contents-end (match-beginning 0)))
1971 (save-excursion
1972 (let* ((begin (car affiliated))
1973 (post-affiliated (point))
1974 (contents-begin (progn (forward-line) (point)))
1975 (pos-before-blank (progn (goto-char contents-end)
1976 (forward-line)
1977 (point)))
1978 (end (progn (skip-chars-forward " \r\t\n" limit)
1979 (if (eobp) (point) (line-beginning-position))))
1980 (value (buffer-substring-no-properties contents-begin
1981 contents-end)))
1982 (list 'export-block
1983 (nconc
1984 (list :begin begin
1985 :end end
1986 :type type
1987 :value value
1988 :post-blank (count-lines pos-before-blank end)
1989 :post-affiliated post-affiliated)
1990 (cdr affiliated)))))))))
1992 (defun org-element-export-block-interpreter (export-block contents)
1993 "Interpret EXPORT-BLOCK element as Org syntax.
1994 CONTENTS is nil."
1995 (let ((type (org-element-property :type export-block)))
1996 (concat (format "#+BEGIN_%s\n" type)
1997 (org-element-property :value export-block)
1998 (format "#+END_%s" type))))
2001 ;;;; Fixed-width
2003 (defun org-element-fixed-width-parser (limit affiliated)
2004 "Parse a fixed-width section.
2006 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2007 the buffer position at the beginning of the first affiliated
2008 keyword and CDR is a plist of affiliated keywords along with
2009 their value.
2011 Return a list whose CAR is `fixed-width' and CDR is a plist
2012 containing `:begin', `:end', `:value', `:post-blank' and
2013 `:post-affiliated' keywords.
2015 Assume point is at the beginning of the fixed-width area."
2016 (save-excursion
2017 (let* ((begin (car affiliated))
2018 (post-affiliated (point))
2019 value
2020 (end-area
2021 (progn
2022 (while (and (< (point) limit)
2023 (looking-at "[ \t]*:\\( \\|$\\)"))
2024 ;; Accumulate text without starting colons.
2025 (setq value
2026 (concat value
2027 (buffer-substring-no-properties
2028 (match-end 0) (point-at-eol))
2029 "\n"))
2030 (forward-line))
2031 (point)))
2032 (end (progn (skip-chars-forward " \r\t\n" limit)
2033 (if (eobp) (point) (line-beginning-position)))))
2034 (list 'fixed-width
2035 (nconc
2036 (list :begin begin
2037 :end end
2038 :value value
2039 :post-blank (count-lines end-area end)
2040 :post-affiliated post-affiliated)
2041 (cdr affiliated))))))
2043 (defun org-element-fixed-width-interpreter (fixed-width contents)
2044 "Interpret FIXED-WIDTH element as Org syntax.
2045 CONTENTS is nil."
2046 (let ((value (org-element-property :value fixed-width)))
2047 (and value
2048 (replace-regexp-in-string
2049 "^" ": "
2050 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
2053 ;;;; Horizontal Rule
2055 (defun org-element-horizontal-rule-parser (limit affiliated)
2056 "Parse an horizontal rule.
2058 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2059 the buffer position at the beginning of the first affiliated
2060 keyword and CDR is a plist of affiliated keywords along with
2061 their value.
2063 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2064 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2065 keywords."
2066 (save-excursion
2067 (let ((begin (car affiliated))
2068 (post-affiliated (point))
2069 (post-hr (progn (forward-line) (point)))
2070 (end (progn (skip-chars-forward " \r\t\n" limit)
2071 (if (eobp) (point) (line-beginning-position)))))
2072 (list 'horizontal-rule
2073 (nconc
2074 (list :begin begin
2075 :end end
2076 :post-blank (count-lines post-hr end)
2077 :post-affiliated post-affiliated)
2078 (cdr affiliated))))))
2080 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
2081 "Interpret HORIZONTAL-RULE element as Org syntax.
2082 CONTENTS is nil."
2083 "-----")
2086 ;;;; Keyword
2088 (defun org-element-keyword-parser (limit affiliated)
2089 "Parse a keyword at point.
2091 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2092 the buffer position at the beginning of the first affiliated
2093 keyword and CDR is a plist of affiliated keywords along with
2094 their value.
2096 Return a list whose CAR is `keyword' and CDR is a plist
2097 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2098 `:post-affiliated' keywords."
2099 (save-excursion
2100 ;; An orphaned affiliated keyword is considered as a regular
2101 ;; keyword. In this case AFFILIATED is nil, so we take care of
2102 ;; this corner case.
2103 (let ((begin (or (car affiliated) (point)))
2104 (post-affiliated (point))
2105 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2106 (upcase (org-match-string-no-properties 1))))
2107 (value (org-trim (buffer-substring-no-properties
2108 (match-end 0) (point-at-eol))))
2109 (pos-before-blank (progn (forward-line) (point)))
2110 (end (progn (skip-chars-forward " \r\t\n" limit)
2111 (if (eobp) (point) (line-beginning-position)))))
2112 (list 'keyword
2113 (nconc
2114 (list :key key
2115 :value value
2116 :begin begin
2117 :end end
2118 :post-blank (count-lines pos-before-blank end)
2119 :post-affiliated post-affiliated)
2120 (cdr affiliated))))))
2122 (defun org-element-keyword-interpreter (keyword contents)
2123 "Interpret KEYWORD element as Org syntax.
2124 CONTENTS is nil."
2125 (format "#+%s: %s"
2126 (org-element-property :key keyword)
2127 (org-element-property :value keyword)))
2130 ;;;; Latex Environment
2132 (defconst org-element--latex-begin-environment
2133 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2134 "Regexp matching the beginning of a LaTeX environment.
2135 The environment is captured by the first group.
2137 See also `org-element--latex-end-environment'.")
2139 (defconst org-element--latex-end-environment
2140 "\\\\end{%s}[ \t]*$"
2141 "Format string matching the ending of a LaTeX environment.
2142 See also `org-element--latex-begin-environment'.")
2144 (defun org-element-latex-environment-parser (limit affiliated)
2145 "Parse a LaTeX environment.
2147 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2148 the buffer position at the beginning of the first affiliated
2149 keyword and CDR is a plist of affiliated keywords along with
2150 their value.
2152 Return a list whose CAR is `latex-environment' and CDR is a plist
2153 containing `:begin', `:end', `:value', `:post-blank' and
2154 `:post-affiliated' keywords.
2156 Assume point is at the beginning of the latex environment."
2157 (save-excursion
2158 (let ((case-fold-search t)
2159 (code-begin (point)))
2160 (looking-at org-element--latex-begin-environment)
2161 (if (not (re-search-forward (format org-element--latex-end-environment
2162 (regexp-quote (match-string 1)))
2163 limit t))
2164 ;; Incomplete latex environment: parse it as a paragraph.
2165 (org-element-paragraph-parser limit affiliated)
2166 (let* ((code-end (progn (forward-line) (point)))
2167 (begin (car affiliated))
2168 (value (buffer-substring-no-properties code-begin code-end))
2169 (end (progn (skip-chars-forward " \r\t\n" limit)
2170 (if (eobp) (point) (line-beginning-position)))))
2171 (list 'latex-environment
2172 (nconc
2173 (list :begin begin
2174 :end end
2175 :value value
2176 :post-blank (count-lines code-end end)
2177 :post-affiliated code-begin)
2178 (cdr affiliated))))))))
2180 (defun org-element-latex-environment-interpreter (latex-environment contents)
2181 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2182 CONTENTS is nil."
2183 (org-element-property :value latex-environment))
2186 ;;;; Node Property
2188 (defun org-element-node-property-parser (limit)
2189 "Parse a node-property at point.
2191 LIMIT bounds the search.
2193 Return a list whose CAR is `node-property' and CDR is a plist
2194 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2195 `:post-affiliated' keywords."
2196 (looking-at org-property-re)
2197 (let ((case-fold-search t)
2198 (begin (point))
2199 (key (org-match-string-no-properties 2))
2200 (value (org-match-string-no-properties 3))
2201 (end (save-excursion
2202 (end-of-line)
2203 (if (re-search-forward org-property-re limit t)
2204 (line-beginning-position)
2205 limit))))
2206 (list 'node-property
2207 (list :key key
2208 :value value
2209 :begin begin
2210 :end end
2211 :post-blank 0
2212 :post-affiliated begin))))
2214 (defun org-element-node-property-interpreter (node-property contents)
2215 "Interpret NODE-PROPERTY element as Org syntax.
2216 CONTENTS is nil."
2217 (format org-property-format
2218 (format ":%s:" (org-element-property :key node-property))
2219 (or (org-element-property :value node-property) "")))
2222 ;;;; Paragraph
2224 (defun org-element-paragraph-parser (limit affiliated)
2225 "Parse a paragraph.
2227 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2228 the buffer position at the beginning of the first affiliated
2229 keyword and CDR is a plist of affiliated keywords along with
2230 their value.
2232 Return a list whose CAR is `paragraph' and CDR is a plist
2233 containing `:begin', `:end', `:contents-begin' and
2234 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2236 Assume point is at the beginning of the paragraph."
2237 (save-excursion
2238 (let* ((begin (car affiliated))
2239 (contents-begin (point))
2240 (before-blank
2241 (let ((case-fold-search t))
2242 (end-of-line)
2243 ;; A matching `org-element-paragraph-separate' is not
2244 ;; necessarily the end of the paragraph. In particular,
2245 ;; drawers, blocks or LaTeX environments opening lines
2246 ;; must be closed. Moreover keywords with a secondary
2247 ;; value must belong to "dual keywords".
2248 (while (not
2249 (cond
2250 ((not (and (re-search-forward
2251 org-element-paragraph-separate limit 'move)
2252 (progn (beginning-of-line) t))))
2253 ((looking-at org-drawer-regexp)
2254 (save-excursion
2255 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
2256 ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2257 (save-excursion
2258 (re-search-forward
2259 (format "^[ \t]*#\\+END_%s[ \t]*$"
2260 (regexp-quote (match-string 1)))
2261 limit t)))
2262 ((looking-at org-element--latex-begin-environment)
2263 (save-excursion
2264 (re-search-forward
2265 (format org-element--latex-end-environment
2266 (regexp-quote (match-string 1)))
2267 limit t)))
2268 ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
2269 (member-ignore-case (match-string 1)
2270 org-element-dual-keywords))
2271 ;; Everything else is unambiguous.
2272 (t)))
2273 (end-of-line))
2274 (if (= (point) limit) limit
2275 (goto-char (line-beginning-position)))))
2276 (contents-end (save-excursion
2277 (skip-chars-backward " \r\t\n" contents-begin)
2278 (line-beginning-position 2)))
2279 (end (progn (skip-chars-forward " \r\t\n" limit)
2280 (if (eobp) (point) (line-beginning-position)))))
2281 (list 'paragraph
2282 (nconc
2283 (list :begin begin
2284 :end end
2285 :contents-begin contents-begin
2286 :contents-end contents-end
2287 :post-blank (count-lines before-blank end)
2288 :post-affiliated contents-begin)
2289 (cdr affiliated))))))
2291 (defun org-element-paragraph-interpreter (paragraph contents)
2292 "Interpret PARAGRAPH element as Org syntax.
2293 CONTENTS is the contents of the element."
2294 contents)
2297 ;;;; Planning
2299 (defun org-element-planning-parser (limit)
2300 "Parse a planning.
2302 LIMIT bounds the search.
2304 Return a list whose CAR is `planning' and CDR is a plist
2305 containing `:closed', `:deadline', `:scheduled', `:begin',
2306 `:end', `:post-blank' and `:post-affiliated' keywords."
2307 (save-excursion
2308 (let* ((case-fold-search nil)
2309 (begin (point))
2310 (post-blank (let ((before-blank (progn (forward-line) (point))))
2311 (skip-chars-forward " \r\t\n" limit)
2312 (skip-chars-backward " \t")
2313 (unless (bolp) (end-of-line))
2314 (count-lines before-blank (point))))
2315 (end (point))
2316 closed deadline scheduled)
2317 (goto-char begin)
2318 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2319 (goto-char (match-end 1))
2320 (skip-chars-forward " \t" end)
2321 (let ((keyword (match-string 1))
2322 (time (org-element-timestamp-parser)))
2323 (cond ((equal keyword org-closed-string) (setq closed time))
2324 ((equal keyword org-deadline-string) (setq deadline time))
2325 (t (setq scheduled time)))))
2326 (list 'planning
2327 (list :closed closed
2328 :deadline deadline
2329 :scheduled scheduled
2330 :begin begin
2331 :end end
2332 :post-blank post-blank
2333 :post-affiliated begin)))))
2335 (defun org-element-planning-interpreter (planning contents)
2336 "Interpret PLANNING element as Org syntax.
2337 CONTENTS is nil."
2338 (mapconcat
2339 'identity
2340 (delq nil
2341 (list (let ((deadline (org-element-property :deadline planning)))
2342 (when deadline
2343 (concat org-deadline-string " "
2344 (org-element-timestamp-interpreter deadline nil))))
2345 (let ((scheduled (org-element-property :scheduled planning)))
2346 (when scheduled
2347 (concat org-scheduled-string " "
2348 (org-element-timestamp-interpreter scheduled nil))))
2349 (let ((closed (org-element-property :closed planning)))
2350 (when closed
2351 (concat org-closed-string " "
2352 (org-element-timestamp-interpreter closed nil))))))
2353 " "))
2356 ;;;; Src Block
2358 (defun org-element-src-block-parser (limit affiliated)
2359 "Parse a src block.
2361 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2362 the buffer position at the beginning of the first affiliated
2363 keyword and CDR is a plist of affiliated keywords along with
2364 their value.
2366 Return a list whose CAR is `src-block' and CDR is a plist
2367 containing `:language', `:switches', `:parameters', `:begin',
2368 `:end', `:number-lines', `:retain-labels', `:use-labels',
2369 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2370 `:post-affiliated' keywords.
2372 Assume point is at the beginning of the block."
2373 (let ((case-fold-search t))
2374 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2375 limit t)))
2376 ;; Incomplete block: parse it as a paragraph.
2377 (org-element-paragraph-parser limit affiliated)
2378 (let ((contents-end (match-beginning 0)))
2379 (save-excursion
2380 (let* ((begin (car affiliated))
2381 (post-affiliated (point))
2382 ;; Get language as a string.
2383 (language
2384 (progn
2385 (looking-at
2386 (concat "^[ \t]*#\\+BEGIN_SRC"
2387 "\\(?: +\\(\\S-+\\)\\)?"
2388 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2389 "\\(.*\\)[ \t]*$"))
2390 (org-match-string-no-properties 1)))
2391 ;; Get switches.
2392 (switches (org-match-string-no-properties 2))
2393 ;; Get parameters.
2394 (parameters (org-match-string-no-properties 3))
2395 ;; Switches analysis
2396 (number-lines
2397 (cond ((not switches) nil)
2398 ((string-match "-n\\>" switches) 'new)
2399 ((string-match "+n\\>" switches) 'continued)))
2400 (preserve-indent (and switches
2401 (string-match "-i\\>" switches)))
2402 (label-fmt
2403 (and switches
2404 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2405 (match-string 1 switches)))
2406 ;; Should labels be retained in (or stripped from)
2407 ;; src blocks?
2408 (retain-labels
2409 (or (not switches)
2410 (not (string-match "-r\\>" switches))
2411 (and number-lines (string-match "-k\\>" switches))))
2412 ;; What should code-references use - labels or
2413 ;; line-numbers?
2414 (use-labels
2415 (or (not switches)
2416 (and retain-labels
2417 (not (string-match "-k\\>" switches)))))
2418 ;; Indentation.
2419 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2420 ;; Retrieve code.
2421 (value (org-element-remove-indentation
2422 (org-unescape-code-in-string
2423 (buffer-substring-no-properties
2424 (progn (forward-line) (point)) contents-end))
2425 block-ind))
2426 (pos-before-blank (progn (goto-char contents-end)
2427 (forward-line)
2428 (point)))
2429 ;; Get position after ending blank lines.
2430 (end (progn (skip-chars-forward " \r\t\n" limit)
2431 (if (eobp) (point) (line-beginning-position)))))
2432 (list 'src-block
2433 (nconc
2434 (list :language language
2435 :switches (and (org-string-nw-p switches)
2436 (org-trim switches))
2437 :parameters (and (org-string-nw-p parameters)
2438 (org-trim parameters))
2439 :begin begin
2440 :end end
2441 :number-lines number-lines
2442 :preserve-indent preserve-indent
2443 :retain-labels retain-labels
2444 :use-labels use-labels
2445 :label-fmt label-fmt
2446 :value value
2447 :post-blank (count-lines pos-before-blank end)
2448 :post-affiliated post-affiliated)
2449 (cdr affiliated)))))))))
2451 (defun org-element-src-block-interpreter (src-block contents)
2452 "Interpret SRC-BLOCK element as Org syntax.
2453 CONTENTS is nil."
2454 (let ((lang (org-element-property :language src-block))
2455 (switches (org-element-property :switches src-block))
2456 (params (org-element-property :parameters src-block))
2457 (value
2458 (let ((val (org-element-property :value src-block)))
2459 (cond
2460 ((or org-src-preserve-indentation
2461 (org-element-property :preserve-indent src-block))
2462 val)
2463 ((zerop org-edit-src-content-indentation) val)
2465 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2466 (replace-regexp-in-string
2467 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2468 (concat (format "#+BEGIN_SRC%s\n"
2469 (concat (and lang (concat " " lang))
2470 (and switches (concat " " switches))
2471 (and params (concat " " params))))
2472 (org-element-normalize-string (org-escape-code-in-string value))
2473 "#+END_SRC")))
2476 ;;;; Table
2478 (defun org-element-table-parser (limit affiliated)
2479 "Parse a table at point.
2481 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2482 the buffer position at the beginning of the first affiliated
2483 keyword and CDR is a plist of affiliated keywords along with
2484 their value.
2486 Return a list whose CAR is `table' and CDR is a plist containing
2487 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2488 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2489 keywords.
2491 Assume point is at the beginning of the table."
2492 (save-excursion
2493 (let* ((case-fold-search t)
2494 (table-begin (point))
2495 (type (if (looking-at "[ \t]*|") 'org 'table.el))
2496 (begin (car affiliated))
2497 (table-end
2498 (if (re-search-forward org-table-any-border-regexp limit 'm)
2499 (goto-char (match-beginning 0))
2500 (point)))
2501 (tblfm (let (acc)
2502 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2503 (push (org-match-string-no-properties 1) acc)
2504 (forward-line))
2505 acc))
2506 (pos-before-blank (point))
2507 (end (progn (skip-chars-forward " \r\t\n" limit)
2508 (if (eobp) (point) (line-beginning-position)))))
2509 (list 'table
2510 (nconc
2511 (list :begin begin
2512 :end end
2513 :type type
2514 :tblfm tblfm
2515 ;; Only `org' tables have contents. `table.el' tables
2516 ;; use a `:value' property to store raw table as
2517 ;; a string.
2518 :contents-begin (and (eq type 'org) table-begin)
2519 :contents-end (and (eq type 'org) table-end)
2520 :value (and (eq type 'table.el)
2521 (buffer-substring-no-properties
2522 table-begin table-end))
2523 :post-blank (count-lines pos-before-blank end)
2524 :post-affiliated table-begin)
2525 (cdr affiliated))))))
2527 (defun org-element-table-interpreter (table contents)
2528 "Interpret TABLE element as Org syntax.
2529 CONTENTS is a string, if table's type is `org', or nil."
2530 (if (eq (org-element-property :type table) 'table.el)
2531 (org-remove-indentation (org-element-property :value table))
2532 (concat (with-temp-buffer (insert contents)
2533 (org-table-align)
2534 (buffer-string))
2535 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2536 (reverse (org-element-property :tblfm table))
2537 "\n"))))
2540 ;;;; Table Row
2542 (defun org-element-table-row-parser (limit)
2543 "Parse table row at point.
2545 LIMIT bounds the search.
2547 Return a list whose CAR is `table-row' and CDR is a plist
2548 containing `:begin', `:end', `:contents-begin', `:contents-end',
2549 `:type', `:post-blank' and `:post-affiliated' keywords."
2550 (save-excursion
2551 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2552 (begin (point))
2553 ;; A table rule has no contents. In that case, ensure
2554 ;; CONTENTS-BEGIN matches CONTENTS-END.
2555 (contents-begin (and (eq type 'standard)
2556 (search-forward "|")
2557 (point)))
2558 (contents-end (and (eq type 'standard)
2559 (progn
2560 (end-of-line)
2561 (skip-chars-backward " \t")
2562 (point))))
2563 (end (progn (forward-line) (point))))
2564 (list 'table-row
2565 (list :type type
2566 :begin begin
2567 :end end
2568 :contents-begin contents-begin
2569 :contents-end contents-end
2570 :post-blank 0
2571 :post-affiliated begin)))))
2573 (defun org-element-table-row-interpreter (table-row contents)
2574 "Interpret TABLE-ROW element as Org syntax.
2575 CONTENTS is the contents of the table row."
2576 (if (eq (org-element-property :type table-row) 'rule) "|-"
2577 (concat "| " contents)))
2580 ;;;; Verse Block
2582 (defun org-element-verse-block-parser (limit affiliated)
2583 "Parse a verse block.
2585 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2586 the buffer position at the beginning of the first affiliated
2587 keyword and CDR is a plist of affiliated keywords along with
2588 their value.
2590 Return a list whose CAR is `verse-block' and CDR is a plist
2591 containing `:begin', `:end', `:contents-begin', `:contents-end',
2592 `:post-blank' and `:post-affiliated' keywords.
2594 Assume point is at beginning of the block."
2595 (let ((case-fold-search t))
2596 (if (not (save-excursion
2597 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2598 ;; Incomplete block: parse it as a paragraph.
2599 (org-element-paragraph-parser limit affiliated)
2600 (let ((contents-end (match-beginning 0)))
2601 (save-excursion
2602 (let* ((begin (car affiliated))
2603 (post-affiliated (point))
2604 (contents-begin (progn (forward-line) (point)))
2605 (pos-before-blank (progn (goto-char contents-end)
2606 (forward-line)
2607 (point)))
2608 (end (progn (skip-chars-forward " \r\t\n" limit)
2609 (if (eobp) (point) (line-beginning-position)))))
2610 (list 'verse-block
2611 (nconc
2612 (list :begin begin
2613 :end end
2614 :contents-begin contents-begin
2615 :contents-end contents-end
2616 :post-blank (count-lines pos-before-blank end)
2617 :post-affiliated post-affiliated)
2618 (cdr affiliated)))))))))
2620 (defun org-element-verse-block-interpreter (verse-block contents)
2621 "Interpret VERSE-BLOCK element as Org syntax.
2622 CONTENTS is verse block contents."
2623 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2627 ;;; Objects
2629 ;; Unlike to elements, raw text can be found between objects. Hence,
2630 ;; `org-element--object-lex' is provided to find the next object in
2631 ;; buffer.
2633 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2634 ;; object types they can contain will be specified in
2635 ;; `org-element-object-restrictions'.
2637 ;; Creating a new type of object requires to alter
2638 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2639 ;; new type in `org-element-all-objects', and possibly add
2640 ;; restrictions in `org-element-object-restrictions'.
2642 ;;;; Bold
2644 (defun org-element-bold-parser ()
2645 "Parse bold object at point, if any.
2647 When at a bold object, return a list whose car is `bold' and cdr
2648 is a plist with `:begin', `:end', `:contents-begin' and
2649 `:contents-end' and `:post-blank' keywords. Otherwise, return
2650 nil.
2652 Assume point is at the first star marker."
2653 (save-excursion
2654 (unless (bolp) (backward-char 1))
2655 (when (looking-at org-emph-re)
2656 (let ((begin (match-beginning 2))
2657 (contents-begin (match-beginning 4))
2658 (contents-end (match-end 4))
2659 (post-blank (progn (goto-char (match-end 2))
2660 (skip-chars-forward " \t")))
2661 (end (point)))
2662 (list 'bold
2663 (list :begin begin
2664 :end end
2665 :contents-begin contents-begin
2666 :contents-end contents-end
2667 :post-blank post-blank))))))
2669 (defun org-element-bold-interpreter (bold contents)
2670 "Interpret BOLD object as Org syntax.
2671 CONTENTS is the contents of the object."
2672 (format "*%s*" contents))
2675 ;;;; Code
2677 (defun org-element-code-parser ()
2678 "Parse code object at point, if any.
2680 When at a code object, return a list whose car is `code' and cdr
2681 is a plist with `:value', `:begin', `:end' and `:post-blank'
2682 keywords. Otherwise, return nil.
2684 Assume point is at the first tilde marker."
2685 (save-excursion
2686 (unless (bolp) (backward-char 1))
2687 (when (looking-at org-emph-re)
2688 (let ((begin (match-beginning 2))
2689 (value (org-match-string-no-properties 4))
2690 (post-blank (progn (goto-char (match-end 2))
2691 (skip-chars-forward " \t")))
2692 (end (point)))
2693 (list 'code
2694 (list :value value
2695 :begin begin
2696 :end end
2697 :post-blank post-blank))))))
2699 (defun org-element-code-interpreter (code contents)
2700 "Interpret CODE object as Org syntax.
2701 CONTENTS is nil."
2702 (format "~%s~" (org-element-property :value code)))
2705 ;;;; Entity
2707 (defun org-element-entity-parser ()
2708 "Parse entity at point, if any.
2710 When at an entity, return a list whose car is `entity' and cdr
2711 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2712 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2713 `:post-blank' as keywords. Otherwise, return nil.
2715 Assume point is at the beginning of the entity."
2716 (catch 'no-object
2717 (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
2718 (save-excursion
2719 (let* ((value (or (org-entity-get (match-string 1))
2720 (throw 'no-object nil)))
2721 (begin (match-beginning 0))
2722 (bracketsp (string= (match-string 2) "{}"))
2723 (post-blank (progn (goto-char (match-end 1))
2724 (when bracketsp (forward-char 2))
2725 (skip-chars-forward " \t")))
2726 (end (point)))
2727 (list 'entity
2728 (list :name (car value)
2729 :latex (nth 1 value)
2730 :latex-math-p (nth 2 value)
2731 :html (nth 3 value)
2732 :ascii (nth 4 value)
2733 :latin1 (nth 5 value)
2734 :utf-8 (nth 6 value)
2735 :begin begin
2736 :end end
2737 :use-brackets-p bracketsp
2738 :post-blank post-blank)))))))
2740 (defun org-element-entity-interpreter (entity contents)
2741 "Interpret ENTITY object as Org syntax.
2742 CONTENTS is nil."
2743 (concat "\\"
2744 (org-element-property :name entity)
2745 (when (org-element-property :use-brackets-p entity) "{}")))
2748 ;;;; Export Snippet
2750 (defun org-element-export-snippet-parser ()
2751 "Parse export snippet at point.
2753 When at an export snippet, return a list whose car is
2754 `export-snippet' and cdr a plist with `:begin', `:end',
2755 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2756 return nil.
2758 Assume point is at the beginning of the snippet."
2759 (save-excursion
2760 (let (contents-end)
2761 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2762 (setq contents-end
2763 (save-match-data (goto-char (match-end 0))
2764 (re-search-forward "@@" nil t)
2765 (match-beginning 0))))
2766 (let* ((begin (match-beginning 0))
2767 (back-end (org-match-string-no-properties 1))
2768 (value (buffer-substring-no-properties
2769 (match-end 0) contents-end))
2770 (post-blank (skip-chars-forward " \t"))
2771 (end (point)))
2772 (list 'export-snippet
2773 (list :back-end back-end
2774 :value value
2775 :begin begin
2776 :end end
2777 :post-blank post-blank)))))))
2779 (defun org-element-export-snippet-interpreter (export-snippet contents)
2780 "Interpret EXPORT-SNIPPET object as Org syntax.
2781 CONTENTS is nil."
2782 (format "@@%s:%s@@"
2783 (org-element-property :back-end export-snippet)
2784 (org-element-property :value export-snippet)))
2787 ;;;; Footnote Reference
2789 (defun org-element-footnote-reference-parser ()
2790 "Parse footnote reference at point, if any.
2792 When at a footnote reference, return a list whose car is
2793 `footnote-reference' and cdr a plist with `:label', `:type',
2794 `:begin', `:end', `:content-begin', `:contents-end' and
2795 `:post-blank' as keywords. Otherwise, return nil."
2796 (when (looking-at org-footnote-re)
2797 (let ((closing (with-syntax-table org-element--pair-square-table
2798 (ignore-errors (scan-lists (point) 1 0)))))
2799 (when closing
2800 (save-excursion
2801 (let* ((begin (point))
2802 (label
2803 (or (org-match-string-no-properties 2)
2804 (org-match-string-no-properties 3)
2805 (and (match-string 1)
2806 (concat "fn:" (org-match-string-no-properties 1)))))
2807 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2808 (inner-begin (match-end 0))
2809 (inner-end (1- closing))
2810 (post-blank (progn (goto-char closing)
2811 (skip-chars-forward " \t")))
2812 (end (point)))
2813 (list 'footnote-reference
2814 (list :label label
2815 :type type
2816 :begin begin
2817 :end end
2818 :contents-begin (and (eq type 'inline) inner-begin)
2819 :contents-end (and (eq type 'inline) inner-end)
2820 :post-blank post-blank))))))))
2822 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2823 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2824 CONTENTS is its definition, when inline, or nil."
2825 (format "[%s]"
2826 (concat (or (org-element-property :label footnote-reference) "fn:")
2827 (and contents (concat ":" contents)))))
2830 ;;;; Inline Babel Call
2832 (defun org-element-inline-babel-call-parser ()
2833 "Parse inline babel call at point, if any.
2835 When at an inline babel call, return a list whose car is
2836 `inline-babel-call' and cdr a plist with `:call',
2837 `:inside-header', `:arguments', `:end-header', `:begin', `:end',
2838 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2840 Assume point is at the beginning of the babel call."
2841 (save-excursion
2842 (unless (bolp) (backward-char))
2843 (when (let ((case-fold-search t))
2844 (looking-at org-babel-inline-lob-one-liner-regexp))
2845 (let ((begin (match-end 1))
2846 (call (org-match-string-no-properties 2))
2847 (inside-header (org-string-nw-p (org-match-string-no-properties 4)))
2848 (arguments (org-string-nw-p (org-match-string-no-properties 6)))
2849 (end-header (org-string-nw-p (org-match-string-no-properties 8)))
2850 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2851 (post-blank (progn (goto-char (match-end 0))
2852 (skip-chars-forward " \t")))
2853 (end (point)))
2854 (list 'inline-babel-call
2855 (list :call call
2856 :inside-header inside-header
2857 :arguments arguments
2858 :end-header end-header
2859 :begin begin
2860 :end end
2861 :value value
2862 :post-blank post-blank))))))
2864 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2865 "Interpret INLINE-BABEL-CALL object as Org syntax.
2866 CONTENTS is nil."
2867 (concat "call_"
2868 (org-element-property :call inline-babel-call)
2869 (let ((h (org-element-property :inside-header inline-babel-call)))
2870 (and h (format "[%s]" h)))
2871 "(" (org-element-property :arguments inline-babel-call) ")"
2872 (let ((h (org-element-property :end-header inline-babel-call)))
2873 (and h (format "[%s]" h)))))
2876 ;;;; Inline Src Block
2878 (defun org-element-inline-src-block-parser ()
2879 "Parse inline source block at point, if any.
2881 When at an inline source block, return a list whose car is
2882 `inline-src-block' and cdr a plist with `:begin', `:end',
2883 `:language', `:value', `:parameters' and `:post-blank' as
2884 keywords. Otherwise, return nil.
2886 Assume point is at the beginning of the inline src block."
2887 (save-excursion
2888 (unless (bolp) (backward-char))
2889 (when (looking-at org-babel-inline-src-block-regexp)
2890 (let ((begin (match-beginning 1))
2891 (language (org-match-string-no-properties 2))
2892 (parameters (org-match-string-no-properties 4))
2893 (value (org-match-string-no-properties 5))
2894 (post-blank (progn (goto-char (match-end 0))
2895 (skip-chars-forward " \t")))
2896 (end (point)))
2897 (list 'inline-src-block
2898 (list :language language
2899 :value value
2900 :parameters parameters
2901 :begin begin
2902 :end end
2903 :post-blank post-blank))))))
2905 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2906 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2907 CONTENTS is nil."
2908 (let ((language (org-element-property :language inline-src-block))
2909 (arguments (org-element-property :parameters inline-src-block))
2910 (body (org-element-property :value inline-src-block)))
2911 (format "src_%s%s{%s}"
2912 language
2913 (if arguments (format "[%s]" arguments) "")
2914 body)))
2916 ;;;; Italic
2918 (defun org-element-italic-parser ()
2919 "Parse italic object at point, if any.
2921 When at an italic object, return a list whose car is `italic' and
2922 cdr is a plist with `:begin', `:end', `:contents-begin' and
2923 `:contents-end' and `:post-blank' keywords. Otherwise, return
2924 nil.
2926 Assume point is at the first slash marker."
2927 (save-excursion
2928 (unless (bolp) (backward-char 1))
2929 (when (looking-at org-emph-re)
2930 (let ((begin (match-beginning 2))
2931 (contents-begin (match-beginning 4))
2932 (contents-end (match-end 4))
2933 (post-blank (progn (goto-char (match-end 2))
2934 (skip-chars-forward " \t")))
2935 (end (point)))
2936 (list 'italic
2937 (list :begin begin
2938 :end end
2939 :contents-begin contents-begin
2940 :contents-end contents-end
2941 :post-blank post-blank))))))
2943 (defun org-element-italic-interpreter (italic contents)
2944 "Interpret ITALIC object as Org syntax.
2945 CONTENTS is the contents of the object."
2946 (format "/%s/" contents))
2949 ;;;; Latex Fragment
2951 (defun org-element-latex-fragment-parser ()
2952 "Parse LaTeX fragment at point, if any.
2954 When at a LaTeX fragment, return a list whose car is
2955 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2956 and `:post-blank' as keywords. Otherwise, return nil.
2958 Assume point is at the beginning of the LaTeX fragment."
2959 (catch 'no-object
2960 (save-excursion
2961 (let* ((begin (point))
2962 (after-fragment
2963 (if (eq (char-after) ?$)
2964 (if (eq (char-after (1+ (point))) ?$)
2965 (search-forward "$$" nil t 2)
2966 (and (not (eq (char-before) ?$))
2967 (search-forward "$" nil t 2)
2968 (not (memq (char-before (match-beginning 0))
2969 '(?\s ?\t ?\n ?, ?.)))
2970 (looking-at "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|$\\)")
2971 (point)))
2972 (case (char-after (1+ (point)))
2973 (?\( (search-forward "\\)" nil t))
2974 (?\[ (search-forward "\\]" nil t))
2975 (otherwise
2976 ;; Macro.
2977 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2978 (match-end 0))))))
2979 (post-blank (if (not after-fragment) (throw 'no-object nil)
2980 (goto-char after-fragment)
2981 (skip-chars-forward " \t")))
2982 (end (point)))
2983 (list 'latex-fragment
2984 (list :value (buffer-substring-no-properties begin after-fragment)
2985 :begin begin
2986 :end end
2987 :post-blank post-blank))))))
2989 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2990 "Interpret LATEX-FRAGMENT object as Org syntax.
2991 CONTENTS is nil."
2992 (org-element-property :value latex-fragment))
2994 ;;;; Line Break
2996 (defun org-element-line-break-parser ()
2997 "Parse line break at point, if any.
2999 When at a line break, return a list whose car is `line-break',
3000 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
3001 Otherwise, return nil.
3003 Assume point is at the beginning of the line break."
3004 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
3005 (not (eq (char-before) ?\\)))
3006 (list 'line-break
3007 (list :begin (point)
3008 :end (line-beginning-position 2)
3009 :post-blank 0))))
3011 (defun org-element-line-break-interpreter (line-break contents)
3012 "Interpret LINE-BREAK object as Org syntax.
3013 CONTENTS is nil."
3014 "\\\\\n")
3017 ;;;; Link
3019 (defun org-element-link-parser ()
3020 "Parse link at point, if any.
3022 When at a link, return a list whose car is `link' and cdr a plist
3023 with `:type', `:path', `:raw-link', `:application',
3024 `:search-option', `:begin', `:end', `:contents-begin',
3025 `:contents-end' and `:post-blank' as keywords. Otherwise, return
3026 nil.
3028 Assume point is at the beginning of the link."
3029 (catch 'no-object
3030 (let ((begin (point))
3031 end contents-begin contents-end link-end post-blank path type
3032 raw-link link search-option application)
3033 (cond
3034 ;; Type 1: Text targeted from a radio target.
3035 ((and org-target-link-regexp
3036 (save-excursion (or (bolp) (backward-char))
3037 (looking-at org-target-link-regexp)))
3038 (setq type "radio"
3039 link-end (match-end 1)
3040 path (org-match-string-no-properties 1)
3041 contents-begin (match-beginning 1)
3042 contents-end (match-end 1)))
3043 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3044 ((looking-at org-bracket-link-regexp)
3045 (setq contents-begin (match-beginning 3)
3046 contents-end (match-end 3)
3047 link-end (match-end 0)
3048 ;; RAW-LINK is the original link. Expand any
3049 ;; abbreviation in it.
3050 raw-link (org-translate-link
3051 (org-link-expand-abbrev
3052 (org-match-string-no-properties 1))))
3053 ;; Determine TYPE of link and set PATH accordingly.
3054 (cond
3055 ;; File type.
3056 ((or (file-name-absolute-p raw-link)
3057 (string-match "\\`\\.\\.?/" raw-link))
3058 (setq type "file" path raw-link))
3059 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3060 ((string-match org-link-types-re raw-link)
3061 (setq type (match-string 1 raw-link)
3062 ;; According to RFC 3986, extra whitespace should be
3063 ;; ignored when a URI is extracted.
3064 path (replace-regexp-in-string
3065 "[ \t]*\n[ \t]*" "" (substring raw-link (match-end 0)))))
3066 ;; Id type: PATH is the id.
3067 ((string-match "\\`id:\\([-a-f0-9]+\\)" raw-link)
3068 (setq type "id" path (match-string 1 raw-link)))
3069 ;; Code-ref type: PATH is the name of the reference.
3070 ((string-match "\\`(\\(.*\\))\\'" raw-link)
3071 (setq type "coderef" path (match-string 1 raw-link)))
3072 ;; Custom-id type: PATH is the name of the custom id.
3073 ((= (string-to-char raw-link) ?#)
3074 (setq type "custom-id" path (substring raw-link 1)))
3075 ;; Fuzzy type: Internal link either matches a target, an
3076 ;; headline name or nothing. PATH is the target or
3077 ;; headline's name.
3078 (t (setq type "fuzzy" path raw-link))))
3079 ;; Type 3: Plain link, e.g., http://orgmode.org
3080 ((looking-at org-plain-link-re)
3081 (setq raw-link (org-match-string-no-properties 0)
3082 type (org-match-string-no-properties 1)
3083 link-end (match-end 0)
3084 path (org-match-string-no-properties 2)))
3085 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3086 ((looking-at org-angle-link-re)
3087 (setq raw-link (buffer-substring-no-properties
3088 (match-beginning 1) (match-end 2))
3089 type (org-match-string-no-properties 1)
3090 link-end (match-end 0)
3091 path (org-match-string-no-properties 2)))
3092 (t (throw 'no-object nil)))
3093 ;; In any case, deduce end point after trailing white space from
3094 ;; LINK-END variable.
3095 (save-excursion
3096 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3097 end (point))
3098 ;; Special "file" type link processing. Extract opening
3099 ;; application and search option, if any. Also normalize URI.
3100 (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
3101 (setq application (match-string 1 type) type "file")
3102 (when (string-match "::\\(.*\\)\\'" path)
3103 (setq search-option (match-string 1 path)
3104 path (replace-match "" nil nil path)))
3105 (setq path (replace-regexp-in-string "\\`/+" "/" path)))
3106 (list 'link
3107 (list :type type
3108 :path path
3109 :raw-link (or raw-link path)
3110 :application application
3111 :search-option search-option
3112 :begin begin
3113 :end end
3114 :contents-begin contents-begin
3115 :contents-end contents-end
3116 :post-blank post-blank))))))
3118 (defun org-element-link-interpreter (link contents)
3119 "Interpret LINK object as Org syntax.
3120 CONTENTS is the contents of the object, or nil."
3121 (let ((type (org-element-property :type link))
3122 (raw-link (org-element-property :raw-link link)))
3123 (if (string= type "radio") raw-link
3124 (format "[[%s]%s]"
3125 raw-link
3126 (if contents (format "[%s]" contents) "")))))
3129 ;;;; Macro
3131 (defun org-element-macro-parser ()
3132 "Parse macro at point, if any.
3134 When at a macro, return a list whose car is `macro' and cdr
3135 a plist with `:key', `:args', `:begin', `:end', `:value' and
3136 `:post-blank' as keywords. Otherwise, return nil.
3138 Assume point is at the macro."
3139 (save-excursion
3140 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3141 (let ((begin (point))
3142 (key (downcase (org-match-string-no-properties 1)))
3143 (value (org-match-string-no-properties 0))
3144 (post-blank (progn (goto-char (match-end 0))
3145 (skip-chars-forward " \t")))
3146 (end (point))
3147 (args (let ((args (org-match-string-no-properties 3)))
3148 (and args (org-macro-extract-arguments args)))))
3149 (list 'macro
3150 (list :key key
3151 :value value
3152 :args args
3153 :begin begin
3154 :end end
3155 :post-blank post-blank))))))
3157 (defun org-element-macro-interpreter (macro contents)
3158 "Interpret MACRO object as Org syntax.
3159 CONTENTS is nil."
3160 (org-element-property :value macro))
3163 ;;;; Radio-target
3165 (defun org-element-radio-target-parser ()
3166 "Parse radio target at point, if any.
3168 When at a radio target, return a list whose car is `radio-target'
3169 and cdr a plist with `:begin', `:end', `:contents-begin',
3170 `:contents-end', `:value' and `:post-blank' as keywords.
3171 Otherwise, return nil.
3173 Assume point is at the radio target."
3174 (save-excursion
3175 (when (looking-at org-radio-target-regexp)
3176 (let ((begin (point))
3177 (contents-begin (match-beginning 1))
3178 (contents-end (match-end 1))
3179 (value (org-match-string-no-properties 1))
3180 (post-blank (progn (goto-char (match-end 0))
3181 (skip-chars-forward " \t")))
3182 (end (point)))
3183 (list 'radio-target
3184 (list :begin begin
3185 :end end
3186 :contents-begin contents-begin
3187 :contents-end contents-end
3188 :post-blank post-blank
3189 :value value))))))
3191 (defun org-element-radio-target-interpreter (target contents)
3192 "Interpret TARGET object as Org syntax.
3193 CONTENTS is the contents of the object."
3194 (concat "<<<" contents ">>>"))
3197 ;;;; Statistics Cookie
3199 (defun org-element-statistics-cookie-parser ()
3200 "Parse statistics cookie at point, if any.
3202 When at a statistics cookie, return a list whose car is
3203 `statistics-cookie', and cdr a plist with `:begin', `:end',
3204 `:value' and `:post-blank' keywords. Otherwise, return nil.
3206 Assume point is at the beginning of the statistics-cookie."
3207 (save-excursion
3208 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3209 (let* ((begin (point))
3210 (value (buffer-substring-no-properties
3211 (match-beginning 0) (match-end 0)))
3212 (post-blank (progn (goto-char (match-end 0))
3213 (skip-chars-forward " \t")))
3214 (end (point)))
3215 (list 'statistics-cookie
3216 (list :begin begin
3217 :end end
3218 :value value
3219 :post-blank post-blank))))))
3221 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3222 "Interpret STATISTICS-COOKIE object as Org syntax.
3223 CONTENTS is nil."
3224 (org-element-property :value statistics-cookie))
3227 ;;;; Strike-Through
3229 (defun org-element-strike-through-parser ()
3230 "Parse strike-through object at point, if any.
3232 When at a strike-through object, return a list whose car is
3233 `strike-through' and cdr is a plist with `:begin', `:end',
3234 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3235 Otherwise, return nil.
3237 Assume point is at the first plus sign marker."
3238 (save-excursion
3239 (unless (bolp) (backward-char 1))
3240 (when (looking-at org-emph-re)
3241 (let ((begin (match-beginning 2))
3242 (contents-begin (match-beginning 4))
3243 (contents-end (match-end 4))
3244 (post-blank (progn (goto-char (match-end 2))
3245 (skip-chars-forward " \t")))
3246 (end (point)))
3247 (list 'strike-through
3248 (list :begin begin
3249 :end end
3250 :contents-begin contents-begin
3251 :contents-end contents-end
3252 :post-blank post-blank))))))
3254 (defun org-element-strike-through-interpreter (strike-through contents)
3255 "Interpret STRIKE-THROUGH object as Org syntax.
3256 CONTENTS is the contents of the object."
3257 (format "+%s+" contents))
3260 ;;;; Subscript
3262 (defun org-element-subscript-parser ()
3263 "Parse subscript at point, if any.
3265 When at a subscript object, return a list whose car is
3266 `subscript' and cdr a plist with `:begin', `:end',
3267 `:contents-begin', `:contents-end', `:use-brackets-p' and
3268 `:post-blank' as keywords. Otherwise, return nil.
3270 Assume point is at the underscore."
3271 (save-excursion
3272 (unless (bolp) (backward-char))
3273 (when (looking-at org-match-substring-regexp)
3274 (let ((bracketsp (match-beginning 4))
3275 (begin (match-beginning 2))
3276 (contents-begin (or (match-beginning 4)
3277 (match-beginning 3)))
3278 (contents-end (or (match-end 4) (match-end 3)))
3279 (post-blank (progn (goto-char (match-end 0))
3280 (skip-chars-forward " \t")))
3281 (end (point)))
3282 (list 'subscript
3283 (list :begin begin
3284 :end end
3285 :use-brackets-p bracketsp
3286 :contents-begin contents-begin
3287 :contents-end contents-end
3288 :post-blank post-blank))))))
3290 (defun org-element-subscript-interpreter (subscript contents)
3291 "Interpret SUBSCRIPT object as Org syntax.
3292 CONTENTS is the contents of the object."
3293 (format
3294 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3295 contents))
3298 ;;;; Superscript
3300 (defun org-element-superscript-parser ()
3301 "Parse superscript at point, if any.
3303 When at a superscript object, return a list whose car is
3304 `superscript' and cdr a plist with `:begin', `:end',
3305 `:contents-begin', `:contents-end', `:use-brackets-p' and
3306 `:post-blank' as keywords. Otherwise, return nil.
3308 Assume point is at the caret."
3309 (save-excursion
3310 (unless (bolp) (backward-char))
3311 (when (looking-at org-match-substring-regexp)
3312 (let ((bracketsp (match-beginning 4))
3313 (begin (match-beginning 2))
3314 (contents-begin (or (match-beginning 4)
3315 (match-beginning 3)))
3316 (contents-end (or (match-end 4) (match-end 3)))
3317 (post-blank (progn (goto-char (match-end 0))
3318 (skip-chars-forward " \t")))
3319 (end (point)))
3320 (list 'superscript
3321 (list :begin begin
3322 :end end
3323 :use-brackets-p bracketsp
3324 :contents-begin contents-begin
3325 :contents-end contents-end
3326 :post-blank post-blank))))))
3328 (defun org-element-superscript-interpreter (superscript contents)
3329 "Interpret SUPERSCRIPT object as Org syntax.
3330 CONTENTS is the contents of the object."
3331 (format
3332 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3333 contents))
3336 ;;;; Table Cell
3338 (defun org-element-table-cell-parser ()
3339 "Parse table cell at point.
3340 Return a list whose car is `table-cell' and cdr is a plist
3341 containing `:begin', `:end', `:contents-begin', `:contents-end'
3342 and `:post-blank' keywords."
3343 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3344 (let* ((begin (match-beginning 0))
3345 (end (match-end 0))
3346 (contents-begin (match-beginning 1))
3347 (contents-end (match-end 1)))
3348 (list 'table-cell
3349 (list :begin begin
3350 :end end
3351 :contents-begin contents-begin
3352 :contents-end contents-end
3353 :post-blank 0))))
3355 (defun org-element-table-cell-interpreter (table-cell contents)
3356 "Interpret TABLE-CELL element as Org syntax.
3357 CONTENTS is the contents of the cell, or nil."
3358 (concat " " contents " |"))
3361 ;;;; Target
3363 (defun org-element-target-parser ()
3364 "Parse target at point, if any.
3366 When at a target, return a list whose car is `target' and cdr
3367 a plist with `:begin', `:end', `:value' and `:post-blank' as
3368 keywords. Otherwise, return nil.
3370 Assume point is at the target."
3371 (save-excursion
3372 (when (looking-at org-target-regexp)
3373 (let ((begin (point))
3374 (value (org-match-string-no-properties 1))
3375 (post-blank (progn (goto-char (match-end 0))
3376 (skip-chars-forward " \t")))
3377 (end (point)))
3378 (list 'target
3379 (list :begin begin
3380 :end end
3381 :value value
3382 :post-blank post-blank))))))
3384 (defun org-element-target-interpreter (target contents)
3385 "Interpret TARGET object as Org syntax.
3386 CONTENTS is nil."
3387 (format "<<%s>>" (org-element-property :value target)))
3390 ;;;; Timestamp
3392 (defconst org-element--timestamp-regexp
3393 (concat org-ts-regexp-both
3394 "\\|"
3395 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3396 "\\|"
3397 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3398 "Regexp matching any timestamp type object.")
3400 (defun org-element-timestamp-parser ()
3401 "Parse time stamp at point, if any.
3403 When at a time stamp, return a list whose car is `timestamp', and
3404 cdr a plist with `:type', `:raw-value', `:year-start',
3405 `:month-start', `:day-start', `:hour-start', `:minute-start',
3406 `:year-end', `:month-end', `:day-end', `:hour-end',
3407 `:minute-end', `:repeater-type', `:repeater-value',
3408 `:repeater-unit', `:warning-type', `:warning-value',
3409 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3410 Otherwise, return nil.
3412 Assume point is at the beginning of the timestamp."
3413 (when (org-looking-at-p org-element--timestamp-regexp)
3414 (save-excursion
3415 (let* ((begin (point))
3416 (activep (eq (char-after) ?<))
3417 (raw-value
3418 (progn
3419 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3420 (match-string-no-properties 0)))
3421 (date-start (match-string-no-properties 1))
3422 (date-end (match-string 3))
3423 (diaryp (match-beginning 2))
3424 (post-blank (progn (goto-char (match-end 0))
3425 (skip-chars-forward " \t")))
3426 (end (point))
3427 (time-range
3428 (and (not diaryp)
3429 (string-match
3430 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3431 date-start)
3432 (cons (string-to-number (match-string 2 date-start))
3433 (string-to-number (match-string 3 date-start)))))
3434 (type (cond (diaryp 'diary)
3435 ((and activep (or date-end time-range)) 'active-range)
3436 (activep 'active)
3437 ((or date-end time-range) 'inactive-range)
3438 (t 'inactive)))
3439 (repeater-props
3440 (and (not diaryp)
3441 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3442 raw-value)
3443 (list
3444 :repeater-type
3445 (let ((type (match-string 1 raw-value)))
3446 (cond ((equal "++" type) 'catch-up)
3447 ((equal ".+" type) 'restart)
3448 (t 'cumulate)))
3449 :repeater-value (string-to-number (match-string 2 raw-value))
3450 :repeater-unit
3451 (case (string-to-char (match-string 3 raw-value))
3452 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3453 (warning-props
3454 (and (not diaryp)
3455 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3456 (list
3457 :warning-type (if (match-string 1 raw-value) 'first 'all)
3458 :warning-value (string-to-number (match-string 2 raw-value))
3459 :warning-unit
3460 (case (string-to-char (match-string 3 raw-value))
3461 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3462 year-start month-start day-start hour-start minute-start year-end
3463 month-end day-end hour-end minute-end)
3464 ;; Parse date-start.
3465 (unless diaryp
3466 (let ((date (org-parse-time-string date-start t)))
3467 (setq year-start (nth 5 date)
3468 month-start (nth 4 date)
3469 day-start (nth 3 date)
3470 hour-start (nth 2 date)
3471 minute-start (nth 1 date))))
3472 ;; Compute date-end. It can be provided directly in time-stamp,
3473 ;; or extracted from time range. Otherwise, it defaults to the
3474 ;; same values as date-start.
3475 (unless diaryp
3476 (let ((date (and date-end (org-parse-time-string date-end t))))
3477 (setq year-end (or (nth 5 date) year-start)
3478 month-end (or (nth 4 date) month-start)
3479 day-end (or (nth 3 date) day-start)
3480 hour-end (or (nth 2 date) (car time-range) hour-start)
3481 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3482 (list 'timestamp
3483 (nconc (list :type type
3484 :raw-value raw-value
3485 :year-start year-start
3486 :month-start month-start
3487 :day-start day-start
3488 :hour-start hour-start
3489 :minute-start minute-start
3490 :year-end year-end
3491 :month-end month-end
3492 :day-end day-end
3493 :hour-end hour-end
3494 :minute-end minute-end
3495 :begin begin
3496 :end end
3497 :post-blank post-blank)
3498 repeater-props
3499 warning-props))))))
3501 (defun org-element-timestamp-interpreter (timestamp contents)
3502 "Interpret TIMESTAMP object as Org syntax.
3503 CONTENTS is nil."
3504 (let* ((repeat-string
3505 (concat
3506 (case (org-element-property :repeater-type timestamp)
3507 (cumulate "+") (catch-up "++") (restart ".+"))
3508 (let ((val (org-element-property :repeater-value timestamp)))
3509 (and val (number-to-string val)))
3510 (case (org-element-property :repeater-unit timestamp)
3511 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3512 (warning-string
3513 (concat
3514 (case (org-element-property :warning-type timestamp)
3515 (first "--")
3516 (all "-"))
3517 (let ((val (org-element-property :warning-value timestamp)))
3518 (and val (number-to-string val)))
3519 (case (org-element-property :warning-unit timestamp)
3520 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3521 (build-ts-string
3522 ;; Build an Org timestamp string from TIME. ACTIVEP is
3523 ;; non-nil when time stamp is active. If WITH-TIME-P is
3524 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3525 ;; specify a time range in the timestamp. REPEAT-STRING is
3526 ;; the repeater string, if any.
3527 (lambda (time activep &optional with-time-p hour-end minute-end)
3528 (let ((ts (format-time-string
3529 (funcall (if with-time-p 'cdr 'car)
3530 org-time-stamp-formats)
3531 time)))
3532 (when (and hour-end minute-end)
3533 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3534 (setq ts
3535 (replace-match
3536 (format "\\&-%02d:%02d" hour-end minute-end)
3537 nil nil ts)))
3538 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3539 (dolist (s (list repeat-string warning-string))
3540 (when (org-string-nw-p s)
3541 (setq ts (concat (substring ts 0 -1)
3544 (substring ts -1)))))
3545 ;; Return value.
3546 ts)))
3547 (type (org-element-property :type timestamp)))
3548 (case type
3549 ((active inactive)
3550 (let* ((minute-start (org-element-property :minute-start timestamp))
3551 (minute-end (org-element-property :minute-end timestamp))
3552 (hour-start (org-element-property :hour-start timestamp))
3553 (hour-end (org-element-property :hour-end timestamp))
3554 (time-range-p (and hour-start hour-end minute-start minute-end
3555 (or (/= hour-start hour-end)
3556 (/= minute-start minute-end)))))
3557 (funcall
3558 build-ts-string
3559 (encode-time 0
3560 (or minute-start 0)
3561 (or hour-start 0)
3562 (org-element-property :day-start timestamp)
3563 (org-element-property :month-start timestamp)
3564 (org-element-property :year-start timestamp))
3565 (eq type 'active)
3566 (and hour-start minute-start)
3567 (and time-range-p hour-end)
3568 (and time-range-p minute-end))))
3569 ((active-range inactive-range)
3570 (let ((minute-start (org-element-property :minute-start timestamp))
3571 (minute-end (org-element-property :minute-end timestamp))
3572 (hour-start (org-element-property :hour-start timestamp))
3573 (hour-end (org-element-property :hour-end timestamp)))
3574 (concat
3575 (funcall
3576 build-ts-string (encode-time
3578 (or minute-start 0)
3579 (or hour-start 0)
3580 (org-element-property :day-start timestamp)
3581 (org-element-property :month-start timestamp)
3582 (org-element-property :year-start timestamp))
3583 (eq type 'active-range)
3584 (and hour-start minute-start))
3585 "--"
3586 (funcall build-ts-string
3587 (encode-time 0
3588 (or minute-end 0)
3589 (or hour-end 0)
3590 (org-element-property :day-end timestamp)
3591 (org-element-property :month-end timestamp)
3592 (org-element-property :year-end timestamp))
3593 (eq type 'active-range)
3594 (and hour-end minute-end)))))
3595 (otherwise (org-element-property :raw-value timestamp)))))
3598 ;;;; Underline
3600 (defun org-element-underline-parser ()
3601 "Parse underline object at point, if any.
3603 When at an underline object, return a list whose car is
3604 `underline' and cdr is a plist with `:begin', `:end',
3605 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3606 Otherwise, return nil.
3608 Assume point is at the first underscore marker."
3609 (save-excursion
3610 (unless (bolp) (backward-char 1))
3611 (when (looking-at org-emph-re)
3612 (let ((begin (match-beginning 2))
3613 (contents-begin (match-beginning 4))
3614 (contents-end (match-end 4))
3615 (post-blank (progn (goto-char (match-end 2))
3616 (skip-chars-forward " \t")))
3617 (end (point)))
3618 (list 'underline
3619 (list :begin begin
3620 :end end
3621 :contents-begin contents-begin
3622 :contents-end contents-end
3623 :post-blank post-blank))))))
3625 (defun org-element-underline-interpreter (underline contents)
3626 "Interpret UNDERLINE object as Org syntax.
3627 CONTENTS is the contents of the object."
3628 (format "_%s_" contents))
3631 ;;;; Verbatim
3633 (defun org-element-verbatim-parser ()
3634 "Parse verbatim object at point, if any.
3636 When at a verbatim object, return a list whose car is `verbatim'
3637 and cdr is a plist with `:value', `:begin', `:end' and
3638 `:post-blank' keywords. Otherwise, return nil.
3640 Assume point is at the first equal sign marker."
3641 (save-excursion
3642 (unless (bolp) (backward-char 1))
3643 (when (looking-at org-emph-re)
3644 (let ((begin (match-beginning 2))
3645 (value (org-match-string-no-properties 4))
3646 (post-blank (progn (goto-char (match-end 2))
3647 (skip-chars-forward " \t")))
3648 (end (point)))
3649 (list 'verbatim
3650 (list :value value
3651 :begin begin
3652 :end end
3653 :post-blank post-blank))))))
3655 (defun org-element-verbatim-interpreter (verbatim contents)
3656 "Interpret VERBATIM object as Org syntax.
3657 CONTENTS is nil."
3658 (format "=%s=" (org-element-property :value verbatim)))
3662 ;;; Parsing Element Starting At Point
3664 ;; `org-element--current-element' is the core function of this section.
3665 ;; It returns the Lisp representation of the element starting at
3666 ;; point.
3668 ;; `org-element--current-element' makes use of special modes. They
3669 ;; are activated for fixed element chaining (e.g., `plain-list' >
3670 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3671 ;; `section'). Special modes are: `first-section', `item',
3672 ;; `node-property', `section' and `table-row'.
3674 (defun org-element--current-element (limit &optional granularity mode structure)
3675 "Parse the element starting at point.
3677 Return value is a list like (TYPE PROPS) where TYPE is the type
3678 of the element and PROPS a plist of properties associated to the
3679 element.
3681 Possible types are defined in `org-element-all-elements'.
3683 LIMIT bounds the search.
3685 Optional argument GRANULARITY determines the depth of the
3686 recursion. Allowed values are `headline', `greater-element',
3687 `element', `object' or nil. When it is broader than `object' (or
3688 nil), secondary values will not be parsed, since they only
3689 contain objects.
3691 Optional argument MODE, when non-nil, can be either
3692 `first-section', `section', `planning', `item', `node-property'
3693 and `table-row'.
3695 If STRUCTURE isn't provided but MODE is set to `item', it will be
3696 computed.
3698 This function assumes point is always at the beginning of the
3699 element it has to parse."
3700 (save-excursion
3701 (let ((case-fold-search t)
3702 ;; Determine if parsing depth allows for secondary strings
3703 ;; parsing. It only applies to elements referenced in
3704 ;; `org-element-secondary-value-alist'.
3705 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3706 (cond
3707 ;; Item.
3708 ((eq mode 'item)
3709 (org-element-item-parser limit structure raw-secondary-p))
3710 ;; Table Row.
3711 ((eq mode 'table-row) (org-element-table-row-parser limit))
3712 ;; Node Property.
3713 ((eq mode 'node-property) (org-element-node-property-parser limit))
3714 ;; Headline.
3715 ((org-with-limited-levels (org-at-heading-p))
3716 (org-element-headline-parser limit raw-secondary-p))
3717 ;; Sections (must be checked after headline).
3718 ((eq mode 'section) (org-element-section-parser limit))
3719 ((eq mode 'first-section)
3720 (org-element-section-parser
3721 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3722 limit)))
3723 ;; Planning.
3724 ((and (eq mode 'planning) (looking-at org-planning-line-re))
3725 (org-element-planning-parser limit))
3726 ;; Property drawer.
3727 ((and (memq mode '(planning property-drawer))
3728 (looking-at org-property-drawer-re))
3729 (org-element-property-drawer-parser limit))
3730 ;; When not at bol, point is at the beginning of an item or
3731 ;; a footnote definition: next item is always a paragraph.
3732 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3733 ;; Clock.
3734 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3735 ;; Inlinetask.
3736 ((org-at-heading-p)
3737 (org-element-inlinetask-parser limit raw-secondary-p))
3738 ;; From there, elements can have affiliated keywords.
3739 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3740 (cond
3741 ;; Jumping over affiliated keywords put point off-limits.
3742 ;; Parse them as regular keywords.
3743 ((and (cdr affiliated) (>= (point) limit))
3744 (goto-char (car affiliated))
3745 (org-element-keyword-parser limit nil))
3746 ;; LaTeX Environment.
3747 ((looking-at org-element--latex-begin-environment)
3748 (org-element-latex-environment-parser limit affiliated))
3749 ;; Drawer and Property Drawer.
3750 ((looking-at org-drawer-regexp)
3751 (org-element-drawer-parser limit affiliated))
3752 ;; Fixed Width
3753 ((looking-at "[ \t]*:\\( \\|$\\)")
3754 (org-element-fixed-width-parser limit affiliated))
3755 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3756 ;; Keywords.
3757 ((looking-at "[ \t]*#")
3758 (goto-char (match-end 0))
3759 (cond ((looking-at "\\(?: \\|$\\)")
3760 (beginning-of-line)
3761 (org-element-comment-parser limit affiliated))
3762 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3763 (beginning-of-line)
3764 (let ((parser (assoc (upcase (match-string 1))
3765 org-element-block-name-alist)))
3766 (if parser (funcall (cdr parser) limit affiliated)
3767 (org-element-special-block-parser limit affiliated))))
3768 ((looking-at "\\+CALL:")
3769 (beginning-of-line)
3770 (org-element-babel-call-parser limit affiliated))
3771 ((looking-at "\\+BEGIN:? ")
3772 (beginning-of-line)
3773 (org-element-dynamic-block-parser limit affiliated))
3774 ((looking-at "\\+\\S-+:")
3775 (beginning-of-line)
3776 (org-element-keyword-parser limit affiliated))
3778 (beginning-of-line)
3779 (org-element-paragraph-parser limit affiliated))))
3780 ;; Footnote Definition.
3781 ((looking-at org-footnote-definition-re)
3782 (org-element-footnote-definition-parser limit affiliated))
3783 ;; Horizontal Rule.
3784 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3785 (org-element-horizontal-rule-parser limit affiliated))
3786 ;; Diary Sexp.
3787 ((looking-at "%%(")
3788 (org-element-diary-sexp-parser limit affiliated))
3789 ;; Table.
3790 ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
3791 (org-element-table-parser limit affiliated))
3792 ;; List.
3793 ((looking-at (org-item-re))
3794 (org-element-plain-list-parser
3795 limit affiliated
3796 (or structure (org-element--list-struct limit))))
3797 ;; Default element: Paragraph.
3798 (t (org-element-paragraph-parser limit affiliated)))))))))
3801 ;; Most elements can have affiliated keywords. When looking for an
3802 ;; element beginning, we want to move before them, as they belong to
3803 ;; that element, and, in the meantime, collect information they give
3804 ;; into appropriate properties. Hence the following function.
3806 (defun org-element--collect-affiliated-keywords (limit)
3807 "Collect affiliated keywords from point down to LIMIT.
3809 Return a list whose CAR is the position at the first of them and
3810 CDR a plist of keywords and values and move point to the
3811 beginning of the first line after them.
3813 As a special case, if element doesn't start at the beginning of
3814 the line (e.g., a paragraph starting an item), CAR is current
3815 position of point and CDR is nil."
3816 (if (not (bolp)) (list (point))
3817 (let ((case-fold-search t)
3818 (origin (point))
3819 ;; RESTRICT is the list of objects allowed in parsed
3820 ;; keywords value.
3821 (restrict (org-element-restriction 'keyword))
3822 output)
3823 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3824 (let* ((raw-kwd (upcase (match-string 1)))
3825 ;; Apply translation to RAW-KWD. From there, KWD is
3826 ;; the official keyword.
3827 (kwd (or (cdr (assoc raw-kwd
3828 org-element-keyword-translation-alist))
3829 raw-kwd))
3830 ;; Find main value for any keyword.
3831 (value
3832 (save-match-data
3833 (org-trim
3834 (buffer-substring-no-properties
3835 (match-end 0) (line-end-position)))))
3836 ;; PARSEDP is non-nil when keyword should have its
3837 ;; value parsed.
3838 (parsedp (member kwd org-element-parsed-keywords))
3839 ;; If KWD is a dual keyword, find its secondary
3840 ;; value. Maybe parse it.
3841 (dualp (member kwd org-element-dual-keywords))
3842 (dual-value
3843 (and dualp
3844 (let ((sec (org-match-string-no-properties 2)))
3845 (if (or (not sec) (not parsedp)) sec
3846 (org-element--parse-objects
3847 (match-beginning 2) (match-end 2) nil restrict)))))
3848 ;; Attribute a property name to KWD.
3849 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3850 ;; Now set final shape for VALUE.
3851 (when parsedp
3852 (setq value
3853 (org-element--parse-objects
3854 (match-end 0)
3855 (progn (end-of-line) (skip-chars-backward " \t") (point))
3856 nil restrict)))
3857 (when dualp
3858 (setq value (and (or value dual-value) (cons value dual-value))))
3859 (when (or (member kwd org-element-multiple-keywords)
3860 ;; Attributes can always appear on multiple lines.
3861 (string-match "^ATTR_" kwd))
3862 (setq value (cons value (plist-get output kwd-sym))))
3863 ;; Eventually store the new value in OUTPUT.
3864 (setq output (plist-put output kwd-sym value))
3865 ;; Move to next keyword.
3866 (forward-line)))
3867 ;; If affiliated keywords are orphaned: move back to first one.
3868 ;; They will be parsed as a paragraph.
3869 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3870 ;; Return value.
3871 (cons origin output))))
3875 ;;; The Org Parser
3877 ;; The two major functions here are `org-element-parse-buffer', which
3878 ;; parses Org syntax inside the current buffer, taking into account
3879 ;; region, narrowing, or even visibility if specified, and
3880 ;; `org-element-parse-secondary-string', which parses objects within
3881 ;; a given string.
3883 ;; The (almost) almighty `org-element-map' allows to apply a function
3884 ;; on elements or objects matching some type, and accumulate the
3885 ;; resulting values. In an export situation, it also skips unneeded
3886 ;; parts of the parse tree.
3888 (defun org-element-parse-buffer (&optional granularity visible-only)
3889 "Recursively parse the buffer and return structure.
3890 If narrowing is in effect, only parse the visible part of the
3891 buffer.
3893 Optional argument GRANULARITY determines the depth of the
3894 recursion. It can be set to the following symbols:
3896 `headline' Only parse headlines.
3897 `greater-element' Don't recurse into greater elements excepted
3898 headlines and sections. Thus, elements
3899 parsed are the top-level ones.
3900 `element' Parse everything but objects and plain text.
3901 `object' Parse the complete buffer (default).
3903 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3904 elements.
3906 An element or an objects is represented as a list with the
3907 pattern (TYPE PROPERTIES CONTENTS), where :
3909 TYPE is a symbol describing the element or object. See
3910 `org-element-all-elements' and `org-element-all-objects' for an
3911 exhaustive list of such symbols. One can retrieve it with
3912 `org-element-type' function.
3914 PROPERTIES is the list of attributes attached to the element or
3915 object, as a plist. Although most of them are specific to the
3916 element or object type, all types share `:begin', `:end',
3917 `:post-blank' and `:parent' properties, which respectively
3918 refer to buffer position where the element or object starts,
3919 ends, the number of white spaces or blank lines after it, and
3920 the element or object containing it. Properties values can be
3921 obtained by using `org-element-property' function.
3923 CONTENTS is a list of elements, objects or raw strings
3924 contained in the current element or object, when applicable.
3925 One can access them with `org-element-contents' function.
3927 The Org buffer has `org-data' as type and nil as properties.
3928 `org-element-map' function can be used to find specific elements
3929 or objects within the parse tree.
3931 This function assumes that current major mode is `org-mode'."
3932 (save-excursion
3933 (goto-char (point-min))
3934 (org-skip-whitespace)
3935 (org-element--parse-elements
3936 (point-at-bol) (point-max)
3937 ;; Start in `first-section' mode so text before the first
3938 ;; headline belongs to a section.
3939 'first-section nil granularity visible-only (list 'org-data nil))))
3941 (defun org-element-parse-secondary-string (string restriction &optional parent)
3942 "Recursively parse objects in STRING and return structure.
3944 RESTRICTION is a symbol limiting the object types that will be
3945 looked after.
3947 Optional argument PARENT, when non-nil, is the element or object
3948 containing the secondary string. It is used to set correctly
3949 `:parent' property within the string.
3951 If STRING is the empty string or nil, return nil."
3952 (cond
3953 ((not string) nil)
3954 ((equal string "") nil)
3955 (t (let ((local-variables (buffer-local-variables)))
3956 (with-temp-buffer
3957 (dolist (v local-variables)
3958 (ignore-errors
3959 (if (symbolp v) (makunbound v)
3960 (org-set-local (car v) (cdr v)))))
3961 (insert string)
3962 (restore-buffer-modified-p nil)
3963 (let ((data (org-element--parse-objects
3964 (point-min) (point-max) nil restriction)))
3965 (when parent
3966 (dolist (o data) (org-element-put-property o :parent parent)))
3967 data))))))
3969 (defun org-element-map
3970 (data types fun &optional info first-match no-recursion with-affiliated)
3971 "Map a function on selected elements or objects.
3973 DATA is a parse tree, an element, an object, a string, or a list
3974 of such constructs. TYPES is a symbol or list of symbols of
3975 elements or objects types (see `org-element-all-elements' and
3976 `org-element-all-objects' for a complete list of types). FUN is
3977 the function called on the matching element or object. It has to
3978 accept one argument: the element or object itself.
3980 When optional argument INFO is non-nil, it should be a plist
3981 holding export options. In that case, parts of the parse tree
3982 not exportable according to that property list will be skipped.
3984 When optional argument FIRST-MATCH is non-nil, stop at the first
3985 match for which FUN doesn't return nil, and return that value.
3987 Optional argument NO-RECURSION is a symbol or a list of symbols
3988 representing elements or objects types. `org-element-map' won't
3989 enter any recursive element or object whose type belongs to that
3990 list. Though, FUN can still be applied on them.
3992 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3993 apply to matching objects within parsed affiliated keywords (see
3994 `org-element-parsed-keywords').
3996 Nil values returned from FUN do not appear in the results.
3999 Examples:
4000 ---------
4002 Assuming TREE is a variable containing an Org buffer parse tree,
4003 the following example will return a flat list of all `src-block'
4004 and `example-block' elements in it:
4006 \(org-element-map tree '(example-block src-block) #'identity)
4008 The following snippet will find the first headline with a level
4009 of 1 and a \"phone\" tag, and will return its beginning position:
4011 \(org-element-map tree 'headline
4012 \(lambda (hl)
4013 \(and (= (org-element-property :level hl) 1)
4014 \(member \"phone\" (org-element-property :tags hl))
4015 \(org-element-property :begin hl)))
4016 nil t)
4018 The next example will return a flat list of all `plain-list' type
4019 elements in TREE that are not a sub-list themselves:
4021 \(org-element-map tree 'plain-list #'identity nil nil 'plain-list)
4023 Eventually, this example will return a flat list of all `bold'
4024 type objects containing a `latex-snippet' type object, even
4025 looking into captions:
4027 \(org-element-map tree 'bold
4028 \(lambda (b)
4029 \(and (org-element-map b 'latex-snippet #'identity nil t) b))
4030 nil nil nil t)"
4031 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4032 (let* ((types (if (listp types) types (list types)))
4033 (no-recursion (if (listp no-recursion) no-recursion
4034 (list no-recursion)))
4035 ;; Recursion depth is determined by --CATEGORY.
4036 (--category
4037 (catch 'found
4038 (let ((category 'greater-elements)
4039 (all-objects (cons 'plain-text org-element-all-objects)))
4040 (dolist (type types category)
4041 (cond ((memq type all-objects)
4042 ;; If one object is found, the function has to
4043 ;; recurse into every object.
4044 (throw 'found 'objects))
4045 ((not (memq type org-element-greater-elements))
4046 ;; If one regular element is found, the
4047 ;; function has to recurse, at least, into
4048 ;; every element it encounters.
4049 (and (not (eq category 'elements))
4050 (setq category 'elements))))))))
4051 --acc
4052 --walk-tree
4053 (--walk-tree
4054 (lambda (--data)
4055 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4056 ;; holding contextual information.
4057 (let ((--type (org-element-type --data)))
4058 (cond
4059 ((not --data))
4060 ;; Ignored element in an export context.
4061 ((and info (memq --data (plist-get info :ignore-list))))
4062 ;; List of elements or objects.
4063 ((not --type) (mapc --walk-tree --data))
4064 ;; Unconditionally enter parse trees.
4065 ((eq --type 'org-data)
4066 (mapc --walk-tree (org-element-contents --data)))
4068 ;; Check if TYPE is matching among TYPES. If so,
4069 ;; apply FUN to --DATA and accumulate return value
4070 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4071 (when (memq --type types)
4072 (let ((result (funcall fun --data)))
4073 (cond ((not result))
4074 (first-match (throw '--map-first-match result))
4075 (t (push result --acc)))))
4076 ;; If --DATA has a secondary string that can contain
4077 ;; objects with their type among TYPES, look into it.
4078 (when (and (eq --category 'objects) (not (stringp --data)))
4079 (dolist (p (cdr (assq --type
4080 org-element-secondary-value-alist)))
4081 (funcall --walk-tree (org-element-property p --data))))
4082 ;; If --DATA has any parsed affiliated keywords and
4083 ;; WITH-AFFILIATED is non-nil, look for objects in
4084 ;; them.
4085 (when (and with-affiliated
4086 (eq --category 'objects)
4087 (memq --type org-element-all-elements))
4088 (dolist (kwd-pair org-element--parsed-properties-alist)
4089 (let ((kwd (car kwd-pair))
4090 (value (org-element-property (cdr kwd-pair) --data)))
4091 ;; Pay attention to the type of parsed keyword.
4092 ;; In particular, preserve order for multiple
4093 ;; keywords.
4094 (cond
4095 ((not value))
4096 ((member kwd org-element-dual-keywords)
4097 (if (member kwd org-element-multiple-keywords)
4098 (dolist (line (reverse value))
4099 (funcall --walk-tree (cdr line))
4100 (funcall --walk-tree (car line)))
4101 (funcall --walk-tree (cdr value))
4102 (funcall --walk-tree (car value))))
4103 ((member kwd org-element-multiple-keywords)
4104 (mapc --walk-tree (reverse value)))
4105 (t (funcall --walk-tree value))))))
4106 ;; Determine if a recursion into --DATA is possible.
4107 (cond
4108 ;; --TYPE is explicitly removed from recursion.
4109 ((memq --type no-recursion))
4110 ;; --DATA has no contents.
4111 ((not (org-element-contents --data)))
4112 ;; Looking for greater elements but --DATA is simply
4113 ;; an element or an object.
4114 ((and (eq --category 'greater-elements)
4115 (not (memq --type org-element-greater-elements))))
4116 ;; Looking for elements but --DATA is an object.
4117 ((and (eq --category 'elements)
4118 (memq --type org-element-all-objects)))
4119 ;; In any other case, map contents.
4120 (t (mapc --walk-tree (org-element-contents --data))))))))))
4121 (catch '--map-first-match
4122 (funcall --walk-tree data)
4123 ;; Return value in a proper order.
4124 (nreverse --acc))))
4125 (put 'org-element-map 'lisp-indent-function 2)
4127 ;; The following functions are internal parts of the parser.
4129 ;; The first one, `org-element--parse-elements' acts at the element's
4130 ;; level.
4132 ;; The second one, `org-element--parse-objects' applies on all objects
4133 ;; of a paragraph or a secondary string. It calls
4134 ;; `org-element--object-lex' to find the next object in the current
4135 ;; container.
4137 (defsubst org-element--next-mode (type parentp)
4138 "Return next special mode according to TYPE, or nil.
4139 TYPE is a symbol representing the type of an element or object
4140 containing next element if PARENTP is non-nil, or before it
4141 otherwise. Modes can be either `first-section', `item',
4142 `node-property', `planning', `property-drawer', `section',
4143 `table-row' or nil."
4144 (if parentp
4145 (case type
4146 (headline 'section)
4147 (plain-list 'item)
4148 (property-drawer 'node-property)
4149 (section 'planning)
4150 (table 'table-row))
4151 (case type
4152 (item 'item)
4153 (node-property 'node-property)
4154 (planning 'property-drawer)
4155 (table-row 'table-row))))
4157 (defun org-element--parse-elements
4158 (beg end mode structure granularity visible-only acc)
4159 "Parse elements between BEG and END positions.
4161 MODE prioritizes some elements over the others. It can be set to
4162 `first-section', `section', `planning', `item', `node-property'
4163 or `table-row'.
4165 When value is `item', STRUCTURE will be used as the current list
4166 structure.
4168 GRANULARITY determines the depth of the recursion. See
4169 `org-element-parse-buffer' for more information.
4171 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4172 elements.
4174 Elements are accumulated into ACC."
4175 (save-excursion
4176 (goto-char beg)
4177 ;; Visible only: skip invisible parts at the beginning of the
4178 ;; element.
4179 (when (and visible-only (org-invisible-p2))
4180 (goto-char (min (1+ (org-find-visible)) end)))
4181 ;; When parsing only headlines, skip any text before first one.
4182 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4183 (org-with-limited-levels (outline-next-heading)))
4184 ;; Main loop start.
4185 (while (< (point) end)
4186 ;; Find current element's type and parse it accordingly to
4187 ;; its category.
4188 (let* ((element (org-element--current-element
4189 end granularity mode structure))
4190 (type (org-element-type element))
4191 (cbeg (org-element-property :contents-begin element)))
4192 (goto-char (org-element-property :end element))
4193 ;; Visible only: skip invisible parts between siblings.
4194 (when (and visible-only (org-invisible-p2))
4195 (goto-char (min (1+ (org-find-visible)) end)))
4196 ;; Fill ELEMENT contents by side-effect.
4197 (cond
4198 ;; If element has no contents, don't modify it.
4199 ((not cbeg))
4200 ;; Greater element: parse it between `contents-begin' and
4201 ;; `contents-end'. Make sure GRANULARITY allows the
4202 ;; recursion, or ELEMENT is a headline, in which case going
4203 ;; inside is mandatory, in order to get sub-level headings.
4204 ((and (memq type org-element-greater-elements)
4205 (or (memq granularity '(element object nil))
4206 (and (eq granularity 'greater-element)
4207 (eq type 'section))
4208 (eq type 'headline)))
4209 (org-element--parse-elements
4210 cbeg (org-element-property :contents-end element)
4211 ;; Possibly switch to a special mode.
4212 (org-element--next-mode type t)
4213 (and (memq type '(item plain-list))
4214 (org-element-property :structure element))
4215 granularity visible-only element))
4216 ;; ELEMENT has contents. Parse objects inside, if
4217 ;; GRANULARITY allows it.
4218 ((memq granularity '(object nil))
4219 (org-element--parse-objects
4220 cbeg (org-element-property :contents-end element) element
4221 (org-element-restriction type))))
4222 (org-element-adopt-elements acc element)
4223 ;; Update mode.
4224 (setq mode (org-element--next-mode type nil))))
4225 ;; Return result.
4226 acc))
4228 (defun org-element--object-lex (restriction)
4229 "Return next object in current buffer or nil.
4230 RESTRICTION is a list of object types, as symbols, that should be
4231 looked after. This function assumes that the buffer is narrowed
4232 to an appropriate container (e.g., a paragraph)."
4233 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4234 (save-excursion
4235 (let ((limit (and org-target-link-regexp
4236 (save-excursion
4237 (or (bolp) (backward-char))
4238 (re-search-forward org-target-link-regexp nil t))
4239 (match-beginning 1)))
4240 found)
4241 (while (and (not found)
4242 (re-search-forward org-element--object-regexp limit t))
4243 (goto-char (match-beginning 0))
4244 (let ((result (match-string 0)))
4245 (setq found
4246 (cond
4247 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4248 (and (memq 'inline-babel-call restriction)
4249 (org-element-inline-babel-call-parser)))
4250 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4251 (and (memq 'inline-src-block restriction)
4252 (org-element-inline-src-block-parser)))
4254 (case (char-after)
4255 (?^ (and (memq 'superscript restriction)
4256 (org-element-superscript-parser)))
4257 (?_ (or (and (memq 'subscript restriction)
4258 (org-element-subscript-parser))
4259 (and (memq 'underline restriction)
4260 (org-element-underline-parser))))
4261 (?* (and (memq 'bold restriction)
4262 (org-element-bold-parser)))
4263 (?/ (and (memq 'italic restriction)
4264 (org-element-italic-parser)))
4265 (?~ (and (memq 'code restriction)
4266 (org-element-code-parser)))
4267 (?= (and (memq 'verbatim restriction)
4268 (org-element-verbatim-parser)))
4269 (?+ (and (memq 'strike-through restriction)
4270 (org-element-strike-through-parser)))
4271 (?@ (and (memq 'export-snippet restriction)
4272 (org-element-export-snippet-parser)))
4273 (?{ (and (memq 'macro restriction)
4274 (org-element-macro-parser)))
4275 (?$ (and (memq 'latex-fragment restriction)
4276 (org-element-latex-fragment-parser)))
4278 (if (eq (aref result 1) ?<)
4279 (or (and (memq 'radio-target restriction)
4280 (org-element-radio-target-parser))
4281 (and (memq 'target restriction)
4282 (org-element-target-parser)))
4283 (or (and (memq 'timestamp restriction)
4284 (org-element-timestamp-parser))
4285 (and (memq 'link restriction)
4286 (org-element-link-parser)))))
4287 (?\\
4288 (if (eq (aref result 1) ?\\)
4289 (and (memq 'line-break restriction)
4290 (org-element-line-break-parser))
4291 (or (and (memq 'entity restriction)
4292 (org-element-entity-parser))
4293 (and (memq 'latex-fragment restriction)
4294 (org-element-latex-fragment-parser)))))
4295 (?\[
4296 (if (eq (aref result 1) ?\[)
4297 (and (memq 'link restriction)
4298 (org-element-link-parser))
4299 (or (and (memq 'footnote-reference restriction)
4300 (org-element-footnote-reference-parser))
4301 (and (memq 'timestamp restriction)
4302 (org-element-timestamp-parser))
4303 (and (memq 'statistics-cookie restriction)
4304 (org-element-statistics-cookie-parser)))))
4305 ;; This is probably a plain link.
4306 (otherwise (and (or (memq 'link restriction)
4307 (memq 'plain-link restriction))
4308 (org-element-link-parser)))))))
4309 (or (eobp) (forward-char))))
4310 (cond (found)
4311 ;; Radio link.
4312 ((and limit (memq 'link restriction))
4313 (goto-char limit) (org-element-link-parser)))))))
4315 (defun org-element--parse-objects (beg end acc restriction)
4316 "Parse objects between BEG and END and return recursive structure.
4318 Objects are accumulated in ACC.
4320 RESTRICTION is a list of object successors which are allowed in
4321 the current object."
4322 (save-excursion
4323 (save-restriction
4324 (narrow-to-region beg end)
4325 (goto-char (point-min))
4326 (let (next-object)
4327 (while (and (not (eobp))
4328 (setq next-object (org-element--object-lex restriction)))
4329 ;; 1. Text before any object. Untabify it.
4330 (let ((obj-beg (org-element-property :begin next-object)))
4331 (unless (= (point) obj-beg)
4332 (setq acc
4333 (org-element-adopt-elements
4335 (replace-regexp-in-string
4336 "\t" (make-string tab-width ? )
4337 (buffer-substring-no-properties (point) obj-beg))))))
4338 ;; 2. Object...
4339 (let ((obj-end (org-element-property :end next-object))
4340 (cont-beg (org-element-property :contents-begin next-object)))
4341 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4342 ;; a recursive type.
4343 (when (and cont-beg
4344 (memq (car next-object) org-element-recursive-objects))
4345 (org-element--parse-objects
4346 cont-beg (org-element-property :contents-end next-object)
4347 next-object (org-element-restriction next-object)))
4348 (setq acc (org-element-adopt-elements acc next-object))
4349 (goto-char obj-end))))
4350 ;; 3. Text after last object. Untabify it.
4351 (unless (eobp)
4352 (setq acc
4353 (org-element-adopt-elements
4355 (replace-regexp-in-string
4356 "\t" (make-string tab-width ? )
4357 (buffer-substring-no-properties (point) end)))))
4358 ;; Result.
4359 acc)))
4363 ;;; Towards A Bijective Process
4365 ;; The parse tree obtained with `org-element-parse-buffer' is really
4366 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4367 ;; interpreted and expanded into a string with canonical Org syntax.
4368 ;; Hence `org-element-interpret-data'.
4370 ;; The function relies internally on
4371 ;; `org-element--interpret-affiliated-keywords'.
4373 ;;;###autoload
4374 (defun org-element-interpret-data (data)
4375 "Interpret DATA as Org syntax.
4376 DATA is a parse tree, an element, an object or a secondary string
4377 to interpret. Return Org syntax as a string."
4378 (org-element--interpret-data-1 data nil))
4380 (defun org-element--interpret-data-1 (data parent)
4381 "Interpret DATA as Org syntax.
4383 DATA is a parse tree, an element, an object or a secondary string
4384 to interpret. PARENT is used for recursive calls. It contains
4385 the element or object containing data, or nil.
4387 Return Org syntax as a string."
4388 (let* ((type (org-element-type data))
4389 ;; Find interpreter for current object or element. If it
4390 ;; doesn't exist (e.g. this is a pseudo object or element),
4391 ;; return contents, if any.
4392 (interpret
4393 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4394 (if (fboundp fun) fun (lambda (data contents) contents))))
4395 (results
4396 (cond
4397 ;; Secondary string.
4398 ((not type)
4399 (mapconcat
4400 (lambda (obj) (org-element--interpret-data-1 obj parent)) data ""))
4401 ;; Full Org document.
4402 ((eq type 'org-data)
4403 (mapconcat (lambda (obj) (org-element--interpret-data-1 obj parent))
4404 (org-element-contents data) ""))
4405 ;; Plain text: return it.
4406 ((stringp data) data)
4407 ;; Element or object without contents.
4408 ((not (org-element-contents data)) (funcall interpret data nil))
4409 ;; Element or object with contents.
4411 (funcall interpret data
4412 ;; Recursively interpret contents.
4413 (mapconcat
4414 (lambda (obj) (org-element--interpret-data-1 obj data))
4415 (org-element-contents
4416 (if (not (memq type '(paragraph verse-block)))
4417 data
4418 ;; Fix indentation of elements containing
4419 ;; objects. We ignore `table-row' elements
4420 ;; as they are one line long anyway.
4421 (org-element-normalize-contents
4422 data
4423 ;; When normalizing first paragraph of an
4424 ;; item or a footnote-definition, ignore
4425 ;; first line's indentation.
4426 (and (eq type 'paragraph)
4427 (equal data (car (org-element-contents parent)))
4428 (memq (org-element-type parent)
4429 '(footnote-definition item))))))
4430 ""))))))
4431 (if (memq type '(org-data plain-text nil)) results
4432 ;; Build white spaces. If no `:post-blank' property is
4433 ;; specified, assume its value is 0.
4434 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4435 (if (or (memq type org-element-all-objects)
4436 (and parent
4437 (let ((type (org-element-type parent)))
4438 (or (not type)
4439 (memq type org-element-object-containers)))))
4440 (concat results (make-string post-blank ?\s))
4441 (concat
4442 (org-element--interpret-affiliated-keywords data)
4443 (org-element-normalize-string results)
4444 (make-string post-blank ?\n)))))))
4446 (defun org-element--interpret-affiliated-keywords (element)
4447 "Return ELEMENT's affiliated keywords as Org syntax.
4448 If there is no affiliated keyword, return the empty string."
4449 (let ((keyword-to-org
4450 (function
4451 (lambda (key value)
4452 (let (dual)
4453 (when (member key org-element-dual-keywords)
4454 (setq dual (cdr value) value (car value)))
4455 (concat "#+" key
4456 (and dual
4457 (format "[%s]" (org-element-interpret-data dual)))
4458 ": "
4459 (if (member key org-element-parsed-keywords)
4460 (org-element-interpret-data value)
4461 value)
4462 "\n"))))))
4463 (mapconcat
4464 (lambda (prop)
4465 (let ((value (org-element-property prop element))
4466 (keyword (upcase (substring (symbol-name prop) 1))))
4467 (when value
4468 (if (or (member keyword org-element-multiple-keywords)
4469 ;; All attribute keywords can have multiple lines.
4470 (string-match "^ATTR_" keyword))
4471 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4472 (reverse value)
4474 (funcall keyword-to-org keyword value)))))
4475 ;; List all ELEMENT's properties matching an attribute line or an
4476 ;; affiliated keyword, but ignore translated keywords since they
4477 ;; cannot belong to the property list.
4478 (loop for prop in (nth 1 element) by 'cddr
4479 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4480 (or (string-match "^ATTR_" keyword)
4481 (and
4482 (member keyword org-element-affiliated-keywords)
4483 (not (assoc keyword
4484 org-element-keyword-translation-alist)))))
4485 collect prop)
4486 "")))
4488 ;; Because interpretation of the parse tree must return the same
4489 ;; number of blank lines between elements and the same number of white
4490 ;; space after objects, some special care must be given to white
4491 ;; spaces.
4493 ;; The first function, `org-element-normalize-string', ensures any
4494 ;; string different from the empty string will end with a single
4495 ;; newline character.
4497 ;; The second function, `org-element-normalize-contents', removes
4498 ;; global indentation from the contents of the current element.
4500 (defun org-element-normalize-string (s)
4501 "Ensure string S ends with a single newline character.
4503 If S isn't a string return it unchanged. If S is the empty
4504 string, return it. Otherwise, return a new string with a single
4505 newline character at its end."
4506 (cond
4507 ((not (stringp s)) s)
4508 ((string= "" s) "")
4509 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4510 (replace-match "\n" nil nil s)))))
4512 (defun org-element-normalize-contents (element &optional ignore-first)
4513 "Normalize plain text in ELEMENT's contents.
4515 ELEMENT must only contain plain text and objects.
4517 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4518 indentation to compute maximal common indentation.
4520 Return the normalized element that is element with global
4521 indentation removed from its contents. The function assumes that
4522 indentation is not done with TAB characters."
4523 (let* ((min-ind most-positive-fixnum)
4524 find-min-ind ; For byte-compiler.
4525 (find-min-ind
4526 ;; Return minimal common indentation within BLOB. This is
4527 ;; done by walking recursively BLOB and updating MIN-IND
4528 ;; along the way. FIRST-FLAG is non-nil when the next
4529 ;; object is expected to be a string that doesn't start with
4530 ;; a newline character. It happens for strings at the
4531 ;; beginnings of the contents or right after a line break.
4532 (lambda (blob first-flag)
4533 (dolist (object (org-element-contents blob))
4534 (when first-flag
4535 (setq first-flag nil)
4536 ;; Objects cannot start with spaces: in this case,
4537 ;; indentation is 0.
4538 (if (not (stringp object)) (throw 'zero (setq min-ind 0))
4539 (string-match "\\` *" object)
4540 (let ((len (match-end 0)))
4541 ;; An indentation of zero means no string will be
4542 ;; modified. Quit the process.
4543 (if (zerop len) (throw 'zero (setq min-ind 0))
4544 (setq min-ind (min len min-ind))))))
4545 (cond
4546 ((stringp object)
4547 (dolist (line (cdr (org-split-string object " *\n")))
4548 (unless (string= line "")
4549 (setq min-ind (min (org-get-indentation line) min-ind)))))
4550 ((eq (org-element-type object) 'line-break) (setq first-flag t))
4551 ((memq (org-element-type object) org-element-recursive-objects)
4552 (funcall find-min-ind object first-flag)))))))
4553 ;; Find minimal indentation in ELEMENT.
4554 (catch 'zero (funcall find-min-ind element (not ignore-first)))
4555 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4556 ;; Build ELEMENT back, replacing each string with the same
4557 ;; string minus common indentation.
4558 (let* (build ; For byte compiler.
4559 (build
4560 (lambda (blob first-flag)
4561 ;; Return BLOB with all its strings indentation
4562 ;; shortened from MIN-IND white spaces. FIRST-FLAG is
4563 ;; non-nil when the next object is expected to be
4564 ;; a string that doesn't start with a newline
4565 ;; character.
4566 (setcdr (cdr blob)
4567 (mapcar
4568 (lambda (object)
4569 (when first-flag
4570 (setq first-flag nil)
4571 (when (stringp object)
4572 (setq object
4573 (replace-regexp-in-string
4574 (format "\\` \\{%d\\}" min-ind)
4575 "" object))))
4576 (cond
4577 ((stringp object)
4578 (replace-regexp-in-string
4579 (format "\n \\{%d\\}" min-ind) "\n" object))
4580 ((memq (org-element-type object)
4581 org-element-recursive-objects)
4582 (funcall build object first-flag))
4583 ((eq (org-element-type object) 'line-break)
4584 (setq first-flag t)
4585 object)
4586 (t object)))
4587 (org-element-contents blob)))
4588 blob)))
4589 (funcall build element (not ignore-first))))))
4593 ;;; Cache
4595 ;; Implement a caching mechanism for `org-element-at-point' and
4596 ;; `org-element-context', which see.
4598 ;; A single public function is provided: `org-element-cache-reset'.
4600 ;; Cache is enabled by default, but can be disabled globally with
4601 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4602 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4603 ;; can be tweaked to control caching behaviour.
4605 ;; Internally, parsed elements are stored in an AVL tree,
4606 ;; `org-element--cache'. This tree is updated lazily: whenever
4607 ;; a change happens to the buffer, a synchronization request is
4608 ;; registered in `org-element--cache-sync-requests' (see
4609 ;; `org-element--cache-submit-request'). During idle time, requests
4610 ;; are processed by `org-element--cache-sync'. Synchronization also
4611 ;; happens when an element is required from the cache. In this case,
4612 ;; the process stops as soon as the needed element is up-to-date.
4614 ;; A synchronization request can only apply on a synchronized part of
4615 ;; the cache. Therefore, the cache is updated at least to the
4616 ;; location where the new request applies. Thus, requests are ordered
4617 ;; from left to right and all elements starting before the first
4618 ;; request are correct. This property is used by functions like
4619 ;; `org-element--cache-find' to retrieve elements in the part of the
4620 ;; cache that can be trusted.
4622 ;; A request applies to every element, starting from its original
4623 ;; location (or key, see below). When a request is processed, it
4624 ;; moves forward and may collide the next one. In this case, both
4625 ;; requests are merged into a new one that starts from that element.
4626 ;; As a consequence, the whole synchronization complexity does not
4627 ;; depend on the number of pending requests, but on the number of
4628 ;; elements the very first request will be applied on.
4630 ;; Elements cannot be accessed through their beginning position, which
4631 ;; may or may not be up-to-date. Instead, each element in the tree is
4632 ;; associated to a key, obtained with `org-element--cache-key'. This
4633 ;; mechanism is robust enough to preserve total order among elements
4634 ;; even when the tree is only partially synchronized.
4636 ;; Objects contained in an element are stored in a hash table,
4637 ;; `org-element--cache-objects'.
4640 (defvar org-element-use-cache t
4641 "Non nil when Org parser should cache its results.
4642 This is mostly for debugging purpose.")
4644 (defvar org-element-cache-sync-idle-time 0.6
4645 "Length, in seconds, of idle time before syncing cache.")
4647 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4648 "Maximum duration, as a time value, for a cache synchronization.
4649 If the synchronization is not over after this delay, the process
4650 pauses and resumes after `org-element-cache-sync-break'
4651 seconds.")
4653 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4654 "Duration, as a time value, of the pause between synchronizations.
4655 See `org-element-cache-sync-duration' for more information.")
4658 ;;;; Data Structure
4660 (defvar org-element--cache nil
4661 "AVL tree used to cache elements.
4662 Each node of the tree contains an element. Comparison is done
4663 with `org-element--cache-compare'. This cache is used in
4664 `org-element-at-point'.")
4666 (defvar org-element--cache-objects nil
4667 "Hash table used as to cache objects.
4668 Key is an element, as returned by `org-element-at-point', and
4669 value is an alist where each association is:
4671 \(PARENT COMPLETEP . OBJECTS)
4673 where PARENT is an element or object, COMPLETEP is a boolean,
4674 non-nil when all direct children of parent are already cached and
4675 OBJECTS is a list of such children, as objects, from farthest to
4676 closest.
4678 In the following example, \\alpha, bold object and \\beta are
4679 contained within a paragraph
4681 \\alpha *\\beta*
4683 If the paragraph is completely parsed, OBJECTS-DATA will be
4685 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4686 \(BOLD-OBJECT t ENTITY-OBJECT))
4688 whereas in a partially parsed paragraph, it could be
4690 \((PARAGRAPH nil ENTITY-OBJECT))
4692 This cache is used in `org-element-context'.")
4694 (defvar org-element--cache-sync-requests nil
4695 "List of pending synchronization requests.
4697 A request is a vector with the following pattern:
4699 \[NEXT BEG END OFFSET PARENT PHASE]
4701 Processing a synchronization request consists of three phases:
4703 0. Delete modified elements,
4704 1. Fill missing area in cache,
4705 2. Shift positions and re-parent elements after the changes.
4707 During phase 0, NEXT is the key of the first element to be
4708 removed, BEG and END is buffer position delimiting the
4709 modifications. Elements starting between them (inclusive) are
4710 removed. So are elements whose parent is removed. PARENT, when
4711 non-nil, is the parent of the first element to be removed.
4713 During phase 1, NEXT is the key of the next known element in
4714 cache and BEG its beginning position. Parse buffer between that
4715 element and the one before it in order to determine the parent of
4716 the next element. Set PARENT to the element containing NEXT.
4718 During phase 2, NEXT is the key of the next element to shift in
4719 the parse tree. All elements starting from this one have their
4720 properties relatives to buffer positions shifted by integer
4721 OFFSET and, if they belong to element PARENT, are adopted by it.
4723 PHASE specifies the phase number, as an integer.")
4725 (defvar org-element--cache-sync-timer nil
4726 "Timer used for cache synchronization.")
4728 (defvar org-element--cache-sync-keys nil
4729 "Hash table used to store keys during synchronization.
4730 See `org-element--cache-key' for more information.")
4732 (defsubst org-element--cache-key (element)
4733 "Return a unique key for ELEMENT in cache tree.
4735 Keys are used to keep a total order among elements in the cache.
4736 Comparison is done with `org-element--cache-key-less-p'.
4738 When no synchronization is taking place, a key is simply the
4739 beginning position of the element, or that position plus one in
4740 the case of an first item (respectively row) in
4741 a list (respectively a table).
4743 During a synchronization, the key is the one the element had when
4744 the cache was synchronized for the last time. Elements added to
4745 cache during the synchronization get a new key generated with
4746 `org-element--cache-generate-key'.
4748 Such keys are stored in `org-element--cache-sync-keys'. The hash
4749 table is cleared once the synchronization is complete."
4750 (or (gethash element org-element--cache-sync-keys)
4751 (let* ((begin (org-element-property :begin element))
4752 ;; Increase beginning position of items (respectively
4753 ;; table rows) by one, so the first item can get
4754 ;; a different key from its parent list (respectively
4755 ;; table).
4756 (key (if (memq (org-element-type element) '(item table-row))
4757 (1+ begin)
4758 begin)))
4759 (if org-element--cache-sync-requests
4760 (puthash element key org-element--cache-sync-keys)
4761 key))))
4763 (defun org-element--cache-generate-key (lower upper)
4764 "Generate a key between LOWER and UPPER.
4766 LOWER and UPPER are integers or lists, possibly empty.
4768 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4769 a unique key, as an integer or a list of integers, according to
4770 the following rules:
4772 - LOWER and UPPER are compared level-wise until values differ.
4774 - If, at a given level, LOWER and UPPER differ from more than
4775 2, the new key shares all the levels above with LOWER and
4776 gets a new level. Its value is the mean between LOWER and
4777 UPPER:
4779 \(1 2) + (1 4) --> (1 3)
4781 - If LOWER has no value to compare with, it is assumed that its
4782 value is `most-negative-fixnum'. E.g.,
4784 \(1 1) + (1 1 2)
4786 is equivalent to
4788 \(1 1 m) + (1 1 2)
4790 where m is `most-negative-fixnum'. Likewise, if UPPER is
4791 short of levels, the current value is `most-positive-fixnum'.
4793 - If they differ from only one, the new key inherits from
4794 current LOWER level and fork it at the next level. E.g.,
4796 \(2 1) + (3 3)
4798 is equivalent to
4800 \(2 1) + (2 M)
4802 where M is `most-positive-fixnum'.
4804 - If the key is only one level long, it is returned as an
4805 integer:
4807 \(1 2) + (3 2) --> 2
4809 When they are not equals, the function assumes that LOWER is
4810 lesser than UPPER, per `org-element--cache-key-less-p'."
4811 (if (equal lower upper) lower
4812 (let ((lower (if (integerp lower) (list lower) lower))
4813 (upper (if (integerp upper) (list upper) upper))
4814 skip-upper key)
4815 (catch 'exit
4816 (while t
4817 (let ((min (or (car lower) most-negative-fixnum))
4818 (max (cond (skip-upper most-positive-fixnum)
4819 ((car upper))
4820 (t most-positive-fixnum))))
4821 (if (< (1+ min) max)
4822 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4823 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4824 (when (and (< min max) (not skip-upper))
4825 ;; When at a given level, LOWER and UPPER differ from
4826 ;; 1, ignore UPPER altogether. Instead create a key
4827 ;; between LOWER and the greatest key with the same
4828 ;; prefix as LOWER so far.
4829 (setq skip-upper t))
4830 (push min key)
4831 (setq lower (cdr lower) upper (cdr upper)))))))))
4833 (defsubst org-element--cache-key-less-p (a b)
4834 "Non-nil if key A is less than key B.
4835 A and B are either integers or lists of integers, as returned by
4836 `org-element--cache-key'."
4837 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4838 (if (integerp b) (< (car a) b)
4839 (catch 'exit
4840 (while (and a b)
4841 (cond ((car-less-than-car a b) (throw 'exit t))
4842 ((car-less-than-car b a) (throw 'exit nil))
4843 (t (setq a (cdr a) b (cdr b)))))
4844 ;; If A is empty, either keys are equal (B is also empty) and
4845 ;; we return nil, or A is lesser than B (B is longer) and we
4846 ;; return a non-nil value.
4848 ;; If A is not empty, B is necessarily empty and A is greater
4849 ;; than B (A is longer). Therefore, return nil.
4850 (and (null a) b)))))
4852 (defun org-element--cache-compare (a b)
4853 "Non-nil when element A is located before element B."
4854 (org-element--cache-key-less-p (org-element--cache-key a)
4855 (org-element--cache-key b)))
4857 (defsubst org-element--cache-root ()
4858 "Return root value in cache.
4859 This function assumes `org-element--cache' is a valid AVL tree."
4860 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4863 ;;;; Tools
4865 (defsubst org-element--cache-active-p ()
4866 "Non-nil when cache is active in current buffer."
4867 (and org-element-use-cache
4868 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4870 (defun org-element--cache-find (pos &optional side)
4871 "Find element in cache starting at POS or before.
4873 POS refers to a buffer position.
4875 When optional argument SIDE is non-nil, the function checks for
4876 elements starting at or past POS instead. If SIDE is `both', the
4877 function returns a cons cell where car is the first element
4878 starting at or before POS and cdr the first element starting
4879 after POS.
4881 The function can only find elements in the synchronized part of
4882 the cache."
4883 (let ((limit (and org-element--cache-sync-requests
4884 (aref (car org-element--cache-sync-requests) 0)))
4885 (node (org-element--cache-root))
4886 lower upper)
4887 (while node
4888 (let* ((element (avl-tree--node-data node))
4889 (begin (org-element-property :begin element)))
4890 (cond
4891 ((and limit
4892 (not (org-element--cache-key-less-p
4893 (org-element--cache-key element) limit)))
4894 (setq node (avl-tree--node-left node)))
4895 ((> begin pos)
4896 (setq upper element
4897 node (avl-tree--node-left node)))
4898 ((< begin pos)
4899 (setq lower element
4900 node (avl-tree--node-right node)))
4901 ;; We found an element in cache starting at POS. If `side'
4902 ;; is `both' we also want the next one in order to generate
4903 ;; a key in-between.
4905 ;; If the element is the first row or item in a table or
4906 ;; a plain list, we always return the table or the plain
4907 ;; list.
4909 ;; In any other case, we return the element found.
4910 ((eq side 'both)
4911 (setq lower element)
4912 (setq node (avl-tree--node-right node)))
4913 ((and (memq (org-element-type element) '(item table-row))
4914 (let ((parent (org-element-property :parent element)))
4915 (and (= (org-element-property :begin element)
4916 (org-element-property :contents-begin parent))
4917 (setq node nil
4918 lower parent
4919 upper parent)))))
4921 (setq node nil
4922 lower element
4923 upper element)))))
4924 (case side
4925 (both (cons lower upper))
4926 ((nil) lower)
4927 (otherwise upper))))
4929 (defun org-element--cache-put (element &optional data)
4930 "Store ELEMENT in current buffer's cache, if allowed.
4931 When optional argument DATA is non-nil, assume is it object data
4932 relative to ELEMENT and store it in the objects cache."
4933 (cond ((not (org-element--cache-active-p)) nil)
4934 ((not data)
4935 (when org-element--cache-sync-requests
4936 ;; During synchronization, first build an appropriate key
4937 ;; for the new element so `avl-tree-enter' can insert it at
4938 ;; the right spot in the cache.
4939 (let ((keys (org-element--cache-find
4940 (org-element-property :begin element) 'both)))
4941 (puthash element
4942 (org-element--cache-generate-key
4943 (and (car keys) (org-element--cache-key (car keys)))
4944 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4945 (org-element--cache-sync-requests
4946 (aref (car org-element--cache-sync-requests) 0))))
4947 org-element--cache-sync-keys)))
4948 (avl-tree-enter org-element--cache element))
4949 ;; Headlines are not stored in cache, so objects in titles are
4950 ;; not stored either.
4951 ((eq (org-element-type element) 'headline) nil)
4952 (t (puthash element data org-element--cache-objects))))
4954 (defsubst org-element--cache-remove (element)
4955 "Remove ELEMENT from cache.
4956 Assume ELEMENT belongs to cache and that a cache is active."
4957 (avl-tree-delete org-element--cache element)
4958 (remhash element org-element--cache-objects))
4961 ;;;; Synchronization
4963 (defsubst org-element--cache-set-timer (buffer)
4964 "Set idle timer for cache synchronization in BUFFER."
4965 (when org-element--cache-sync-timer
4966 (cancel-timer org-element--cache-sync-timer))
4967 (setq org-element--cache-sync-timer
4968 (run-with-idle-timer
4969 (let ((idle (current-idle-time)))
4970 (if idle (time-add idle org-element-cache-sync-break)
4971 org-element-cache-sync-idle-time))
4973 #'org-element--cache-sync
4974 buffer)))
4976 (defsubst org-element--cache-interrupt-p (time-limit)
4977 "Non-nil when synchronization process should be interrupted.
4978 TIME-LIMIT is a time value or nil."
4979 (and time-limit
4980 (or (input-pending-p)
4981 (time-less-p time-limit (current-time)))))
4983 (defsubst org-element--cache-shift-positions (element offset &optional props)
4984 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4986 Properties containing buffer positions are `:begin', `:end',
4987 `:contents-begin', `:contents-end' and `:structure'. When
4988 optional argument PROPS is a list of keywords, only shift
4989 properties provided in that list.
4991 Properties are modified by side-effect."
4992 (let ((properties (nth 1 element)))
4993 ;; Shift `:structure' property for the first plain list only: it
4994 ;; is the only one that really matters and it prevents from
4995 ;; shifting it more than once.
4996 (when (and (or (not props) (memq :structure props))
4997 (eq (org-element-type element) 'plain-list)
4998 (not (eq (org-element-type (plist-get properties :parent))
4999 'item)))
5000 (dolist (item (plist-get properties :structure))
5001 (incf (car item) offset)
5002 (incf (nth 6 item) offset)))
5003 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5004 (let ((value (and (or (not props) (memq key props))
5005 (plist-get properties key))))
5006 (and value (plist-put properties key (+ offset value)))))))
5008 (defun org-element--cache-sync (buffer &optional threshold future-change)
5009 "Synchronize cache with recent modification in BUFFER.
5011 When optional argument THRESHOLD is non-nil, do the
5012 synchronization for all elements starting before or at threshold,
5013 then exit. Otherwise, synchronize cache for as long as
5014 `org-element-cache-sync-duration' or until Emacs leaves idle
5015 state.
5017 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5018 not registered yet in the cache are going to happen. It is used
5019 in `org-element--cache-submit-request', where cache is partially
5020 updated before current modification are actually submitted."
5021 (when (buffer-live-p buffer)
5022 (with-current-buffer buffer
5023 (let ((inhibit-quit t) request next)
5024 (when org-element--cache-sync-timer
5025 (cancel-timer org-element--cache-sync-timer))
5026 (catch 'interrupt
5027 (while org-element--cache-sync-requests
5028 (setq request (car org-element--cache-sync-requests)
5029 next (nth 1 org-element--cache-sync-requests))
5030 (org-element--cache-process-request
5031 request
5032 (and next (aref next 0))
5033 threshold
5034 (and (not threshold)
5035 (time-add (current-time)
5036 org-element-cache-sync-duration))
5037 future-change)
5038 ;; Request processed. Merge current and next offsets and
5039 ;; transfer ending position.
5040 (when next
5041 (incf (aref next 3) (aref request 3))
5042 (aset next 2 (aref request 2)))
5043 (setq org-element--cache-sync-requests
5044 (cdr org-element--cache-sync-requests))))
5045 ;; If more requests are awaiting, set idle timer accordingly.
5046 ;; Otherwise, reset keys.
5047 (if org-element--cache-sync-requests
5048 (org-element--cache-set-timer buffer)
5049 (clrhash org-element--cache-sync-keys))))))
5051 (defun org-element--cache-process-request
5052 (request next threshold time-limit future-change)
5053 "Process synchronization REQUEST for all entries before NEXT.
5055 REQUEST is a vector, built by `org-element--cache-submit-request'.
5057 NEXT is a cache key, as returned by `org-element--cache-key'.
5059 When non-nil, THRESHOLD is a buffer position. Synchronization
5060 stops as soon as a shifted element begins after it.
5062 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5063 after this time or when Emacs exits idle state.
5065 When non-nil, FUTURE-CHANGE is a buffer position where changes
5066 not registered yet in the cache are going to happen. See
5067 `org-element--cache-submit-request' for more information.
5069 Throw `interrupt' if the process stops before completing the
5070 request."
5071 (catch 'quit
5072 (when (= (aref request 5) 0)
5073 ;; Phase 0.
5075 ;; Delete all elements starting after BEG, but not after buffer
5076 ;; position END or past element with key NEXT. Also delete
5077 ;; elements contained within a previously removed element
5078 ;; (stored in `last-container').
5080 ;; At each iteration, we start again at tree root since
5081 ;; a deletion modifies structure of the balanced tree.
5082 (catch 'end-phase
5083 (while t
5084 (when (org-element--cache-interrupt-p time-limit)
5085 (throw 'interrupt nil))
5086 ;; Find first element in cache with key BEG or after it.
5087 (let ((beg (aref request 0))
5088 (end (aref request 2))
5089 (node (org-element--cache-root))
5090 data data-key last-container)
5091 (while node
5092 (let* ((element (avl-tree--node-data node))
5093 (key (org-element--cache-key element)))
5094 (cond
5095 ((org-element--cache-key-less-p key beg)
5096 (setq node (avl-tree--node-right node)))
5097 ((org-element--cache-key-less-p beg key)
5098 (setq data element
5099 data-key key
5100 node (avl-tree--node-left node)))
5101 (t (setq data element
5102 data-key key
5103 node nil)))))
5104 (if data
5105 (let ((pos (org-element-property :begin data)))
5106 (if (if (or (not next)
5107 (org-element--cache-key-less-p data-key next))
5108 (<= pos end)
5109 (and last-container
5110 (let ((up data))
5111 (while (and up (not (eq up last-container)))
5112 (setq up (org-element-property :parent up)))
5113 up)))
5114 (progn (when (and (not last-container)
5115 (> (org-element-property :end data)
5116 end))
5117 (setq last-container data))
5118 (org-element--cache-remove data))
5119 (aset request 0 data-key)
5120 (aset request 1 pos)
5121 (aset request 5 1)
5122 (throw 'end-phase nil)))
5123 ;; No element starting after modifications left in
5124 ;; cache: further processing is futile.
5125 (throw 'quit t))))))
5126 (when (= (aref request 5) 1)
5127 ;; Phase 1.
5129 ;; Phase 0 left a hole in the cache. Some elements after it
5130 ;; could have parents within. For example, in the following
5131 ;; buffer:
5133 ;; - item
5136 ;; Paragraph1
5138 ;; Paragraph2
5140 ;; if we remove a blank line between "item" and "Paragraph1",
5141 ;; everything down to "Paragraph2" is removed from cache. But
5142 ;; the paragraph now belongs to the list, and its `:parent'
5143 ;; property no longer is accurate.
5145 ;; Therefore we need to parse again elements in the hole, or at
5146 ;; least in its last section, so that we can re-parent
5147 ;; subsequent elements, during phase 2.
5149 ;; Note that we only need to get the parent from the first
5150 ;; element in cache after the hole.
5152 ;; When next key is lesser or equal to the current one, delegate
5153 ;; phase 1 processing to next request in order to preserve key
5154 ;; order among requests.
5155 (let ((key (aref request 0)))
5156 (when (and next (not (org-element--cache-key-less-p key next)))
5157 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5158 (aset next-request 0 key)
5159 (aset next-request 1 (aref request 1))
5160 (aset next-request 5 1))
5161 (throw 'quit t)))
5162 ;; Next element will start at its beginning position plus
5163 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5164 ;; contains the real beginning position of the first element to
5165 ;; shift and re-parent.
5166 (let ((limit (+ (aref request 1) (aref request 3))))
5167 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5168 ((and future-change (>= limit future-change))
5169 ;; Changes are going to happen around this element and
5170 ;; they will trigger another phase 1 request. Skip the
5171 ;; current one.
5172 (aset request 5 2))
5174 (let ((parent (org-element--parse-to limit t time-limit)))
5175 (aset request 4 parent)
5176 (aset request 5 2))))))
5177 ;; Phase 2.
5179 ;; Shift all elements starting from key START, but before NEXT, by
5180 ;; OFFSET, and re-parent them when appropriate.
5182 ;; Elements are modified by side-effect so the tree structure
5183 ;; remains intact.
5185 ;; Once THRESHOLD, if any, is reached, or once there is an input
5186 ;; pending, exit. Before leaving, the current synchronization
5187 ;; request is updated.
5188 (let ((start (aref request 0))
5189 (offset (aref request 3))
5190 (parent (aref request 4))
5191 (node (org-element--cache-root))
5192 (stack (list nil))
5193 (leftp t)
5194 exit-flag)
5195 ;; No re-parenting nor shifting planned: request is over.
5196 (when (and (not parent) (zerop offset)) (throw 'quit t))
5197 (while node
5198 (let* ((data (avl-tree--node-data node))
5199 (key (org-element--cache-key data)))
5200 (if (and leftp (avl-tree--node-left node)
5201 (not (org-element--cache-key-less-p key start)))
5202 (progn (push node stack)
5203 (setq node (avl-tree--node-left node)))
5204 (unless (org-element--cache-key-less-p key start)
5205 ;; We reached NEXT. Request is complete.
5206 (when (equal key next) (throw 'quit t))
5207 ;; Handle interruption request. Update current request.
5208 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5209 (aset request 0 key)
5210 (aset request 4 parent)
5211 (throw 'interrupt nil))
5212 ;; Shift element.
5213 (unless (zerop offset)
5214 (org-element--cache-shift-positions data offset)
5215 ;; Shift associated objects data, if any.
5216 (dolist (object-data (gethash data org-element--cache-objects))
5217 (dolist (object (cddr object-data))
5218 (org-element--cache-shift-positions object offset))))
5219 (let ((begin (org-element-property :begin data)))
5220 ;; Update PARENT and re-parent DATA, only when
5221 ;; necessary. Propagate new structures for lists.
5222 (while (and parent
5223 (<= (org-element-property :end parent) begin))
5224 (setq parent (org-element-property :parent parent)))
5225 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5226 ((and parent
5227 (let ((p (org-element-property :parent data)))
5228 (or (not p)
5229 (< (org-element-property :begin p)
5230 (org-element-property :begin parent)))))
5231 (org-element-put-property data :parent parent)
5232 (let ((s (org-element-property :structure parent)))
5233 (when (and s (org-element-property :structure data))
5234 (org-element-put-property data :structure s)))))
5235 ;; Cache is up-to-date past THRESHOLD. Request
5236 ;; interruption.
5237 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5238 (setq node (if (setq leftp (avl-tree--node-right node))
5239 (avl-tree--node-right node)
5240 (pop stack))))))
5241 ;; We reached end of tree: synchronization complete.
5242 t)))
5244 (defun org-element--parse-to (pos &optional syncp time-limit)
5245 "Parse elements in current section, down to POS.
5247 Start parsing from the closest between the last known element in
5248 cache or headline above. Return the smallest element containing
5249 POS.
5251 When optional argument SYNCP is non-nil, return the parent of the
5252 element containing POS instead. In that case, it is also
5253 possible to provide TIME-LIMIT, which is a time value specifying
5254 when the parsing should stop. The function throws `interrupt' if
5255 the process stopped before finding the expected result."
5256 (catch 'exit
5257 (org-with-wide-buffer
5258 (goto-char pos)
5259 (let* ((cached (and (org-element--cache-active-p)
5260 (org-element--cache-find pos nil)))
5261 (begin (org-element-property :begin cached))
5262 element next mode)
5263 (cond
5264 ;; Nothing in cache before point: start parsing from first
5265 ;; element following headline above, or first element in
5266 ;; buffer.
5267 ((not cached)
5268 (when (org-with-limited-levels (outline-previous-heading))
5269 (setq mode 'planning)
5270 (forward-line))
5271 (skip-chars-forward " \r\t\n")
5272 (beginning-of-line))
5273 ;; Cache returned exact match: return it.
5274 ((= pos begin)
5275 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5276 ;; There's a headline between cached value and POS: cached
5277 ;; value is invalid. Start parsing from first element
5278 ;; following the headline.
5279 ((re-search-backward
5280 (org-with-limited-levels org-outline-regexp-bol) begin t)
5281 (forward-line)
5282 (skip-chars-forward " \r\t\n")
5283 (beginning-of-line)
5284 (setq mode 'planning))
5285 ;; Check if CACHED or any of its ancestors contain point.
5287 ;; If there is such an element, we inspect it in order to know
5288 ;; if we return it or if we need to parse its contents.
5289 ;; Otherwise, we just start parsing from current location,
5290 ;; which is right after the top-most element containing
5291 ;; CACHED.
5293 ;; As a special case, if POS is at the end of the buffer, we
5294 ;; want to return the innermost element ending there.
5296 ;; Also, if we find an ancestor and discover that we need to
5297 ;; parse its contents, make sure we don't start from
5298 ;; `:contents-begin', as we would otherwise go past CACHED
5299 ;; again. Instead, in that situation, we will resume parsing
5300 ;; from NEXT, which is located after CACHED or its higher
5301 ;; ancestor not containing point.
5303 (let ((up cached)
5304 (pos (if (= (point-max) pos) (1- pos) pos)))
5305 (goto-char (or (org-element-property :contents-begin cached) begin))
5306 (while (let ((end (org-element-property :end up)))
5307 (and (<= end pos)
5308 (goto-char end)
5309 (setq up (org-element-property :parent up)))))
5310 (cond ((not up))
5311 ((eobp) (setq element up))
5312 (t (setq element up next (point)))))))
5313 ;; Parse successively each element until we reach POS.
5314 (let ((end (or (org-element-property :end element)
5315 (save-excursion
5316 (org-with-limited-levels (outline-next-heading))
5317 (point))))
5318 (parent element))
5319 (while t
5320 (when syncp
5321 (cond ((= (point) pos) (throw 'exit parent))
5322 ((org-element--cache-interrupt-p time-limit)
5323 (throw 'interrupt nil))))
5324 (unless element
5325 (setq element (org-element--current-element
5326 end 'element mode
5327 (org-element-property :structure parent)))
5328 (org-element-put-property element :parent parent)
5329 (org-element--cache-put element))
5330 (let ((elem-end (org-element-property :end element))
5331 (type (org-element-type element)))
5332 (cond
5333 ;; Skip any element ending before point. Also skip
5334 ;; element ending at point (unless it is also the end of
5335 ;; buffer) since we're sure that another element begins
5336 ;; after it.
5337 ((and (<= elem-end pos) (/= (point-max) elem-end))
5338 (goto-char elem-end)
5339 (setq mode (org-element--next-mode type nil)))
5340 ;; A non-greater element contains point: return it.
5341 ((not (memq type org-element-greater-elements))
5342 (throw 'exit element))
5343 ;; Otherwise, we have to decide if ELEMENT really
5344 ;; contains POS. In that case we start parsing from
5345 ;; contents' beginning.
5347 ;; If POS is at contents' beginning but it is also at
5348 ;; the beginning of the first item in a list or a table.
5349 ;; In that case, we need to create an anchor for that
5350 ;; list or table, so return it.
5352 ;; Also, if POS is at the end of the buffer, no element
5353 ;; can start after it, but more than one may end there.
5354 ;; Arbitrarily, we choose to return the innermost of
5355 ;; such elements.
5356 ((let ((cbeg (org-element-property :contents-begin element))
5357 (cend (org-element-property :contents-end element)))
5358 (when (or syncp
5359 (and cbeg cend
5360 (or (< cbeg pos)
5361 (and (= cbeg pos)
5362 (not (memq type '(plain-list table)))))
5363 (or (> cend pos)
5364 (and (= cend pos) (= (point-max) pos)))))
5365 (goto-char (or next cbeg))
5366 (setq next nil
5367 mode (org-element--next-mode type t)
5368 parent element
5369 end cend))))
5370 ;; Otherwise, return ELEMENT as it is the smallest
5371 ;; element containing POS.
5372 (t (throw 'exit element))))
5373 (setq element nil)))))))
5376 ;;;; Staging Buffer Changes
5378 (defconst org-element--cache-sensitive-re
5379 (concat
5380 org-outline-regexp-bol "\\|"
5381 "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
5382 "^[ \t]*\\(?:"
5383 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5384 "\\\\begin{[A-Za-z0-9*]+}" "\\|"
5385 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5386 "\\)")
5387 "Regexp matching a sensitive line, structure wise.
5388 A sensitive line is a headline, inlinetask, block, drawer, or
5389 latex-environment boundary. When such a line is modified,
5390 structure changes in the document may propagate in the whole
5391 section, possibly making cache invalid.")
5393 (defvar org-element--cache-change-warning nil
5394 "Non-nil when a sensitive line is about to be changed.
5395 It is a symbol among nil, t and `headline'.")
5397 (defun org-element--cache-before-change (beg end)
5398 "Request extension of area going to be modified if needed.
5399 BEG and END are the beginning and end of the range of changed
5400 text. See `before-change-functions' for more information."
5401 (when (org-element--cache-active-p)
5402 (org-with-wide-buffer
5403 (goto-char beg)
5404 (beginning-of-line)
5405 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5406 (setq org-element--cache-change-warning
5407 (save-match-data
5408 (if (and (org-with-limited-levels (org-at-heading-p))
5409 (= (line-end-position) bottom))
5410 'headline
5411 (let ((case-fold-search t))
5412 (re-search-forward
5413 org-element--cache-sensitive-re bottom t)))))))))
5415 (defun org-element--cache-after-change (beg end pre)
5416 "Update buffer modifications for current buffer.
5417 BEG and END are the beginning and end of the range of changed
5418 text, and the length in bytes of the pre-change text replaced by
5419 that range. See `after-change-functions' for more information."
5420 (when (org-element--cache-active-p)
5421 (org-with-wide-buffer
5422 (goto-char beg)
5423 (beginning-of-line)
5424 (save-match-data
5425 (let ((top (point))
5426 (bottom (save-excursion (goto-char end) (line-end-position))))
5427 ;; Determine if modified area needs to be extended, according
5428 ;; to both previous and current state. We make a special
5429 ;; case for headline editing: if a headline is modified but
5430 ;; not removed, do not extend.
5431 (when (case org-element--cache-change-warning
5432 ((t) t)
5433 (headline
5434 (not (and (org-with-limited-levels (org-at-heading-p))
5435 (= (line-end-position) bottom))))
5436 (otherwise
5437 (let ((case-fold-search t))
5438 (re-search-forward
5439 org-element--cache-sensitive-re bottom t))))
5440 ;; Effectively extend modified area.
5441 (org-with-limited-levels
5442 (setq top (progn (goto-char top)
5443 (when (outline-previous-heading) (forward-line))
5444 (point)))
5445 (setq bottom (progn (goto-char bottom)
5446 (if (outline-next-heading) (1- (point))
5447 (point))))))
5448 ;; Store synchronization request.
5449 (let ((offset (- end beg pre)))
5450 (org-element--cache-submit-request top (- bottom offset) offset)))))
5451 ;; Activate a timer to process the request during idle time.
5452 (org-element--cache-set-timer (current-buffer))))
5454 (defun org-element--cache-for-removal (beg end offset)
5455 "Return first element to remove from cache.
5457 BEG and END are buffer positions delimiting buffer modifications.
5458 OFFSET is the size of the changes.
5460 Returned element is usually the first element in cache containing
5461 any position between BEG and END. As an exception, greater
5462 elements around the changes that are robust to contents
5463 modifications are preserved and updated according to the
5464 changes."
5465 (let* ((elements (org-element--cache-find (1- beg) 'both))
5466 (before (car elements))
5467 (after (cdr elements)))
5468 (if (not before) after
5469 (let ((up before)
5470 (robust-flag t))
5471 (while up
5472 (if (let ((type (org-element-type up)))
5473 (and (or (memq type '(center-block dynamic-block quote-block
5474 special-block))
5475 ;; Drawers named "PROPERTIES" are probably
5476 ;; a properties drawer being edited. Force
5477 ;; parsing to check if editing is over.
5478 (and (eq type 'drawer)
5479 (not (string=
5480 (org-element-property :drawer-name up)
5481 "PROPERTIES"))))
5482 (let ((cbeg (org-element-property :contents-begin up)))
5483 (and cbeg
5484 (<= cbeg beg)
5485 (> (org-element-property :contents-end up) end)))))
5486 ;; UP is a robust greater element containing changes.
5487 ;; We only need to extend its ending boundaries.
5488 (org-element--cache-shift-positions
5489 up offset '(:contents-end :end))
5490 (setq before up)
5491 (when robust-flag (setq robust-flag nil)))
5492 (setq up (org-element-property :parent up)))
5493 ;; We're at top level element containing ELEMENT: if it's
5494 ;; altered by buffer modifications, it is first element in
5495 ;; cache to be removed. Otherwise, that first element is the
5496 ;; following one.
5498 ;; As a special case, do not remove BEFORE if it is a robust
5499 ;; container for current changes.
5500 (if (or (< (org-element-property :end before) beg) robust-flag) after
5501 before)))))
5503 (defun org-element--cache-submit-request (beg end offset)
5504 "Submit a new cache synchronization request for current buffer.
5505 BEG and END are buffer positions delimiting the minimal area
5506 where cache data should be removed. OFFSET is the size of the
5507 change, as an integer."
5508 (let ((next (car org-element--cache-sync-requests))
5509 delete-to delete-from)
5510 (if (and next
5511 (zerop (aref next 5))
5512 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5513 (<= (setq delete-from (aref next 1)) end))
5514 ;; Current changes can be merged with first sync request: we
5515 ;; can save a partial cache synchronization.
5516 (progn
5517 (incf (aref next 3) offset)
5518 ;; If last change happened within area to be removed, extend
5519 ;; boundaries of robust parents, if any. Otherwise, find
5520 ;; first element to remove and update request accordingly.
5521 (if (> beg delete-from)
5522 (let ((up (aref next 4)))
5523 (while up
5524 (org-element--cache-shift-positions
5525 up offset '(:contents-end :end))
5526 (setq up (org-element-property :parent up))))
5527 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5528 (when first
5529 (aset next 0 (org-element--cache-key first))
5530 (aset next 1 (org-element-property :begin first))
5531 (aset next 4 (org-element-property :parent first))))))
5532 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5533 ;; if any, is no longer a 0-phase request, thus ensuring that
5534 ;; phases are properly ordered. We need to provide OFFSET as
5535 ;; optional parameter since current modifications are not known
5536 ;; yet to the otherwise correct part of the cache (i.e, before
5537 ;; the first request).
5538 (when next (org-element--cache-sync (current-buffer) end beg))
5539 (let ((first (org-element--cache-for-removal beg end offset)))
5540 (if first
5541 (push (let ((beg (org-element-property :begin first))
5542 (key (org-element--cache-key first)))
5543 (cond
5544 ;; When changes happen before the first known
5545 ;; element, re-parent and shift the rest of the
5546 ;; cache.
5547 ((> beg end) (vector key beg nil offset nil 1))
5548 ;; Otherwise, we find the first non robust
5549 ;; element containing END. All elements between
5550 ;; FIRST and this one are to be removed.
5551 ((let ((first-end (org-element-property :end first)))
5552 (and (> first-end end)
5553 (vector key beg first-end offset first 0))))
5555 (let* ((element (org-element--cache-find end))
5556 (end (org-element-property :end element))
5557 (up element))
5558 (while (and (setq up (org-element-property :parent up))
5559 (>= (org-element-property :begin up) beg))
5560 (setq end (org-element-property :end up)
5561 element up))
5562 (vector key beg end offset element 0)))))
5563 org-element--cache-sync-requests)
5564 ;; No element to remove. No need to re-parent either.
5565 ;; Simply shift additional elements, if any, by OFFSET.
5566 (when org-element--cache-sync-requests
5567 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5570 ;;;; Public Functions
5572 ;;;###autoload
5573 (defun org-element-cache-reset (&optional all)
5574 "Reset cache in current buffer.
5575 When optional argument ALL is non-nil, reset cache in all Org
5576 buffers."
5577 (interactive "P")
5578 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5579 (with-current-buffer buffer
5580 (when (org-element--cache-active-p)
5581 (org-set-local 'org-element--cache
5582 (avl-tree-create #'org-element--cache-compare))
5583 (org-set-local 'org-element--cache-objects (make-hash-table :test #'eq))
5584 (org-set-local 'org-element--cache-sync-keys
5585 (make-hash-table :weakness 'key :test #'eq))
5586 (org-set-local 'org-element--cache-change-warning nil)
5587 (org-set-local 'org-element--cache-sync-requests nil)
5588 (org-set-local 'org-element--cache-sync-timer nil)
5589 (add-hook 'before-change-functions
5590 #'org-element--cache-before-change nil t)
5591 (add-hook 'after-change-functions
5592 #'org-element--cache-after-change nil t)))))
5594 ;;;###autoload
5595 (defun org-element-cache-refresh (pos)
5596 "Refresh cache at position POS."
5597 (when (org-element--cache-active-p)
5598 (org-element--cache-sync (current-buffer) pos)
5599 (org-element--cache-submit-request pos pos 0)
5600 (org-element--cache-set-timer (current-buffer))))
5604 ;;; The Toolbox
5606 ;; The first move is to implement a way to obtain the smallest element
5607 ;; containing point. This is the job of `org-element-at-point'. It
5608 ;; basically jumps back to the beginning of section containing point
5609 ;; and proceed, one element after the other, with
5610 ;; `org-element--current-element' until the container is found. Note:
5611 ;; When using `org-element-at-point', secondary values are never
5612 ;; parsed since the function focuses on elements, not on objects.
5614 ;; At a deeper level, `org-element-context' lists all elements and
5615 ;; objects containing point.
5617 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5618 ;; internally by navigation and manipulation tools.
5621 ;;;###autoload
5622 (defun org-element-at-point ()
5623 "Determine closest element around point.
5625 Return value is a list like (TYPE PROPS) where TYPE is the type
5626 of the element and PROPS a plist of properties associated to the
5627 element.
5629 Possible types are defined in `org-element-all-elements'.
5630 Properties depend on element or object type, but always include
5631 `:begin', `:end', `:parent' and `:post-blank' properties.
5633 As a special case, if point is at the very beginning of the first
5634 item in a list or sub-list, returned element will be that list
5635 instead of the item. Likewise, if point is at the beginning of
5636 the first row of a table, returned element will be the table
5637 instead of the first row.
5639 When point is at the end of the buffer, return the innermost
5640 element ending there."
5641 (org-with-wide-buffer
5642 (let ((origin (point)))
5643 (end-of-line)
5644 (skip-chars-backward " \r\t\n")
5645 (cond
5646 ;; Within blank lines at the beginning of buffer, return nil.
5647 ((bobp) nil)
5648 ;; Within blank lines right after a headline, return that
5649 ;; headline.
5650 ((org-with-limited-levels (org-at-heading-p))
5651 (beginning-of-line)
5652 (org-element-headline-parser (point-max) t))
5653 ;; Otherwise parse until we find element containing ORIGIN.
5655 (when (org-element--cache-active-p)
5656 (if (not org-element--cache) (org-element-cache-reset)
5657 (org-element--cache-sync (current-buffer) origin)))
5658 (org-element--parse-to origin))))))
5660 ;;;###autoload
5661 (defun org-element-context (&optional element)
5662 "Return smallest element or object around point.
5664 Return value is a list like (TYPE PROPS) where TYPE is the type
5665 of the element or object and PROPS a plist of properties
5666 associated to it.
5668 Possible types are defined in `org-element-all-elements' and
5669 `org-element-all-objects'. Properties depend on element or
5670 object type, but always include `:begin', `:end', `:parent' and
5671 `:post-blank'.
5673 As a special case, if point is right after an object and not at
5674 the beginning of any other object, return that object.
5676 Optional argument ELEMENT, when non-nil, is the closest element
5677 containing point, as returned by `org-element-at-point'.
5678 Providing it allows for quicker computation."
5679 (catch 'objects-forbidden
5680 (org-with-wide-buffer
5681 (let* ((pos (point))
5682 (element (or element (org-element-at-point)))
5683 (type (org-element-type element)))
5684 ;; If point is inside an element containing objects or
5685 ;; a secondary string, narrow buffer to the container and
5686 ;; proceed with parsing. Otherwise, return ELEMENT.
5687 (cond
5688 ;; At a parsed affiliated keyword, check if we're inside main
5689 ;; or dual value.
5690 ((let ((post (org-element-property :post-affiliated element)))
5691 (and post (< pos post)))
5692 (beginning-of-line)
5693 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5694 (cond
5695 ((not (member-ignore-case (match-string 1)
5696 org-element-parsed-keywords))
5697 (throw 'objects-forbidden element))
5698 ((< (match-end 0) pos)
5699 (narrow-to-region (match-end 0) (line-end-position)))
5700 ((and (match-beginning 2)
5701 (>= pos (match-beginning 2))
5702 (< pos (match-end 2)))
5703 (narrow-to-region (match-beginning 2) (match-end 2)))
5704 (t (throw 'objects-forbidden element)))
5705 ;; Also change type to retrieve correct restrictions.
5706 (setq type 'keyword))
5707 ;; At an item, objects can only be located within tag, if any.
5708 ((eq type 'item)
5709 (let ((tag (org-element-property :tag element)))
5710 (if (not tag) (throw 'objects-forbidden element)
5711 (beginning-of-line)
5712 (search-forward tag (line-end-position))
5713 (goto-char (match-beginning 0))
5714 (if (and (>= pos (point)) (< pos (match-end 0)))
5715 (narrow-to-region (point) (match-end 0))
5716 (throw 'objects-forbidden element)))))
5717 ;; At an headline or inlinetask, objects are in title.
5718 ((memq type '(headline inlinetask))
5719 (goto-char (org-element-property :begin element))
5720 (skip-chars-forward "*")
5721 (if (and (> pos (point)) (< pos (line-end-position)))
5722 (narrow-to-region (point) (line-end-position))
5723 (throw 'objects-forbidden element)))
5724 ;; At a paragraph, a table-row or a verse block, objects are
5725 ;; located within their contents.
5726 ((memq type '(paragraph table-row verse-block))
5727 (let ((cbeg (org-element-property :contents-begin element))
5728 (cend (org-element-property :contents-end element)))
5729 ;; CBEG is nil for table rules.
5730 (if (and cbeg cend (>= pos cbeg)
5731 (or (< pos cend) (and (= pos cend) (eobp))))
5732 (narrow-to-region cbeg cend)
5733 (throw 'objects-forbidden element))))
5734 ;; At a planning line, if point is at a timestamp, return it,
5735 ;; otherwise, return element.
5736 ((eq type 'planning)
5737 (dolist (p '(:closed :deadline :scheduled))
5738 (let ((timestamp (org-element-property p element)))
5739 (when (and timestamp
5740 (<= (org-element-property :begin timestamp) pos)
5741 (> (org-element-property :end timestamp) pos))
5742 (throw 'objects-forbidden timestamp))))
5743 ;; All other locations cannot contain objects: bail out.
5744 (throw 'objects-forbidden element))
5745 (t (throw 'objects-forbidden element)))
5746 (goto-char (point-min))
5747 (let ((restriction (org-element-restriction type))
5748 (parent element)
5749 (cache (cond ((not (org-element--cache-active-p)) nil)
5750 (org-element--cache-objects
5751 (gethash element org-element--cache-objects))
5752 (t (org-element-cache-reset) nil)))
5753 next object-data last)
5754 (prog1
5755 (catch 'exit
5756 (while t
5757 ;; When entering PARENT for the first time, get list
5758 ;; of objects within known so far. Store it in
5759 ;; OBJECT-DATA.
5760 (unless next
5761 (let ((data (assq parent cache)))
5762 (if data (setq object-data data)
5763 (push (setq object-data (list parent nil)) cache))))
5764 ;; Find NEXT object for analysis.
5765 (catch 'found
5766 ;; If NEXT is non-nil, we already exhausted the
5767 ;; cache so we can parse buffer to find the object
5768 ;; after it.
5769 (if next (setq next (org-element--object-lex restriction))
5770 ;; Otherwise, check if cache can help us.
5771 (let ((objects (cddr object-data))
5772 (completep (nth 1 object-data)))
5773 (cond
5774 ((and (not objects) completep) (throw 'exit parent))
5775 ((not objects)
5776 (setq next (org-element--object-lex restriction)))
5778 (let ((cache-limit
5779 (org-element-property :end (car objects))))
5780 (if (>= cache-limit pos)
5781 ;; Cache contains the information needed.
5782 (dolist (object objects (throw 'exit parent))
5783 (when (<= (org-element-property :begin object)
5784 pos)
5785 (if (>= (org-element-property :end object)
5786 pos)
5787 (throw 'found (setq next object))
5788 (throw 'exit parent))))
5789 (goto-char cache-limit)
5790 (setq next
5791 (org-element--object-lex restriction))))))))
5792 ;; If we have a new object to analyze, store it in
5793 ;; cache. Otherwise record that there is nothing
5794 ;; more to parse in this element at this depth.
5795 (if next
5796 (progn (org-element-put-property next :parent parent)
5797 (push next (cddr object-data)))
5798 (setcar (cdr object-data) t)))
5799 ;; Process NEXT, if any, in order to know if we need
5800 ;; to skip it, return it or move into it.
5801 (if (or (not next) (> (org-element-property :begin next) pos))
5802 (throw 'exit (or last parent))
5803 (let ((end (org-element-property :end next))
5804 (cbeg (org-element-property :contents-begin next))
5805 (cend (org-element-property :contents-end next)))
5806 (cond
5807 ;; Skip objects ending before point. Also skip
5808 ;; objects ending at point unless it is also the
5809 ;; end of buffer, since we want to return the
5810 ;; innermost object.
5811 ((and (<= end pos) (/= (point-max) end))
5812 (goto-char end)
5813 ;; For convenience, when object ends at POS,
5814 ;; without any space, store it in LAST, as we
5815 ;; will return it if no object starts here.
5816 (when (and (= end pos)
5817 (not (memq (char-before) '(?\s ?\t))))
5818 (setq last next)))
5819 ;; If POS is within a container object, move
5820 ;; into that object.
5821 ((and cbeg cend
5822 (>= pos cbeg)
5823 (or (< pos cend)
5824 ;; At contents' end, if there is no
5825 ;; space before point, also move into
5826 ;; object, for consistency with
5827 ;; convenience feature above.
5828 (and (= pos cend)
5829 (or (= (point-max) pos)
5830 (not (memq (char-before pos)
5831 '(?\s ?\t)))))))
5832 (goto-char cbeg)
5833 (narrow-to-region (point) cend)
5834 (setq parent next
5835 restriction (org-element-restriction next)
5836 next nil
5837 object-data nil))
5838 ;; Otherwise, return NEXT.
5839 (t (throw 'exit next)))))))
5840 ;; Store results in cache, if applicable.
5841 (org-element--cache-put element cache)))))))
5843 (defun org-element-lineage (blob &optional types with-self)
5844 "List all ancestors of a given element or object.
5846 BLOB is an object or element.
5848 When optional argument TYPES is a list of symbols, return the
5849 first element or object in the lineage whose type belongs to that
5850 list.
5852 When optional argument WITH-SELF is non-nil, lineage includes
5853 BLOB itself as the first element, and TYPES, if provided, also
5854 apply to it.
5856 When BLOB is obtained through `org-element-context' or
5857 `org-element-at-point', only ancestors from its section can be
5858 found. There is no such limitation when BLOB belongs to a full
5859 parse tree."
5860 (let ((up (if with-self blob (org-element-property :parent blob)))
5861 ancestors)
5862 (while (and up (not (memq (org-element-type up) types)))
5863 (unless types (push up ancestors))
5864 (setq up (org-element-property :parent up)))
5865 (if types up (nreverse ancestors))))
5867 (defun org-element-nested-p (elem-A elem-B)
5868 "Non-nil when elements ELEM-A and ELEM-B are nested."
5869 (let ((beg-A (org-element-property :begin elem-A))
5870 (beg-B (org-element-property :begin elem-B))
5871 (end-A (org-element-property :end elem-A))
5872 (end-B (org-element-property :end elem-B)))
5873 (or (and (>= beg-A beg-B) (<= end-A end-B))
5874 (and (>= beg-B beg-A) (<= end-B end-A)))))
5876 (defun org-element-swap-A-B (elem-A elem-B)
5877 "Swap elements ELEM-A and ELEM-B.
5878 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5879 end of ELEM-A."
5880 (goto-char (org-element-property :begin elem-A))
5881 ;; There are two special cases when an element doesn't start at bol:
5882 ;; the first paragraph in an item or in a footnote definition.
5883 (let ((specialp (not (bolp))))
5884 ;; Only a paragraph without any affiliated keyword can be moved at
5885 ;; ELEM-A position in such a situation. Note that the case of
5886 ;; a footnote definition is impossible: it cannot contain two
5887 ;; paragraphs in a row because it cannot contain a blank line.
5888 (if (and specialp
5889 (or (not (eq (org-element-type elem-B) 'paragraph))
5890 (/= (org-element-property :begin elem-B)
5891 (org-element-property :contents-begin elem-B))))
5892 (error "Cannot swap elements"))
5893 ;; In a special situation, ELEM-A will have no indentation. We'll
5894 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5895 (let* ((ind-B (when specialp
5896 (goto-char (org-element-property :begin elem-B))
5897 (org-get-indentation)))
5898 (beg-A (org-element-property :begin elem-A))
5899 (end-A (save-excursion
5900 (goto-char (org-element-property :end elem-A))
5901 (skip-chars-backward " \r\t\n")
5902 (point-at-eol)))
5903 (beg-B (org-element-property :begin elem-B))
5904 (end-B (save-excursion
5905 (goto-char (org-element-property :end elem-B))
5906 (skip-chars-backward " \r\t\n")
5907 (point-at-eol)))
5908 ;; Store inner overlays responsible for visibility status.
5909 ;; We also need to store their boundaries as they will be
5910 ;; removed from buffer.
5911 (overlays
5912 (cons
5913 (delq nil
5914 (mapcar (lambda (o)
5915 (and (>= (overlay-start o) beg-A)
5916 (<= (overlay-end o) end-A)
5917 (list o (overlay-start o) (overlay-end o))))
5918 (overlays-in beg-A end-A)))
5919 (delq nil
5920 (mapcar (lambda (o)
5921 (and (>= (overlay-start o) beg-B)
5922 (<= (overlay-end o) end-B)
5923 (list o (overlay-start o) (overlay-end o))))
5924 (overlays-in beg-B end-B)))))
5925 ;; Get contents.
5926 (body-A (buffer-substring beg-A end-A))
5927 (body-B (delete-and-extract-region beg-B end-B)))
5928 (goto-char beg-B)
5929 (when specialp
5930 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5931 (org-indent-to-column ind-B))
5932 (insert body-A)
5933 ;; Restore ex ELEM-A overlays.
5934 (let ((offset (- beg-B beg-A)))
5935 (dolist (o (car overlays))
5936 (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
5937 (goto-char beg-A)
5938 (delete-region beg-A end-A)
5939 (insert body-B)
5940 ;; Restore ex ELEM-B overlays.
5941 (dolist (o (cdr overlays))
5942 (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
5943 (goto-char (org-element-property :end elem-B)))))
5945 (defun org-element-remove-indentation (s &optional n)
5946 "Remove maximum common indentation in string S and return it.
5947 When optional argument N is a positive integer, remove exactly
5948 that much characters from indentation, if possible, or return
5949 S as-is otherwise. Unlike to `org-remove-indentation', this
5950 function doesn't call `untabify' on S."
5951 (catch 'exit
5952 (with-temp-buffer
5953 (insert s)
5954 (goto-char (point-min))
5955 ;; Find maximum common indentation, if not specified.
5956 (setq n (or n
5957 (let ((min-ind (point-max)))
5958 (save-excursion
5959 (while (re-search-forward "^[ \t]*\\S-" nil t)
5960 (let ((ind (1- (current-column))))
5961 (if (zerop ind) (throw 'exit s)
5962 (setq min-ind (min min-ind ind))))))
5963 min-ind)))
5964 (if (zerop n) s
5965 ;; Remove exactly N indentation, but give up if not possible.
5966 (while (not (eobp))
5967 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5968 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5969 ((< ind n) (throw 'exit s))
5970 (t (org-indent-line-to (- ind n))))
5971 (forward-line)))
5972 (buffer-string)))))
5976 (provide 'org-element)
5978 ;; Local variables:
5979 ;; generated-autoload-file: "org-loaddefs.el"
5980 ;; End:
5982 ;;; org-element.el ends here