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