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