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