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