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