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