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