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