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