Fix `org-outline-overlay-data' marker insertion-type
[org-mode.git] / lisp / org-element.el
blobfc835e51546acbcd57b5c9e9be538c21b122928c
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', `quote-section' `section' and
35 ;; `table-row' types), it can also accept a fixed set of keywords as
36 ;; attributes. Those are called "affiliated keywords" to distinguish
37 ;; them from other keywords, which are full-fledged elements. Almost
38 ;; all affiliated keywords are referenced in
39 ;; `org-element-affiliated-keywords'; the others are export attributes
40 ;; and start with "ATTR_" prefix.
42 ;; Element containing other elements (and only elements) are called
43 ;; greater elements. Concerned types are: `center-block', `drawer',
44 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
45 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
46 ;; and `special-block'.
48 ;; Other element types are: `babel-call', `clock', `comment',
49 ;; `comment-block', `diary-sexp', `example-block', `export-block',
50 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
51 ;; `node-property', `paragraph', `planning', `quote-section',
52 ;; `src-block', `table', `table-row' and `verse-block'. Among them,
53 ;; `paragraph' and `verse-block' types can contain Org objects and
54 ;; plain text.
56 ;; Objects are related to document's contents. Some of them are
57 ;; recursive. Associated types are of the following: `bold', `code',
58 ;; `entity', `export-snippet', `footnote-reference',
59 ;; `inline-babel-call', `inline-src-block', `italic',
60 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
61 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
62 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
64 ;; Some elements also have special properties whose value can hold
65 ;; objects themselves (i.e. an item tag or a headline name). Such
66 ;; values are called "secondary strings". Any object belongs to
67 ;; either an element or a secondary string.
69 ;; Notwithstanding affiliated keywords, each greater element, element
70 ;; and object has a fixed set of properties attached to it. Among
71 ;; them, four are shared by all types: `:begin' and `:end', which
72 ;; refer to the beginning and ending buffer positions of the
73 ;; considered element or object, `:post-blank', which holds the number
74 ;; of blank lines, or white spaces, at its end and `:parent' which
75 ;; refers to the element or object containing it. Greater elements,
76 ;; elements and objects containing objects will also have
77 ;; `:contents-begin' and `:contents-end' properties to delimit
78 ;; contents. Eventually, greater elements and elements accepting
79 ;; affiliated keywords will have a `:post-affiliated' property,
80 ;; referring to the buffer position after all such keywords.
82 ;; At the lowest level, a `:parent' property is also attached to any
83 ;; string, as a text property.
85 ;; Lisp-wise, an element or an object can be represented as a list.
86 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
87 ;; TYPE is a symbol describing the Org element or object.
88 ;; PROPERTIES is the property list attached to it. See docstring of
89 ;; appropriate parsing function to get an exhaustive
90 ;; list.
91 ;; CONTENTS is a list of elements, objects or raw strings contained
92 ;; in the current element or object, when applicable.
94 ;; An Org buffer is a nested list of such elements and objects, whose
95 ;; type is `org-data' and properties is nil.
97 ;; The first part of this file defines Org syntax, while the second
98 ;; one provide accessors and setters functions.
100 ;; The next part implements a parser and an interpreter for each
101 ;; element and object type in Org syntax.
103 ;; The following part creates a fully recursive buffer parser. It
104 ;; also provides a tool to map a function to elements or objects
105 ;; matching some criteria in the parse tree. Functions of interest
106 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
107 ;; extent, `org-element-parse-secondary-string'.
109 ;; The penultimate part is the cradle of an interpreter for the
110 ;; obtained parse tree: `org-element-interpret-data'.
112 ;; The library ends by furnishing `org-element-at-point' function, and
113 ;; a way to give information about document structure around point
114 ;; with `org-element-context'. A simple cache mechanism is also
115 ;; provided for these functions.
118 ;;; Code:
120 (eval-when-compile (require 'cl))
121 (require 'org)
122 (require 'avl-tree)
126 ;;; Definitions And Rules
128 ;; Define elements, greater elements and specify recursive objects,
129 ;; along with the affiliated keywords recognized. Also set up
130 ;; restrictions on recursive objects combinations.
132 ;; These variables really act as a control center for the parsing
133 ;; process.
135 (defconst org-element-paragraph-separate
136 (concat "^\\(?:"
137 ;; Headlines, inlinetasks.
138 org-outline-regexp "\\|"
139 ;; Footnote definitions.
140 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
141 ;; Diary sexps.
142 "%%(" "\\|"
143 "[ \t]*\\(?:"
144 ;; Empty lines.
145 "$" "\\|"
146 ;; Tables (any type).
147 "\\(?:|\\|\\+-[-+]\\)" "\\|"
148 ;; Blocks (any type), Babel calls and keywords. Note: this
149 ;; is only an indication and need some thorough check.
150 "#\\(?:[+ ]\\|$\\)" "\\|"
151 ;; Drawers (any type) and fixed-width areas. This is also
152 ;; only an indication.
153 ":" "\\|"
154 ;; Horizontal rules.
155 "-\\{5,\\}[ \t]*$" "\\|"
156 ;; LaTeX environments.
157 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
158 ;; Planning and Clock lines.
159 (regexp-opt (list org-scheduled-string
160 org-deadline-string
161 org-closed-string
162 org-clock-string))
163 "\\|"
164 ;; Lists.
165 (let ((term (case org-plain-list-ordered-item-terminator
166 (?\) ")") (?. "\\.") (otherwise "[.)]")))
167 (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
168 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
169 "\\(?:[ \t]\\|$\\)"))
170 "\\)\\)")
171 "Regexp to separate paragraphs in an Org buffer.
172 In the case of lines starting with \"#\" and \":\", this regexp
173 is not sufficient to know if point is at a paragraph ending. See
174 `org-element-paragraph-parser' for more information.")
176 (defconst org-element-all-elements
177 '(babel-call center-block clock comment comment-block diary-sexp drawer
178 dynamic-block example-block export-block fixed-width
179 footnote-definition headline horizontal-rule inlinetask item
180 keyword latex-environment node-property paragraph plain-list
181 planning property-drawer quote-block quote-section section
182 special-block src-block table table-row verse-block)
183 "Complete list of element types.")
185 (defconst org-element-greater-elements
186 '(center-block drawer dynamic-block footnote-definition headline inlinetask
187 item plain-list property-drawer quote-block section
188 special-block table)
189 "List of recursive element types aka Greater Elements.")
191 (defconst org-element-all-successors
192 '(export-snippet footnote-reference inline-babel-call inline-src-block
193 latex-or-entity line-break link macro plain-link radio-target
194 statistics-cookie sub/superscript table-cell target
195 text-markup timestamp)
196 "Complete list of successors.")
198 (defconst org-element-object-successor-alist
199 '((subscript . sub/superscript) (superscript . sub/superscript)
200 (bold . text-markup) (code . text-markup) (italic . text-markup)
201 (strike-through . text-markup) (underline . text-markup)
202 (verbatim . text-markup) (entity . latex-or-entity)
203 (latex-fragment . latex-or-entity))
204 "Alist of translations between object type and successor name.
205 Sharing the same successor comes handy when, for example, the
206 regexp matching one object can also match the other object.")
208 (defconst org-element-all-objects
209 '(bold code entity export-snippet footnote-reference inline-babel-call
210 inline-src-block italic line-break latex-fragment link macro
211 radio-target statistics-cookie strike-through subscript superscript
212 table-cell target timestamp underline verbatim)
213 "Complete list of object types.")
215 (defconst org-element-recursive-objects
216 '(bold italic link subscript radio-target strike-through superscript
217 table-cell underline)
218 "List of recursive object types.")
220 (defvar org-element-block-name-alist
221 '(("CENTER" . org-element-center-block-parser)
222 ("COMMENT" . org-element-comment-block-parser)
223 ("EXAMPLE" . org-element-example-block-parser)
224 ("QUOTE" . org-element-quote-block-parser)
225 ("SRC" . org-element-src-block-parser)
226 ("VERSE" . org-element-verse-block-parser))
227 "Alist between block names and the associated parsing function.
228 Names must be uppercase. Any block whose name has no association
229 is parsed with `org-element-special-block-parser'.")
231 (defconst org-element-link-type-is-file
232 '("file" "file+emacs" "file+sys" "docview")
233 "List of link types equivalent to \"file\".
234 Only these types can accept search options and an explicit
235 application to open them.")
237 (defconst org-element-affiliated-keywords
238 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
239 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
240 "List of affiliated keywords as strings.
241 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
242 are affiliated keywords and need not to be in this list.")
244 (defconst org-element-keyword-translation-alist
245 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
246 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
247 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
248 "Alist of usual translations for keywords.
249 The key is the old name and the value the new one. The property
250 holding their value will be named after the translated name.")
252 (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
253 "List of affiliated keywords that can occur more than once in an element.
255 Their value will be consed into a list of strings, which will be
256 returned as the value of the property.
258 This list is checked after translations have been applied. See
259 `org-element-keyword-translation-alist'.
261 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
262 allow multiple occurrences and need not to be in this list.")
264 (defconst org-element-parsed-keywords '("CAPTION")
265 "List of affiliated keywords whose value can be parsed.
267 Their value will be stored as a secondary string: a list of
268 strings and objects.
270 This list is checked after translations have been applied. See
271 `org-element-keyword-translation-alist'.")
273 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
274 "List of affiliated keywords which can have a secondary value.
276 In Org syntax, they can be written with optional square brackets
277 before the colons. For example, RESULTS keyword can be
278 associated to a hash value with the following:
280 #+RESULTS[hash-string]: some-source
282 This list is checked after translations have been applied. See
283 `org-element-keyword-translation-alist'.")
285 (defconst org-element-document-properties '("AUTHOR" "DATE" "TITLE")
286 "List of properties associated to the whole document.
287 Any keyword in this list will have its value parsed and stored as
288 a secondary string.")
290 (defconst org-element--affiliated-re
291 (format "[ \t]*#\\+\\(?:%s\\):\\(?: \\|$\\)"
292 (concat
293 ;; Dual affiliated keywords.
294 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
295 (regexp-opt org-element-dual-keywords))
296 "\\|"
297 ;; Regular affiliated keywords.
298 (format "\\(?1:%s\\)"
299 (regexp-opt
300 (org-remove-if
301 #'(lambda (keyword)
302 (member keyword org-element-dual-keywords))
303 org-element-affiliated-keywords)))
304 "\\|"
305 ;; Export attributes.
306 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
307 "Regexp matching any affiliated keyword.
309 Keyword name is put in match group 1. Moreover, if keyword
310 belongs to `org-element-dual-keywords', put the dual value in
311 match group 2.
313 Don't modify it, set `org-element-affiliated-keywords' instead.")
315 (defconst org-element-object-restrictions
316 (let* ((standard-set
317 (remq 'plain-link (remq 'table-cell org-element-all-successors)))
318 (standard-set-no-line-break (remq 'line-break standard-set)))
319 `((bold ,@standard-set)
320 (footnote-reference ,@standard-set)
321 (headline ,@standard-set-no-line-break)
322 (inlinetask ,@standard-set-no-line-break)
323 (italic ,@standard-set)
324 (item ,@standard-set-no-line-break)
325 (keyword ,@standard-set)
326 ;; Ignore all links excepted plain links in a link description.
327 ;; Also ignore radio-targets and line breaks.
328 (link export-snippet inline-babel-call inline-src-block latex-or-entity
329 macro plain-link statistics-cookie sub/superscript text-markup)
330 (paragraph ,@standard-set)
331 ;; Remove any variable object from radio target as it would
332 ;; prevent it from being properly recognized.
333 (radio-target latex-or-entity sub/superscript)
334 (strike-through ,@standard-set)
335 (subscript ,@standard-set)
336 (superscript ,@standard-set)
337 ;; Ignore inline babel call and inline src block as formulas are
338 ;; possible. Also ignore line breaks and statistics cookies.
339 (table-cell export-snippet footnote-reference latex-or-entity link macro
340 radio-target sub/superscript target text-markup timestamp)
341 (table-row table-cell)
342 (underline ,@standard-set)
343 (verse-block ,@standard-set)))
344 "Alist of objects restrictions.
346 CAR is an element or object type containing objects and CDR is
347 a list of successors that will be called within an element or
348 object of such type.
350 For example, in a `radio-target' object, one can only find
351 entities, latex-fragments, subscript and superscript.
353 This alist also applies to secondary string. For example, an
354 `headline' type element doesn't directly contain objects, but
355 still has an entry since one of its properties (`:title') does.")
357 (defconst org-element-secondary-value-alist
358 '((headline . :title)
359 (inlinetask . :title)
360 (item . :tag)
361 (footnote-reference . :inline-definition))
362 "Alist between element types and location of secondary value.")
364 (defconst org-element-object-variables '(org-link-abbrev-alist-local)
365 "List of buffer-local variables used when parsing objects.
366 These variables are copied to the temporary buffer created by
367 `org-export-secondary-string'.")
371 ;;; Accessors and Setters
373 ;; Provide four accessors: `org-element-type', `org-element-property'
374 ;; `org-element-contents' and `org-element-restriction'.
376 ;; Setter functions allow to modify elements by side effect. There is
377 ;; `org-element-put-property', `org-element-set-contents'. These
378 ;; low-level functions are useful to build a parse tree.
380 ;; `org-element-adopt-element', `org-element-set-element',
381 ;; `org-element-extract-element' and `org-element-insert-before' are
382 ;; high-level functions useful to modify a parse tree.
384 ;; `org-element-secondary-p' is a predicate used to know if a given
385 ;; object belongs to a secondary string.
387 (defsubst org-element-type (element)
388 "Return type of ELEMENT.
390 The function returns the type of the element or object provided.
391 It can also return the following special value:
392 `plain-text' for a string
393 `org-data' for a complete document
394 nil in any other case."
395 (cond
396 ((not (consp element)) (and (stringp element) 'plain-text))
397 ((symbolp (car element)) (car element))))
399 (defsubst org-element-property (property element)
400 "Extract the value from the PROPERTY of an ELEMENT."
401 (if (stringp element) (get-text-property 0 property element)
402 (plist-get (nth 1 element) property)))
404 (defsubst org-element-contents (element)
405 "Extract contents from an ELEMENT."
406 (cond ((not (consp element)) nil)
407 ((symbolp (car element)) (nthcdr 2 element))
408 (t element)))
410 (defsubst org-element-restriction (element)
411 "Return restriction associated to ELEMENT.
412 ELEMENT can be an element, an object or a symbol representing an
413 element or object type."
414 (cdr (assq (if (symbolp element) element (org-element-type element))
415 org-element-object-restrictions)))
417 (defsubst org-element-put-property (element property value)
418 "In ELEMENT set PROPERTY to VALUE.
419 Return modified element."
420 (if (stringp element) (org-add-props element nil property value)
421 (setcar (cdr element) (plist-put (nth 1 element) property value))
422 element))
424 (defsubst org-element-set-contents (element &rest contents)
425 "Set ELEMENT contents to CONTENTS.
426 Return modified element."
427 (cond ((not element) (list contents))
428 ((not (symbolp (car element))) contents)
429 ((cdr element) (setcdr (cdr element) contents))
430 (t (nconc element contents))))
432 (defun org-element-secondary-p (object)
433 "Non-nil when OBJECT belongs to a secondary string.
434 Return value is the property name, as a keyword, or nil."
435 (let* ((parent (org-element-property :parent object))
436 (property (cdr (assq (org-element-type parent)
437 org-element-secondary-value-alist))))
438 (and property
439 (memq object (org-element-property property parent))
440 property)))
442 (defsubst org-element-adopt-elements (parent &rest children)
443 "Append elements to the contents of another element.
445 PARENT is an element or object. CHILDREN can be elements,
446 objects, or a strings.
448 The function takes care of setting `:parent' property for CHILD.
449 Return parent element."
450 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
451 ;; string: parent is the list itself.
452 (mapc (lambda (child)
453 (org-element-put-property child :parent (or parent children)))
454 children)
455 ;; Add CHILDREN at the end of PARENT contents.
456 (when parent
457 (apply 'org-element-set-contents
458 parent
459 (nconc (org-element-contents parent) children)))
460 ;; Return modified PARENT element.
461 (or parent children))
463 (defun org-element-extract-element (element)
464 "Extract ELEMENT from parse tree.
465 Remove element from the parse tree by side-effect, and return it
466 with its `:parent' property stripped out."
467 (let ((parent (org-element-property :parent element))
468 (secondary (org-element-secondary-p element)))
469 (if secondary
470 (org-element-put-property
471 parent secondary
472 (delq element (org-element-property secondary parent)))
473 (apply #'org-element-set-contents
474 parent
475 (delq element (org-element-contents parent))))
476 ;; Return ELEMENT with its :parent removed.
477 (org-element-put-property element :parent nil)))
479 (defun org-element-insert-before (element location)
480 "Insert ELEMENT before LOCATION in parse tree.
481 LOCATION is an element, object or string within the parse tree.
482 Parse tree is modified by side effect."
483 (let* ((parent (org-element-property :parent location))
484 (property (org-element-secondary-p location))
485 (siblings (if property (org-element-property property parent)
486 (org-element-contents parent)))
487 ;; Special case: LOCATION is the first element of an
488 ;; independent secondary string (e.g. :title property). Add
489 ;; ELEMENT in-place.
490 (specialp (and (not property)
491 (eq siblings parent)
492 (eq (car parent) location))))
493 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
494 (cond (specialp)
495 ((or (null siblings) (eq (car siblings) location))
496 (push element siblings))
497 ((null location) (nconc siblings (list element)))
498 (t (let ((previous (cadr (memq location (reverse siblings)))))
499 (if (not previous)
500 (error "No location found to insert element")
501 (let ((next (memq previous siblings)))
502 (setcdr next (cons element (cdr next))))))))
503 ;; Store SIBLINGS at appropriate place in parse tree.
504 (cond
505 (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
506 (property (org-element-put-property parent property siblings))
507 (t (apply #'org-element-set-contents parent siblings)))
508 ;; Set appropriate :parent property.
509 (org-element-put-property element :parent parent)))
511 (defun org-element-set-element (old new)
512 "Replace element or object OLD with element or object NEW.
513 The function takes care of setting `:parent' property for NEW."
514 ;; Ensure OLD and NEW have the same parent.
515 (org-element-put-property new :parent (org-element-property :parent old))
516 (if (or (memq (org-element-type old) '(plain-text nil))
517 (memq (org-element-type new) '(plain-text nil)))
518 ;; We cannot replace OLD with NEW since one of them is not an
519 ;; object or element. We take the long path.
520 (progn (org-element-insert-before new old)
521 (org-element-extract-element old))
522 ;; Since OLD is going to be changed into NEW by side-effect, first
523 ;; make sure that every element or object within NEW has OLD as
524 ;; parent.
525 (dolist (blob (org-element-contents new))
526 (org-element-put-property blob :parent old))
527 ;; Transfer contents.
528 (apply #'org-element-set-contents old (org-element-contents new))
529 ;; Overwrite OLD's properties with NEW's.
530 (setcar (cdr old) (nth 1 new))
531 ;; Transfer type.
532 (setcar old (car new))))
536 ;;; Greater elements
538 ;; For each greater element type, we define a parser and an
539 ;; interpreter.
541 ;; A parser returns the element or object as the list described above.
542 ;; Most of them accepts no argument. Though, exceptions exist. Hence
543 ;; every element containing a secondary string (see
544 ;; `org-element-secondary-value-alist') will accept an optional
545 ;; argument to toggle parsing of that secondary string. Moreover,
546 ;; `item' parser requires current list's structure as its first
547 ;; element.
549 ;; An interpreter accepts two arguments: the list representation of
550 ;; the element or object, and its contents. The latter may be nil,
551 ;; depending on the element or object considered. It returns the
552 ;; appropriate Org syntax, as a string.
554 ;; Parsing functions must follow the naming convention:
555 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
556 ;; defined in `org-element-greater-elements'.
558 ;; Similarly, interpreting functions must follow the naming
559 ;; convention: org-element-TYPE-interpreter.
561 ;; With the exception of `headline' and `item' types, greater elements
562 ;; cannot contain other greater elements of their own type.
564 ;; Beside implementing a parser and an interpreter, adding a new
565 ;; greater element requires to tweak `org-element--current-element'.
566 ;; Moreover, the newly defined type must be added to both
567 ;; `org-element-all-elements' and `org-element-greater-elements'.
570 ;;;; Center Block
572 (defun org-element-center-block-parser (limit affiliated)
573 "Parse a center block.
575 LIMIT bounds the search. AFFILIATED is a list of which CAR is
576 the buffer position at the beginning of the first affiliated
577 keyword and CDR is a plist of affiliated keywords along with
578 their value.
580 Return a list whose CAR is `center-block' and CDR is a plist
581 containing `:begin', `:end', `:contents-begin', `:contents-end',
582 `:post-blank' and `:post-affiliated' keywords.
584 Assume point is at the beginning of the block."
585 (let ((case-fold-search t))
586 (if (not (save-excursion
587 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
588 ;; Incomplete block: parse it as a paragraph.
589 (org-element-paragraph-parser limit affiliated)
590 (let ((block-end-line (match-beginning 0)))
591 (let* ((begin (car affiliated))
592 (post-affiliated (point))
593 ;; Empty blocks have no contents.
594 (contents-begin (progn (forward-line)
595 (and (< (point) block-end-line)
596 (point))))
597 (contents-end (and contents-begin block-end-line))
598 (pos-before-blank (progn (goto-char block-end-line)
599 (forward-line)
600 (point)))
601 (end (save-excursion
602 (skip-chars-forward " \r\t\n" limit)
603 (if (eobp) (point) (line-beginning-position)))))
604 (list 'center-block
605 (nconc
606 (list :begin begin
607 :end end
608 :contents-begin contents-begin
609 :contents-end contents-end
610 :post-blank (count-lines pos-before-blank end)
611 :post-affiliated post-affiliated)
612 (cdr affiliated))))))))
614 (defun org-element-center-block-interpreter (center-block contents)
615 "Interpret CENTER-BLOCK element as Org syntax.
616 CONTENTS is the contents of the element."
617 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
620 ;;;; Drawer
622 (defun org-element-drawer-parser (limit affiliated)
623 "Parse a drawer.
625 LIMIT bounds the search. AFFILIATED is a list of which CAR is
626 the buffer position at the beginning of the first affiliated
627 keyword and CDR is a plist of affiliated keywords along with
628 their value.
630 Return a list whose CAR is `drawer' and CDR is a plist containing
631 `:drawer-name', `:begin', `:end', `:contents-begin',
632 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
634 Assume point is at beginning of drawer."
635 (let ((case-fold-search t))
636 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
637 ;; Incomplete drawer: parse it as a paragraph.
638 (org-element-paragraph-parser limit affiliated)
639 (save-excursion
640 (let* ((drawer-end-line (match-beginning 0))
641 (name (progn (looking-at org-drawer-regexp)
642 (org-match-string-no-properties 1)))
643 (begin (car affiliated))
644 (post-affiliated (point))
645 ;; Empty drawers have no contents.
646 (contents-begin (progn (forward-line)
647 (and (< (point) drawer-end-line)
648 (point))))
649 (contents-end (and contents-begin drawer-end-line))
650 (pos-before-blank (progn (goto-char drawer-end-line)
651 (forward-line)
652 (point)))
653 (end (progn (skip-chars-forward " \r\t\n" limit)
654 (if (eobp) (point) (line-beginning-position)))))
655 (list 'drawer
656 (nconc
657 (list :begin begin
658 :end end
659 :drawer-name name
660 :contents-begin contents-begin
661 :contents-end contents-end
662 :post-blank (count-lines pos-before-blank end)
663 :post-affiliated post-affiliated)
664 (cdr affiliated))))))))
666 (defun org-element-drawer-interpreter (drawer contents)
667 "Interpret DRAWER element as Org syntax.
668 CONTENTS is the contents of the element."
669 (format ":%s:\n%s:END:"
670 (org-element-property :drawer-name drawer)
671 contents))
674 ;;;; Dynamic Block
676 (defun org-element-dynamic-block-parser (limit affiliated)
677 "Parse a dynamic block.
679 LIMIT bounds the search. AFFILIATED is a list of which CAR is
680 the buffer position at the beginning of the first affiliated
681 keyword and CDR is a plist of affiliated keywords along with
682 their value.
684 Return a list whose CAR is `dynamic-block' and CDR is a plist
685 containing `:block-name', `:begin', `:end', `:contents-begin',
686 `:contents-end', `:arguments', `:post-blank' and
687 `:post-affiliated' keywords.
689 Assume point is at beginning of dynamic block."
690 (let ((case-fold-search t))
691 (if (not (save-excursion
692 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
693 ;; Incomplete block: parse it as a paragraph.
694 (org-element-paragraph-parser limit affiliated)
695 (let ((block-end-line (match-beginning 0)))
696 (save-excursion
697 (let* ((name (progn (looking-at org-dblock-start-re)
698 (org-match-string-no-properties 1)))
699 (arguments (org-match-string-no-properties 3))
700 (begin (car affiliated))
701 (post-affiliated (point))
702 ;; Empty blocks have no contents.
703 (contents-begin (progn (forward-line)
704 (and (< (point) block-end-line)
705 (point))))
706 (contents-end (and contents-begin block-end-line))
707 (pos-before-blank (progn (goto-char block-end-line)
708 (forward-line)
709 (point)))
710 (end (progn (skip-chars-forward " \r\t\n" limit)
711 (if (eobp) (point) (line-beginning-position)))))
712 (list 'dynamic-block
713 (nconc
714 (list :begin begin
715 :end end
716 :block-name name
717 :arguments arguments
718 :contents-begin contents-begin
719 :contents-end contents-end
720 :post-blank (count-lines pos-before-blank end)
721 :post-affiliated post-affiliated)
722 (cdr affiliated)))))))))
724 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
725 "Interpret DYNAMIC-BLOCK element as Org syntax.
726 CONTENTS is the contents of the element."
727 (format "#+BEGIN: %s%s\n%s#+END:"
728 (org-element-property :block-name dynamic-block)
729 (let ((args (org-element-property :arguments dynamic-block)))
730 (and args (concat " " args)))
731 contents))
734 ;;;; Footnote Definition
736 (defun org-element-footnote-definition-parser (limit affiliated)
737 "Parse a footnote definition.
739 LIMIT bounds the search. AFFILIATED is a list of which CAR is
740 the buffer position at the beginning of the first affiliated
741 keyword and CDR is a plist of affiliated keywords along with
742 their value.
744 Return a list whose CAR is `footnote-definition' and CDR is
745 a plist containing `:label', `:begin' `:end', `:contents-begin',
746 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
748 Assume point is at the beginning of the footnote definition."
749 (save-excursion
750 (let* ((label (progn (looking-at org-footnote-definition-re)
751 (org-match-string-no-properties 1)))
752 (begin (car affiliated))
753 (post-affiliated (point))
754 (ending (save-excursion
755 (if (progn
756 (end-of-line)
757 (re-search-forward
758 (concat org-outline-regexp-bol "\\|"
759 org-footnote-definition-re "\\|"
760 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
761 (match-beginning 0)
762 (point))))
763 (contents-begin (progn
764 (search-forward "]")
765 (skip-chars-forward " \r\t\n" ending)
766 (cond ((= (point) ending) nil)
767 ((= (line-beginning-position) begin) (point))
768 (t (line-beginning-position)))))
769 (contents-end (and contents-begin ending))
770 (end (progn (goto-char ending)
771 (skip-chars-forward " \r\t\n" limit)
772 (if (eobp) (point) (line-beginning-position)))))
773 (list 'footnote-definition
774 (nconc
775 (list :label label
776 :begin begin
777 :end end
778 :contents-begin contents-begin
779 :contents-end contents-end
780 :post-blank (count-lines ending end)
781 :post-affiliated post-affiliated)
782 (cdr affiliated))))))
784 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
785 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
786 CONTENTS is the contents of the footnote-definition."
787 (concat (format "[%s]" (org-element-property :label footnote-definition))
789 contents))
792 ;;;; Headline
794 (defun org-element-headline-parser (limit &optional raw-secondary-p)
795 "Parse a headline.
797 Return a list whose CAR is `headline' and CDR is a plist
798 containing `:raw-value', `:title', `:alt-title', `:begin',
799 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
800 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
801 `:scheduled', `:deadline', `:closed', `:quotedp', `:archivedp',
802 `:commentedp' and `:footnote-section-p' keywords.
804 The plist also contains any property set in the property drawer,
805 with its name in upper cases and colons added at the
806 beginning (i.e. `:CUSTOM_ID').
808 When RAW-SECONDARY-P is non-nil, headline's title will not be
809 parsed as a secondary string, but as a plain string instead.
811 Assume point is at beginning of the headline."
812 (save-excursion
813 (let* ((components (org-heading-components))
814 (level (nth 1 components))
815 (todo (nth 2 components))
816 (todo-type
817 (and todo (if (member todo org-done-keywords) 'done 'todo)))
818 (tags (let ((raw-tags (nth 5 components)))
819 (and raw-tags (org-split-string raw-tags ":"))))
820 (raw-value (or (nth 4 components) ""))
821 (quotedp
822 (let ((case-fold-search nil))
823 (string-match (format "^%s\\( \\|$\\)" org-quote-string)
824 raw-value)))
825 (commentedp
826 (let ((case-fold-search nil))
827 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
828 raw-value)))
829 (archivedp (member org-archive-tag tags))
830 (footnote-section-p (and org-footnote-section
831 (string= org-footnote-section raw-value)))
832 ;; Upcase property names. It avoids confusion between
833 ;; properties obtained through property drawer and default
834 ;; properties from the parser (e.g. `:end' and :END:)
835 (standard-props
836 (let (plist)
837 (mapc
838 (lambda (p)
839 (setq plist
840 (plist-put plist
841 (intern (concat ":" (upcase (car p))))
842 (cdr p))))
843 (org-entry-properties nil 'standard))
844 plist))
845 (time-props
846 ;; Read time properties on the line below the headline.
847 (save-excursion
848 (when (progn (forward-line)
849 (looking-at org-planning-or-clock-line-re))
850 (let ((end (line-end-position)) plist)
851 (while (re-search-forward
852 org-keyword-time-not-clock-regexp end t)
853 (goto-char (match-end 1))
854 (skip-chars-forward " \t")
855 (let ((keyword (match-string 1))
856 (time (org-element-timestamp-parser)))
857 (cond ((equal keyword org-scheduled-string)
858 (setq plist (plist-put plist :scheduled time)))
859 ((equal keyword org-deadline-string)
860 (setq plist (plist-put plist :deadline time)))
861 (t (setq plist (plist-put plist :closed time))))))
862 plist))))
863 (begin (point))
864 (end (save-excursion (goto-char (org-end-of-subtree t t))))
865 (pos-after-head (progn (forward-line) (point)))
866 (contents-begin (save-excursion
867 (skip-chars-forward " \r\t\n" end)
868 (and (/= (point) end) (line-beginning-position))))
869 (contents-end (and contents-begin
870 (progn (goto-char end)
871 (skip-chars-backward " \r\t\n")
872 (forward-line)
873 (point)))))
874 ;; Clean RAW-VALUE from any quote or comment string.
875 (when (or quotedp commentedp)
876 (let ((case-fold-search nil))
877 (setq raw-value
878 (replace-regexp-in-string
879 (concat
880 (regexp-opt (list org-quote-string org-comment-string))
881 "\\(?: \\|$\\)")
883 raw-value))))
884 ;; Clean TAGS from archive tag, if any.
885 (when archivedp (setq tags (delete org-archive-tag tags)))
886 (let ((headline
887 (list 'headline
888 (nconc
889 (list :raw-value raw-value
890 :begin begin
891 :end end
892 :pre-blank
893 (if (not contents-begin) 0
894 (count-lines pos-after-head contents-begin))
895 :contents-begin contents-begin
896 :contents-end contents-end
897 :level level
898 :priority (nth 3 components)
899 :tags tags
900 :todo-keyword todo
901 :todo-type todo-type
902 :post-blank (count-lines
903 (if (not contents-end) pos-after-head
904 (goto-char contents-end)
905 (forward-line)
906 (point))
907 end)
908 :footnote-section-p footnote-section-p
909 :archivedp archivedp
910 :commentedp commentedp
911 :quotedp quotedp)
912 time-props
913 standard-props))))
914 (let ((alt-title (org-element-property :ALT_TITLE headline)))
915 (when alt-title
916 (org-element-put-property
917 headline :alt-title
918 (if raw-secondary-p alt-title
919 (org-element-parse-secondary-string
920 alt-title (org-element-restriction 'headline) headline)))))
921 (org-element-put-property
922 headline :title
923 (if raw-secondary-p raw-value
924 (org-element-parse-secondary-string
925 raw-value (org-element-restriction 'headline) headline)))))))
927 (defun org-element-headline-interpreter (headline contents)
928 "Interpret HEADLINE element as Org syntax.
929 CONTENTS is the contents of the element."
930 (let* ((level (org-element-property :level headline))
931 (todo (org-element-property :todo-keyword headline))
932 (priority (org-element-property :priority headline))
933 (title (org-element-interpret-data
934 (org-element-property :title headline)))
935 (tags (let ((tag-list (if (org-element-property :archivedp headline)
936 (cons org-archive-tag
937 (org-element-property :tags headline))
938 (org-element-property :tags headline))))
939 (and tag-list
940 (format ":%s:" (mapconcat 'identity tag-list ":")))))
941 (commentedp (org-element-property :commentedp headline))
942 (quotedp (org-element-property :quotedp headline))
943 (pre-blank (or (org-element-property :pre-blank headline) 0))
944 (heading (concat (make-string (org-reduced-level level) ?*)
945 (and todo (concat " " todo))
946 (and quotedp (concat " " org-quote-string))
947 (and commentedp (concat " " org-comment-string))
948 (and priority
949 (format " [#%s]" (char-to-string priority)))
950 (cond ((and org-footnote-section
951 (org-element-property
952 :footnote-section-p headline))
953 (concat " " org-footnote-section))
954 (title (concat " " title))))))
955 (concat heading
956 ;; Align tags.
957 (when tags
958 (cond
959 ((zerop org-tags-column) (format " %s" tags))
960 ((< org-tags-column 0)
961 (concat
962 (make-string
963 (max (- (+ org-tags-column (length heading) (length tags))) 1)
965 tags))
967 (concat
968 (make-string (max (- org-tags-column (length heading)) 1) ? )
969 tags))))
970 (make-string (1+ pre-blank) 10)
971 contents)))
974 ;;;; Inlinetask
976 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
977 "Parse an inline task.
979 Return a list whose CAR is `inlinetask' and CDR is a plist
980 containing `:title', `:begin', `:end', `:contents-begin' and
981 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
982 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
983 `:closed' and `:post-blank' keywords.
985 The plist also contains any property set in the property drawer,
986 with its name in upper cases and colons added at the
987 beginning (i.e. `:CUSTOM_ID').
989 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
990 title will not be parsed as a secondary string, but as a plain
991 string instead.
993 Assume point is at beginning of the inline task."
994 (save-excursion
995 (let* ((begin (point))
996 (components (org-heading-components))
997 (todo (nth 2 components))
998 (todo-type (and todo
999 (if (member todo org-done-keywords) 'done 'todo)))
1000 (tags (let ((raw-tags (nth 5 components)))
1001 (and raw-tags (org-split-string raw-tags ":"))))
1002 (raw-value (or (nth 4 components) ""))
1003 ;; Upcase property names. It avoids confusion between
1004 ;; properties obtained through property drawer and default
1005 ;; properties from the parser (e.g. `:end' and :END:)
1006 (standard-props
1007 (let (plist)
1008 (mapc
1009 (lambda (p)
1010 (setq plist
1011 (plist-put plist
1012 (intern (concat ":" (upcase (car p))))
1013 (cdr p))))
1014 (org-entry-properties nil 'standard))
1015 plist))
1016 (time-props
1017 ;; Read time properties on the line below the inlinetask
1018 ;; opening string.
1019 (save-excursion
1020 (when (progn (forward-line)
1021 (looking-at org-planning-or-clock-line-re))
1022 (let ((end (line-end-position)) plist)
1023 (while (re-search-forward
1024 org-keyword-time-not-clock-regexp end t)
1025 (goto-char (match-end 1))
1026 (skip-chars-forward " \t")
1027 (let ((keyword (match-string 1))
1028 (time (org-element-timestamp-parser)))
1029 (cond ((equal keyword org-scheduled-string)
1030 (setq plist (plist-put plist :scheduled time)))
1031 ((equal keyword org-deadline-string)
1032 (setq plist (plist-put plist :deadline time)))
1033 (t (setq plist (plist-put plist :closed time))))))
1034 plist))))
1035 (task-end (save-excursion
1036 (end-of-line)
1037 (and (re-search-forward "^\\*+ END" limit t)
1038 (match-beginning 0))))
1039 (contents-begin (progn (forward-line)
1040 (and task-end (< (point) task-end) (point))))
1041 (contents-end (and contents-begin task-end))
1042 (before-blank (if (not task-end) (point)
1043 (goto-char task-end)
1044 (forward-line)
1045 (point)))
1046 (end (progn (skip-chars-forward " \r\t\n" limit)
1047 (if (eobp) (point) (line-beginning-position))))
1048 (inlinetask
1049 (list 'inlinetask
1050 (nconc
1051 (list :raw-value raw-value
1052 :begin begin
1053 :end end
1054 :contents-begin contents-begin
1055 :contents-end contents-end
1056 :level (nth 1 components)
1057 :priority (nth 3 components)
1058 :tags tags
1059 :todo-keyword todo
1060 :todo-type todo-type
1061 :post-blank (count-lines before-blank end))
1062 time-props
1063 standard-props))))
1064 (org-element-put-property
1065 inlinetask :title
1066 (if raw-secondary-p raw-value
1067 (org-element-parse-secondary-string
1068 raw-value
1069 (org-element-restriction 'inlinetask)
1070 inlinetask))))))
1072 (defun org-element-inlinetask-interpreter (inlinetask contents)
1073 "Interpret INLINETASK element as Org syntax.
1074 CONTENTS is the contents of inlinetask."
1075 (let* ((level (org-element-property :level inlinetask))
1076 (todo (org-element-property :todo-keyword inlinetask))
1077 (priority (org-element-property :priority inlinetask))
1078 (title (org-element-interpret-data
1079 (org-element-property :title inlinetask)))
1080 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1081 (and tag-list
1082 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1083 (task (concat (make-string level ?*)
1084 (and todo (concat " " todo))
1085 (and priority
1086 (format " [#%s]" (char-to-string priority)))
1087 (and title (concat " " title)))))
1088 (concat task
1089 ;; Align tags.
1090 (when tags
1091 (cond
1092 ((zerop org-tags-column) (format " %s" tags))
1093 ((< org-tags-column 0)
1094 (concat
1095 (make-string
1096 (max (- (+ org-tags-column (length task) (length tags))) 1)
1098 tags))
1100 (concat
1101 (make-string (max (- org-tags-column (length task)) 1) ? )
1102 tags))))
1103 ;; Prefer degenerate inlinetasks when there are no
1104 ;; contents.
1105 (when contents
1106 (concat "\n"
1107 contents
1108 (make-string level ?*) " END")))))
1111 ;;;; Item
1113 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1114 "Parse an item.
1116 STRUCT is the structure of the plain list.
1118 Return a list whose CAR is `item' and CDR is a plist containing
1119 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1120 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1121 keywords.
1123 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1124 any, will not be parsed as a secondary string, but as a plain
1125 string instead.
1127 Assume point is at the beginning of the item."
1128 (save-excursion
1129 (beginning-of-line)
1130 (looking-at org-list-full-item-re)
1131 (let* ((begin (point))
1132 (bullet (org-match-string-no-properties 1))
1133 (checkbox (let ((box (org-match-string-no-properties 3)))
1134 (cond ((equal "[ ]" box) 'off)
1135 ((equal "[X]" box) 'on)
1136 ((equal "[-]" box) 'trans))))
1137 (counter (let ((c (org-match-string-no-properties 2)))
1138 (save-match-data
1139 (cond
1140 ((not c) nil)
1141 ((string-match "[A-Za-z]" c)
1142 (- (string-to-char (upcase (match-string 0 c)))
1143 64))
1144 ((string-match "[0-9]+" c)
1145 (string-to-number (match-string 0 c)))))))
1146 (end (progn (goto-char (nth 6 (assq (point) struct)))
1147 (unless (bolp) (forward-line))
1148 (point)))
1149 (contents-begin
1150 (progn (goto-char
1151 ;; Ignore tags in un-ordered lists: they are just
1152 ;; a part of item's body.
1153 (if (and (match-beginning 4)
1154 (save-match-data (string-match "[.)]" bullet)))
1155 (match-beginning 4)
1156 (match-end 0)))
1157 (skip-chars-forward " \r\t\n" limit)
1158 ;; If first line isn't empty, contents really start
1159 ;; at the text after item's meta-data.
1160 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1161 (contents-end (progn (goto-char end)
1162 (skip-chars-backward " \r\t\n")
1163 (forward-line)
1164 (point)))
1165 (item
1166 (list 'item
1167 (list :bullet bullet
1168 :begin begin
1169 :end end
1170 ;; CONTENTS-BEGIN and CONTENTS-END may be
1171 ;; mixed up in the case of an empty item
1172 ;; separated from the next by a blank line.
1173 ;; Thus ensure the former is always the
1174 ;; smallest.
1175 :contents-begin (min contents-begin contents-end)
1176 :contents-end (max contents-begin contents-end)
1177 :checkbox checkbox
1178 :counter counter
1179 :structure struct
1180 :post-blank (count-lines contents-end end)))))
1181 (org-element-put-property
1182 item :tag
1183 (let ((raw-tag (org-list-get-tag begin struct)))
1184 (and raw-tag
1185 (if raw-secondary-p raw-tag
1186 (org-element-parse-secondary-string
1187 raw-tag (org-element-restriction 'item) item))))))))
1189 (defun org-element-item-interpreter (item contents)
1190 "Interpret ITEM element as Org syntax.
1191 CONTENTS is the contents of the element."
1192 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1193 (org-list-bullet-string
1194 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1195 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1196 (t "1.")))))
1197 (checkbox (org-element-property :checkbox item))
1198 (counter (org-element-property :counter item))
1199 (tag (let ((tag (org-element-property :tag item)))
1200 (and tag (org-element-interpret-data tag))))
1201 ;; Compute indentation.
1202 (ind (make-string (length bullet) 32))
1203 (item-starts-with-par-p
1204 (eq (org-element-type (car (org-element-contents item)))
1205 'paragraph)))
1206 ;; Indent contents.
1207 (concat
1208 bullet
1209 (and counter (format "[@%d] " counter))
1210 (case checkbox
1211 (on "[X] ")
1212 (off "[ ] ")
1213 (trans "[-] "))
1214 (and tag (format "%s :: " tag))
1215 (when contents
1216 (let ((contents (replace-regexp-in-string
1217 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1218 (if item-starts-with-par-p (org-trim contents)
1219 (concat "\n" contents)))))))
1222 ;;;; Plain List
1224 (defun org-element--list-struct (limit)
1225 ;; Return structure of list at point. Internal function. See
1226 ;; `org-list-struct' for details.
1227 (let ((case-fold-search t)
1228 (top-ind limit)
1229 (item-re (org-item-re))
1230 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1231 items struct)
1232 (save-excursion
1233 (catch 'exit
1234 (while t
1235 (cond
1236 ;; At limit: end all items.
1237 ((>= (point) limit)
1238 (throw 'exit
1239 (let ((end (progn (skip-chars-backward " \r\t\n")
1240 (forward-line)
1241 (point))))
1242 (dolist (item items (sort (nconc items struct)
1243 'car-less-than-car))
1244 (setcar (nthcdr 6 item) end)))))
1245 ;; At list end: end all items.
1246 ((looking-at org-list-end-re)
1247 (throw 'exit (dolist (item items (sort (nconc items struct)
1248 'car-less-than-car))
1249 (setcar (nthcdr 6 item) (point)))))
1250 ;; At a new item: end previous sibling.
1251 ((looking-at item-re)
1252 (let ((ind (save-excursion (skip-chars-forward " \t")
1253 (current-column))))
1254 (setq top-ind (min top-ind ind))
1255 (while (and items (<= ind (nth 1 (car items))))
1256 (let ((item (pop items)))
1257 (setcar (nthcdr 6 item) (point))
1258 (push item struct)))
1259 (push (progn (looking-at org-list-full-item-re)
1260 (let ((bullet (match-string-no-properties 1)))
1261 (list (point)
1263 bullet
1264 (match-string-no-properties 2) ; counter
1265 (match-string-no-properties 3) ; checkbox
1266 ;; Description tag.
1267 (and (save-match-data
1268 (string-match "[-+*]" bullet))
1269 (match-string-no-properties 4))
1270 ;; Ending position, unknown so far.
1271 nil)))
1272 items))
1273 (forward-line 1))
1274 ;; Skip empty lines.
1275 ((looking-at "^[ \t]*$") (forward-line))
1276 ;; Skip inline tasks and blank lines along the way.
1277 ((and inlinetask-re (looking-at inlinetask-re))
1278 (forward-line)
1279 (let ((origin (point)))
1280 (when (re-search-forward inlinetask-re limit t)
1281 (if (looking-at "^\\*+ END[ \t]*$") (forward-line)
1282 (goto-char origin)))))
1283 ;; At some text line. Check if it ends any previous item.
1285 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1286 (when (<= ind top-ind)
1287 (skip-chars-backward " \r\t\n")
1288 (forward-line))
1289 (while (<= ind (nth 1 (car items)))
1290 (let ((item (pop items)))
1291 (setcar (nthcdr 6 item) (line-beginning-position))
1292 (push item struct)
1293 (unless items
1294 (throw 'exit (sort struct 'car-less-than-car))))))
1295 ;; Skip blocks (any type) and drawers contents.
1296 (cond
1297 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1298 (re-search-forward
1299 (format "^[ \t]*#\\+END%s[ \t]*$"
1300 (org-match-string-no-properties 1))
1301 limit t)))
1302 ((and (looking-at org-drawer-regexp)
1303 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1304 (forward-line))))))))
1306 (defun org-element-plain-list-parser (limit affiliated structure)
1307 "Parse a plain list.
1309 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1310 the buffer position at the beginning of the first affiliated
1311 keyword and CDR is a plist of affiliated keywords along with
1312 their value. STRUCTURE is the structure of the plain list being
1313 parsed.
1315 Return a list whose CAR is `plain-list' and CDR is a plist
1316 containing `:type', `:begin', `:end', `:contents-begin' and
1317 `:contents-end', `:structure', `:post-blank' and
1318 `:post-affiliated' keywords.
1320 Assume point is at the beginning of the list."
1321 (save-excursion
1322 (let* ((struct (or structure (org-element--list-struct limit)))
1323 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1324 ((nth 5 (assq (point) struct)) 'descriptive)
1325 (t 'unordered)))
1326 (contents-begin (point))
1327 (begin (car affiliated))
1328 (contents-end (let* ((item (assq contents-begin struct))
1329 (ind (nth 1 item))
1330 (pos (nth 6 item)))
1331 (while (and (setq item (assq pos struct))
1332 (= (nth 1 item) ind))
1333 (setq pos (nth 6 item)))
1334 pos))
1335 (end (progn (goto-char contents-end)
1336 (skip-chars-forward " \r\t\n" limit)
1337 (if (= (point) limit) limit (line-beginning-position)))))
1338 ;; Return value.
1339 (list 'plain-list
1340 (nconc
1341 (list :type type
1342 :begin begin
1343 :end end
1344 :contents-begin contents-begin
1345 :contents-end contents-end
1346 :structure struct
1347 :post-blank (count-lines contents-end end)
1348 :post-affiliated contents-begin)
1349 (cdr affiliated))))))
1351 (defun org-element-plain-list-interpreter (plain-list contents)
1352 "Interpret PLAIN-LIST element as Org syntax.
1353 CONTENTS is the contents of the element."
1354 (with-temp-buffer
1355 (insert contents)
1356 (goto-char (point-min))
1357 (org-list-repair)
1358 (buffer-string)))
1361 ;;;; Property Drawer
1363 (defun org-element-property-drawer-parser (limit affiliated)
1364 "Parse a property drawer.
1366 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1367 the buffer position at the beginning of the first affiliated
1368 keyword and CDR is a plist of affiliated keywords along with
1369 their value.
1371 Return a list whose CAR is `property-drawer' and CDR is a plist
1372 containing `:begin', `:end', `:contents-begin', `:contents-end',
1373 `:post-blank' and `:post-affiliated' keywords.
1375 Assume point is at the beginning of the property drawer."
1376 (save-excursion
1377 (let ((case-fold-search t))
1378 (if (not (save-excursion
1379 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1380 ;; Incomplete drawer: parse it as a paragraph.
1381 (org-element-paragraph-parser limit affiliated)
1382 (save-excursion
1383 (let* ((drawer-end-line (match-beginning 0))
1384 (begin (car affiliated))
1385 (post-affiliated (point))
1386 (contents-begin (progn (forward-line)
1387 (and (< (point) drawer-end-line)
1388 (point))))
1389 (contents-end (and contents-begin drawer-end-line))
1390 (pos-before-blank (progn (goto-char drawer-end-line)
1391 (forward-line)
1392 (point)))
1393 (end (progn (skip-chars-forward " \r\t\n" limit)
1394 (if (eobp) (point) (line-beginning-position)))))
1395 (list 'property-drawer
1396 (nconc
1397 (list :begin begin
1398 :end end
1399 :contents-begin contents-begin
1400 :contents-end contents-end
1401 :post-blank (count-lines pos-before-blank end)
1402 :post-affiliated post-affiliated)
1403 (cdr affiliated)))))))))
1405 (defun org-element-property-drawer-interpreter (property-drawer contents)
1406 "Interpret PROPERTY-DRAWER element as Org syntax.
1407 CONTENTS is the properties within the drawer."
1408 (format ":PROPERTIES:\n%s:END:" contents))
1411 ;;;; Quote Block
1413 (defun org-element-quote-block-parser (limit affiliated)
1414 "Parse a quote block.
1416 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1417 the buffer position at the beginning of the first affiliated
1418 keyword and CDR is a plist of affiliated keywords along with
1419 their value.
1421 Return a list whose CAR is `quote-block' and CDR is a plist
1422 containing `:begin', `:end', `:contents-begin', `:contents-end',
1423 `:post-blank' and `:post-affiliated' keywords.
1425 Assume point is at the beginning of the block."
1426 (let ((case-fold-search t))
1427 (if (not (save-excursion
1428 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1429 ;; Incomplete block: parse it as a paragraph.
1430 (org-element-paragraph-parser limit affiliated)
1431 (let ((block-end-line (match-beginning 0)))
1432 (save-excursion
1433 (let* ((begin (car affiliated))
1434 (post-affiliated (point))
1435 ;; Empty blocks have no contents.
1436 (contents-begin (progn (forward-line)
1437 (and (< (point) block-end-line)
1438 (point))))
1439 (contents-end (and contents-begin block-end-line))
1440 (pos-before-blank (progn (goto-char block-end-line)
1441 (forward-line)
1442 (point)))
1443 (end (progn (skip-chars-forward " \r\t\n" limit)
1444 (if (eobp) (point) (line-beginning-position)))))
1445 (list 'quote-block
1446 (nconc
1447 (list :begin begin
1448 :end end
1449 :contents-begin contents-begin
1450 :contents-end contents-end
1451 :post-blank (count-lines pos-before-blank end)
1452 :post-affiliated post-affiliated)
1453 (cdr affiliated)))))))))
1455 (defun org-element-quote-block-interpreter (quote-block contents)
1456 "Interpret QUOTE-BLOCK element as Org syntax.
1457 CONTENTS is the contents of the element."
1458 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1461 ;;;; Section
1463 (defun org-element-section-parser (limit)
1464 "Parse a section.
1466 LIMIT bounds the search.
1468 Return a list whose CAR is `section' and CDR is a plist
1469 containing `:begin', `:end', `:contents-begin', `contents-end'
1470 and `:post-blank' keywords."
1471 (save-excursion
1472 ;; Beginning of section is the beginning of the first non-blank
1473 ;; line after previous headline.
1474 (let ((begin (point))
1475 (end (progn (org-with-limited-levels (outline-next-heading))
1476 (point)))
1477 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1478 (forward-line)
1479 (point))))
1480 (list 'section
1481 (list :begin begin
1482 :end end
1483 :contents-begin begin
1484 :contents-end pos-before-blank
1485 :post-blank (count-lines pos-before-blank end))))))
1487 (defun org-element-section-interpreter (section contents)
1488 "Interpret SECTION element as Org syntax.
1489 CONTENTS is the contents of the element."
1490 contents)
1493 ;;;; Special Block
1495 (defun org-element-special-block-parser (limit affiliated)
1496 "Parse a special block.
1498 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1499 the buffer position at the beginning of the first affiliated
1500 keyword and CDR is a plist of affiliated keywords along with
1501 their value.
1503 Return a list whose CAR is `special-block' and CDR is a plist
1504 containing `:type', `:begin', `:end', `:contents-begin',
1505 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1507 Assume point is at the beginning of the block."
1508 (let* ((case-fold-search t)
1509 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1510 (upcase (match-string-no-properties 1)))))
1511 (if (not (save-excursion
1512 (re-search-forward
1513 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1514 limit t)))
1515 ;; Incomplete block: parse it as a paragraph.
1516 (org-element-paragraph-parser limit affiliated)
1517 (let ((block-end-line (match-beginning 0)))
1518 (save-excursion
1519 (let* ((begin (car affiliated))
1520 (post-affiliated (point))
1521 ;; Empty blocks have no contents.
1522 (contents-begin (progn (forward-line)
1523 (and (< (point) block-end-line)
1524 (point))))
1525 (contents-end (and contents-begin block-end-line))
1526 (pos-before-blank (progn (goto-char block-end-line)
1527 (forward-line)
1528 (point)))
1529 (end (progn (skip-chars-forward " \r\t\n" limit)
1530 (if (eobp) (point) (line-beginning-position)))))
1531 (list 'special-block
1532 (nconc
1533 (list :type type
1534 :begin begin
1535 :end end
1536 :contents-begin contents-begin
1537 :contents-end contents-end
1538 :post-blank (count-lines pos-before-blank end)
1539 :post-affiliated post-affiliated)
1540 (cdr affiliated)))))))))
1542 (defun org-element-special-block-interpreter (special-block contents)
1543 "Interpret SPECIAL-BLOCK element as Org syntax.
1544 CONTENTS is the contents of the element."
1545 (let ((block-type (org-element-property :type special-block)))
1546 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1550 ;;; Elements
1552 ;; For each element, a parser and an interpreter are also defined.
1553 ;; Both follow the same naming convention used for greater elements.
1555 ;; Also, as for greater elements, adding a new element type is done
1556 ;; through the following steps: implement a parser and an interpreter,
1557 ;; tweak `org-element--current-element' so that it recognizes the new
1558 ;; type and add that new type to `org-element-all-elements'.
1560 ;; As a special case, when the newly defined type is a block type,
1561 ;; `org-element-block-name-alist' has to be modified accordingly.
1564 ;;;; Babel Call
1566 (defun org-element-babel-call-parser (limit affiliated)
1567 "Parse a babel call.
1569 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1570 the buffer position at the beginning of the first affiliated
1571 keyword and CDR is a plist of affiliated keywords along with
1572 their value.
1574 Return a list whose CAR is `babel-call' and CDR is a plist
1575 containing `:begin', `:end', `:value', `:post-blank' and
1576 `:post-affiliated' as keywords."
1577 (save-excursion
1578 (let ((begin (car affiliated))
1579 (post-affiliated (point))
1580 (value (progn (let ((case-fold-search t))
1581 (re-search-forward "call:[ \t]*" nil t))
1582 (buffer-substring-no-properties (point)
1583 (line-end-position))))
1584 (pos-before-blank (progn (forward-line) (point)))
1585 (end (progn (skip-chars-forward " \r\t\n" limit)
1586 (if (eobp) (point) (line-beginning-position)))))
1587 (list 'babel-call
1588 (nconc
1589 (list :begin begin
1590 :end end
1591 :value value
1592 :post-blank (count-lines pos-before-blank end)
1593 :post-affiliated post-affiliated)
1594 (cdr affiliated))))))
1596 (defun org-element-babel-call-interpreter (babel-call contents)
1597 "Interpret BABEL-CALL element as Org syntax.
1598 CONTENTS is nil."
1599 (concat "#+CALL: " (org-element-property :value babel-call)))
1602 ;;;; Clock
1604 (defun org-element-clock-parser (limit)
1605 "Parse a clock.
1607 LIMIT bounds the search.
1609 Return a list whose CAR is `clock' and CDR is a plist containing
1610 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1611 as keywords."
1612 (save-excursion
1613 (let* ((case-fold-search nil)
1614 (begin (point))
1615 (value (progn (search-forward org-clock-string (line-end-position) t)
1616 (skip-chars-forward " \t")
1617 (org-element-timestamp-parser)))
1618 (duration (and (search-forward " => " (line-end-position) t)
1619 (progn (skip-chars-forward " \t")
1620 (looking-at "\\(\\S-+\\)[ \t]*$"))
1621 (org-match-string-no-properties 1)))
1622 (status (if duration 'closed 'running))
1623 (post-blank (let ((before-blank (progn (forward-line) (point))))
1624 (skip-chars-forward " \r\t\n" limit)
1625 (skip-chars-backward " \t")
1626 (unless (bolp) (end-of-line))
1627 (count-lines before-blank (point))))
1628 (end (point)))
1629 (list 'clock
1630 (list :status status
1631 :value value
1632 :duration duration
1633 :begin begin
1634 :end end
1635 :post-blank post-blank)))))
1637 (defun org-element-clock-interpreter (clock contents)
1638 "Interpret CLOCK element as Org syntax.
1639 CONTENTS is nil."
1640 (concat org-clock-string " "
1641 (org-element-timestamp-interpreter
1642 (org-element-property :value clock) nil)
1643 (let ((duration (org-element-property :duration clock)))
1644 (and duration
1645 (concat " => "
1646 (apply 'format
1647 "%2s:%02s"
1648 (org-split-string duration ":")))))))
1651 ;;;; Comment
1653 (defun org-element-comment-parser (limit affiliated)
1654 "Parse a comment.
1656 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1657 the buffer position at the beginning of the first affiliated
1658 keyword and CDR is a plist of affiliated keywords along with
1659 their value.
1661 Return a list whose CAR is `comment' and CDR is a plist
1662 containing `:begin', `:end', `:value', `:post-blank',
1663 `:post-affiliated' keywords.
1665 Assume point is at comment beginning."
1666 (save-excursion
1667 (let* ((begin (car affiliated))
1668 (post-affiliated (point))
1669 (value (prog2 (looking-at "[ \t]*# ?")
1670 (buffer-substring-no-properties
1671 (match-end 0) (line-end-position))
1672 (forward-line)))
1673 (com-end
1674 ;; Get comments ending.
1675 (progn
1676 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1677 ;; Accumulate lines without leading hash and first
1678 ;; whitespace.
1679 (setq value
1680 (concat value
1681 "\n"
1682 (buffer-substring-no-properties
1683 (match-end 0) (line-end-position))))
1684 (forward-line))
1685 (point)))
1686 (end (progn (goto-char com-end)
1687 (skip-chars-forward " \r\t\n" limit)
1688 (if (eobp) (point) (line-beginning-position)))))
1689 (list 'comment
1690 (nconc
1691 (list :begin begin
1692 :end end
1693 :value value
1694 :post-blank (count-lines com-end end)
1695 :post-affiliated post-affiliated)
1696 (cdr affiliated))))))
1698 (defun org-element-comment-interpreter (comment contents)
1699 "Interpret COMMENT element as Org syntax.
1700 CONTENTS is nil."
1701 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1704 ;;;; Comment Block
1706 (defun org-element-comment-block-parser (limit affiliated)
1707 "Parse an export block.
1709 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1710 the buffer position at the beginning of the first affiliated
1711 keyword and CDR is a plist of affiliated keywords along with
1712 their value.
1714 Return a list whose CAR is `comment-block' and CDR is a plist
1715 containing `:begin', `:end', `:value', `:post-blank' and
1716 `:post-affiliated' keywords.
1718 Assume point is at comment block beginning."
1719 (let ((case-fold-search t))
1720 (if (not (save-excursion
1721 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1722 ;; Incomplete block: parse it as a paragraph.
1723 (org-element-paragraph-parser limit affiliated)
1724 (let ((contents-end (match-beginning 0)))
1725 (save-excursion
1726 (let* ((begin (car affiliated))
1727 (post-affiliated (point))
1728 (contents-begin (progn (forward-line) (point)))
1729 (pos-before-blank (progn (goto-char contents-end)
1730 (forward-line)
1731 (point)))
1732 (end (progn (skip-chars-forward " \r\t\n" limit)
1733 (if (eobp) (point) (line-beginning-position))))
1734 (value (buffer-substring-no-properties
1735 contents-begin contents-end)))
1736 (list 'comment-block
1737 (nconc
1738 (list :begin begin
1739 :end end
1740 :value value
1741 :post-blank (count-lines pos-before-blank end)
1742 :post-affiliated post-affiliated)
1743 (cdr affiliated)))))))))
1745 (defun org-element-comment-block-interpreter (comment-block contents)
1746 "Interpret COMMENT-BLOCK element as Org syntax.
1747 CONTENTS is nil."
1748 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1749 (org-remove-indentation (org-element-property :value comment-block))))
1752 ;;;; Diary Sexp
1754 (defun org-element-diary-sexp-parser (limit affiliated)
1755 "Parse a diary sexp.
1757 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1758 the buffer position at the beginning of the first affiliated
1759 keyword and CDR is a plist of affiliated keywords along with
1760 their value.
1762 Return a list whose CAR is `diary-sexp' and CDR is a plist
1763 containing `:begin', `:end', `:value', `:post-blank' and
1764 `:post-affiliated' keywords."
1765 (save-excursion
1766 (let ((begin (car affiliated))
1767 (post-affiliated (point))
1768 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1769 (org-match-string-no-properties 1)))
1770 (pos-before-blank (progn (forward-line) (point)))
1771 (end (progn (skip-chars-forward " \r\t\n" limit)
1772 (if (eobp) (point) (line-beginning-position)))))
1773 (list 'diary-sexp
1774 (nconc
1775 (list :value value
1776 :begin begin
1777 :end end
1778 :post-blank (count-lines pos-before-blank end)
1779 :post-affiliated post-affiliated)
1780 (cdr affiliated))))))
1782 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1783 "Interpret DIARY-SEXP as Org syntax.
1784 CONTENTS is nil."
1785 (org-element-property :value diary-sexp))
1788 ;;;; Example Block
1790 (defun org-element-example-block-parser (limit affiliated)
1791 "Parse an example block.
1793 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1794 the buffer position at the beginning of the first affiliated
1795 keyword and CDR is a plist of affiliated keywords along with
1796 their value.
1798 Return a list whose CAR is `example-block' and CDR is a plist
1799 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1800 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1801 `:value', `:post-blank' and `:post-affiliated' keywords."
1802 (let ((case-fold-search t))
1803 (if (not (save-excursion
1804 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1805 ;; Incomplete block: parse it as a paragraph.
1806 (org-element-paragraph-parser limit affiliated)
1807 (let ((contents-end (match-beginning 0)))
1808 (save-excursion
1809 (let* ((switches
1810 (progn
1811 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1812 (org-match-string-no-properties 1)))
1813 ;; Switches analysis
1814 (number-lines
1815 (cond ((not switches) nil)
1816 ((string-match "-n\\>" switches) 'new)
1817 ((string-match "+n\\>" switches) 'continued)))
1818 (preserve-indent
1819 (and switches (string-match "-i\\>" switches)))
1820 ;; Should labels be retained in (or stripped from) example
1821 ;; blocks?
1822 (retain-labels
1823 (or (not switches)
1824 (not (string-match "-r\\>" switches))
1825 (and number-lines (string-match "-k\\>" switches))))
1826 ;; What should code-references use - labels or
1827 ;; line-numbers?
1828 (use-labels
1829 (or (not switches)
1830 (and retain-labels
1831 (not (string-match "-k\\>" switches)))))
1832 (label-fmt
1833 (and switches
1834 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1835 (match-string 1 switches)))
1836 ;; Standard block parsing.
1837 (begin (car affiliated))
1838 (post-affiliated (point))
1839 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1840 (contents-begin (progn (forward-line) (point)))
1841 (value (org-element-remove-indentation
1842 (org-unescape-code-in-string
1843 (buffer-substring-no-properties
1844 contents-begin contents-end))
1845 block-ind))
1846 (pos-before-blank (progn (goto-char contents-end)
1847 (forward-line)
1848 (point)))
1849 (end (progn (skip-chars-forward " \r\t\n" limit)
1850 (if (eobp) (point) (line-beginning-position)))))
1851 (list 'example-block
1852 (nconc
1853 (list :begin begin
1854 :end end
1855 :value value
1856 :switches switches
1857 :number-lines number-lines
1858 :preserve-indent preserve-indent
1859 :retain-labels retain-labels
1860 :use-labels use-labels
1861 :label-fmt label-fmt
1862 :post-blank (count-lines pos-before-blank end)
1863 :post-affiliated post-affiliated)
1864 (cdr affiliated)))))))))
1866 (defun org-element-example-block-interpreter (example-block contents)
1867 "Interpret EXAMPLE-BLOCK element as Org syntax.
1868 CONTENTS is nil."
1869 (let ((switches (org-element-property :switches example-block))
1870 (value (org-element-property :value example-block)))
1871 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1872 (org-escape-code-in-string
1873 (if (or org-src-preserve-indentation
1874 (org-element-property :preserve-indent example-block))
1875 value
1876 (org-element-remove-indentation value)))
1877 "#+END_EXAMPLE")))
1880 ;;;; Export Block
1882 (defun org-element-export-block-parser (limit affiliated)
1883 "Parse an export block.
1885 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1886 the buffer position at the beginning of the first affiliated
1887 keyword and CDR is a plist of affiliated keywords along with
1888 their value.
1890 Return a list whose CAR is `export-block' and CDR is a plist
1891 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1892 `:post-affiliated' keywords.
1894 Assume point is at export-block beginning."
1895 (let* ((case-fold-search t)
1896 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1897 (upcase (org-match-string-no-properties 1)))))
1898 (if (not (save-excursion
1899 (re-search-forward
1900 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1901 ;; Incomplete block: parse it as a paragraph.
1902 (org-element-paragraph-parser limit affiliated)
1903 (let ((contents-end (match-beginning 0)))
1904 (save-excursion
1905 (let* ((begin (car affiliated))
1906 (post-affiliated (point))
1907 (contents-begin (progn (forward-line) (point)))
1908 (pos-before-blank (progn (goto-char contents-end)
1909 (forward-line)
1910 (point)))
1911 (end (progn (skip-chars-forward " \r\t\n" limit)
1912 (if (eobp) (point) (line-beginning-position))))
1913 (value (buffer-substring-no-properties contents-begin
1914 contents-end)))
1915 (list 'export-block
1916 (nconc
1917 (list :begin begin
1918 :end end
1919 :type type
1920 :value value
1921 :post-blank (count-lines pos-before-blank end)
1922 :post-affiliated post-affiliated)
1923 (cdr affiliated)))))))))
1925 (defun org-element-export-block-interpreter (export-block contents)
1926 "Interpret EXPORT-BLOCK element as Org syntax.
1927 CONTENTS is nil."
1928 (let ((type (org-element-property :type export-block)))
1929 (concat (format "#+BEGIN_%s\n" type)
1930 (org-element-property :value export-block)
1931 (format "#+END_%s" type))))
1934 ;;;; Fixed-width
1936 (defun org-element-fixed-width-parser (limit affiliated)
1937 "Parse a fixed-width section.
1939 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1940 the buffer position at the beginning of the first affiliated
1941 keyword and CDR is a plist of affiliated keywords along with
1942 their value.
1944 Return a list whose CAR is `fixed-width' and CDR is a plist
1945 containing `:begin', `:end', `:value', `:post-blank' and
1946 `:post-affiliated' keywords.
1948 Assume point is at the beginning of the fixed-width area."
1949 (save-excursion
1950 (let* ((begin (car affiliated))
1951 (post-affiliated (point))
1952 value
1953 (end-area
1954 (progn
1955 (while (and (< (point) limit)
1956 (looking-at "[ \t]*:\\( \\|$\\)"))
1957 ;; Accumulate text without starting colons.
1958 (setq value
1959 (concat value
1960 (buffer-substring-no-properties
1961 (match-end 0) (point-at-eol))
1962 "\n"))
1963 (forward-line))
1964 (point)))
1965 (end (progn (skip-chars-forward " \r\t\n" limit)
1966 (if (eobp) (point) (line-beginning-position)))))
1967 (list 'fixed-width
1968 (nconc
1969 (list :begin begin
1970 :end end
1971 :value value
1972 :post-blank (count-lines end-area end)
1973 :post-affiliated post-affiliated)
1974 (cdr affiliated))))))
1976 (defun org-element-fixed-width-interpreter (fixed-width contents)
1977 "Interpret FIXED-WIDTH element as Org syntax.
1978 CONTENTS is nil."
1979 (let ((value (org-element-property :value fixed-width)))
1980 (and value
1981 (replace-regexp-in-string
1982 "^" ": "
1983 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1986 ;;;; Horizontal Rule
1988 (defun org-element-horizontal-rule-parser (limit affiliated)
1989 "Parse an horizontal rule.
1991 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1992 the buffer position at the beginning of the first affiliated
1993 keyword and CDR is a plist of affiliated keywords along with
1994 their value.
1996 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1997 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1998 keywords."
1999 (save-excursion
2000 (let ((begin (car affiliated))
2001 (post-affiliated (point))
2002 (post-hr (progn (forward-line) (point)))
2003 (end (progn (skip-chars-forward " \r\t\n" limit)
2004 (if (eobp) (point) (line-beginning-position)))))
2005 (list 'horizontal-rule
2006 (nconc
2007 (list :begin begin
2008 :end end
2009 :post-blank (count-lines post-hr end)
2010 :post-affiliated post-affiliated)
2011 (cdr affiliated))))))
2013 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
2014 "Interpret HORIZONTAL-RULE element as Org syntax.
2015 CONTENTS is nil."
2016 "-----")
2019 ;;;; Keyword
2021 (defun org-element-keyword-parser (limit affiliated)
2022 "Parse a keyword at point.
2024 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2025 the buffer position at the beginning of the first affiliated
2026 keyword and CDR is a plist of affiliated keywords along with
2027 their value.
2029 Return a list whose CAR is `keyword' and CDR is a plist
2030 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2031 `:post-affiliated' keywords."
2032 (save-excursion
2033 ;; An orphaned affiliated keyword is considered as a regular
2034 ;; keyword. In this case AFFILIATED is nil, so we take care of
2035 ;; this corner case.
2036 (let ((begin (or (car affiliated) (point)))
2037 (post-affiliated (point))
2038 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2039 (upcase (org-match-string-no-properties 1))))
2040 (value (org-trim (buffer-substring-no-properties
2041 (match-end 0) (point-at-eol))))
2042 (pos-before-blank (progn (forward-line) (point)))
2043 (end (progn (skip-chars-forward " \r\t\n" limit)
2044 (if (eobp) (point) (line-beginning-position)))))
2045 (list 'keyword
2046 (nconc
2047 (list :key key
2048 :value value
2049 :begin begin
2050 :end end
2051 :post-blank (count-lines pos-before-blank end)
2052 :post-affiliated post-affiliated)
2053 (cdr affiliated))))))
2055 (defun org-element-keyword-interpreter (keyword contents)
2056 "Interpret KEYWORD element as Org syntax.
2057 CONTENTS is nil."
2058 (format "#+%s: %s"
2059 (org-element-property :key keyword)
2060 (org-element-property :value keyword)))
2063 ;;;; Latex Environment
2065 (defun org-element-latex-environment-parser (limit affiliated)
2066 "Parse a LaTeX environment.
2068 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2069 the buffer position at the beginning of the first affiliated
2070 keyword and CDR is a plist of affiliated keywords along with
2071 their value.
2073 Return a list whose CAR is `latex-environment' and CDR is a plist
2074 containing `:begin', `:end', `:value', `:post-blank' and
2075 `:post-affiliated' keywords.
2077 Assume point is at the beginning of the latex environment."
2078 (save-excursion
2079 (let ((case-fold-search t)
2080 (code-begin (point)))
2081 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2082 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2083 (regexp-quote (match-string 1)))
2084 limit t))
2085 ;; Incomplete latex environment: parse it as a paragraph.
2086 (org-element-paragraph-parser limit affiliated)
2087 (let* ((code-end (progn (forward-line) (point)))
2088 (begin (car affiliated))
2089 (value (buffer-substring-no-properties code-begin code-end))
2090 (end (progn (skip-chars-forward " \r\t\n" limit)
2091 (if (eobp) (point) (line-beginning-position)))))
2092 (list 'latex-environment
2093 (nconc
2094 (list :begin begin
2095 :end end
2096 :value value
2097 :post-blank (count-lines code-end end)
2098 :post-affiliated code-begin)
2099 (cdr affiliated))))))))
2101 (defun org-element-latex-environment-interpreter (latex-environment contents)
2102 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2103 CONTENTS is nil."
2104 (org-element-property :value latex-environment))
2107 ;;;; Node Property
2109 (defun org-element-node-property-parser (limit)
2110 "Parse a node-property at point.
2112 LIMIT bounds the search.
2114 Return a list whose CAR is `node-property' and CDR is a plist
2115 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2116 keywords."
2117 (save-excursion
2118 (looking-at org-property-re)
2119 (let ((case-fold-search t)
2120 (begin (point))
2121 (key (org-match-string-no-properties 2))
2122 (value (org-match-string-no-properties 3))
2123 (pos-before-blank (progn (forward-line) (point)))
2124 (end (progn (skip-chars-forward " \r\t\n" limit)
2125 (if (eobp) (point) (point-at-bol)))))
2126 (list 'node-property
2127 (list :key key
2128 :value value
2129 :begin begin
2130 :end end
2131 :post-blank (count-lines pos-before-blank end))))))
2133 (defun org-element-node-property-interpreter (node-property contents)
2134 "Interpret NODE-PROPERTY element as Org syntax.
2135 CONTENTS is nil."
2136 (format org-property-format
2137 (format ":%s:" (org-element-property :key node-property))
2138 (org-element-property :value node-property)))
2141 ;;;; Paragraph
2143 (defun org-element-paragraph-parser (limit affiliated)
2144 "Parse a paragraph.
2146 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2147 the buffer position at the beginning of the first affiliated
2148 keyword and CDR is a plist of affiliated keywords along with
2149 their value.
2151 Return a list whose CAR is `paragraph' and CDR is a plist
2152 containing `:begin', `:end', `:contents-begin' and
2153 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2155 Assume point is at the beginning of the paragraph."
2156 (save-excursion
2157 (let* ((begin (car affiliated))
2158 (contents-begin (point))
2159 (before-blank
2160 (let ((case-fold-search t))
2161 (end-of-line)
2162 (if (not (re-search-forward
2163 org-element-paragraph-separate limit 'm))
2164 limit
2165 ;; A matching `org-element-paragraph-separate' is not
2166 ;; necessarily the end of the paragraph. In
2167 ;; particular, lines starting with # or : as a first
2168 ;; non-space character are ambiguous. We have check
2169 ;; if they are valid Org syntax (i.e. not an
2170 ;; incomplete keyword).
2171 (beginning-of-line)
2172 (while (not
2174 ;; There's no ambiguity for other symbols or
2175 ;; empty lines: stop here.
2176 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2177 ;; Stop at valid fixed-width areas.
2178 (looking-at "[ \t]*:\\(?: \\|$\\)")
2179 ;; Stop at drawers.
2180 (and (looking-at org-drawer-regexp)
2181 (save-excursion
2182 (re-search-forward
2183 "^[ \t]*:END:[ \t]*$" limit t)))
2184 ;; Stop at valid comments.
2185 (looking-at "[ \t]*#\\(?: \\|$\\)")
2186 ;; Stop at valid dynamic blocks.
2187 (and (looking-at org-dblock-start-re)
2188 (save-excursion
2189 (re-search-forward
2190 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2191 ;; Stop at valid blocks.
2192 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2193 (save-excursion
2194 (re-search-forward
2195 (format "^[ \t]*#\\+END_%s[ \t]*$"
2196 (regexp-quote
2197 (org-match-string-no-properties 1)))
2198 limit t)))
2199 ;; Stop at valid latex environments.
2200 (and (looking-at
2201 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2202 (save-excursion
2203 (re-search-forward
2204 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2205 (regexp-quote
2206 (org-match-string-no-properties 1)))
2207 limit t)))
2208 ;; Stop at valid keywords.
2209 (looking-at "[ \t]*#\\+\\S-+:")
2210 ;; Skip everything else.
2211 (not
2212 (progn
2213 (end-of-line)
2214 (re-search-forward org-element-paragraph-separate
2215 limit 'm)))))
2216 (beginning-of-line)))
2217 (if (= (point) limit) limit
2218 (goto-char (line-beginning-position)))))
2219 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2220 (forward-line)
2221 (point)))
2222 (end (progn (skip-chars-forward " \r\t\n" limit)
2223 (if (eobp) (point) (line-beginning-position)))))
2224 (list 'paragraph
2225 (nconc
2226 (list :begin begin
2227 :end end
2228 :contents-begin contents-begin
2229 :contents-end contents-end
2230 :post-blank (count-lines before-blank end)
2231 :post-affiliated contents-begin)
2232 (cdr affiliated))))))
2234 (defun org-element-paragraph-interpreter (paragraph contents)
2235 "Interpret PARAGRAPH element as Org syntax.
2236 CONTENTS is the contents of the element."
2237 contents)
2240 ;;;; Planning
2242 (defun org-element-planning-parser (limit)
2243 "Parse a planning.
2245 LIMIT bounds the search.
2247 Return a list whose CAR is `planning' and CDR is a plist
2248 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2249 and `:post-blank' keywords."
2250 (save-excursion
2251 (let* ((case-fold-search nil)
2252 (begin (point))
2253 (post-blank (let ((before-blank (progn (forward-line) (point))))
2254 (skip-chars-forward " \r\t\n" limit)
2255 (skip-chars-backward " \t")
2256 (unless (bolp) (end-of-line))
2257 (count-lines before-blank (point))))
2258 (end (point))
2259 closed deadline scheduled)
2260 (goto-char begin)
2261 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2262 (goto-char (match-end 1))
2263 (skip-chars-forward " \t" end)
2264 (let ((keyword (match-string 1))
2265 (time (org-element-timestamp-parser)))
2266 (cond ((equal keyword org-closed-string) (setq closed time))
2267 ((equal keyword org-deadline-string) (setq deadline time))
2268 (t (setq scheduled time)))))
2269 (list 'planning
2270 (list :closed closed
2271 :deadline deadline
2272 :scheduled scheduled
2273 :begin begin
2274 :end end
2275 :post-blank post-blank)))))
2277 (defun org-element-planning-interpreter (planning contents)
2278 "Interpret PLANNING element as Org syntax.
2279 CONTENTS is nil."
2280 (mapconcat
2281 'identity
2282 (delq nil
2283 (list (let ((deadline (org-element-property :deadline planning)))
2284 (when deadline
2285 (concat org-deadline-string " "
2286 (org-element-timestamp-interpreter deadline nil))))
2287 (let ((scheduled (org-element-property :scheduled planning)))
2288 (when scheduled
2289 (concat org-scheduled-string " "
2290 (org-element-timestamp-interpreter scheduled nil))))
2291 (let ((closed (org-element-property :closed planning)))
2292 (when closed
2293 (concat org-closed-string " "
2294 (org-element-timestamp-interpreter closed nil))))))
2295 " "))
2298 ;;;; Quote Section
2300 (defun org-element-quote-section-parser (limit)
2301 "Parse a quote section.
2303 LIMIT bounds the search.
2305 Return a list whose CAR is `quote-section' and CDR is a plist
2306 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2308 Assume point is at beginning of the section."
2309 (save-excursion
2310 (let* ((begin (point))
2311 (end (progn (org-with-limited-levels (outline-next-heading))
2312 (point)))
2313 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2314 (forward-line)
2315 (point)))
2316 (value (buffer-substring-no-properties begin pos-before-blank)))
2317 (list 'quote-section
2318 (list :begin begin
2319 :end end
2320 :value value
2321 :post-blank (count-lines pos-before-blank end))))))
2323 (defun org-element-quote-section-interpreter (quote-section contents)
2324 "Interpret QUOTE-SECTION element as Org syntax.
2325 CONTENTS is nil."
2326 (org-element-property :value quote-section))
2329 ;;;; Src Block
2331 (defun org-element-src-block-parser (limit affiliated)
2332 "Parse a src block.
2334 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2335 the buffer position at the beginning of the first affiliated
2336 keyword and CDR is a plist of affiliated keywords along with
2337 their value.
2339 Return a list whose CAR is `src-block' and CDR is a plist
2340 containing `:language', `:switches', `:parameters', `:begin',
2341 `:end', `:number-lines', `:retain-labels', `:use-labels',
2342 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2343 `:post-affiliated' keywords.
2345 Assume point is at the beginning of the block."
2346 (let ((case-fold-search t))
2347 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2348 limit t)))
2349 ;; Incomplete block: parse it as a paragraph.
2350 (org-element-paragraph-parser limit affiliated)
2351 (let ((contents-end (match-beginning 0)))
2352 (save-excursion
2353 (let* ((begin (car affiliated))
2354 (post-affiliated (point))
2355 ;; Get language as a string.
2356 (language
2357 (progn
2358 (looking-at
2359 (concat "^[ \t]*#\\+BEGIN_SRC"
2360 "\\(?: +\\(\\S-+\\)\\)?"
2361 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2362 "\\(.*\\)[ \t]*$"))
2363 (org-match-string-no-properties 1)))
2364 ;; Get switches.
2365 (switches (org-match-string-no-properties 2))
2366 ;; Get parameters.
2367 (parameters (org-match-string-no-properties 3))
2368 ;; Switches analysis
2369 (number-lines
2370 (cond ((not switches) nil)
2371 ((string-match "-n\\>" switches) 'new)
2372 ((string-match "+n\\>" switches) 'continued)))
2373 (preserve-indent (and switches
2374 (string-match "-i\\>" switches)))
2375 (label-fmt
2376 (and switches
2377 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2378 (match-string 1 switches)))
2379 ;; Should labels be retained in (or stripped from)
2380 ;; src blocks?
2381 (retain-labels
2382 (or (not switches)
2383 (not (string-match "-r\\>" switches))
2384 (and number-lines (string-match "-k\\>" switches))))
2385 ;; What should code-references use - labels or
2386 ;; line-numbers?
2387 (use-labels
2388 (or (not switches)
2389 (and retain-labels
2390 (not (string-match "-k\\>" switches)))))
2391 ;; Indentation.
2392 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2393 ;; Retrieve code.
2394 (value (org-element-remove-indentation
2395 (org-unescape-code-in-string
2396 (buffer-substring-no-properties
2397 (progn (forward-line) (point)) contents-end))
2398 block-ind))
2399 (pos-before-blank (progn (goto-char contents-end)
2400 (forward-line)
2401 (point)))
2402 ;; Get position after ending blank lines.
2403 (end (progn (skip-chars-forward " \r\t\n" limit)
2404 (if (eobp) (point) (line-beginning-position)))))
2405 (list 'src-block
2406 (nconc
2407 (list :language language
2408 :switches (and (org-string-nw-p switches)
2409 (org-trim switches))
2410 :parameters (and (org-string-nw-p parameters)
2411 (org-trim parameters))
2412 :begin begin
2413 :end end
2414 :number-lines number-lines
2415 :preserve-indent preserve-indent
2416 :retain-labels retain-labels
2417 :use-labels use-labels
2418 :label-fmt label-fmt
2419 :value value
2420 :post-blank (count-lines pos-before-blank end)
2421 :post-affiliated post-affiliated)
2422 (cdr affiliated)))))))))
2424 (defun org-element-src-block-interpreter (src-block contents)
2425 "Interpret SRC-BLOCK element as Org syntax.
2426 CONTENTS is nil."
2427 (let ((lang (org-element-property :language src-block))
2428 (switches (org-element-property :switches src-block))
2429 (params (org-element-property :parameters src-block))
2430 (value
2431 (let ((val (org-element-property :value src-block)))
2432 (cond
2433 ((or org-src-preserve-indentation
2434 (org-element-property :preserve-indent src-block))
2435 val)
2436 ((zerop org-edit-src-content-indentation) val)
2438 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2439 (replace-regexp-in-string
2440 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2441 (concat (format "#+BEGIN_SRC%s\n"
2442 (concat (and lang (concat " " lang))
2443 (and switches (concat " " switches))
2444 (and params (concat " " params))))
2445 (org-escape-code-in-string value)
2446 "#+END_SRC")))
2449 ;;;; Table
2451 (defun org-element-table-parser (limit affiliated)
2452 "Parse a table at point.
2454 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2455 the buffer position at the beginning of the first affiliated
2456 keyword and CDR is a plist of affiliated keywords along with
2457 their value.
2459 Return a list whose CAR is `table' and CDR is a plist containing
2460 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2461 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2462 keywords.
2464 Assume point is at the beginning of the table."
2465 (save-excursion
2466 (let* ((case-fold-search t)
2467 (table-begin (point))
2468 (type (if (org-at-table.el-p) 'table.el 'org))
2469 (begin (car affiliated))
2470 (table-end
2471 (if (re-search-forward org-table-any-border-regexp limit 'm)
2472 (goto-char (match-beginning 0))
2473 (point)))
2474 (tblfm (let (acc)
2475 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2476 (push (org-match-string-no-properties 1) acc)
2477 (forward-line))
2478 acc))
2479 (pos-before-blank (point))
2480 (end (progn (skip-chars-forward " \r\t\n" limit)
2481 (if (eobp) (point) (line-beginning-position)))))
2482 (list 'table
2483 (nconc
2484 (list :begin begin
2485 :end end
2486 :type type
2487 :tblfm tblfm
2488 ;; Only `org' tables have contents. `table.el' tables
2489 ;; use a `:value' property to store raw table as
2490 ;; a string.
2491 :contents-begin (and (eq type 'org) table-begin)
2492 :contents-end (and (eq type 'org) table-end)
2493 :value (and (eq type 'table.el)
2494 (buffer-substring-no-properties
2495 table-begin table-end))
2496 :post-blank (count-lines pos-before-blank end)
2497 :post-affiliated table-begin)
2498 (cdr affiliated))))))
2500 (defun org-element-table-interpreter (table contents)
2501 "Interpret TABLE element as Org syntax.
2502 CONTENTS is nil."
2503 (if (eq (org-element-property :type table) 'table.el)
2504 (org-remove-indentation (org-element-property :value table))
2505 (concat (with-temp-buffer (insert contents)
2506 (org-table-align)
2507 (buffer-string))
2508 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2509 (reverse (org-element-property :tblfm table))
2510 "\n"))))
2513 ;;;; Table Row
2515 (defun org-element-table-row-parser (limit)
2516 "Parse table row at point.
2518 LIMIT bounds the search.
2520 Return a list whose CAR is `table-row' and CDR is a plist
2521 containing `:begin', `:end', `:contents-begin', `:contents-end',
2522 `:type' and `:post-blank' keywords."
2523 (save-excursion
2524 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2525 (begin (point))
2526 ;; A table rule has no contents. In that case, ensure
2527 ;; CONTENTS-BEGIN matches CONTENTS-END.
2528 (contents-begin (and (eq type 'standard)
2529 (search-forward "|")
2530 (point)))
2531 (contents-end (and (eq type 'standard)
2532 (progn
2533 (end-of-line)
2534 (skip-chars-backward " \t")
2535 (point))))
2536 (end (progn (forward-line) (point))))
2537 (list 'table-row
2538 (list :type type
2539 :begin begin
2540 :end end
2541 :contents-begin contents-begin
2542 :contents-end contents-end
2543 :post-blank 0)))))
2545 (defun org-element-table-row-interpreter (table-row contents)
2546 "Interpret TABLE-ROW element as Org syntax.
2547 CONTENTS is the contents of the table row."
2548 (if (eq (org-element-property :type table-row) 'rule) "|-"
2549 (concat "| " contents)))
2552 ;;;; Verse Block
2554 (defun org-element-verse-block-parser (limit affiliated)
2555 "Parse a verse block.
2557 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2558 the buffer position at the beginning of the first affiliated
2559 keyword and CDR is a plist of affiliated keywords along with
2560 their value.
2562 Return a list whose CAR is `verse-block' and CDR is a plist
2563 containing `:begin', `:end', `:contents-begin', `:contents-end',
2564 `:post-blank' and `:post-affiliated' keywords.
2566 Assume point is at beginning of the block."
2567 (let ((case-fold-search t))
2568 (if (not (save-excursion
2569 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2570 ;; Incomplete block: parse it as a paragraph.
2571 (org-element-paragraph-parser limit affiliated)
2572 (let ((contents-end (match-beginning 0)))
2573 (save-excursion
2574 (let* ((begin (car affiliated))
2575 (post-affiliated (point))
2576 (contents-begin (progn (forward-line) (point)))
2577 (pos-before-blank (progn (goto-char contents-end)
2578 (forward-line)
2579 (point)))
2580 (end (progn (skip-chars-forward " \r\t\n" limit)
2581 (if (eobp) (point) (line-beginning-position)))))
2582 (list 'verse-block
2583 (nconc
2584 (list :begin begin
2585 :end end
2586 :contents-begin contents-begin
2587 :contents-end contents-end
2588 :post-blank (count-lines pos-before-blank end)
2589 :post-affiliated post-affiliated)
2590 (cdr affiliated)))))))))
2592 (defun org-element-verse-block-interpreter (verse-block contents)
2593 "Interpret VERSE-BLOCK element as Org syntax.
2594 CONTENTS is verse block contents."
2595 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2599 ;;; Objects
2601 ;; Unlike to elements, interstices can be found between objects.
2602 ;; That's why, along with the parser, successor functions are provided
2603 ;; for each object. Some objects share the same successor (i.e. `code'
2604 ;; and `verbatim' objects).
2606 ;; A successor must accept a single argument bounding the search. It
2607 ;; will return either a cons cell whose CAR is the object's type, as
2608 ;; a symbol, and CDR the position of its next occurrence, or nil.
2610 ;; Successors follow the naming convention:
2611 ;; org-element-NAME-successor, where NAME is the name of the
2612 ;; successor, as defined in `org-element-all-successors'.
2614 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2615 ;; object types they can contain will be specified in
2616 ;; `org-element-object-restrictions'.
2618 ;; Adding a new type of object is simple. Implement a successor,
2619 ;; a parser, and an interpreter for it, all following the naming
2620 ;; convention. Register type in `org-element-all-objects' and
2621 ;; successor in `org-element-all-successors'. Maybe tweak
2622 ;; restrictions about it, and that's it.
2625 ;;;; Bold
2627 (defun org-element-bold-parser ()
2628 "Parse bold object at point.
2630 Return a list whose CAR is `bold' and CDR is a plist with
2631 `:begin', `:end', `:contents-begin' and `:contents-end' and
2632 `:post-blank' keywords.
2634 Assume point is at the first star marker."
2635 (save-excursion
2636 (unless (bolp) (backward-char 1))
2637 (looking-at org-emph-re)
2638 (let ((begin (match-beginning 2))
2639 (contents-begin (match-beginning 4))
2640 (contents-end (match-end 4))
2641 (post-blank (progn (goto-char (match-end 2))
2642 (skip-chars-forward " \t")))
2643 (end (point)))
2644 (list 'bold
2645 (list :begin begin
2646 :end end
2647 :contents-begin contents-begin
2648 :contents-end contents-end
2649 :post-blank post-blank)))))
2651 (defun org-element-bold-interpreter (bold contents)
2652 "Interpret BOLD object as Org syntax.
2653 CONTENTS is the contents of the object."
2654 (format "*%s*" contents))
2656 (defun org-element-text-markup-successor ()
2657 "Search for the next text-markup object.
2659 Return value is a cons cell whose CAR is a symbol among `bold',
2660 `italic', `underline', `strike-through', `code' and `verbatim'
2661 and CDR is beginning position."
2662 (save-excursion
2663 (unless (bolp) (backward-char))
2664 (when (re-search-forward org-emph-re nil t)
2665 (let ((marker (match-string 3)))
2666 (cons (cond
2667 ((equal marker "*") 'bold)
2668 ((equal marker "/") 'italic)
2669 ((equal marker "_") 'underline)
2670 ((equal marker "+") 'strike-through)
2671 ((equal marker "~") 'code)
2672 ((equal marker "=") 'verbatim)
2673 (t (error "Unknown marker at %d" (match-beginning 3))))
2674 (match-beginning 2))))))
2677 ;;;; Code
2679 (defun org-element-code-parser ()
2680 "Parse code object at point.
2682 Return a list whose CAR is `code' and CDR is a plist with
2683 `:value', `:begin', `:end' and `:post-blank' keywords.
2685 Assume point is at the first tilde marker."
2686 (save-excursion
2687 (unless (bolp) (backward-char 1))
2688 (looking-at org-emph-re)
2689 (let ((begin (match-beginning 2))
2690 (value (org-match-string-no-properties 4))
2691 (post-blank (progn (goto-char (match-end 2))
2692 (skip-chars-forward " \t")))
2693 (end (point)))
2694 (list 'code
2695 (list :value value
2696 :begin begin
2697 :end end
2698 :post-blank post-blank)))))
2700 (defun org-element-code-interpreter (code contents)
2701 "Interpret CODE object as Org syntax.
2702 CONTENTS is nil."
2703 (format "~%s~" (org-element-property :value code)))
2706 ;;;; Entity
2708 (defun org-element-entity-parser ()
2709 "Parse entity at point.
2711 Return a list whose CAR is `entity' and CDR a plist with
2712 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2713 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2714 keywords.
2716 Assume point is at the beginning of the entity."
2717 (save-excursion
2718 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2719 (let* ((value (org-entity-get (match-string 1)))
2720 (begin (match-beginning 0))
2721 (bracketsp (string= (match-string 2) "{}"))
2722 (post-blank (progn (goto-char (match-end 1))
2723 (when bracketsp (forward-char 2))
2724 (skip-chars-forward " \t")))
2725 (end (point)))
2726 (list 'entity
2727 (list :name (car value)
2728 :latex (nth 1 value)
2729 :latex-math-p (nth 2 value)
2730 :html (nth 3 value)
2731 :ascii (nth 4 value)
2732 :latin1 (nth 5 value)
2733 :utf-8 (nth 6 value)
2734 :begin begin
2735 :end end
2736 :use-brackets-p bracketsp
2737 :post-blank post-blank)))))
2739 (defun org-element-entity-interpreter (entity contents)
2740 "Interpret ENTITY object as Org syntax.
2741 CONTENTS is nil."
2742 (concat "\\"
2743 (org-element-property :name entity)
2744 (when (org-element-property :use-brackets-p entity) "{}")))
2746 (defun org-element-latex-or-entity-successor ()
2747 "Search for the next latex-fragment or entity object.
2749 Return value is a cons cell whose CAR is `entity' or
2750 `latex-fragment' and CDR is beginning position."
2751 (save-excursion
2752 (unless (bolp) (backward-char))
2753 (let ((matchers (cdr org-latex-regexps))
2754 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2755 (entity-re
2756 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2757 (when (re-search-forward
2758 (concat (mapconcat #'cadr matchers "\\|") "\\|" entity-re) nil t)
2759 (goto-char (match-beginning 0))
2760 (if (looking-at entity-re)
2761 ;; Determine if it's a real entity or a LaTeX command.
2762 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2763 (match-beginning 0))
2764 ;; No entity nor command: point is at a LaTeX fragment.
2765 ;; Determine its type to get the correct beginning position.
2766 (cons 'latex-fragment
2767 (catch 'return
2768 (dolist (e matchers)
2769 (when (looking-at (nth 1 e))
2770 (throw 'return (match-beginning (nth 2 e)))))
2771 (point))))))))
2774 ;;;; Export Snippet
2776 (defun org-element-export-snippet-parser ()
2777 "Parse export snippet at point.
2779 Return a list whose CAR is `export-snippet' and CDR a plist with
2780 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2781 keywords.
2783 Assume point is at the beginning of the snippet."
2784 (save-excursion
2785 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2786 (let* ((begin (match-beginning 0))
2787 (back-end (org-match-string-no-properties 1))
2788 (value (buffer-substring-no-properties
2789 (point)
2790 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2791 (post-blank (skip-chars-forward " \t"))
2792 (end (point)))
2793 (list 'export-snippet
2794 (list :back-end back-end
2795 :value value
2796 :begin begin
2797 :end end
2798 :post-blank post-blank)))))
2800 (defun org-element-export-snippet-interpreter (export-snippet contents)
2801 "Interpret EXPORT-SNIPPET object as Org syntax.
2802 CONTENTS is nil."
2803 (format "@@%s:%s@@"
2804 (org-element-property :back-end export-snippet)
2805 (org-element-property :value export-snippet)))
2807 (defun org-element-export-snippet-successor ()
2808 "Search for the next export-snippet object.
2810 Return value is a cons cell whose CAR is `export-snippet' and CDR
2811 its beginning position."
2812 (save-excursion
2813 (let (beg)
2814 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2815 (setq beg (match-beginning 0))
2816 (search-forward "@@" nil t))
2817 (cons 'export-snippet beg)))))
2820 ;;;; Footnote Reference
2822 (defun org-element-footnote-reference-parser ()
2823 "Parse footnote reference at point.
2825 Return a list whose CAR is `footnote-reference' and CDR a plist
2826 with `:label', `:type', `:inline-definition', `:begin', `:end'
2827 and `:post-blank' as keywords."
2828 (save-excursion
2829 (looking-at org-footnote-re)
2830 (let* ((begin (point))
2831 (label (or (org-match-string-no-properties 2)
2832 (org-match-string-no-properties 3)
2833 (and (match-string 1)
2834 (concat "fn:" (org-match-string-no-properties 1)))))
2835 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2836 (inner-begin (match-end 0))
2837 (inner-end
2838 (let ((count 1))
2839 (forward-char)
2840 (while (and (> count 0) (re-search-forward "[][]" nil t))
2841 (if (equal (match-string 0) "[") (incf count) (decf count)))
2842 (1- (point))))
2843 (post-blank (progn (goto-char (1+ inner-end))
2844 (skip-chars-forward " \t")))
2845 (end (point))
2846 (footnote-reference
2847 (list 'footnote-reference
2848 (list :label label
2849 :type type
2850 :begin begin
2851 :end end
2852 :post-blank post-blank))))
2853 (org-element-put-property
2854 footnote-reference :inline-definition
2855 (and (eq type 'inline)
2856 (org-element-parse-secondary-string
2857 (buffer-substring inner-begin inner-end)
2858 (org-element-restriction 'footnote-reference)
2859 footnote-reference))))))
2861 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2862 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2863 CONTENTS is nil."
2864 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2865 (def
2866 (let ((inline-def
2867 (org-element-property :inline-definition footnote-reference)))
2868 (if (not inline-def) ""
2869 (concat ":" (org-element-interpret-data inline-def))))))
2870 (format "[%s]" (concat label def))))
2872 (defun org-element-footnote-reference-successor ()
2873 "Search for the next footnote-reference object.
2875 Return value is a cons cell whose CAR is `footnote-reference' and
2876 CDR is beginning position."
2877 (save-excursion
2878 (catch 'exit
2879 (while (re-search-forward org-footnote-re nil t)
2880 (save-excursion
2881 (let ((beg (match-beginning 0))
2882 (count 1))
2883 (backward-char)
2884 (while (re-search-forward "[][]" nil t)
2885 (if (equal (match-string 0) "[") (incf count) (decf count))
2886 (when (zerop count)
2887 (throw 'exit (cons 'footnote-reference beg))))))))))
2890 ;;;; Inline Babel Call
2892 (defun org-element-inline-babel-call-parser ()
2893 "Parse inline babel call at point.
2895 Return a list whose CAR is `inline-babel-call' and CDR a plist
2896 with `:begin', `:end', `:value' and `:post-blank' as keywords.
2898 Assume point is at the beginning of the babel call."
2899 (save-excursion
2900 (unless (bolp) (backward-char))
2901 (let ((case-fold-search t))
2902 (looking-at org-babel-inline-lob-one-liner-regexp))
2903 (let ((begin (match-end 1))
2904 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2905 (post-blank (progn (goto-char (match-end 0))
2906 (skip-chars-forward " \t")))
2907 (end (point)))
2908 (list 'inline-babel-call
2909 (list :begin begin
2910 :end end
2911 :value value
2912 :post-blank post-blank)))))
2914 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2915 "Interpret INLINE-BABEL-CALL object as Org syntax.
2916 CONTENTS is nil."
2917 (org-element-property :value inline-babel-call))
2919 (defun org-element-inline-babel-call-successor ()
2920 "Search for the next inline-babel-call object.
2922 Return value is a cons cell whose CAR is `inline-babel-call' and
2923 CDR is beginning position."
2924 (save-excursion
2925 (when (re-search-forward org-babel-inline-lob-one-liner-regexp nil t)
2926 (cons 'inline-babel-call (match-end 1)))))
2929 ;;;; Inline Src Block
2931 (defun org-element-inline-src-block-parser ()
2932 "Parse inline source block at point.
2934 Return a list whose CAR is `inline-src-block' and CDR a plist
2935 with `:begin', `:end', `:language', `:value', `:parameters' and
2936 `:post-blank' as keywords.
2938 Assume point is at the beginning of the inline src block."
2939 (save-excursion
2940 (unless (bolp) (backward-char))
2941 (looking-at org-babel-inline-src-block-regexp)
2942 (let ((begin (match-beginning 1))
2943 (language (org-match-string-no-properties 2))
2944 (parameters (org-match-string-no-properties 4))
2945 (value (org-match-string-no-properties 5))
2946 (post-blank (progn (goto-char (match-end 0))
2947 (skip-chars-forward " \t")))
2948 (end (point)))
2949 (list 'inline-src-block
2950 (list :language language
2951 :value value
2952 :parameters parameters
2953 :begin begin
2954 :end end
2955 :post-blank post-blank)))))
2957 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2958 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2959 CONTENTS is nil."
2960 (let ((language (org-element-property :language inline-src-block))
2961 (arguments (org-element-property :parameters inline-src-block))
2962 (body (org-element-property :value inline-src-block)))
2963 (format "src_%s%s{%s}"
2964 language
2965 (if arguments (format "[%s]" arguments) "")
2966 body)))
2968 (defun org-element-inline-src-block-successor ()
2969 "Search for the next inline-babel-call element.
2971 Return value is a cons cell whose CAR is `inline-babel-call' and
2972 CDR is beginning position."
2973 (save-excursion
2974 (unless (bolp) (backward-char))
2975 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2976 (cons 'inline-src-block (match-beginning 1)))))
2978 ;;;; Italic
2980 (defun org-element-italic-parser ()
2981 "Parse italic object at point.
2983 Return a list whose CAR is `italic' and CDR is a plist with
2984 `:begin', `:end', `:contents-begin' and `:contents-end' and
2985 `:post-blank' keywords.
2987 Assume point is at the first slash marker."
2988 (save-excursion
2989 (unless (bolp) (backward-char 1))
2990 (looking-at org-emph-re)
2991 (let ((begin (match-beginning 2))
2992 (contents-begin (match-beginning 4))
2993 (contents-end (match-end 4))
2994 (post-blank (progn (goto-char (match-end 2))
2995 (skip-chars-forward " \t")))
2996 (end (point)))
2997 (list 'italic
2998 (list :begin begin
2999 :end end
3000 :contents-begin contents-begin
3001 :contents-end contents-end
3002 :post-blank post-blank)))))
3004 (defun org-element-italic-interpreter (italic contents)
3005 "Interpret ITALIC object as Org syntax.
3006 CONTENTS is the contents of the object."
3007 (format "/%s/" contents))
3010 ;;;; Latex Fragment
3012 (defun org-element-latex-fragment-parser ()
3013 "Parse LaTeX fragment at point.
3015 Return a list whose CAR is `latex-fragment' and CDR a plist with
3016 `:value', `:begin', `:end', and `:post-blank' as keywords.
3018 Assume point is at the beginning of the LaTeX fragment."
3019 (save-excursion
3020 (let* ((begin (point))
3021 (substring-match
3022 (catch 'exit
3023 (dolist (e (cdr org-latex-regexps))
3024 (let ((latex-regexp (nth 1 e)))
3025 (when (or (looking-at latex-regexp)
3026 (and (not (bobp))
3027 (save-excursion
3028 (backward-char)
3029 (looking-at latex-regexp))))
3030 (throw 'exit (nth 2 e)))))
3031 ;; None found: it's a macro.
3032 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
3034 (value (org-match-string-no-properties substring-match))
3035 (post-blank (progn (goto-char (match-end substring-match))
3036 (skip-chars-forward " \t")))
3037 (end (point)))
3038 (list 'latex-fragment
3039 (list :value value
3040 :begin begin
3041 :end end
3042 :post-blank post-blank)))))
3044 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
3045 "Interpret LATEX-FRAGMENT object as Org syntax.
3046 CONTENTS is nil."
3047 (org-element-property :value latex-fragment))
3049 ;;;; Line Break
3051 (defun org-element-line-break-parser ()
3052 "Parse line break at point.
3054 Return a list whose CAR is `line-break', and CDR a plist with
3055 `:begin', `:end' and `:post-blank' keywords.
3057 Assume point is at the beginning of the line break."
3058 (list 'line-break
3059 (list :begin (point)
3060 :end (progn (forward-line) (point))
3061 :post-blank 0)))
3063 (defun org-element-line-break-interpreter (line-break contents)
3064 "Interpret LINE-BREAK object as Org syntax.
3065 CONTENTS is nil."
3066 "\\\\\n")
3068 (defun org-element-line-break-successor ()
3069 "Search for the next line-break object.
3071 Return value is a cons cell whose CAR is `line-break' and CDR is
3072 beginning position."
3073 (save-excursion
3074 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
3075 (goto-char (match-beginning 1)))))
3076 ;; A line break can only happen on a non-empty line.
3077 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
3078 (cons 'line-break beg)))))
3081 ;;;; Link
3083 (defun org-element-link-parser ()
3084 "Parse link at point.
3086 Return a list whose CAR is `link' and CDR a plist with `:type',
3087 `:path', `:raw-link', `:application', `:search-option', `:begin',
3088 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3089 keywords.
3091 Assume point is at the beginning of the link."
3092 (save-excursion
3093 (let ((begin (point))
3094 end contents-begin contents-end link-end post-blank path type
3095 raw-link link search-option application)
3096 (cond
3097 ;; Type 1: Text targeted from a radio target.
3098 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3099 (setq type "radio"
3100 link-end (match-end 0)
3101 path (org-match-string-no-properties 0)))
3102 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3103 ((looking-at org-bracket-link-regexp)
3104 (setq contents-begin (match-beginning 3)
3105 contents-end (match-end 3)
3106 link-end (match-end 0)
3107 ;; RAW-LINK is the original link. Expand any
3108 ;; abbreviation in it.
3109 raw-link (org-translate-link
3110 (org-link-expand-abbrev
3111 (org-match-string-no-properties 1))))
3112 ;; Determine TYPE of link and set PATH accordingly.
3113 (cond
3114 ;; File type.
3115 ((or (file-name-absolute-p raw-link)
3116 (string-match "^\\.\\.?/" raw-link))
3117 (setq type "file" path raw-link))
3118 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3119 ((string-match org-link-re-with-space3 raw-link)
3120 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3121 ;; Id type: PATH is the id.
3122 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3123 (setq type "id" path (match-string 1 raw-link)))
3124 ;; Code-ref type: PATH is the name of the reference.
3125 ((string-match "^(\\(.*\\))$" raw-link)
3126 (setq type "coderef" path (match-string 1 raw-link)))
3127 ;; Custom-id type: PATH is the name of the custom id.
3128 ((= (aref raw-link 0) ?#)
3129 (setq type "custom-id" path (substring raw-link 1)))
3130 ;; Fuzzy type: Internal link either matches a target, an
3131 ;; headline name or nothing. PATH is the target or
3132 ;; headline's name.
3133 (t (setq type "fuzzy" path raw-link))))
3134 ;; Type 3: Plain link, i.e. http://orgmode.org
3135 ((looking-at org-plain-link-re)
3136 (setq raw-link (org-match-string-no-properties 0)
3137 type (org-match-string-no-properties 1)
3138 link-end (match-end 0)
3139 path (org-match-string-no-properties 2)))
3140 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3141 ((looking-at org-angle-link-re)
3142 (setq raw-link (buffer-substring-no-properties
3143 (match-beginning 1) (match-end 2))
3144 type (org-match-string-no-properties 1)
3145 link-end (match-end 0)
3146 path (org-match-string-no-properties 2))))
3147 ;; In any case, deduce end point after trailing white space from
3148 ;; LINK-END variable.
3149 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3150 end (point))
3151 ;; Extract search option and opening application out of
3152 ;; "file"-type links.
3153 (when (member type org-element-link-type-is-file)
3154 ;; Application.
3155 (cond ((string-match "^file\\+\\(.*\\)$" type)
3156 (setq application (match-string 1 type)))
3157 ((not (string-match "^file" type))
3158 (setq application type)))
3159 ;; Extract search option from PATH.
3160 (when (string-match "::\\(.*\\)$" path)
3161 (setq search-option (match-string 1 path)
3162 path (replace-match "" nil nil path)))
3163 ;; Make sure TYPE always reports "file".
3164 (setq type "file"))
3165 (list 'link
3166 (list :type type
3167 :path path
3168 :raw-link (or raw-link path)
3169 :application application
3170 :search-option search-option
3171 :begin begin
3172 :end end
3173 :contents-begin contents-begin
3174 :contents-end contents-end
3175 :post-blank post-blank)))))
3177 (defun org-element-link-interpreter (link contents)
3178 "Interpret LINK object as Org syntax.
3179 CONTENTS is the contents of the object, or nil."
3180 (let ((type (org-element-property :type link))
3181 (raw-link (org-element-property :raw-link link)))
3182 (if (string= type "radio") raw-link
3183 (format "[[%s]%s]"
3184 raw-link
3185 (if contents (format "[%s]" contents) "")))))
3187 (defun org-element-link-successor ()
3188 "Search for the next link object.
3190 Return value is a cons cell whose CAR is `link' and CDR is
3191 beginning position."
3192 (save-excursion
3193 (let ((link-regexp
3194 (if (not org-target-link-regexp) org-any-link-re
3195 (concat org-any-link-re "\\|" org-target-link-regexp))))
3196 (when (re-search-forward link-regexp nil t)
3197 (cons 'link (match-beginning 0))))))
3199 (defun org-element-plain-link-successor ()
3200 "Search for the next plain link object.
3202 Return value is a cons cell whose CAR is `link' and CDR is
3203 beginning position."
3204 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3205 (cons 'link (match-beginning 0))))
3208 ;;;; Macro
3210 (defun org-element-macro-parser ()
3211 "Parse macro at point.
3213 Return a list whose CAR is `macro' and CDR a plist with `:key',
3214 `:args', `:begin', `:end', `:value' and `:post-blank' as
3215 keywords.
3217 Assume point is at the macro."
3218 (save-excursion
3219 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3220 (let ((begin (point))
3221 (key (downcase (org-match-string-no-properties 1)))
3222 (value (org-match-string-no-properties 0))
3223 (post-blank (progn (goto-char (match-end 0))
3224 (skip-chars-forward " \t")))
3225 (end (point))
3226 (args (let ((args (org-match-string-no-properties 3)))
3227 (when args
3228 ;; Do not use `org-split-string' since empty
3229 ;; strings are meaningful here.
3230 (split-string
3231 (replace-regexp-in-string
3232 "\\(\\\\*\\)\\(,\\)"
3233 (lambda (str)
3234 (let ((len (length (match-string 1 str))))
3235 (concat (make-string (/ len 2) ?\\)
3236 (if (zerop (mod len 2)) "\000" ","))))
3237 args nil t)
3238 "\000")))))
3239 (list 'macro
3240 (list :key key
3241 :value value
3242 :args args
3243 :begin begin
3244 :end end
3245 :post-blank post-blank)))))
3247 (defun org-element-macro-interpreter (macro contents)
3248 "Interpret MACRO object as Org syntax.
3249 CONTENTS is nil."
3250 (org-element-property :value macro))
3252 (defun org-element-macro-successor ()
3253 "Search for the next macro object.
3255 Return value is cons cell whose CAR is `macro' and CDR is
3256 beginning position."
3257 (save-excursion
3258 (when (re-search-forward
3259 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3260 nil t)
3261 (cons 'macro (match-beginning 0)))))
3264 ;;;; Radio-target
3266 (defun org-element-radio-target-parser ()
3267 "Parse radio target at point.
3269 Return a list whose CAR is `radio-target' and CDR a plist with
3270 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3271 and `:post-blank' as keywords.
3273 Assume point is at the radio target."
3274 (save-excursion
3275 (looking-at org-radio-target-regexp)
3276 (let ((begin (point))
3277 (contents-begin (match-beginning 1))
3278 (contents-end (match-end 1))
3279 (value (org-match-string-no-properties 1))
3280 (post-blank (progn (goto-char (match-end 0))
3281 (skip-chars-forward " \t")))
3282 (end (point)))
3283 (list 'radio-target
3284 (list :begin begin
3285 :end end
3286 :contents-begin contents-begin
3287 :contents-end contents-end
3288 :post-blank post-blank
3289 :value value)))))
3291 (defun org-element-radio-target-interpreter (target contents)
3292 "Interpret TARGET object as Org syntax.
3293 CONTENTS is the contents of the object."
3294 (concat "<<<" contents ">>>"))
3296 (defun org-element-radio-target-successor ()
3297 "Search for the next radio-target object.
3299 Return value is a cons cell whose CAR is `radio-target' and CDR
3300 is beginning position."
3301 (save-excursion
3302 (when (re-search-forward org-radio-target-regexp nil t)
3303 (cons 'radio-target (match-beginning 0)))))
3306 ;;;; Statistics Cookie
3308 (defun org-element-statistics-cookie-parser ()
3309 "Parse statistics cookie at point.
3311 Return a list whose CAR is `statistics-cookie', and CDR a plist
3312 with `:begin', `:end', `:value' and `:post-blank' keywords.
3314 Assume point is at the beginning of the statistics-cookie."
3315 (save-excursion
3316 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3317 (let* ((begin (point))
3318 (value (buffer-substring-no-properties
3319 (match-beginning 0) (match-end 0)))
3320 (post-blank (progn (goto-char (match-end 0))
3321 (skip-chars-forward " \t")))
3322 (end (point)))
3323 (list 'statistics-cookie
3324 (list :begin begin
3325 :end end
3326 :value value
3327 :post-blank post-blank)))))
3329 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3330 "Interpret STATISTICS-COOKIE object as Org syntax.
3331 CONTENTS is nil."
3332 (org-element-property :value statistics-cookie))
3334 (defun org-element-statistics-cookie-successor ()
3335 "Search for the next statistics cookie object.
3337 Return value is a cons cell whose CAR is `statistics-cookie' and
3338 CDR is beginning position."
3339 (save-excursion
3340 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3341 (cons 'statistics-cookie (match-beginning 0)))))
3344 ;;;; Strike-Through
3346 (defun org-element-strike-through-parser ()
3347 "Parse strike-through object at point.
3349 Return a list whose CAR is `strike-through' and CDR is a plist
3350 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3351 `:post-blank' keywords.
3353 Assume point is at the first plus sign marker."
3354 (save-excursion
3355 (unless (bolp) (backward-char 1))
3356 (looking-at org-emph-re)
3357 (let ((begin (match-beginning 2))
3358 (contents-begin (match-beginning 4))
3359 (contents-end (match-end 4))
3360 (post-blank (progn (goto-char (match-end 2))
3361 (skip-chars-forward " \t")))
3362 (end (point)))
3363 (list 'strike-through
3364 (list :begin begin
3365 :end end
3366 :contents-begin contents-begin
3367 :contents-end contents-end
3368 :post-blank post-blank)))))
3370 (defun org-element-strike-through-interpreter (strike-through contents)
3371 "Interpret STRIKE-THROUGH object as Org syntax.
3372 CONTENTS is the contents of the object."
3373 (format "+%s+" contents))
3376 ;;;; Subscript
3378 (defun org-element-subscript-parser ()
3379 "Parse subscript at point.
3381 Return a list whose CAR is `subscript' and CDR a plist with
3382 `:begin', `:end', `:contents-begin', `:contents-end',
3383 `:use-brackets-p' and `:post-blank' as keywords.
3385 Assume point is at the underscore."
3386 (save-excursion
3387 (unless (bolp) (backward-char))
3388 (looking-at org-match-substring-regexp)
3389 (let ((bracketsp (match-beginning 4))
3390 (begin (match-beginning 2))
3391 (contents-begin (or (match-beginning 4)
3392 (match-beginning 3)))
3393 (contents-end (or (match-end 4) (match-end 3)))
3394 (post-blank (progn (goto-char (match-end 0))
3395 (skip-chars-forward " \t")))
3396 (end (point)))
3397 (list 'subscript
3398 (list :begin begin
3399 :end end
3400 :use-brackets-p bracketsp
3401 :contents-begin contents-begin
3402 :contents-end contents-end
3403 :post-blank post-blank)))))
3405 (defun org-element-subscript-interpreter (subscript contents)
3406 "Interpret SUBSCRIPT object as Org syntax.
3407 CONTENTS is the contents of the object."
3408 (format
3409 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3410 contents))
3412 (defun org-element-sub/superscript-successor ()
3413 "Search for the next sub/superscript object.
3415 Return value is a cons cell whose CAR is either `subscript' or
3416 `superscript' and CDR is beginning position."
3417 (save-excursion
3418 (unless (bolp) (backward-char))
3419 (when (re-search-forward org-match-substring-regexp nil t)
3420 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3421 (match-beginning 2)))))
3424 ;;;; Superscript
3426 (defun org-element-superscript-parser ()
3427 "Parse superscript at point.
3429 Return a list whose CAR is `superscript' and CDR a plist with
3430 `:begin', `:end', `:contents-begin', `:contents-end',
3431 `:use-brackets-p' and `:post-blank' as keywords.
3433 Assume point is at the caret."
3434 (save-excursion
3435 (unless (bolp) (backward-char))
3436 (looking-at org-match-substring-regexp)
3437 (let ((bracketsp (match-beginning 4))
3438 (begin (match-beginning 2))
3439 (contents-begin (or (match-beginning 4)
3440 (match-beginning 3)))
3441 (contents-end (or (match-end 4) (match-end 3)))
3442 (post-blank (progn (goto-char (match-end 0))
3443 (skip-chars-forward " \t")))
3444 (end (point)))
3445 (list 'superscript
3446 (list :begin begin
3447 :end end
3448 :use-brackets-p bracketsp
3449 :contents-begin contents-begin
3450 :contents-end contents-end
3451 :post-blank post-blank)))))
3453 (defun org-element-superscript-interpreter (superscript contents)
3454 "Interpret SUPERSCRIPT object as Org syntax.
3455 CONTENTS is the contents of the object."
3456 (format
3457 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3458 contents))
3461 ;;;; Table Cell
3463 (defun org-element-table-cell-parser ()
3464 "Parse table cell at point.
3466 Return a list whose CAR is `table-cell' and CDR is a plist
3467 containing `:begin', `:end', `:contents-begin', `:contents-end'
3468 and `:post-blank' keywords."
3469 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3470 (let* ((begin (match-beginning 0))
3471 (end (match-end 0))
3472 (contents-begin (match-beginning 1))
3473 (contents-end (match-end 1)))
3474 (list 'table-cell
3475 (list :begin begin
3476 :end end
3477 :contents-begin contents-begin
3478 :contents-end contents-end
3479 :post-blank 0))))
3481 (defun org-element-table-cell-interpreter (table-cell contents)
3482 "Interpret TABLE-CELL element as Org syntax.
3483 CONTENTS is the contents of the cell, or nil."
3484 (concat " " contents " |"))
3486 (defun org-element-table-cell-successor ()
3487 "Search for the next table-cell object.
3489 Return value is a cons cell whose CAR is `table-cell' and CDR is
3490 beginning position."
3491 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3494 ;;;; Target
3496 (defun org-element-target-parser ()
3497 "Parse target at point.
3499 Return a list whose CAR is `target' and CDR a plist with
3500 `:begin', `:end', `:value' and `:post-blank' as keywords.
3502 Assume point is at the target."
3503 (save-excursion
3504 (looking-at org-target-regexp)
3505 (let ((begin (point))
3506 (value (org-match-string-no-properties 1))
3507 (post-blank (progn (goto-char (match-end 0))
3508 (skip-chars-forward " \t")))
3509 (end (point)))
3510 (list 'target
3511 (list :begin begin
3512 :end end
3513 :value value
3514 :post-blank post-blank)))))
3516 (defun org-element-target-interpreter (target contents)
3517 "Interpret TARGET object as Org syntax.
3518 CONTENTS is nil."
3519 (format "<<%s>>" (org-element-property :value target)))
3521 (defun org-element-target-successor ()
3522 "Search for the next target object.
3524 Return value is a cons cell whose CAR is `target' and CDR is
3525 beginning position."
3526 (save-excursion
3527 (when (re-search-forward org-target-regexp nil t)
3528 (cons 'target (match-beginning 0)))))
3531 ;;;; Timestamp
3533 (defun org-element-timestamp-parser ()
3534 "Parse time stamp at point.
3536 Return a list whose CAR is `timestamp', and CDR a plist with
3537 `:type', `:raw-value', `:year-start', `:month-start',
3538 `:day-start', `:hour-start', `:minute-start', `:year-end',
3539 `:month-end', `:day-end', `:hour-end', `:minute-end',
3540 `:repeater-type', `:repeater-value', `:repeater-unit',
3541 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3542 `:end', `:value' and `:post-blank' keywords.
3544 Assume point is at the beginning of the timestamp."
3545 (save-excursion
3546 (let* ((begin (point))
3547 (activep (eq (char-after) ?<))
3548 (raw-value
3549 (progn
3550 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3551 (match-string-no-properties 0)))
3552 (date-start (match-string-no-properties 1))
3553 (date-end (match-string 3))
3554 (diaryp (match-beginning 2))
3555 (post-blank (progn (goto-char (match-end 0))
3556 (skip-chars-forward " \t")))
3557 (end (point))
3558 (time-range
3559 (and (not diaryp)
3560 (string-match
3561 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3562 date-start)
3563 (cons (string-to-number (match-string 2 date-start))
3564 (string-to-number (match-string 3 date-start)))))
3565 (type (cond (diaryp 'diary)
3566 ((and activep (or date-end time-range)) 'active-range)
3567 (activep 'active)
3568 ((or date-end time-range) 'inactive-range)
3569 (t 'inactive)))
3570 (repeater-props
3571 (and (not diaryp)
3572 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3573 raw-value)
3574 (list
3575 :repeater-type
3576 (let ((type (match-string 1 raw-value)))
3577 (cond ((equal "++" type) 'catch-up)
3578 ((equal ".+" type) 'restart)
3579 (t 'cumulate)))
3580 :repeater-value (string-to-number (match-string 2 raw-value))
3581 :repeater-unit
3582 (case (string-to-char (match-string 3 raw-value))
3583 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3584 (warning-props
3585 (and (not diaryp)
3586 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3587 (list
3588 :warning-type (if (match-string 1 raw-value) 'first 'all)
3589 :warning-value (string-to-number (match-string 2 raw-value))
3590 :warning-unit
3591 (case (string-to-char (match-string 3 raw-value))
3592 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3593 year-start month-start day-start hour-start minute-start year-end
3594 month-end day-end hour-end minute-end)
3595 ;; Parse date-start.
3596 (unless diaryp
3597 (let ((date (org-parse-time-string date-start t)))
3598 (setq year-start (nth 5 date)
3599 month-start (nth 4 date)
3600 day-start (nth 3 date)
3601 hour-start (nth 2 date)
3602 minute-start (nth 1 date))))
3603 ;; Compute date-end. It can be provided directly in time-stamp,
3604 ;; or extracted from time range. Otherwise, it defaults to the
3605 ;; same values as date-start.
3606 (unless diaryp
3607 (let ((date (and date-end (org-parse-time-string date-end t))))
3608 (setq year-end (or (nth 5 date) year-start)
3609 month-end (or (nth 4 date) month-start)
3610 day-end (or (nth 3 date) day-start)
3611 hour-end (or (nth 2 date) (car time-range) hour-start)
3612 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3613 (list 'timestamp
3614 (nconc (list :type type
3615 :raw-value raw-value
3616 :year-start year-start
3617 :month-start month-start
3618 :day-start day-start
3619 :hour-start hour-start
3620 :minute-start minute-start
3621 :year-end year-end
3622 :month-end month-end
3623 :day-end day-end
3624 :hour-end hour-end
3625 :minute-end minute-end
3626 :begin begin
3627 :end end
3628 :post-blank post-blank)
3629 repeater-props
3630 warning-props)))))
3632 (defun org-element-timestamp-interpreter (timestamp contents)
3633 "Interpret TIMESTAMP object as Org syntax.
3634 CONTENTS is nil."
3635 (let* ((repeat-string
3636 (concat
3637 (case (org-element-property :repeater-type timestamp)
3638 (cumulate "+") (catch-up "++") (restart ".+"))
3639 (let ((val (org-element-property :repeater-value timestamp)))
3640 (and val (number-to-string val)))
3641 (case (org-element-property :repeater-unit timestamp)
3642 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3643 (warning-string
3644 (concat
3645 (case (org-element-property :warning-type timestamp)
3646 (first "--")
3647 (all "-"))
3648 (let ((val (org-element-property :warning-value timestamp)))
3649 (and val (number-to-string val)))
3650 (case (org-element-property :warning-unit timestamp)
3651 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3652 (build-ts-string
3653 ;; Build an Org timestamp string from TIME. ACTIVEP is
3654 ;; non-nil when time stamp is active. If WITH-TIME-P is
3655 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3656 ;; specify a time range in the timestamp. REPEAT-STRING is
3657 ;; the repeater string, if any.
3658 (lambda (time activep &optional with-time-p hour-end minute-end)
3659 (let ((ts (format-time-string
3660 (funcall (if with-time-p 'cdr 'car)
3661 org-time-stamp-formats)
3662 time)))
3663 (when (and hour-end minute-end)
3664 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3665 (setq ts
3666 (replace-match
3667 (format "\\&-%02d:%02d" hour-end minute-end)
3668 nil nil ts)))
3669 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3670 (dolist (s (list repeat-string warning-string))
3671 (when (org-string-nw-p s)
3672 (setq ts (concat (substring ts 0 -1)
3675 (substring ts -1)))))
3676 ;; Return value.
3677 ts)))
3678 (type (org-element-property :type timestamp)))
3679 (case type
3680 ((active inactive)
3681 (let* ((minute-start (org-element-property :minute-start timestamp))
3682 (minute-end (org-element-property :minute-end timestamp))
3683 (hour-start (org-element-property :hour-start timestamp))
3684 (hour-end (org-element-property :hour-end timestamp))
3685 (time-range-p (and hour-start hour-end minute-start minute-end
3686 (or (/= hour-start hour-end)
3687 (/= minute-start minute-end)))))
3688 (funcall
3689 build-ts-string
3690 (encode-time 0
3691 (or minute-start 0)
3692 (or hour-start 0)
3693 (org-element-property :day-start timestamp)
3694 (org-element-property :month-start timestamp)
3695 (org-element-property :year-start timestamp))
3696 (eq type 'active)
3697 (and hour-start minute-start)
3698 (and time-range-p hour-end)
3699 (and time-range-p minute-end))))
3700 ((active-range inactive-range)
3701 (let ((minute-start (org-element-property :minute-start timestamp))
3702 (minute-end (org-element-property :minute-end timestamp))
3703 (hour-start (org-element-property :hour-start timestamp))
3704 (hour-end (org-element-property :hour-end timestamp)))
3705 (concat
3706 (funcall
3707 build-ts-string (encode-time
3709 (or minute-start 0)
3710 (or hour-start 0)
3711 (org-element-property :day-start timestamp)
3712 (org-element-property :month-start timestamp)
3713 (org-element-property :year-start timestamp))
3714 (eq type 'active-range)
3715 (and hour-start minute-start))
3716 "--"
3717 (funcall build-ts-string
3718 (encode-time 0
3719 (or minute-end 0)
3720 (or hour-end 0)
3721 (org-element-property :day-end timestamp)
3722 (org-element-property :month-end timestamp)
3723 (org-element-property :year-end timestamp))
3724 (eq type 'active-range)
3725 (and hour-end minute-end))))))))
3727 (defun org-element-timestamp-successor ()
3728 "Search for the next timestamp object.
3730 Return value is a cons cell whose CAR is `timestamp' and CDR is
3731 beginning position."
3732 (save-excursion
3733 (when (re-search-forward
3734 (concat org-ts-regexp-both
3735 "\\|"
3736 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3737 "\\|"
3738 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3739 nil t)
3740 (cons 'timestamp (match-beginning 0)))))
3743 ;;;; Underline
3745 (defun org-element-underline-parser ()
3746 "Parse underline object at point.
3748 Return a list whose CAR is `underline' and CDR is a plist with
3749 `:begin', `:end', `:contents-begin' and `:contents-end' and
3750 `:post-blank' keywords.
3752 Assume point is at the first underscore marker."
3753 (save-excursion
3754 (unless (bolp) (backward-char 1))
3755 (looking-at org-emph-re)
3756 (let ((begin (match-beginning 2))
3757 (contents-begin (match-beginning 4))
3758 (contents-end (match-end 4))
3759 (post-blank (progn (goto-char (match-end 2))
3760 (skip-chars-forward " \t")))
3761 (end (point)))
3762 (list 'underline
3763 (list :begin begin
3764 :end end
3765 :contents-begin contents-begin
3766 :contents-end contents-end
3767 :post-blank post-blank)))))
3769 (defun org-element-underline-interpreter (underline contents)
3770 "Interpret UNDERLINE object as Org syntax.
3771 CONTENTS is the contents of the object."
3772 (format "_%s_" contents))
3775 ;;;; Verbatim
3777 (defun org-element-verbatim-parser ()
3778 "Parse verbatim object at point.
3780 Return a list whose CAR is `verbatim' and CDR is a plist with
3781 `:value', `:begin', `:end' and `:post-blank' keywords.
3783 Assume point is at the first equal sign marker."
3784 (save-excursion
3785 (unless (bolp) (backward-char 1))
3786 (looking-at org-emph-re)
3787 (let ((begin (match-beginning 2))
3788 (value (org-match-string-no-properties 4))
3789 (post-blank (progn (goto-char (match-end 2))
3790 (skip-chars-forward " \t")))
3791 (end (point)))
3792 (list 'verbatim
3793 (list :value value
3794 :begin begin
3795 :end end
3796 :post-blank post-blank)))))
3798 (defun org-element-verbatim-interpreter (verbatim contents)
3799 "Interpret VERBATIM object as Org syntax.
3800 CONTENTS is nil."
3801 (format "=%s=" (org-element-property :value verbatim)))
3805 ;;; Parsing Element Starting At Point
3807 ;; `org-element--current-element' is the core function of this section.
3808 ;; It returns the Lisp representation of the element starting at
3809 ;; point.
3811 ;; `org-element--current-element' makes use of special modes. They
3812 ;; are activated for fixed element chaining (i.e. `plain-list' >
3813 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3814 ;; `section'). Special modes are: `first-section', `item',
3815 ;; `node-property', `quote-section', `section' and `table-row'.
3817 (defun org-element--current-element
3818 (limit &optional granularity special structure)
3819 "Parse the element starting at point.
3821 Return value is a list like (TYPE PROPS) where TYPE is the type
3822 of the element and PROPS a plist of properties associated to the
3823 element.
3825 Possible types are defined in `org-element-all-elements'.
3827 LIMIT bounds the search.
3829 Optional argument GRANULARITY determines the depth of the
3830 recursion. Allowed values are `headline', `greater-element',
3831 `element', `object' or nil. When it is broader than `object' (or
3832 nil), secondary values will not be parsed, since they only
3833 contain objects.
3835 Optional argument SPECIAL, when non-nil, can be either
3836 `first-section', `item', `node-property', `quote-section',
3837 `section', and `table-row'.
3839 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3840 be computed.
3842 This function assumes point is always at the beginning of the
3843 element it has to parse."
3844 (save-excursion
3845 (let ((case-fold-search t)
3846 ;; Determine if parsing depth allows for secondary strings
3847 ;; parsing. It only applies to elements referenced in
3848 ;; `org-element-secondary-value-alist'.
3849 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3850 (cond
3851 ;; Item.
3852 ((eq special 'item)
3853 (org-element-item-parser limit structure raw-secondary-p))
3854 ;; Table Row.
3855 ((eq special 'table-row) (org-element-table-row-parser limit))
3856 ;; Node Property.
3857 ((eq special 'node-property) (org-element-node-property-parser limit))
3858 ;; Headline.
3859 ((org-with-limited-levels (org-at-heading-p))
3860 (org-element-headline-parser limit raw-secondary-p))
3861 ;; Sections (must be checked after headline).
3862 ((eq special 'section) (org-element-section-parser limit))
3863 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3864 ((eq special 'first-section)
3865 (org-element-section-parser
3866 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3867 limit)))
3868 ;; When not at bol, point is at the beginning of an item or
3869 ;; a footnote definition: next item is always a paragraph.
3870 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3871 ;; Planning and Clock.
3872 ((looking-at org-planning-or-clock-line-re)
3873 (if (equal (match-string 1) org-clock-string)
3874 (org-element-clock-parser limit)
3875 (org-element-planning-parser limit)))
3876 ;; Inlinetask.
3877 ((org-at-heading-p)
3878 (org-element-inlinetask-parser limit raw-secondary-p))
3879 ;; From there, elements can have affiliated keywords.
3880 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3881 (cond
3882 ;; Jumping over affiliated keywords put point off-limits.
3883 ;; Parse them as regular keywords.
3884 ((and (cdr affiliated) (>= (point) limit))
3885 (goto-char (car affiliated))
3886 (org-element-keyword-parser limit nil))
3887 ;; LaTeX Environment.
3888 ((looking-at
3889 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3890 (org-element-latex-environment-parser limit affiliated))
3891 ;; Drawer and Property Drawer.
3892 ((looking-at org-drawer-regexp)
3893 (if (equal (match-string 1) "PROPERTIES")
3894 (org-element-property-drawer-parser limit affiliated)
3895 (org-element-drawer-parser limit affiliated)))
3896 ;; Fixed Width
3897 ((looking-at "[ \t]*:\\( \\|$\\)")
3898 (org-element-fixed-width-parser limit affiliated))
3899 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3900 ;; Keywords.
3901 ((looking-at "[ \t]*#")
3902 (goto-char (match-end 0))
3903 (cond ((looking-at "\\(?: \\|$\\)")
3904 (beginning-of-line)
3905 (org-element-comment-parser limit affiliated))
3906 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3907 (beginning-of-line)
3908 (let ((parser (assoc (upcase (match-string 1))
3909 org-element-block-name-alist)))
3910 (if parser (funcall (cdr parser) limit affiliated)
3911 (org-element-special-block-parser limit affiliated))))
3912 ((looking-at "\\+CALL:")
3913 (beginning-of-line)
3914 (org-element-babel-call-parser limit affiliated))
3915 ((looking-at "\\+BEGIN:? ")
3916 (beginning-of-line)
3917 (org-element-dynamic-block-parser limit affiliated))
3918 ((looking-at "\\+\\S-+:")
3919 (beginning-of-line)
3920 (org-element-keyword-parser limit affiliated))
3922 (beginning-of-line)
3923 (org-element-paragraph-parser limit affiliated))))
3924 ;; Footnote Definition.
3925 ((looking-at org-footnote-definition-re)
3926 (org-element-footnote-definition-parser limit affiliated))
3927 ;; Horizontal Rule.
3928 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3929 (org-element-horizontal-rule-parser limit affiliated))
3930 ;; Diary Sexp.
3931 ((looking-at "%%(")
3932 (org-element-diary-sexp-parser limit affiliated))
3933 ;; Table.
3934 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3935 ;; List.
3936 ((looking-at (org-item-re))
3937 (org-element-plain-list-parser
3938 limit affiliated
3939 (or structure (org-element--list-struct limit))))
3940 ;; Default element: Paragraph.
3941 (t (org-element-paragraph-parser limit affiliated)))))))))
3944 ;; Most elements can have affiliated keywords. When looking for an
3945 ;; element beginning, we want to move before them, as they belong to
3946 ;; that element, and, in the meantime, collect information they give
3947 ;; into appropriate properties. Hence the following function.
3949 (defun org-element--collect-affiliated-keywords (limit)
3950 "Collect affiliated keywords from point down to LIMIT.
3952 Return a list whose CAR is the position at the first of them and
3953 CDR a plist of keywords and values and move point to the
3954 beginning of the first line after them.
3956 As a special case, if element doesn't start at the beginning of
3957 the line (i.e. a paragraph starting an item), CAR is current
3958 position of point and CDR is nil."
3959 (if (not (bolp)) (list (point))
3960 (let ((case-fold-search t)
3961 (origin (point))
3962 ;; RESTRICT is the list of objects allowed in parsed
3963 ;; keywords value.
3964 (restrict (org-element-restriction 'keyword))
3965 output)
3966 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3967 (let* ((raw-kwd (upcase (match-string 1)))
3968 ;; Apply translation to RAW-KWD. From there, KWD is
3969 ;; the official keyword.
3970 (kwd (or (cdr (assoc raw-kwd
3971 org-element-keyword-translation-alist))
3972 raw-kwd))
3973 ;; Find main value for any keyword.
3974 (value
3975 (save-match-data
3976 (org-trim
3977 (buffer-substring-no-properties
3978 (match-end 0) (point-at-eol)))))
3979 ;; PARSEDP is non-nil when keyword should have its
3980 ;; value parsed.
3981 (parsedp (member kwd org-element-parsed-keywords))
3982 ;; If KWD is a dual keyword, find its secondary
3983 ;; value. Maybe parse it.
3984 (dualp (member kwd org-element-dual-keywords))
3985 (dual-value
3986 (and dualp
3987 (let ((sec (org-match-string-no-properties 2)))
3988 (if (or (not sec) (not parsedp)) sec
3989 (org-element-parse-secondary-string sec restrict)))))
3990 ;; Attribute a property name to KWD.
3991 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3992 ;; Now set final shape for VALUE.
3993 (when parsedp
3994 (setq value (org-element-parse-secondary-string value restrict)))
3995 (when dualp
3996 (setq value (and (or value dual-value) (cons value dual-value))))
3997 (when (or (member kwd org-element-multiple-keywords)
3998 ;; Attributes can always appear on multiple lines.
3999 (string-match "^ATTR_" kwd))
4000 (setq value (cons value (plist-get output kwd-sym))))
4001 ;; Eventually store the new value in OUTPUT.
4002 (setq output (plist-put output kwd-sym value))
4003 ;; Move to next keyword.
4004 (forward-line)))
4005 ;; If affiliated keywords are orphaned: move back to first one.
4006 ;; They will be parsed as a paragraph.
4007 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
4008 ;; Return value.
4009 (cons origin output))))
4013 ;;; The Org Parser
4015 ;; The two major functions here are `org-element-parse-buffer', which
4016 ;; parses Org syntax inside the current buffer, taking into account
4017 ;; region, narrowing, or even visibility if specified, and
4018 ;; `org-element-parse-secondary-string', which parses objects within
4019 ;; a given string.
4021 ;; The (almost) almighty `org-element-map' allows to apply a function
4022 ;; on elements or objects matching some type, and accumulate the
4023 ;; resulting values. In an export situation, it also skips unneeded
4024 ;; parts of the parse tree.
4026 (defun org-element-parse-buffer (&optional granularity visible-only)
4027 "Recursively parse the buffer and return structure.
4028 If narrowing is in effect, only parse the visible part of the
4029 buffer.
4031 Optional argument GRANULARITY determines the depth of the
4032 recursion. It can be set to the following symbols:
4034 `headline' Only parse headlines.
4035 `greater-element' Don't recurse into greater elements excepted
4036 headlines and sections. Thus, elements
4037 parsed are the top-level ones.
4038 `element' Parse everything but objects and plain text.
4039 `object' Parse the complete buffer (default).
4041 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4042 elements.
4044 An element or an objects is represented as a list with the
4045 pattern (TYPE PROPERTIES CONTENTS), where :
4047 TYPE is a symbol describing the element or object. See
4048 `org-element-all-elements' and `org-element-all-objects' for an
4049 exhaustive list of such symbols. One can retrieve it with
4050 `org-element-type' function.
4052 PROPERTIES is the list of attributes attached to the element or
4053 object, as a plist. Although most of them are specific to the
4054 element or object type, all types share `:begin', `:end',
4055 `:post-blank' and `:parent' properties, which respectively
4056 refer to buffer position where the element or object starts,
4057 ends, the number of white spaces or blank lines after it, and
4058 the element or object containing it. Properties values can be
4059 obtained by using `org-element-property' function.
4061 CONTENTS is a list of elements, objects or raw strings
4062 contained in the current element or object, when applicable.
4063 One can access them with `org-element-contents' function.
4065 The Org buffer has `org-data' as type and nil as properties.
4066 `org-element-map' function can be used to find specific elements
4067 or objects within the parse tree.
4069 This function assumes that current major mode is `org-mode'."
4070 (save-excursion
4071 (goto-char (point-min))
4072 (org-skip-whitespace)
4073 (org-element--parse-elements
4074 (point-at-bol) (point-max)
4075 ;; Start in `first-section' mode so text before the first
4076 ;; headline belongs to a section.
4077 'first-section nil granularity visible-only (list 'org-data nil))))
4079 (defun org-element-parse-secondary-string (string restriction &optional parent)
4080 "Recursively parse objects in STRING and return structure.
4082 RESTRICTION is a symbol limiting the object types that will be
4083 looked after.
4085 Optional argument PARENT, when non-nil, is the element or object
4086 containing the secondary string. It is used to set correctly
4087 `:parent' property within the string."
4088 ;; Copy buffer-local variables listed in
4089 ;; `org-element-object-variables' into temporary buffer. This is
4090 ;; required since object parsing is dependent on these variables.
4091 (let ((pairs (delq nil (mapcar (lambda (var)
4092 (when (boundp var)
4093 (cons var (symbol-value var))))
4094 org-element-object-variables))))
4095 (with-temp-buffer
4096 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4097 (insert string)
4098 (let ((secondary (org-element--parse-objects
4099 (point-min) (point-max) nil restriction)))
4100 (when parent
4101 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4102 secondary))
4103 secondary))))
4105 (defun org-element-map
4106 (data types fun &optional info first-match no-recursion with-affiliated)
4107 "Map a function on selected elements or objects.
4109 DATA is a parse tree, an element, an object, a string, or a list
4110 of such constructs. TYPES is a symbol or list of symbols of
4111 elements or objects types (see `org-element-all-elements' and
4112 `org-element-all-objects' for a complete list of types). FUN is
4113 the function called on the matching element or object. It has to
4114 accept one argument: the element or object itself.
4116 When optional argument INFO is non-nil, it should be a plist
4117 holding export options. In that case, parts of the parse tree
4118 not exportable according to that property list will be skipped.
4120 When optional argument FIRST-MATCH is non-nil, stop at the first
4121 match for which FUN doesn't return nil, and return that value.
4123 Optional argument NO-RECURSION is a symbol or a list of symbols
4124 representing elements or objects types. `org-element-map' won't
4125 enter any recursive element or object whose type belongs to that
4126 list. Though, FUN can still be applied on them.
4128 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4129 apply to matching objects within parsed affiliated keywords (see
4130 `org-element-parsed-keywords').
4132 Nil values returned from FUN do not appear in the results.
4135 Examples:
4136 ---------
4138 Assuming TREE is a variable containing an Org buffer parse tree,
4139 the following example will return a flat list of all `src-block'
4140 and `example-block' elements in it:
4142 \(org-element-map tree '(example-block src-block) 'identity)
4144 The following snippet will find the first headline with a level
4145 of 1 and a \"phone\" tag, and will return its beginning position:
4147 \(org-element-map tree 'headline
4148 \(lambda (hl)
4149 \(and (= (org-element-property :level hl) 1)
4150 \(member \"phone\" (org-element-property :tags hl))
4151 \(org-element-property :begin hl)))
4152 nil t)
4154 The next example will return a flat list of all `plain-list' type
4155 elements in TREE that are not a sub-list themselves:
4157 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4159 Eventually, this example will return a flat list of all `bold'
4160 type objects containing a `latex-snippet' type object, even
4161 looking into captions:
4163 \(org-element-map tree 'bold
4164 \(lambda (b)
4165 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4166 nil nil nil t)"
4167 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4168 (unless (listp types) (setq types (list types)))
4169 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4170 ;; Recursion depth is determined by --CATEGORY.
4171 (let* ((--category
4172 (catch 'found
4173 (let ((category 'greater-elements))
4174 (mapc (lambda (type)
4175 (cond ((or (memq type org-element-all-objects)
4176 (eq type 'plain-text))
4177 ;; If one object is found, the function
4178 ;; has to recurse into every object.
4179 (throw 'found 'objects))
4180 ((not (memq type org-element-greater-elements))
4181 ;; If one regular element is found, the
4182 ;; function has to recurse, at least,
4183 ;; into every element it encounters.
4184 (and (not (eq category 'elements))
4185 (setq category 'elements)))))
4186 types)
4187 category)))
4188 ;; Compute properties for affiliated keywords if necessary.
4189 (--affiliated-alist
4190 (and with-affiliated
4191 (mapcar (lambda (kwd)
4192 (cons kwd (intern (concat ":" (downcase kwd)))))
4193 org-element-affiliated-keywords)))
4194 --acc
4195 --walk-tree
4196 (--walk-tree
4197 (function
4198 (lambda (--data)
4199 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4200 ;; holding contextual information.
4201 (let ((--type (org-element-type --data)))
4202 (cond
4203 ((not --data))
4204 ;; Ignored element in an export context.
4205 ((and info (memq --data (plist-get info :ignore-list))))
4206 ;; List of elements or objects.
4207 ((not --type) (mapc --walk-tree --data))
4208 ;; Unconditionally enter parse trees.
4209 ((eq --type 'org-data)
4210 (mapc --walk-tree (org-element-contents --data)))
4212 ;; Check if TYPE is matching among TYPES. If so,
4213 ;; apply FUN to --DATA and accumulate return value
4214 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4215 (when (memq --type types)
4216 (let ((result (funcall fun --data)))
4217 (cond ((not result))
4218 (first-match (throw '--map-first-match result))
4219 (t (push result --acc)))))
4220 ;; If --DATA has a secondary string that can contain
4221 ;; objects with their type among TYPES, look into it.
4222 (when (and (eq --category 'objects) (not (stringp --data)))
4223 (let ((sec-prop
4224 (assq --type org-element-secondary-value-alist)))
4225 (when sec-prop
4226 (funcall --walk-tree
4227 (org-element-property (cdr sec-prop) --data)))))
4228 ;; If --DATA has any affiliated keywords and
4229 ;; WITH-AFFILIATED is non-nil, look for objects in
4230 ;; them.
4231 (when (and with-affiliated
4232 (eq --category 'objects)
4233 (memq --type org-element-all-elements))
4234 (mapc (lambda (kwd-pair)
4235 (let ((kwd (car kwd-pair))
4236 (value (org-element-property
4237 (cdr kwd-pair) --data)))
4238 ;; Pay attention to the type of value.
4239 ;; Preserve order for multiple keywords.
4240 (cond
4241 ((not value))
4242 ((and (member kwd org-element-multiple-keywords)
4243 (member kwd org-element-dual-keywords))
4244 (mapc (lambda (line)
4245 (funcall --walk-tree (cdr line))
4246 (funcall --walk-tree (car line)))
4247 (reverse value)))
4248 ((member kwd org-element-multiple-keywords)
4249 (mapc (lambda (line) (funcall --walk-tree line))
4250 (reverse value)))
4251 ((member kwd org-element-dual-keywords)
4252 (funcall --walk-tree (cdr value))
4253 (funcall --walk-tree (car value)))
4254 (t (funcall --walk-tree value)))))
4255 --affiliated-alist))
4256 ;; Determine if a recursion into --DATA is possible.
4257 (cond
4258 ;; --TYPE is explicitly removed from recursion.
4259 ((memq --type no-recursion))
4260 ;; --DATA has no contents.
4261 ((not (org-element-contents --data)))
4262 ;; Looking for greater elements but --DATA is simply
4263 ;; an element or an object.
4264 ((and (eq --category 'greater-elements)
4265 (not (memq --type org-element-greater-elements))))
4266 ;; Looking for elements but --DATA is an object.
4267 ((and (eq --category 'elements)
4268 (memq --type org-element-all-objects)))
4269 ;; In any other case, map contents.
4270 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4271 (catch '--map-first-match
4272 (funcall --walk-tree data)
4273 ;; Return value in a proper order.
4274 (nreverse --acc))))
4275 (put 'org-element-map 'lisp-indent-function 2)
4277 ;; The following functions are internal parts of the parser.
4279 ;; The first one, `org-element--parse-elements' acts at the element's
4280 ;; level.
4282 ;; The second one, `org-element--parse-objects' applies on all objects
4283 ;; of a paragraph or a secondary string. It uses
4284 ;; `org-element--get-next-object-candidates' to optimize the search of
4285 ;; the next object in the buffer.
4287 ;; More precisely, that function looks for every allowed object type
4288 ;; first. Then, it discards failed searches, keeps further matches,
4289 ;; and searches again types matched behind point, for subsequent
4290 ;; calls. Thus, searching for a given type fails only once, and every
4291 ;; object is searched only once at top level (but sometimes more for
4292 ;; nested types).
4294 (defun org-element--parse-elements
4295 (beg end special structure granularity visible-only acc)
4296 "Parse elements between BEG and END positions.
4298 SPECIAL prioritize some elements over the others. It can be set
4299 to `first-section', `quote-section', `section' `item' or
4300 `table-row'.
4302 When value is `item', STRUCTURE will be used as the current list
4303 structure.
4305 GRANULARITY determines the depth of the recursion. See
4306 `org-element-parse-buffer' for more information.
4308 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4309 elements.
4311 Elements are accumulated into ACC."
4312 (save-excursion
4313 (goto-char beg)
4314 ;; Visible only: skip invisible parts at the beginning of the
4315 ;; element.
4316 (when (and visible-only (org-invisible-p2))
4317 (goto-char (min (1+ (org-find-visible)) end)))
4318 ;; When parsing only headlines, skip any text before first one.
4319 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4320 (org-with-limited-levels (outline-next-heading)))
4321 ;; Main loop start.
4322 (while (< (point) end)
4323 ;; Find current element's type and parse it accordingly to
4324 ;; its category.
4325 (let* ((element (org-element--current-element
4326 end granularity special structure))
4327 (type (org-element-type element))
4328 (cbeg (org-element-property :contents-begin element)))
4329 (goto-char (org-element-property :end element))
4330 ;; Visible only: skip invisible parts between siblings.
4331 (when (and visible-only (org-invisible-p2))
4332 (goto-char (min (1+ (org-find-visible)) end)))
4333 ;; Fill ELEMENT contents by side-effect.
4334 (cond
4335 ;; If element has no contents, don't modify it.
4336 ((not cbeg))
4337 ;; Greater element: parse it between `contents-begin' and
4338 ;; `contents-end'. Make sure GRANULARITY allows the
4339 ;; recursion, or ELEMENT is a headline, in which case going
4340 ;; inside is mandatory, in order to get sub-level headings.
4341 ((and (memq type org-element-greater-elements)
4342 (or (memq granularity '(element object nil))
4343 (and (eq granularity 'greater-element)
4344 (eq type 'section))
4345 (eq type 'headline)))
4346 (org-element--parse-elements
4347 cbeg (org-element-property :contents-end element)
4348 ;; Possibly switch to a special mode.
4349 (case type
4350 (headline
4351 (if (org-element-property :quotedp element) 'quote-section
4352 'section))
4353 (plain-list 'item)
4354 (property-drawer 'node-property)
4355 (table 'table-row))
4356 (and (memq type '(item plain-list))
4357 (org-element-property :structure element))
4358 granularity visible-only element))
4359 ;; ELEMENT has contents. Parse objects inside, if
4360 ;; GRANULARITY allows it.
4361 ((memq granularity '(object nil))
4362 (org-element--parse-objects
4363 cbeg (org-element-property :contents-end element) element
4364 (org-element-restriction type))))
4365 (org-element-adopt-elements acc element)))
4366 ;; Return result.
4367 acc))
4369 (defun org-element--parse-objects (beg end acc restriction)
4370 "Parse objects between BEG and END and return recursive structure.
4372 Objects are accumulated in ACC.
4374 RESTRICTION is a list of object successors which are allowed in
4375 the current object."
4376 (let ((candidates 'initial))
4377 (save-excursion
4378 (save-restriction
4379 (narrow-to-region beg end)
4380 (goto-char (point-min))
4381 (while (and (not (eobp))
4382 (setq candidates
4383 (org-element--get-next-object-candidates
4384 restriction candidates)))
4385 (let ((next-object
4386 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4387 (save-excursion
4388 (goto-char pos)
4389 (funcall (intern (format "org-element-%s-parser"
4390 (car (rassq pos candidates)))))))))
4391 ;; 1. Text before any object. Untabify it.
4392 (let ((obj-beg (org-element-property :begin next-object)))
4393 (unless (= (point) obj-beg)
4394 (setq acc
4395 (org-element-adopt-elements
4397 (replace-regexp-in-string
4398 "\t" (make-string tab-width ? )
4399 (buffer-substring-no-properties (point) obj-beg))))))
4400 ;; 2. Object...
4401 (let ((obj-end (org-element-property :end next-object))
4402 (cont-beg (org-element-property :contents-begin next-object)))
4403 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4404 ;; a recursive type.
4405 (when (and cont-beg
4406 (memq (car next-object) org-element-recursive-objects))
4407 (org-element--parse-objects
4408 cont-beg (org-element-property :contents-end next-object)
4409 next-object (org-element-restriction next-object)))
4410 (setq acc (org-element-adopt-elements acc next-object))
4411 (goto-char obj-end))))
4412 ;; 3. Text after last object. Untabify it.
4413 (unless (eobp)
4414 (setq acc
4415 (org-element-adopt-elements
4417 (replace-regexp-in-string
4418 "\t" (make-string tab-width ? )
4419 (buffer-substring-no-properties (point) end)))))
4420 ;; Result.
4421 acc))))
4423 (defun org-element--get-next-object-candidates (restriction objects)
4424 "Return an alist of candidates for the next object.
4426 RESTRICTION is a list of object types, as symbols. Only
4427 candidates with such types are looked after.
4429 OBJECTS is the previous candidates alist. If it is set to
4430 `initial', no search has been done before, and all symbols in
4431 RESTRICTION should be looked after.
4433 Return value is an alist whose CAR is the object type and CDR its
4434 beginning position."
4435 (delq
4437 (if (eq objects 'initial)
4438 ;; When searching for the first time, look for every successor
4439 ;; allowed in RESTRICTION.
4440 (mapcar
4441 (lambda (res)
4442 (funcall (intern (format "org-element-%s-successor" res))))
4443 restriction)
4444 ;; Focus on objects returned during last search. Keep those
4445 ;; still after point. Search again objects before it.
4446 (mapcar
4447 (lambda (obj)
4448 (if (>= (cdr obj) (point)) obj
4449 (let* ((type (car obj))
4450 (succ (or (cdr (assq type org-element-object-successor-alist))
4451 type)))
4452 (and succ
4453 (funcall (intern (format "org-element-%s-successor" succ)))))))
4454 objects))))
4458 ;;; Towards A Bijective Process
4460 ;; The parse tree obtained with `org-element-parse-buffer' is really
4461 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4462 ;; interpreted and expanded into a string with canonical Org syntax.
4463 ;; Hence `org-element-interpret-data'.
4465 ;; The function relies internally on
4466 ;; `org-element--interpret-affiliated-keywords'.
4468 ;;;###autoload
4469 (defun org-element-interpret-data (data &optional pseudo-objects)
4470 "Interpret DATA as Org syntax.
4472 DATA is a parse tree, an element, an object or a secondary string
4473 to interpret.
4475 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4476 new types that should be treated as objects. An unknown type not
4477 belonging to this list is seen as a pseudo-element instead. Both
4478 pseudo-objects and pseudo-elements are transparent entities, i.e.
4479 only their contents are interpreted.
4481 Return Org syntax as a string."
4482 (org-element--interpret-data-1 data nil pseudo-objects))
4484 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4485 "Interpret DATA as Org syntax.
4487 DATA is a parse tree, an element, an object or a secondary string
4488 to interpret. PARENT is used for recursive calls. It contains
4489 the element or object containing data, or nil. PSEUDO-OBJECTS
4490 are list of symbols defining new element or object types.
4491 Unknown types that don't belong to this list are treated as
4492 pseudo-elements instead.
4494 Return Org syntax as a string."
4495 (let* ((type (org-element-type data))
4496 ;; Find interpreter for current object or element. If it
4497 ;; doesn't exist (e.g. this is a pseudo object or element),
4498 ;; return contents, if any.
4499 (interpret
4500 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4501 (if (fboundp fun) fun (lambda (data contents) contents))))
4502 (results
4503 (cond
4504 ;; Secondary string.
4505 ((not type)
4506 (mapconcat
4507 (lambda (obj)
4508 (org-element--interpret-data-1 obj parent pseudo-objects))
4509 data ""))
4510 ;; Full Org document.
4511 ((eq type 'org-data)
4512 (mapconcat
4513 (lambda (obj)
4514 (org-element--interpret-data-1 obj parent pseudo-objects))
4515 (org-element-contents data) ""))
4516 ;; Plain text: remove `:parent' text property from output.
4517 ((stringp data) (org-no-properties data))
4518 ;; Element or object without contents.
4519 ((not (org-element-contents data)) (funcall interpret data nil))
4520 ;; Element or object with contents.
4522 (funcall interpret data
4523 ;; Recursively interpret contents.
4524 (mapconcat
4525 (lambda (obj)
4526 (org-element--interpret-data-1 obj data pseudo-objects))
4527 (org-element-contents
4528 (if (not (memq type '(paragraph verse-block)))
4529 data
4530 ;; Fix indentation of elements containing
4531 ;; objects. We ignore `table-row' elements
4532 ;; as they are one line long anyway.
4533 (org-element-normalize-contents
4534 data
4535 ;; When normalizing first paragraph of an
4536 ;; item or a footnote-definition, ignore
4537 ;; first line's indentation.
4538 (and (eq type 'paragraph)
4539 (equal data (car (org-element-contents parent)))
4540 (memq (org-element-type parent)
4541 '(footnote-definition item))))))
4542 ""))))))
4543 (if (memq type '(org-data plain-text nil)) results
4544 ;; Build white spaces. If no `:post-blank' property is
4545 ;; specified, assume its value is 0.
4546 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4547 (if (or (memq type org-element-all-objects)
4548 (memq type pseudo-objects))
4549 (concat results (make-string post-blank ?\s))
4550 (concat
4551 (org-element--interpret-affiliated-keywords data)
4552 (org-element-normalize-string results)
4553 (make-string post-blank ?\n)))))))
4555 (defun org-element--interpret-affiliated-keywords (element)
4556 "Return ELEMENT's affiliated keywords as Org syntax.
4557 If there is no affiliated keyword, return the empty string."
4558 (let ((keyword-to-org
4559 (function
4560 (lambda (key value)
4561 (let (dual)
4562 (when (member key org-element-dual-keywords)
4563 (setq dual (cdr value) value (car value)))
4564 (concat "#+" key
4565 (and dual
4566 (format "[%s]" (org-element-interpret-data dual)))
4567 ": "
4568 (if (member key org-element-parsed-keywords)
4569 (org-element-interpret-data value)
4570 value)
4571 "\n"))))))
4572 (mapconcat
4573 (lambda (prop)
4574 (let ((value (org-element-property prop element))
4575 (keyword (upcase (substring (symbol-name prop) 1))))
4576 (when value
4577 (if (or (member keyword org-element-multiple-keywords)
4578 ;; All attribute keywords can have multiple lines.
4579 (string-match "^ATTR_" keyword))
4580 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4581 (reverse value)
4583 (funcall keyword-to-org keyword value)))))
4584 ;; List all ELEMENT's properties matching an attribute line or an
4585 ;; affiliated keyword, but ignore translated keywords since they
4586 ;; cannot belong to the property list.
4587 (loop for prop in (nth 1 element) by 'cddr
4588 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4589 (or (string-match "^ATTR_" keyword)
4590 (and
4591 (member keyword org-element-affiliated-keywords)
4592 (not (assoc keyword
4593 org-element-keyword-translation-alist)))))
4594 collect prop)
4595 "")))
4597 ;; Because interpretation of the parse tree must return the same
4598 ;; number of blank lines between elements and the same number of white
4599 ;; space after objects, some special care must be given to white
4600 ;; spaces.
4602 ;; The first function, `org-element-normalize-string', ensures any
4603 ;; string different from the empty string will end with a single
4604 ;; newline character.
4606 ;; The second function, `org-element-normalize-contents', removes
4607 ;; global indentation from the contents of the current element.
4609 (defun org-element-normalize-string (s)
4610 "Ensure string S ends with a single newline character.
4612 If S isn't a string return it unchanged. If S is the empty
4613 string, return it. Otherwise, return a new string with a single
4614 newline character at its end."
4615 (cond
4616 ((not (stringp s)) s)
4617 ((string= "" s) "")
4618 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4619 (replace-match "\n" nil nil s)))))
4621 (defun org-element-normalize-contents (element &optional ignore-first)
4622 "Normalize plain text in ELEMENT's contents.
4624 ELEMENT must only contain plain text and objects.
4626 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4627 indentation to compute maximal common indentation.
4629 Return the normalized element that is element with global
4630 indentation removed from its contents. The function assumes that
4631 indentation is not done with TAB characters."
4632 (let* (ind-list ; for byte-compiler
4633 collect-inds ; for byte-compiler
4634 (collect-inds
4635 (function
4636 ;; Return list of indentations within BLOB. This is done by
4637 ;; walking recursively BLOB and updating IND-LIST along the
4638 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4639 ;; been seen yet. It is required as this string is the only
4640 ;; one whose indentation doesn't happen after a newline
4641 ;; character.
4642 (lambda (blob first-flag)
4643 (mapc
4644 (lambda (object)
4645 (when (and first-flag (stringp object))
4646 (setq first-flag nil)
4647 (string-match "\\`\\( *\\)" object)
4648 (let ((len (length (match-string 1 object))))
4649 ;; An indentation of zero means no string will be
4650 ;; modified. Quit the process.
4651 (if (zerop len) (throw 'zero (setq ind-list nil))
4652 (push len ind-list))))
4653 (cond
4654 ((stringp object)
4655 (let ((start 0))
4656 ;; Avoid matching blank or empty lines.
4657 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4658 (not (equal (match-string 2 object) " ")))
4659 (setq start (match-end 0))
4660 (push (length (match-string 1 object)) ind-list))))
4661 ((memq (org-element-type object) org-element-recursive-objects)
4662 (funcall collect-inds object first-flag))))
4663 (org-element-contents blob))))))
4664 ;; Collect indentation list in ELEMENT. Possibly remove first
4665 ;; value if IGNORE-FIRST is non-nil.
4666 (catch 'zero (funcall collect-inds element (not ignore-first)))
4667 (if (not ind-list) element
4668 ;; Build ELEMENT back, replacing each string with the same
4669 ;; string minus common indentation.
4670 (let* (build ; For byte compiler.
4671 (build
4672 (function
4673 (lambda (blob mci first-flag)
4674 ;; Return BLOB with all its strings indentation
4675 ;; shortened from MCI white spaces. FIRST-FLAG is
4676 ;; non-nil when the first string hasn't been seen
4677 ;; yet.
4678 (setcdr (cdr blob)
4679 (mapcar
4680 (lambda (object)
4681 (when (and first-flag (stringp object))
4682 (setq first-flag nil)
4683 (setq object
4684 (replace-regexp-in-string
4685 (format "\\` \\{%d\\}" mci) "" object)))
4686 (cond
4687 ((stringp object)
4688 (replace-regexp-in-string
4689 (format "\n \\{%d\\}" mci) "\n" object))
4690 ((memq (org-element-type object)
4691 org-element-recursive-objects)
4692 (funcall build object mci first-flag))
4693 (t object)))
4694 (org-element-contents blob)))
4695 blob))))
4696 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4700 ;;; The Toolbox
4702 ;; The first move is to implement a way to obtain the smallest element
4703 ;; containing point. This is the job of `org-element-at-point'. It
4704 ;; basically jumps back to the beginning of section containing point
4705 ;; and proceed, one element after the other, with
4706 ;; `org-element--current-element' until the container is found. Note:
4707 ;; When using `org-element-at-point', secondary values are never
4708 ;; parsed since the function focuses on elements, not on objects.
4710 ;; At a deeper level, `org-element-context' lists all elements and
4711 ;; objects containing point.
4713 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4714 ;; internally by navigation and manipulation tools.
4717 ;;;###autoload
4718 (defun org-element-at-point ()
4719 "Determine closest element around point.
4721 Return value is a list like (TYPE PROPS) where TYPE is the type
4722 of the element and PROPS a plist of properties associated to the
4723 element.
4725 Possible types are defined in `org-element-all-elements'.
4726 Properties depend on element or object type, but always include
4727 `:begin', `:end', `:parent' and `:post-blank' properties.
4729 As a special case, if point is at the very beginning of the first
4730 item in a list or sub-list, returned element will be that list
4731 instead of the item. Likewise, if point is at the beginning of
4732 the first row of a table, returned element will be the table
4733 instead of the first row.
4735 When point is at the end of the buffer, return the innermost
4736 element ending there."
4737 (catch 'exit
4738 (org-with-wide-buffer
4739 (let ((origin (point)) element next)
4740 (end-of-line)
4741 (skip-chars-backward " \r\t\n")
4742 (cond
4743 ;; Within blank lines at the beginning of buffer, return nil.
4744 ((bobp) (throw 'exit nil))
4745 ;; Within blank lines right after a headline, return that
4746 ;; headline.
4747 ((org-with-limited-levels (org-at-heading-p))
4748 (beginning-of-line)
4749 (throw 'exit (org-element-headline-parser (point-max) t))))
4750 ;; Otherwise use cache in order to approximate current element.
4751 (goto-char origin)
4752 (let* ((cached (org-element-cache-get origin))
4753 (begin (org-element-property :begin cached)))
4754 (cond
4755 ;; Nothing in cache before point: start parsing from first
4756 ;; element following headline above, or first element in
4757 ;; buffer.
4758 ((not cached)
4759 (org-with-limited-levels (outline-previous-heading)
4760 (when (org-at-heading-p) (forward-line)))
4761 (skip-chars-forward " \r\t\n")
4762 (beginning-of-line))
4763 ;; Cache returned exact match: return it.
4764 ((= origin begin) (throw 'exit cached))
4765 ;; There's a headline between cached value and ORIGIN:
4766 ;; cached value is invalid. Start parsing from first
4767 ;; element following the headline.
4768 ((re-search-backward
4769 (org-with-limited-levels org-outline-regexp-bol) begin t)
4770 (forward-line)
4771 (skip-chars-forward " \r\t\n")
4772 (beginning-of-line))
4773 ;; Check if CACHED or any of its ancestors contain point.
4775 ;; If there is such an element, we inspect it in order to
4776 ;; know if we return it or if we need to parse its contents.
4777 ;; Otherwise, we just start parsing from current location,
4778 ;; which is right after the top-most element containing
4779 ;; CACHED.
4781 ;; As a special case, if ORIGIN is at the end of the buffer,
4782 ;; we want to return the innermost element ending there.
4784 ;; Also, if we find an ancestor and discover that we need to
4785 ;; parse its contents, make sure we don't start from
4786 ;; `:contents-begin', as we would otherwise go past CACHED
4787 ;; again. Instead, in that situation, we will resume
4788 ;; parsing from NEXT, which is located after CACHED or its
4789 ;; higher ancestor not containing point.
4791 (let ((up cached)
4792 (origin (if (= (point-max) origin) (1- origin) origin)))
4793 (goto-char (or (org-element-property :contents-begin cached)
4794 begin))
4795 (while (let ((end (org-element-property :end up)))
4796 (and (<= end origin)
4797 (goto-char end)
4798 (setq up (org-element-property :parent up)))))
4799 (cond ((not up))
4800 ((eobp) (setq element up))
4801 (t (setq element up next (point))))))))
4802 ;; Parse successively each element until we reach ORIGIN.
4803 (let ((end (or (org-element-property :end element)
4804 (save-excursion
4805 (org-with-limited-levels (outline-next-heading))
4806 (point))))
4807 parent special-flag)
4808 (while t
4809 (unless element
4810 (let ((e (org-element--current-element
4811 end 'element special-flag
4812 (org-element-property :structure parent))))
4813 (org-element-put-property e :parent parent)
4814 (setq element (org-element-cache-put e))))
4815 (let ((elem-end (org-element-property :end element))
4816 (type (org-element-type element)))
4817 (cond
4818 ;; Special case: ORIGIN is at the end of the buffer and
4819 ;; CACHED ends here. No element can start after it, but
4820 ;; more than one may end there. Arbitrarily, we choose
4821 ;; to return the innermost of such elements.
4822 ((and (= (point-max) origin) (= origin elem-end))
4823 (let ((cend (org-element-property :contents-end element)))
4824 (if (or (not (memq type org-element-greater-elements))
4825 (not cend)
4826 (< cend origin))
4827 (throw 'exit element)
4828 (goto-char
4829 (or next (org-element-property :contents-begin element)))
4830 (setq special-flag (case type
4831 (plain-list 'item)
4832 (property-drawer 'node-property)
4833 (table 'table-row))
4834 parent element
4835 end cend))))
4836 ;; Skip any element ending before point. Also skip
4837 ;; element ending at point since we're sure that another
4838 ;; element begins after it.
4839 ((<= elem-end origin) (goto-char elem-end))
4840 ;; A non-greater element contains point: return it.
4841 ((not (memq type org-element-greater-elements))
4842 (throw 'exit element))
4843 ;; Otherwise, we have to decide if ELEMENT really
4844 ;; contains ORIGIN. In that case we start parsing from
4845 ;; contents' beginning. Otherwise we return UP as it is
4846 ;; the smallest element containing ORIGIN.
4848 ;; There is a special cases to consider, though. If
4849 ;; ORIGIN is at contents' beginning but it is also at
4850 ;; the beginning of the first item in a list or a table.
4851 ;; In that case, we need to create an anchor for that
4852 ;; list or table, so return it.
4854 (let ((cbeg (org-element-property :contents-begin element))
4855 (cend (org-element-property :contents-end element)))
4856 (if (or (not cbeg) (not cend) (> cbeg origin) (<= cend origin)
4857 (and (= cbeg origin) (memq type '(plain-list table))))
4858 (throw 'exit element)
4859 (goto-char (or next cbeg))
4860 (setq special-flag (case type
4861 (plain-list 'item)
4862 (property-drawer 'node-property)
4863 (table 'table-row))
4864 parent element
4865 end cend))))))
4866 ;; Continue parsing buffer contents from new position.
4867 (setq element nil next nil)))))))
4869 ;;;###autoload
4870 (defun org-element-context (&optional element)
4871 "Return closest element or object around point.
4873 Return value is a list like (TYPE PROPS) where TYPE is the type
4874 of the element or object and PROPS a plist of properties
4875 associated to it.
4877 Possible types are defined in `org-element-all-elements' and
4878 `org-element-all-objects'. Properties depend on element or
4879 object type, but always include `:begin', `:end', `:parent' and
4880 `:post-blank'.
4882 Optional argument ELEMENT, when non-nil, is the closest element
4883 containing point, as returned by `org-element-at-point'.
4884 Providing it allows for quicker computation."
4885 (catch 'objects-forbidden
4886 (org-with-wide-buffer
4887 (let* ((origin (point))
4888 (element (or element (org-element-at-point)))
4889 (type (org-element-type element)))
4890 ;; If point is inside an element containing objects or
4891 ;; a secondary string, narrow buffer to the container and
4892 ;; proceed with parsing. Otherwise, return ELEMENT.
4893 (cond
4894 ;; At a parsed affiliated keyword, check if we're inside main
4895 ;; or dual value.
4896 ((let ((post (org-element-property :post-affiliated element)))
4897 (and post (< origin post)))
4898 (beginning-of-line)
4899 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
4900 (cond
4901 ((not (member-ignore-case (match-string 1)
4902 org-element-parsed-keywords))
4903 (throw 'objects-forbidden element))
4904 ((< (match-end 0) origin)
4905 (narrow-to-region (match-end 0) (line-end-position)))
4906 ((and (match-beginning 2)
4907 (>= origin (match-beginning 2))
4908 (< origin (match-end 2)))
4909 (narrow-to-region (match-beginning 2) (match-end 2)))
4910 (t (throw 'objects-forbidden element)))
4911 ;; Also change type to retrieve correct restrictions.
4912 (setq type 'keyword))
4913 ;; At an item, objects can only be located within tag, if any.
4914 ((eq type 'item)
4915 (let ((tag (org-element-property :tag element)))
4916 (if (not tag) (throw 'objects-forbidden element)
4917 (beginning-of-line)
4918 (search-forward tag (line-end-position))
4919 (goto-char (match-beginning 0))
4920 (if (and (>= origin (point)) (< origin (match-end 0)))
4921 (narrow-to-region (point) (match-end 0))
4922 (throw 'objects-forbidden element)))))
4923 ;; At an headline or inlinetask, objects are in title.
4924 ((memq type '(headline inlinetask))
4925 (goto-char (org-element-property :begin element))
4926 (skip-chars-forward "* ")
4927 (if (and (>= origin (point)) (< origin (line-end-position)))
4928 (narrow-to-region (point) (line-end-position))
4929 (throw 'objects-forbidden element)))
4930 ;; At a paragraph, a table-row or a verse block, objects are
4931 ;; located within their contents.
4932 ((memq type '(paragraph table-row verse-block))
4933 (let ((cbeg (org-element-property :contents-begin element))
4934 (cend (org-element-property :contents-end element)))
4935 ;; CBEG is nil for table rules.
4936 (if (and cbeg cend (>= origin cbeg) (< origin cend))
4937 (narrow-to-region cbeg cend)
4938 (throw 'objects-forbidden element))))
4939 ;; At a parsed keyword, objects are located within value.
4940 ((eq type 'keyword)
4941 (if (not (member (org-element-property :key element)
4942 org-element-document-properties))
4943 (throw 'objects-forbidden element)
4944 (beginning-of-line)
4945 (search-forward ":")
4946 (if (and (>= origin (point)) (< origin (line-end-position)))
4947 (narrow-to-region (point) (line-end-position))
4948 (throw 'objects-forbidden element))))
4949 ;; All other locations cannot contain objects: bail out.
4950 (t (throw 'objects-forbidden element)))
4951 (goto-char (point-min))
4952 (let* ((restriction (org-element-restriction type))
4953 (parent element)
4954 (candidates 'initial)
4955 (cache (org-element-cache-get element))
4956 objects-data next update-cache-flag)
4957 (prog1
4958 (catch 'exit
4959 (while t
4960 ;; Get list of next object candidates in CANDIDATES.
4961 ;; When entering for the first time PARENT, grab it
4962 ;; from cache, if available, or compute it. Then,
4963 ;; for each subsequent iteration in PARENT, always
4964 ;; compute it since we're beyond cache anyway.
4965 (unless next
4966 (let ((data (assq (point) cache)))
4967 (if data (setq candidates (nth 1 (setq objects-data data)))
4968 (push (setq objects-data (list (point) 'initial))
4969 cache))))
4970 (when (or next (eq 'initial candidates))
4971 (setq candidates
4972 (org-element--get-next-object-candidates
4973 restriction candidates))
4974 (setcar (cdr objects-data) candidates))
4975 ;; Compare ORIGIN with next object starting position,
4976 ;; if any.
4978 ;; If ORIGIN is lesser or if there is no object
4979 ;; following, look for a previous object that might
4980 ;; contain it in cache. If there is no cache, we
4981 ;; didn't miss any object so simply return PARENT.
4983 ;; If ORIGIN is greater or equal, parse next
4984 ;; candidate for further processing.
4985 (let ((closest
4986 (and candidates
4987 (rassq (apply #'min (mapcar #'cdr candidates))
4988 candidates))))
4989 (if (or (not closest) (> (cdr closest) origin))
4990 (catch 'found
4991 (dolist (obj (cddr objects-data) (throw 'exit parent))
4992 (when (<= (org-element-property :begin obj) origin)
4993 (if (<= (org-element-property :end obj) origin)
4994 ;; Object ends before ORIGIN and we
4995 ;; know next one in cache starts
4996 ;; after it: bail out.
4997 (throw 'exit parent)
4998 (throw 'found (setq next obj))))))
4999 (goto-char (cdr closest))
5000 (setq next
5001 (funcall (intern (format "org-element-%s-parser"
5002 (car closest)))))
5003 (push next (cddr objects-data))))
5004 ;; Process NEXT to know if we need to skip it, return
5005 ;; it or move into it.
5006 (let ((cbeg (org-element-property :contents-begin next))
5007 (cend (org-element-property :contents-end next))
5008 (obj-end (org-element-property :end next)))
5009 (cond
5010 ;; ORIGIN is after NEXT, so skip it.
5011 ((<= obj-end origin) (goto-char obj-end))
5012 ;; ORIGIN is within a non-recursive next or
5013 ;; at an object boundaries: Return that object.
5014 ((or (not cbeg) (< origin cbeg) (>= origin cend))
5015 (throw 'exit
5016 (org-element-put-property next :parent parent)))
5017 ;; Otherwise, move into NEXT and reset flags as we
5018 ;; shift parent.
5019 (t (goto-char cbeg)
5020 (narrow-to-region (point) cend)
5021 (org-element-put-property next :parent parent)
5022 (setq parent next
5023 restriction (org-element-restriction next)
5024 next nil
5025 objects-data nil
5026 candidates 'initial))))))
5027 ;; Store results in cache, if applicable.
5028 (org-element-cache-put cache element)))))))
5030 (defun org-element-nested-p (elem-A elem-B)
5031 "Non-nil when elements ELEM-A and ELEM-B are nested."
5032 (let ((beg-A (org-element-property :begin elem-A))
5033 (beg-B (org-element-property :begin elem-B))
5034 (end-A (org-element-property :end elem-A))
5035 (end-B (org-element-property :end elem-B)))
5036 (or (and (>= beg-A beg-B) (<= end-A end-B))
5037 (and (>= beg-B beg-A) (<= end-B end-A)))))
5039 (defun org-element-swap-A-B (elem-A elem-B)
5040 "Swap elements ELEM-A and ELEM-B.
5041 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5042 end of ELEM-A."
5043 (goto-char (org-element-property :begin elem-A))
5044 ;; There are two special cases when an element doesn't start at bol:
5045 ;; the first paragraph in an item or in a footnote definition.
5046 (let ((specialp (not (bolp))))
5047 ;; Only a paragraph without any affiliated keyword can be moved at
5048 ;; ELEM-A position in such a situation. Note that the case of
5049 ;; a footnote definition is impossible: it cannot contain two
5050 ;; paragraphs in a row because it cannot contain a blank line.
5051 (if (and specialp
5052 (or (not (eq (org-element-type elem-B) 'paragraph))
5053 (/= (org-element-property :begin elem-B)
5054 (org-element-property :contents-begin elem-B))))
5055 (error "Cannot swap elements"))
5056 ;; In a special situation, ELEM-A will have no indentation. We'll
5057 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5058 (let* ((ind-B (when specialp
5059 (goto-char (org-element-property :begin elem-B))
5060 (org-get-indentation)))
5061 (beg-A (org-element-property :begin elem-A))
5062 (end-A (save-excursion
5063 (goto-char (org-element-property :end elem-A))
5064 (skip-chars-backward " \r\t\n")
5065 (point-at-eol)))
5066 (beg-B (org-element-property :begin elem-B))
5067 (end-B (save-excursion
5068 (goto-char (org-element-property :end elem-B))
5069 (skip-chars-backward " \r\t\n")
5070 (point-at-eol)))
5071 ;; Store overlays responsible for visibility status. We
5072 ;; also need to store their boundaries as they will be
5073 ;; removed from buffer.
5074 (overlays
5075 (cons
5076 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5077 (overlays-in beg-A end-A))
5078 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5079 (overlays-in beg-B end-B))))
5080 ;; Get contents.
5081 (body-A (buffer-substring beg-A end-A))
5082 (body-B (delete-and-extract-region beg-B end-B)))
5083 (goto-char beg-B)
5084 (when specialp
5085 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5086 (org-indent-to-column ind-B))
5087 (insert body-A)
5088 ;; Restore ex ELEM-A overlays.
5089 (let ((offset (- beg-B beg-A)))
5090 (mapc (lambda (ov)
5091 (move-overlay
5092 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5093 (car overlays))
5094 (goto-char beg-A)
5095 (delete-region beg-A end-A)
5096 (insert body-B)
5097 ;; Restore ex ELEM-B overlays.
5098 (mapc (lambda (ov)
5099 (move-overlay
5100 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5101 (cdr overlays)))
5102 (goto-char (org-element-property :end elem-B)))))
5104 (defun org-element-remove-indentation (s &optional n)
5105 "Remove maximum common indentation in string S and return it.
5106 When optional argument N is a positive integer, remove exactly
5107 that much characters from indentation, if possible, or return
5108 S as-is otherwise. Unlike to `org-remove-indentation', this
5109 function doesn't call `untabify' on S."
5110 (catch 'exit
5111 (with-temp-buffer
5112 (insert s)
5113 (goto-char (point-min))
5114 ;; Find maximum common indentation, if not specified.
5115 (setq n (or n
5116 (let ((min-ind (point-max)))
5117 (save-excursion
5118 (while (re-search-forward "^[ \t]*\\S-" nil t)
5119 (let ((ind (1- (current-column))))
5120 (if (zerop ind) (throw 'exit s)
5121 (setq min-ind (min min-ind ind))))))
5122 min-ind)))
5123 (if (zerop n) s
5124 ;; Remove exactly N indentation, but give up if not possible.
5125 (while (not (eobp))
5126 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5127 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5128 ((< ind n) (throw 'exit s))
5129 (t (org-indent-line-to (- ind n))))
5130 (forward-line)))
5131 (buffer-string)))))
5135 ;;; Cache
5137 ;; Both functions `org-element-at-point' and `org-element-context'
5138 ;; benefit from a simple caching mechanism.
5140 ;; Three public functions are provided: `org-element-cache-put',
5141 ;; `org-element-cache-get' and `org-element-cache-reset'.
5143 ;; Cache is enabled by default, but can be disabled globally with
5144 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time' and
5145 ;; `org-element-cache-merge-changes-threshold' can be tweaked to
5146 ;; control caching behaviour.
5149 (defvar org-element-use-cache t
5150 "Non nil when Org parser should cache its results.
5151 This is mostly for debugging purpose.")
5153 (defvar org-element-cache-merge-changes-threshold 200
5154 "Number of characters triggering cache syncing.
5156 The cache mechanism only stores one buffer modification at any
5157 given time. When another change happens, it replaces it with
5158 a change containing both the stored modification and the current
5159 one. This is a trade-off, as merging them prevents another
5160 syncing, but every element between them is then lost.
5162 This variable determines the maximum size, in characters, we
5163 accept to lose in order to avoid syncing the cache.")
5165 (defvar org-element-cache-sync-idle-time 0.5
5166 "Number of seconds of idle time wait before syncing buffer cache.
5167 Syncing also happens when current modification is too distant
5168 from the stored one (for more information, see
5169 `org-element-cache-merge-changes-threshold').")
5172 ;;;; Data Structure
5174 (defvar org-element--cache nil
5175 "AVL tree used to cache elements.
5176 Each node of the tree contains an element. Comparison is done
5177 with `org-element--cache-compare'. This cache is used in
5178 `org-element-at-point'.")
5180 (defvar org-element--cache-objects nil
5181 "Hash table used as to cache objects.
5182 Key is an element, as returned by `org-element-at-point', and
5183 value is an alist where each association is:
5185 \(POS CANDIDATES . OBJECTS)
5187 where POS is a buffer position, CANDIDATES is the last know list
5188 of successors (see `org-element--get-next-object-candidates') in
5189 container starting at POS and OBJECTS is a list of objects known
5190 to live within that container, from farthest to closest.
5192 In the following example, \\alpha, bold object and \\beta start
5193 at, respectively, positions 1, 7 and 8,
5195 \\alpha *\\beta*
5197 If the paragraph is completely parsed, OBJECTS-DATA will be
5199 \((1 nil BOLD-OBJECT ENTITY-OBJECT)
5200 \(8 nil ENTITY-OBJECT))
5202 whereas in a partially parsed paragraph, it could be
5204 \((1 ((entity . 1) (bold . 7)) ENTITY-OBJECT))
5206 This cache is used in `org-element-context'.")
5208 (defun org-element--cache-compare (a b)
5209 "Non-nil when element A is located before element B."
5210 (let ((beg-a (org-element-property :begin a))
5211 (beg-b (org-element-property :begin b)))
5212 (or (< beg-a beg-b)
5213 ;; Items and plain lists on the one hand, table rows and
5214 ;; tables on the other hand can start at the same position.
5215 ;; In this case, the parent element is always before its child
5216 ;; in the buffer.
5217 (and (= beg-a beg-b)
5218 (memq (org-element-type a) '(plain-list table))
5219 (memq (org-element-type b) '(item table-row))))))
5221 (defsubst org-element--cache-root ()
5222 "Return root value in cache.
5223 This function assumes `org-element--cache' is a valid AVL tree."
5224 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
5227 ;;;; Staging Buffer Changes
5229 (defvar org-element--cache-status nil
5230 "Contains data about cache validity for current buffer.
5232 Value is a vector of seven elements,
5234 [ACTIVEP BEGIN END OFFSET TIMER PREVIOUS-STATE]
5236 ACTIVEP is a boolean non-nil when changes described in the other
5237 slots are valid for current buffer.
5239 BEGIN and END are the beginning and ending position of the area
5240 for which cache cannot be trusted.
5242 OFFSET it an integer specifying the number to add to position of
5243 elements after that area.
5245 TIMER is a timer used to apply these changes to cache when Emacs
5246 is idle.
5248 PREVIOUS-STATE is a symbol referring to the state of the buffer
5249 before a change happens. It is used to know if sensitive
5250 areas (block boundaries, headlines) were modified. It can be set
5251 to nil, `headline' or `other'.")
5253 (defconst org-element--cache-opening-line
5254 (concat "^[ \t]*\\(?:"
5255 "#\\+BEGIN[:_]" "\\|"
5256 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
5257 ":\\S-+:[ \t]*$"
5258 "\\)")
5259 "Regexp matching an element opening line.
5260 When such a line is modified, modifications may propagate after
5261 modified area. In that situation, every element between that
5262 area and next section is removed from cache.")
5264 (defconst org-element--cache-closing-line
5265 (concat "^[ \t]*\\(?:"
5266 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
5267 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
5268 ":END:[ \t]*$"
5269 "\\)")
5270 "Regexp matching an element closing line.
5271 When such a line is modified, modifications may propagate before
5272 modified area. In that situation, every element between that
5273 area and previous section is removed from cache.")
5275 (defsubst org-element--cache-pending-changes-p ()
5276 "Non-nil when changes are not integrated in cache yet."
5277 (and org-element--cache-status
5278 (aref org-element--cache-status 0)))
5280 (defsubst org-element--cache-push-change (beg end offset)
5281 "Push change to current buffer staging area.
5282 BEG and END and the beginning and ending position of the
5283 modification area. OFFSET is the size of the change, as an
5284 integer."
5285 (aset org-element--cache-status 1 beg)
5286 (aset org-element--cache-status 2 end)
5287 (aset org-element--cache-status 3 offset)
5288 (let ((timer (aref org-element--cache-status 4)))
5289 (if timer (timer-activate-when-idle timer t)
5290 (aset org-element--cache-status 4
5291 (run-with-idle-timer org-element-cache-sync-idle-time
5293 #'org-element--cache-sync
5294 (current-buffer)))))
5295 (aset org-element--cache-status 0 t))
5297 (defsubst org-element--cache-cancel-changes ()
5298 "Remove any cache change set for current buffer."
5299 (let ((timer (aref org-element--cache-status 4)))
5300 (and timer (cancel-timer timer)))
5301 (aset org-element--cache-status 0 nil))
5303 (defun org-element--cache-before-change (beg end)
5304 "Request extension of area going to be modified if needed.
5305 BEG and END are the beginning and end of the range of changed
5306 text. See `before-change-functions' for more information."
5307 (let ((inhibit-quit t))
5308 (org-with-wide-buffer
5309 (goto-char beg)
5310 (beginning-of-line)
5311 (let ((top (point))
5312 (bottom (save-excursion (goto-char end) (line-end-position)))
5313 (sensitive-re
5314 ;; A sensitive line is a headline or a block (or drawer,
5315 ;; or latex-environment) boundary. Inserting one can
5316 ;; modify buffer drastically both above and below that
5317 ;; line, possibly making cache invalid. Therefore, we
5318 ;; need to pay special attention to changes happening to
5319 ;; them.
5320 (concat
5321 "\\(" (org-with-limited-levels org-outline-regexp-bol) "\\)" "\\|"
5322 org-element--cache-closing-line "\\|"
5323 org-element--cache-opening-line)))
5324 (save-match-data
5325 (aset org-element--cache-status 5
5326 (cond ((not (re-search-forward sensitive-re bottom t)) nil)
5327 ((and (match-beginning 1)
5328 (progn (goto-char bottom)
5329 (or (not (re-search-backward sensitive-re
5330 (match-end 1) t))
5331 (match-beginning 1))))
5332 'headline)
5333 (t 'other))))))))
5335 (defun org-element--cache-record-change (beg end pre)
5336 "Update buffer modifications for current buffer.
5338 BEG and END are the beginning and end of the range of changed
5339 text, and the length in bytes of the pre-change text replaced by
5340 that range. See `after-change-functions' for more information.
5342 If there are already pending changes, try to merge them into
5343 a bigger change record. If that's not possible, the function
5344 will first synchronize cache with previous change and store the
5345 new one."
5346 (let ((inhibit-quit t))
5347 (when (and org-element-use-cache org-element--cache)
5348 (org-with-wide-buffer
5349 (goto-char beg)
5350 (beginning-of-line)
5351 (let ((top (point))
5352 (bottom (save-excursion (goto-char end) (line-end-position))))
5353 (org-with-limited-levels
5354 (save-match-data
5355 ;; Determine if modified area needs to be extended,
5356 ;; according to both previous and current state. We make
5357 ;; a special case for headline editing: if a headline is
5358 ;; modified but not removed, do not extend.
5359 (when (let ((previous-state (aref org-element--cache-status 5))
5360 (sensitive-re
5361 (concat "\\(" org-outline-regexp-bol "\\)" "\\|"
5362 org-element--cache-closing-line "\\|"
5363 org-element--cache-opening-line)))
5364 (cond ((eq previous-state 'other))
5365 ((not (re-search-forward sensitive-re bottom t))
5366 (eq previous-state 'headline))
5367 ((match-beginning 1)
5368 (or (not (eq previous-state 'headline))
5369 (and (progn (goto-char bottom)
5370 (re-search-backward
5371 sensitive-re (match-end 1) t))
5372 (not (match-beginning 1)))))
5373 (t)))
5374 ;; Effectively extend modified area.
5375 (setq top (progn (goto-char top)
5376 (outline-previous-heading)
5377 ;; Headline above is inclusive.
5378 (point)))
5379 (setq bottom (progn (goto-char bottom)
5380 (outline-next-heading)
5381 ;; Headline below is exclusive.
5382 (if (eobp) (point) (1- (point))))))))
5383 ;; Store changes.
5384 (let ((offset (- end beg pre)))
5385 (if (not (org-element--cache-pending-changes-p))
5386 ;; No pending changes. Store the new ones.
5387 (org-element--cache-push-change top (- bottom offset) offset)
5388 (let* ((current-start (aref org-element--cache-status 1))
5389 (current-end (+ (aref org-element--cache-status 2)
5390 (aref org-element--cache-status 3)))
5391 (gap (max (- beg current-end) (- current-start end))))
5392 (if (> gap org-element-cache-merge-changes-threshold)
5393 ;; If we cannot merge two change sets (i.e. they
5394 ;; modify distinct buffer parts) first apply current
5395 ;; change set and store new one. This way, there is
5396 ;; never more than one pending change set, which
5397 ;; avoids handling costly merges.
5398 (progn (org-element--cache-sync (current-buffer))
5399 (org-element--cache-push-change
5400 top (- bottom offset) offset))
5401 ;; Change sets can be merged. We can expand the area
5402 ;; that requires an update, and postpone the sync.
5403 (timer-activate-when-idle (aref org-element--cache-status 4) t)
5404 (aset org-element--cache-status 0 t)
5405 (aset org-element--cache-status 1 (min top current-start))
5406 (aset org-element--cache-status 2
5407 (- (max current-end bottom) offset))
5408 (incf (aref org-element--cache-status 3) offset))))))))))
5411 ;;;; Synchronization
5413 (defsubst org-element--cache-shift-positions (element offset &optional props)
5414 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5416 Properties containing buffer positions are `:begin', `:end',
5417 `:contents-begin', `:contents-end' and `:structure'. When
5418 optional argument PROPS is a list of keywords, only shift
5419 properties provided in that list.
5421 Properties are modified by side-effect. Return ELEMENT."
5422 (let ((properties (nth 1 element)))
5423 ;; Shift :structure property for the first plain list only: it is
5424 ;; the only one that really matters and it prevents from shifting
5425 ;; it more than once.
5426 (when (and (or (not props) (memq :structure props))
5427 (eq (org-element-type element) 'plain-list)
5428 (not (eq (org-element-type (plist-get properties :parent))
5429 'item)))
5430 (dolist (item (plist-get properties :structure))
5431 (incf (car item) offset)
5432 (incf (nth 6 item) offset)))
5433 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5434 (let ((value (and (or (not props) (memq key props))
5435 (plist-get properties key))))
5436 (and value (plist-put properties key (+ offset value))))))
5437 element)
5439 (defun org-element--cache-sync (buffer)
5440 "Synchronize cache with recent modification in BUFFER.
5441 Elements ending before modification area are kept in cache.
5442 Elements starting after modification area have their position
5443 shifted by the size of the modification. Every other element is
5444 removed from the cache."
5445 (when (buffer-live-p buffer)
5446 (with-current-buffer buffer
5447 (when (org-element--cache-pending-changes-p)
5448 (catch 'escape
5449 (let ((inhibit-quit t)
5450 (offset (aref org-element--cache-status 3))
5451 ;; END is the beginning position of the first element
5452 ;; in cache that isn't removed but needs to be
5453 ;; shifted. It will be updated during phase 1.
5454 (end (aref org-element--cache-status 2)))
5455 ;; Phase 1.
5457 ;; Delete, in ascending order, all elements starting after
5458 ;; BEG, but before END.
5460 ;; BEG is the position of the first element in cache to
5461 ;; remove. It takes into consideration partially modified
5462 ;; elements (starting before changes but ending after
5463 ;; them). Though, it preserves greater elements that are
5464 ;; not affected when changes alter only their contents.
5466 ;; END is updated when necessary to include elements
5467 ;; starting after modifications but included in an element
5468 ;; altered by modifications.
5470 ;; At each iteration, we start again at tree root since
5471 ;; a deletion modifies structure of the balanced tree.
5472 (let ((beg
5473 (let* ((beg (aref org-element--cache-status 1))
5474 (element (org-element-cache-get (1- beg) t)))
5475 (if (not element) beg
5476 (catch 'exit
5477 (let ((up element))
5478 (while (setq up (org-element-property :parent up))
5479 (if (and
5480 (memq (org-element-type up)
5481 '(center-block
5482 drawer dynamic-block inlinetask
5483 property-drawer quote-block
5484 special-block))
5485 (<= (org-element-property :contents-begin up)
5486 beg)
5487 (> (org-element-property :contents-end up)
5488 end))
5489 ;; UP is a greater element that is
5490 ;; wrapped around the changes. We
5491 ;; only need to extend its ending
5492 ;; boundaries and those of all its
5493 ;; parents.
5494 (throw 'exit
5495 (progn
5496 (while up
5497 (org-element--cache-shift-positions
5498 up offset '(:contents-end :end))
5499 (setq up (org-element-property
5500 :parent up)))
5501 (org-element-property
5502 :begin element))))
5503 (setq element up))
5504 ;; We're at top level element containing
5505 ;; ELEMENT: if it's altered by buffer
5506 ;; modifications, it is first element in
5507 ;; cache to be removed. Otherwise, that
5508 ;; first element is the following one.
5509 (if (< (org-element-property :end element) beg)
5510 (org-element-property :end element)
5511 (org-element-property :begin element))))))))
5512 (while (let ((node (org-element--cache-root)) data)
5513 ;; DATA will contain the closest element from
5514 ;; BEG, always after it.
5515 (while node
5516 (let* ((element (avl-tree--node-data node))
5517 (pos (org-element-property :begin element)))
5518 (cond
5519 ((< pos beg)
5520 (setq node (avl-tree--node-right node)))
5521 ((> pos beg)
5522 (setq data (avl-tree--node-data node)
5523 node (avl-tree--node-left node)))
5525 (setq data (avl-tree--node-data node)
5526 node nil)))))
5527 (cond
5528 ;; No DATA is found so there's no element left
5529 ;; after BEG. Bail out.
5530 ((not data) (throw 'escape t))
5531 ;; Element starts after END, it is the first
5532 ;; one that needn't be removed from cache.
5533 ;; Move to second phase.
5534 ((> (org-element-property :begin data) end) nil)
5535 ;; Remove element. Extend END so that all
5536 ;; elements it may contain are also removed.
5538 (setq end
5539 (max (1- (org-element-property :end data)) end))
5540 (avl-tree-delete org-element--cache data nil t))))))
5541 ;; Phase 2.
5543 ;; Shift all elements starting after END by OFFSET (for an
5544 ;; offset different from 0).
5546 ;; Increasing all beginning positions by OFFSET doesn't
5547 ;; alter tree structure, so elements are modified by
5548 ;; side-effect.
5550 ;; We change all elements in decreasing order and make
5551 ;; sure to quit at the first element in cache starting
5552 ;; before END.
5553 (unless (zerop offset)
5554 (catch 'exit
5555 (avl-tree-mapc
5556 #'(lambda (data)
5557 (if (<= (org-element-property :begin data) end)
5558 (throw 'exit t)
5559 ;; Shift element.
5560 (org-element--cache-shift-positions data offset)
5561 ;; Shift associated objects data, if any.
5562 (dolist (object-data
5563 (gethash data org-element--cache-objects))
5564 (incf (car object-data) offset)
5565 (dolist (successor (nth 1 object-data))
5566 (incf (cdr successor) offset))
5567 (dolist (object (cddr object-data))
5568 (org-element--cache-shift-positions
5569 object offset)))))
5570 org-element--cache 'reverse)))))
5571 ;; Eventually signal cache as up-to-date.
5572 (org-element--cache-cancel-changes)))))
5575 ;;;; Public Functions
5577 (defun org-element-cache-get (key &optional ignore-changes)
5578 "Return cached data relative to KEY.
5580 KEY is either a number or an Org element, as returned by
5581 `org-element-at-point'. If KEY is a number, return closest
5582 cached data before or at position KEY. Otherwise, return cached
5583 objects contained in element KEY.
5585 In any case, return nil if no data is found, or if caching is not
5586 allowed.
5588 If changes are pending in current buffer, first synchronize the
5589 cache, unless optional argument IGNORE-CHANGES is non-nil."
5590 (when (and org-element-use-cache org-element--cache)
5591 ;; If there are pending changes, first sync them.
5592 (when (and (not ignore-changes) (org-element--cache-pending-changes-p))
5593 (org-element--cache-sync (current-buffer)))
5594 (if (not (wholenump key)) (gethash key org-element--cache-objects)
5595 (let ((node (org-element--cache-root)) last)
5596 (catch 'found
5597 (while node
5598 (let* ((element (avl-tree--node-data node))
5599 (beg (org-element-property :begin element)))
5600 (cond
5601 ((< key beg)
5602 (setq node (avl-tree--node-left node)))
5603 ((> key beg)
5604 (setq last (avl-tree--node-data node)
5605 node (avl-tree--node-right node)))
5606 ;; When KEY is at the beginning of a table or list,
5607 ;; make sure to return it instead of the first row or
5608 ;; item.
5609 ((and (memq (org-element-type element) '(item table-row))
5610 (= (org-element-property
5611 :contents-begin (org-element-property :parent element))
5612 beg))
5613 (setq last (avl-tree--node-data node)
5614 node (avl-tree--node-left node)))
5615 (t (throw 'found (avl-tree--node-data node))))))
5616 last)))))
5618 (defun org-element-cache-put (data &optional element)
5619 "Store DATA in current buffer's cache, if allowed.
5620 If optional argument ELEMENT is non-nil, store DATA as objects
5621 relative to it. Otherwise, store DATA as an element. Nothing
5622 will be stored if `org-element-use-cache' is nil. Return DATA."
5623 (if (not (and org-element-use-cache (derived-mode-p 'org-mode))) data
5624 (unless (and org-element--cache org-element--cache-objects)
5625 (org-element-cache-reset))
5626 (if element (puthash element data org-element--cache-objects)
5627 (avl-tree-enter org-element--cache data))))
5629 ;;;###autoload
5630 (defun org-element-cache-reset (&optional all)
5631 "Reset cache in current buffer.
5632 When optional argument ALL is non-nil, reset cache in all Org
5633 buffers. This function will do nothing if
5634 `org-element-use-cache' is nil."
5635 (interactive "P")
5636 (when org-element-use-cache
5637 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5638 (with-current-buffer buffer
5639 (when (derived-mode-p 'org-mode)
5640 (if (org-bound-and-true-p org-element--cache)
5641 (avl-tree-clear org-element--cache)
5642 (org-set-local 'org-element--cache
5643 (avl-tree-create #'org-element--cache-compare)))
5644 (if org-element--cache-objects (clrhash org-element--cache-objects)
5645 (org-set-local
5646 'org-element--cache-objects
5647 (make-hash-table :size 1009 :weakness 'key :test #'eq)))
5648 (org-set-local 'org-element--cache-status (make-vector 6 nil))
5649 (add-hook 'before-change-functions
5650 'org-element--cache-before-change nil t)
5651 (add-hook 'after-change-functions
5652 'org-element--cache-record-change nil t))))))
5656 (provide 'org-element)
5658 ;; Local variables:
5659 ;; generated-autoload-file: "org-loaddefs.el"
5660 ;; End:
5662 ;;; org-element.el ends here