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/>.
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; Elements are related to the structure of the document. Indeed, all
29 ;; elements are a cover for the document: each position within belongs
30 ;; to at least one element.
32 ;; An element always starts and ends at the beginning of a line. With
33 ;; a few exceptions (`clock', `headline', `inlinetask', `item',
34 ;; `planning', `node-property', `section' and `table-row' types), it
35 ;; can also accept a fixed set of keywords as attributes. Those are
36 ;; called "affiliated keywords" to distinguish them from other
37 ;; keywords, which are full-fledged elements. Almost all affiliated
38 ;; keywords are referenced in `org-element-affiliated-keywords'; the
39 ;; others are export attributes and start with "ATTR_" prefix.
41 ;; Element containing other elements (and only elements) are called
42 ;; greater elements. Concerned types are: `center-block', `drawer',
43 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
44 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
45 ;; and `special-block'.
47 ;; Other element types are: `babel-call', `clock', `comment',
48 ;; `comment-block', `diary-sexp', `example-block', `export-block',
49 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
50 ;; `node-property', `paragraph', `planning', `src-block', `table',
51 ;; `table-row' and `verse-block'. Among them, `paragraph' and
52 ;; `verse-block' types can contain Org objects and plain text.
54 ;; Objects are related to document's contents. Some of them are
55 ;; recursive. Associated types are of the following: `bold', `code',
56 ;; `entity', `export-snippet', `footnote-reference',
57 ;; `inline-babel-call', `inline-src-block', `italic',
58 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
59 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
60 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
62 ;; Some elements also have special properties whose value can hold
63 ;; objects themselves (e.g. an item tag or a headline name). Such
64 ;; values are called "secondary strings". Any object belongs to
65 ;; either an element or a secondary string.
67 ;; Notwithstanding affiliated keywords, each greater element, element
68 ;; and object has a fixed set of properties attached to it. Among
69 ;; them, four are shared by all types: `:begin' and `:end', which
70 ;; refer to the beginning and ending buffer positions of the
71 ;; considered element or object, `:post-blank', which holds the number
72 ;; of blank lines, or white spaces, at its end and `:parent' which
73 ;; refers to the element or object containing it. Greater elements,
74 ;; elements and objects containing objects will also have
75 ;; `:contents-begin' and `:contents-end' properties to delimit
76 ;; contents. Eventually, greater elements and elements accepting
77 ;; affiliated keywords will have a `:post-affiliated' property,
78 ;; referring to the buffer position after all such keywords.
80 ;; At the lowest level, a `:parent' property is also attached to any
81 ;; string, as a text property.
83 ;; Lisp-wise, an element or an object can be represented as a list.
84 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
85 ;; TYPE is a symbol describing the Org element or object.
86 ;; PROPERTIES is the property list attached to it. See docstring of
87 ;; appropriate parsing function to get an exhaustive
89 ;; CONTENTS is a list of elements, objects or raw strings contained
90 ;; in the current element or object, when applicable.
92 ;; An Org buffer is a nested list of such elements and objects, whose
93 ;; type is `org-data' and properties is nil.
95 ;; The first part of this file defines Org syntax, while the second
96 ;; one provide accessors and setters functions.
98 ;; The next part implements a parser and an interpreter for each
99 ;; element and object type in Org syntax.
101 ;; The following part creates a fully recursive buffer parser. It
102 ;; also provides a tool to map a function to elements or objects
103 ;; matching some criteria in the parse tree. Functions of interest
104 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
105 ;; extent, `org-element-parse-secondary-string'.
107 ;; The penultimate part is the cradle of an interpreter for the
108 ;; obtained parse tree: `org-element-interpret-data'.
110 ;; The library ends by furnishing `org-element-at-point' function, and
111 ;; a way to give information about document structure around point
112 ;; with `org-element-context'. A cache mechanism is also provided for
118 (eval-when-compile (require 'cl
))
124 ;;; Definitions And Rules
126 ;; Define elements, greater elements and specify recursive objects,
127 ;; along with the affiliated keywords recognized. Also set up
128 ;; restrictions on recursive objects combinations.
130 ;; These variables really act as a control center for the parsing
133 (defconst org-element-paragraph-separate
135 ;; Headlines, inlinetasks.
136 org-outline-regexp
"\\|"
137 ;; Footnote definitions.
138 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
144 ;; Tables (any type).
145 "\\(?:|\\|\\+-[-+]\\)" "\\|"
146 ;; Blocks (any type), Babel calls and keywords. Note: this
147 ;; is only an indication and need some thorough check.
148 "#\\(?:[+ ]\\|$\\)" "\\|"
149 ;; Drawers (any type) and fixed-width areas. This is also
150 ;; only an indication.
153 "-\\{5,\\}[ \t]*$" "\\|"
154 ;; LaTeX environments.
155 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
156 ;; Planning and Clock lines.
157 (regexp-opt (list org-scheduled-string
163 (let ((term (case org-plain-list-ordered-item-terminator
164 (?\
) ")") (?.
"\\.") (otherwise "[.)]")))
165 (alpha (and org-list-allow-alphabetical
"\\|[A-Za-z]")))
166 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha
"\\)" term
"\\)"
167 "\\(?:[ \t]\\|$\\)"))
169 "Regexp to separate paragraphs in an Org buffer.
170 In the case of lines starting with \"#\" and \":\", this regexp
171 is not sufficient to know if point is at a paragraph ending. See
172 `org-element-paragraph-parser' for more information.")
174 (defconst org-element-all-elements
175 '(babel-call center-block clock comment comment-block diary-sexp drawer
176 dynamic-block example-block export-block fixed-width
177 footnote-definition headline horizontal-rule inlinetask item
178 keyword latex-environment node-property paragraph plain-list
179 planning property-drawer quote-block section
180 special-block src-block table table-row verse-block
)
181 "Complete list of element types.")
183 (defconst org-element-greater-elements
184 '(center-block drawer dynamic-block footnote-definition headline inlinetask
185 item plain-list property-drawer quote-block section
187 "List of recursive element types aka Greater Elements.")
189 (defconst org-element-all-objects
190 '(bold code entity export-snippet footnote-reference inline-babel-call
191 inline-src-block italic line-break latex-fragment link macro
192 radio-target statistics-cookie strike-through subscript superscript
193 table-cell target timestamp underline verbatim
)
194 "Complete list of object types.")
196 (defconst org-element-recursive-objects
197 '(bold italic link subscript radio-target strike-through superscript
198 table-cell underline
)
199 "List of recursive object types.")
201 (defvar org-element-block-name-alist
202 '(("CENTER" . org-element-center-block-parser
)
203 ("COMMENT" . org-element-comment-block-parser
)
204 ("EXAMPLE" . org-element-example-block-parser
)
205 ("QUOTE" . org-element-quote-block-parser
)
206 ("SRC" . org-element-src-block-parser
)
207 ("VERSE" . org-element-verse-block-parser
))
208 "Alist between block names and the associated parsing function.
209 Names must be uppercase. Any block whose name has no association
210 is parsed with `org-element-special-block-parser'.")
212 (defconst org-element-link-type-is-file
213 '("file" "file+emacs" "file+sys" "docview")
214 "List of link types equivalent to \"file\".
215 Only these types can accept search options and an explicit
216 application to open them.")
218 (defconst org-element-affiliated-keywords
219 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
220 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
221 "List of affiliated keywords as strings.
222 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
223 are affiliated keywords and need not to be in this list.")
225 (defconst org-element-keyword-translation-alist
226 '(("DATA" .
"NAME") ("LABEL" .
"NAME") ("RESNAME" .
"NAME")
227 ("SOURCE" .
"NAME") ("SRCNAME" .
"NAME") ("TBLNAME" .
"NAME")
228 ("RESULT" .
"RESULTS") ("HEADERS" .
"HEADER"))
229 "Alist of usual translations for keywords.
230 The key is the old name and the value the new one. The property
231 holding their value will be named after the translated name.")
233 (defconst org-element-multiple-keywords
'("CAPTION" "HEADER")
234 "List of affiliated keywords that can occur more than once in an element.
236 Their value will be consed into a list of strings, which will be
237 returned as the value of the property.
239 This list is checked after translations have been applied. See
240 `org-element-keyword-translation-alist'.
242 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
243 allow multiple occurrences and need not to be in this list.")
245 (defconst org-element-parsed-keywords
'("CAPTION")
246 "List of affiliated keywords whose value can be parsed.
248 Their value will be stored as a secondary string: a list of
251 This list is checked after translations have been applied. See
252 `org-element-keyword-translation-alist'.")
254 (defconst org-element-dual-keywords
'("CAPTION" "RESULTS")
255 "List of affiliated keywords which can have a secondary value.
257 In Org syntax, they can be written with optional square brackets
258 before the colons. For example, RESULTS keyword can be
259 associated to a hash value with the following:
261 #+RESULTS[hash-string]: some-source
263 This list is checked after translations have been applied. See
264 `org-element-keyword-translation-alist'.")
266 (defconst org-element-document-properties
'("AUTHOR" "DATE" "TITLE")
267 "List of properties associated to the whole document.
268 Any keyword in this list will have its value parsed and stored as
269 a secondary string.")
271 (defconst org-element--affiliated-re
272 (format "[ \t]*#\\+\\(?:%s\\):\\(?: \\|$\\)"
274 ;; Dual affiliated keywords.
275 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
276 (regexp-opt org-element-dual-keywords
))
278 ;; Regular affiliated keywords.
279 (format "\\(?1:%s\\)"
283 (member keyword org-element-dual-keywords
))
284 org-element-affiliated-keywords
)))
286 ;; Export attributes.
287 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
288 "Regexp matching any affiliated keyword.
290 Keyword name is put in match group 1. Moreover, if keyword
291 belongs to `org-element-dual-keywords', put the dual value in
294 Don't modify it, set `org-element-affiliated-keywords' instead.")
296 (defconst org-element-object-restrictions
297 (let* ((standard-set (remq 'table-cell org-element-all-objects
))
298 (standard-set-no-line-break (remq 'line-break standard-set
)))
299 `((bold ,@standard-set
)
300 (footnote-reference ,@standard-set
)
301 (headline ,@standard-set-no-line-break
)
302 (inlinetask ,@standard-set-no-line-break
)
303 (italic ,@standard-set
)
304 (item ,@standard-set-no-line-break
)
305 (keyword ,@standard-set
)
306 ;; Ignore all links excepted plain links in a link description.
307 ;; Also ignore radio-targets and line breaks.
308 (link bold code entity export-snippet inline-babel-call inline-src-block
309 italic latex-fragment macro plain-link statistics-cookie
310 strike-through subscript superscript underline verbatim
)
311 (paragraph ,@standard-set
)
312 ;; Remove any variable object from radio target as it would
313 ;; prevent it from being properly recognized.
314 (radio-target bold code entity italic latex-fragment strike-through
315 subscript superscript underline superscript
)
316 (strike-through ,@standard-set
)
317 (subscript ,@standard-set
)
318 (superscript ,@standard-set
)
319 ;; Ignore inline babel call and inline src block as formulas are
320 ;; possible. Also ignore line breaks and statistics cookies.
321 (table-cell bold code entity export-snippet footnote-reference italic
322 latex-fragment link macro radio-target strike-through
323 subscript superscript target timestamp underline verbatim
)
324 (table-row table-cell
)
325 (underline ,@standard-set
)
326 (verse-block ,@standard-set
)))
327 "Alist of objects restrictions.
329 key is an element or object type containing objects and value is
330 a list of types that can be contained within an element or object
333 For example, in a `radio-target' object, one can only find
334 entities, latex-fragments, subscript, superscript and text
337 This alist also applies to secondary string. For example, an
338 `headline' type element doesn't directly contain objects, but
339 still has an entry since one of its properties (`:title') does.")
341 (defconst org-element-secondary-value-alist
342 '((headline .
:title
)
343 (inlinetask .
:title
)
345 (footnote-reference .
:inline-definition
))
346 "Alist between element types and location of secondary value.")
348 (defconst org-element-object-variables
'(org-link-abbrev-alist-local)
349 "List of buffer-local variables used when parsing objects.
350 These variables are copied to the temporary buffer created by
351 `org-export-secondary-string'.")
355 ;;; Accessors and Setters
357 ;; Provide four accessors: `org-element-type', `org-element-property'
358 ;; `org-element-contents' and `org-element-restriction'.
360 ;; Setter functions allow to modify elements by side effect. There is
361 ;; `org-element-put-property', `org-element-set-contents'. These
362 ;; low-level functions are useful to build a parse tree.
364 ;; `org-element-adopt-element', `org-element-set-element',
365 ;; `org-element-extract-element' and `org-element-insert-before' are
366 ;; high-level functions useful to modify a parse tree.
368 ;; `org-element-secondary-p' is a predicate used to know if a given
369 ;; object belongs to a secondary string.
371 (defsubst org-element-type
(element)
372 "Return type of ELEMENT.
374 The function returns the type of the element or object provided.
375 It can also return the following special value:
376 `plain-text' for a string
377 `org-data' for a complete document
378 nil in any other case."
380 ((not (consp element
)) (and (stringp element
) 'plain-text
))
381 ((symbolp (car element
)) (car element
))))
383 (defsubst org-element-property
(property element
)
384 "Extract the value from the PROPERTY of an ELEMENT."
385 (if (stringp element
) (get-text-property 0 property element
)
386 (plist-get (nth 1 element
) property
)))
388 (defsubst org-element-contents
(element)
389 "Extract contents from an ELEMENT."
390 (cond ((not (consp element
)) nil
)
391 ((symbolp (car element
)) (nthcdr 2 element
))
394 (defsubst org-element-restriction
(element)
395 "Return restriction associated to ELEMENT.
396 ELEMENT can be an element, an object or a symbol representing an
397 element or object type."
398 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
399 org-element-object-restrictions
)))
401 (defsubst org-element-put-property
(element property value
)
402 "In ELEMENT set PROPERTY to VALUE.
403 Return modified element."
404 (if (stringp element
) (org-add-props element nil property value
)
405 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
408 (defsubst org-element-set-contents
(element &rest contents
)
409 "Set ELEMENT contents to CONTENTS.
410 Return modified element."
411 (cond ((not element
) (list contents
))
412 ((not (symbolp (car element
))) contents
)
413 ((cdr element
) (setcdr (cdr element
) contents
))
414 (t (nconc element contents
))))
416 (defun org-element-secondary-p (object)
417 "Non-nil when OBJECT belongs to a secondary string.
418 Return value is the property name, as a keyword, or nil."
419 (let* ((parent (org-element-property :parent object
))
420 (property (cdr (assq (org-element-type parent
)
421 org-element-secondary-value-alist
))))
423 (memq object
(org-element-property property parent
))
426 (defsubst org-element-adopt-elements
(parent &rest children
)
427 "Append elements to the contents of another element.
429 PARENT is an element or object. CHILDREN can be elements,
430 objects, or a strings.
432 The function takes care of setting `:parent' property for CHILD.
433 Return parent element."
434 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
435 ;; string: parent is the list itself.
436 (mapc (lambda (child)
437 (org-element-put-property child
:parent
(or parent children
)))
439 ;; Add CHILDREN at the end of PARENT contents.
441 (apply 'org-element-set-contents
443 (nconc (org-element-contents parent
) children
)))
444 ;; Return modified PARENT element.
445 (or parent children
))
447 (defun org-element-extract-element (element)
448 "Extract ELEMENT from parse tree.
449 Remove element from the parse tree by side-effect, and return it
450 with its `:parent' property stripped out."
451 (let ((parent (org-element-property :parent element
))
452 (secondary (org-element-secondary-p element
)))
454 (org-element-put-property
456 (delq element
(org-element-property secondary parent
)))
457 (apply #'org-element-set-contents
459 (delq element
(org-element-contents parent
))))
460 ;; Return ELEMENT with its :parent removed.
461 (org-element-put-property element
:parent nil
)))
463 (defun org-element-insert-before (element location
)
464 "Insert ELEMENT before LOCATION in parse tree.
465 LOCATION is an element, object or string within the parse tree.
466 Parse tree is modified by side effect."
467 (let* ((parent (org-element-property :parent location
))
468 (property (org-element-secondary-p location
))
469 (siblings (if property
(org-element-property property parent
)
470 (org-element-contents parent
)))
471 ;; Special case: LOCATION is the first element of an
472 ;; independent secondary string (e.g. :title property). Add
474 (specialp (and (not property
)
476 (eq (car parent
) location
))))
477 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
479 ((or (null siblings
) (eq (car siblings
) location
))
480 (push element siblings
))
481 ((null location
) (nconc siblings
(list element
)))
482 (t (let ((previous (cadr (memq location
(reverse siblings
)))))
484 (error "No location found to insert element")
485 (let ((next (memq previous siblings
)))
486 (setcdr next
(cons element
(cdr next
))))))))
487 ;; Store SIBLINGS at appropriate place in parse tree.
489 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
490 (property (org-element-put-property parent property siblings
))
491 (t (apply #'org-element-set-contents parent siblings
)))
492 ;; Set appropriate :parent property.
493 (org-element-put-property element
:parent parent
)))
495 (defun org-element-set-element (old new
)
496 "Replace element or object OLD with element or object NEW.
497 The function takes care of setting `:parent' property for NEW."
498 ;; Ensure OLD and NEW have the same parent.
499 (org-element-put-property new
:parent
(org-element-property :parent old
))
500 (if (or (memq (org-element-type old
) '(plain-text nil
))
501 (memq (org-element-type new
) '(plain-text nil
)))
502 ;; We cannot replace OLD with NEW since one of them is not an
503 ;; object or element. We take the long path.
504 (progn (org-element-insert-before new old
)
505 (org-element-extract-element old
))
506 ;; Since OLD is going to be changed into NEW by side-effect, first
507 ;; make sure that every element or object within NEW has OLD as
509 (dolist (blob (org-element-contents new
))
510 (org-element-put-property blob
:parent old
))
511 ;; Transfer contents.
512 (apply #'org-element-set-contents old
(org-element-contents new
))
513 ;; Overwrite OLD's properties with NEW's.
514 (setcar (cdr old
) (nth 1 new
))
516 (setcar old
(car new
))))
522 ;; For each greater element type, we define a parser and an
525 ;; A parser returns the element or object as the list described above.
526 ;; Most of them accepts no argument. Though, exceptions exist. Hence
527 ;; every element containing a secondary string (see
528 ;; `org-element-secondary-value-alist') will accept an optional
529 ;; argument to toggle parsing of that secondary string. Moreover,
530 ;; `item' parser requires current list's structure as its first
533 ;; An interpreter accepts two arguments: the list representation of
534 ;; the element or object, and its contents. The latter may be nil,
535 ;; depending on the element or object considered. It returns the
536 ;; appropriate Org syntax, as a string.
538 ;; Parsing functions must follow the naming convention:
539 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
540 ;; defined in `org-element-greater-elements'.
542 ;; Similarly, interpreting functions must follow the naming
543 ;; convention: org-element-TYPE-interpreter.
545 ;; With the exception of `headline' and `item' types, greater elements
546 ;; cannot contain other greater elements of their own type.
548 ;; Beside implementing a parser and an interpreter, adding a new
549 ;; greater element requires to tweak `org-element--current-element'.
550 ;; Moreover, the newly defined type must be added to both
551 ;; `org-element-all-elements' and `org-element-greater-elements'.
556 (defun org-element-center-block-parser (limit affiliated
)
557 "Parse a center block.
559 LIMIT bounds the search. AFFILIATED is a list of which CAR is
560 the buffer position at the beginning of the first affiliated
561 keyword and CDR is a plist of affiliated keywords along with
564 Return a list whose CAR is `center-block' and CDR is a plist
565 containing `:begin', `:end', `:contents-begin', `:contents-end',
566 `:post-blank' and `:post-affiliated' keywords.
568 Assume point is at the beginning of the block."
569 (let ((case-fold-search t
))
570 (if (not (save-excursion
571 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
572 ;; Incomplete block: parse it as a paragraph.
573 (org-element-paragraph-parser limit affiliated
)
574 (let ((block-end-line (match-beginning 0)))
575 (let* ((begin (car affiliated
))
576 (post-affiliated (point))
577 ;; Empty blocks have no contents.
578 (contents-begin (progn (forward-line)
579 (and (< (point) block-end-line
)
581 (contents-end (and contents-begin block-end-line
))
582 (pos-before-blank (progn (goto-char block-end-line
)
586 (skip-chars-forward " \r\t\n" limit
)
587 (if (eobp) (point) (line-beginning-position)))))
592 :contents-begin contents-begin
593 :contents-end contents-end
594 :post-blank
(count-lines pos-before-blank end
)
595 :post-affiliated post-affiliated
)
596 (cdr affiliated
))))))))
598 (defun org-element-center-block-interpreter (center-block contents
)
599 "Interpret CENTER-BLOCK element as Org syntax.
600 CONTENTS is the contents of the element."
601 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
606 (defun org-element-drawer-parser (limit affiliated
)
609 LIMIT bounds the search. AFFILIATED is a list of which CAR is
610 the buffer position at the beginning of the first affiliated
611 keyword and CDR is a plist of affiliated keywords along with
614 Return a list whose CAR is `drawer' and CDR is a plist containing
615 `:drawer-name', `:begin', `:end', `:contents-begin',
616 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
618 Assume point is at beginning of drawer."
619 (let ((case-fold-search t
))
620 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
621 ;; Incomplete drawer: parse it as a paragraph.
622 (org-element-paragraph-parser limit affiliated
)
624 (let* ((drawer-end-line (match-beginning 0))
625 (name (progn (looking-at org-drawer-regexp
)
626 (org-match-string-no-properties 1)))
627 (begin (car affiliated
))
628 (post-affiliated (point))
629 ;; Empty drawers have no contents.
630 (contents-begin (progn (forward-line)
631 (and (< (point) drawer-end-line
)
633 (contents-end (and contents-begin drawer-end-line
))
634 (pos-before-blank (progn (goto-char drawer-end-line
)
637 (end (progn (skip-chars-forward " \r\t\n" limit
)
638 (if (eobp) (point) (line-beginning-position)))))
644 :contents-begin contents-begin
645 :contents-end contents-end
646 :post-blank
(count-lines pos-before-blank end
)
647 :post-affiliated post-affiliated
)
648 (cdr affiliated
))))))))
650 (defun org-element-drawer-interpreter (drawer contents
)
651 "Interpret DRAWER element as Org syntax.
652 CONTENTS is the contents of the element."
653 (format ":%s:\n%s:END:"
654 (org-element-property :drawer-name drawer
)
660 (defun org-element-dynamic-block-parser (limit affiliated
)
661 "Parse a dynamic block.
663 LIMIT bounds the search. AFFILIATED is a list of which CAR is
664 the buffer position at the beginning of the first affiliated
665 keyword and CDR is a plist of affiliated keywords along with
668 Return a list whose CAR is `dynamic-block' and CDR is a plist
669 containing `:block-name', `:begin', `:end', `:contents-begin',
670 `:contents-end', `:arguments', `:post-blank' and
671 `:post-affiliated' keywords.
673 Assume point is at beginning of dynamic block."
674 (let ((case-fold-search t
))
675 (if (not (save-excursion
676 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
677 ;; Incomplete block: parse it as a paragraph.
678 (org-element-paragraph-parser limit affiliated
)
679 (let ((block-end-line (match-beginning 0)))
681 (let* ((name (progn (looking-at org-dblock-start-re
)
682 (org-match-string-no-properties 1)))
683 (arguments (org-match-string-no-properties 3))
684 (begin (car affiliated
))
685 (post-affiliated (point))
686 ;; Empty blocks have no contents.
687 (contents-begin (progn (forward-line)
688 (and (< (point) block-end-line
)
690 (contents-end (and contents-begin block-end-line
))
691 (pos-before-blank (progn (goto-char block-end-line
)
694 (end (progn (skip-chars-forward " \r\t\n" limit
)
695 (if (eobp) (point) (line-beginning-position)))))
702 :contents-begin contents-begin
703 :contents-end contents-end
704 :post-blank
(count-lines pos-before-blank end
)
705 :post-affiliated post-affiliated
)
706 (cdr affiliated
)))))))))
708 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
709 "Interpret DYNAMIC-BLOCK element as Org syntax.
710 CONTENTS is the contents of the element."
711 (format "#+BEGIN: %s%s\n%s#+END:"
712 (org-element-property :block-name dynamic-block
)
713 (let ((args (org-element-property :arguments dynamic-block
)))
714 (and args
(concat " " args
)))
718 ;;;; Footnote Definition
720 (defun org-element-footnote-definition-parser (limit affiliated
)
721 "Parse a footnote definition.
723 LIMIT bounds the search. AFFILIATED is a list of which CAR is
724 the buffer position at the beginning of the first affiliated
725 keyword and CDR is a plist of affiliated keywords along with
728 Return a list whose CAR is `footnote-definition' and CDR is
729 a plist containing `:label', `:begin' `:end', `:contents-begin',
730 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
732 Assume point is at the beginning of the footnote definition."
734 (let* ((label (progn (looking-at org-footnote-definition-re
)
735 (org-match-string-no-properties 1)))
736 (begin (car affiliated
))
737 (post-affiliated (point))
738 (ending (save-excursion
742 (concat org-outline-regexp-bol
"\\|"
743 org-footnote-definition-re
"\\|"
744 "^\\([ \t]*\n\\)\\{2,\\}") limit
'move
))
747 (contents-begin (progn
749 (skip-chars-forward " \r\t\n" ending
)
750 (cond ((= (point) ending
) nil
)
751 ((= (line-beginning-position) begin
) (point))
752 (t (line-beginning-position)))))
753 (contents-end (and contents-begin ending
))
754 (end (progn (goto-char ending
)
755 (skip-chars-forward " \r\t\n" limit
)
756 (if (eobp) (point) (line-beginning-position)))))
757 (list 'footnote-definition
762 :contents-begin contents-begin
763 :contents-end contents-end
764 :post-blank
(count-lines ending end
)
765 :post-affiliated post-affiliated
)
766 (cdr affiliated
))))))
768 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
769 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
770 CONTENTS is the contents of the footnote-definition."
771 (concat (format "[%s]" (org-element-property :label footnote-definition
))
778 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
781 Return a list whose CAR is `headline' and CDR is a plist
782 containing `:raw-value', `:title', `:alt-title', `:begin',
783 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
784 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
785 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
786 and `:footnote-section-p' keywords.
788 The plist also contains any property set in the property drawer,
789 with its name in upper cases and colons added at the
790 beginning (e.g., `:CUSTOM_ID').
792 LIMIT is a buffer position bounding the search.
794 When RAW-SECONDARY-P is non-nil, headline's title will not be
795 parsed as a secondary string, but as a plain string instead.
797 Assume point is at beginning of the headline."
799 (let* ((components (org-heading-components))
800 (level (nth 1 components
))
801 (todo (nth 2 components
))
803 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
804 (tags (let ((raw-tags (nth 5 components
)))
805 (and raw-tags
(org-split-string raw-tags
":"))))
806 (raw-value (or (nth 4 components
) ""))
808 (let ((case-fold-search nil
))
809 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
811 (archivedp (member org-archive-tag tags
))
812 (footnote-section-p (and org-footnote-section
813 (string= org-footnote-section raw-value
)))
815 ;; Find property drawer associated to current headline and
816 ;; extract properties.
818 ;; Upcase property names. It avoids confusion between
819 ;; properties obtained through property drawer and default
820 ;; properties from the parser (e.g. `:end' and :END:)
821 (let ((end (save-excursion
822 (org-with-limited-levels (outline-next-heading))
826 (while (and (null plist
)
827 (re-search-forward org-property-start-re end t
))
828 (let ((drawer (org-element-at-point)))
829 (when (and (eq (org-element-type drawer
) 'property-drawer
)
830 ;; Make sure drawer is not associated
833 (while (and (setq p
(org-element-property
835 (not (eq (org-element-type p
)
838 (let ((end (org-element-property :contents-end drawer
)))
841 (while (< (point) end
)
842 (looking-at org-property-re
)
847 (concat ":" (upcase (match-string 2))))
848 (org-match-string-no-properties 3)))
852 ;; Read time properties on the line below the headline.
855 (when (looking-at org-planning-or-clock-line-re
)
856 (let ((end (line-end-position)) plist
)
857 (while (re-search-forward
858 org-keyword-time-not-clock-regexp end t
)
859 (goto-char (match-end 1))
860 (skip-chars-forward " \t")
861 (let ((keyword (match-string 1))
862 (time (org-element-timestamp-parser)))
863 (cond ((equal keyword org-scheduled-string
)
864 (setq plist
(plist-put plist
:scheduled time
)))
865 ((equal keyword org-deadline-string
)
866 (setq plist
(plist-put plist
:deadline time
)))
867 (t (setq plist
(plist-put plist
:closed time
))))))
870 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
871 (pos-after-head (progn (forward-line) (point)))
872 (contents-begin (save-excursion
873 (skip-chars-forward " \r\t\n" end
)
874 (and (/= (point) end
) (line-beginning-position))))
875 (contents-end (and contents-begin
876 (progn (goto-char end
)
877 (skip-chars-backward " \r\t\n")
880 ;; Clean RAW-VALUE from any comment string.
882 (let ((case-fold-search nil
))
884 (replace-regexp-in-string
885 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
888 ;; Clean TAGS from archive tag, if any.
889 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
893 (list :raw-value raw-value
897 (if (not contents-begin
) 0
898 (count-lines pos-after-head contents-begin
))
899 :contents-begin contents-begin
900 :contents-end contents-end
902 :priority
(nth 3 components
)
906 :post-blank
(count-lines
907 (or contents-end pos-after-head
)
909 :footnote-section-p footnote-section-p
911 :commentedp commentedp
)
914 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
916 (org-element-put-property
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
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
))))
940 (format ":%s:" (mapconcat 'identity tag-list
":")))))
941 (commentedp (org-element-property :commentedp headline
))
942 (pre-blank (or (org-element-property :pre-blank headline
) 0))
943 (heading (concat (make-string (org-reduced-level level
) ?
*)
944 (and todo
(concat " " todo
))
945 (and commentedp
(concat " " org-comment-string
))
947 (format " [#%s]" (char-to-string priority
)))
948 (cond ((and org-footnote-section
949 (org-element-property
950 :footnote-section-p headline
))
951 (concat " " org-footnote-section
))
952 (title (concat " " title
))))))
957 ((zerop org-tags-column
) (format " %s" tags
))
958 ((< org-tags-column
0)
961 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
966 (make-string (max (- org-tags-column
(length heading
)) 1) ?
)
968 (make-string (1+ pre-blank
) 10)
974 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
975 "Parse an inline task.
977 Return a list whose CAR is `inlinetask' and CDR is a plist
978 containing `:title', `:begin', `:end', `:contents-begin' and
979 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
980 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
981 `:closed' and `:post-blank' keywords.
983 The plist also contains any property set in the property drawer,
984 with its name in upper cases and colons added at the
985 beginning (e.g., `:CUSTOM_ID').
987 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
988 title will not be parsed as a secondary string, but as a plain
991 Assume point is at beginning of the inline task."
993 (let* ((begin (point))
994 (components (org-heading-components))
995 (todo (nth 2 components
))
997 (if (member todo org-done-keywords
) 'done
'todo
)))
998 (tags (let ((raw-tags (nth 5 components
)))
999 (and raw-tags
(org-split-string raw-tags
":"))))
1000 (raw-value (or (nth 4 components
) ""))
1001 (task-end (save-excursion
1003 (and (re-search-forward org-outline-regexp-bol limit t
)
1004 (org-looking-at-p "END[ \t]*$")
1005 (line-beginning-position))))
1007 ;; Find property drawer associated to current inlinetask
1008 ;; and extract properties.
1010 ;; Upcase property names. It avoids confusion between
1011 ;; properties obtained through property drawer and default
1012 ;; properties from the parser (e.g. `:end' and :END:)
1016 (while (and (null plist
)
1018 org-property-start-re task-end t
))
1019 (let ((d (org-element-at-point)))
1020 (when (eq (org-element-type d
) 'property-drawer
)
1021 (let ((end (org-element-property :contents-end d
)))
1024 (while (< (point) end
)
1025 (looking-at org-property-re
)
1030 (concat ":" (upcase (match-string 2))))
1031 (org-match-string-no-properties 3)))
1032 (forward-line)))))))
1035 ;; Read time properties on the line below the inlinetask
1039 (when (progn (forward-line)
1040 (looking-at org-planning-or-clock-line-re
))
1041 (let ((end (line-end-position)) plist
)
1042 (while (re-search-forward
1043 org-keyword-time-not-clock-regexp end t
)
1044 (goto-char (match-end 1))
1045 (skip-chars-forward " \t")
1046 (let ((keyword (match-string 1))
1047 (time (org-element-timestamp-parser)))
1048 (cond ((equal keyword org-scheduled-string
)
1049 (setq plist
(plist-put plist
:scheduled time
)))
1050 ((equal keyword org-deadline-string
)
1051 (setq plist
(plist-put plist
:deadline time
)))
1052 (t (setq plist
(plist-put plist
:closed time
))))))
1054 (contents-begin (progn (forward-line)
1055 (and task-end
(< (point) task-end
) (point))))
1056 (contents-end (and contents-begin task-end
))
1057 (before-blank (if (not task-end
) (point)
1058 (goto-char task-end
)
1061 (end (progn (skip-chars-forward " \r\t\n" limit
)
1062 (if (eobp) (point) (line-beginning-position))))
1066 (list :raw-value raw-value
1069 :contents-begin contents-begin
1070 :contents-end contents-end
1071 :level
(nth 1 components
)
1072 :priority
(nth 3 components
)
1075 :todo-type todo-type
1076 :post-blank
(count-lines before-blank end
))
1079 (org-element-put-property
1081 (if raw-secondary-p raw-value
1082 (org-element-parse-secondary-string
1084 (org-element-restriction 'inlinetask
)
1087 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1088 "Interpret INLINETASK element as Org syntax.
1089 CONTENTS is the contents of inlinetask."
1090 (let* ((level (org-element-property :level inlinetask
))
1091 (todo (org-element-property :todo-keyword inlinetask
))
1092 (priority (org-element-property :priority inlinetask
))
1093 (title (org-element-interpret-data
1094 (org-element-property :title inlinetask
)))
1095 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1097 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1098 (task (concat (make-string level ?
*)
1099 (and todo
(concat " " todo
))
1101 (format " [#%s]" (char-to-string priority
)))
1102 (and title
(concat " " title
)))))
1107 ((zerop org-tags-column
) (format " %s" tags
))
1108 ((< org-tags-column
0)
1111 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1116 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1118 ;; Prefer degenerate inlinetasks when there are no
1123 (make-string level ?
*) " END")))))
1128 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1131 STRUCT is the structure of the plain list.
1133 Return a list whose CAR is `item' and CDR is a plist containing
1134 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1135 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1138 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1139 any, will not be parsed as a secondary string, but as a plain
1142 Assume point is at the beginning of the item."
1145 (looking-at org-list-full-item-re
)
1146 (let* ((begin (point))
1147 (bullet (org-match-string-no-properties 1))
1148 (checkbox (let ((box (org-match-string-no-properties 3)))
1149 (cond ((equal "[ ]" box
) 'off
)
1150 ((equal "[X]" box
) 'on
)
1151 ((equal "[-]" box
) 'trans
))))
1152 (counter (let ((c (org-match-string-no-properties 2)))
1156 ((string-match "[A-Za-z]" c
)
1157 (- (string-to-char (upcase (match-string 0 c
)))
1159 ((string-match "[0-9]+" c
)
1160 (string-to-number (match-string 0 c
)))))))
1161 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1162 (unless (bolp) (forward-line))
1166 ;; Ignore tags in un-ordered lists: they are just
1167 ;; a part of item's body.
1168 (if (and (match-beginning 4)
1169 (save-match-data (string-match "[.)]" bullet
)))
1172 (skip-chars-forward " \r\t\n" limit
)
1173 ;; If first line isn't empty, contents really start
1174 ;; at the text after item's meta-data.
1175 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1176 (contents-end (progn (goto-char end
)
1177 (skip-chars-backward " \r\t\n")
1182 (list :bullet bullet
1185 ;; CONTENTS-BEGIN and CONTENTS-END may be
1186 ;; mixed up in the case of an empty item
1187 ;; separated from the next by a blank line.
1188 ;; Thus ensure the former is always the
1190 :contents-begin
(min contents-begin contents-end
)
1191 :contents-end
(max contents-begin contents-end
)
1195 :post-blank
(count-lines contents-end end
)))))
1196 (org-element-put-property
1198 (let ((raw-tag (org-list-get-tag begin struct
)))
1200 (if raw-secondary-p raw-tag
1201 (org-element-parse-secondary-string
1202 raw-tag
(org-element-restriction 'item
) item
))))))))
1204 (defun org-element-item-interpreter (item contents
)
1205 "Interpret ITEM element as Org syntax.
1206 CONTENTS is the contents of the element."
1207 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1208 (org-list-bullet-string
1209 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1210 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1212 (checkbox (org-element-property :checkbox item
))
1213 (counter (org-element-property :counter item
))
1214 (tag (let ((tag (org-element-property :tag item
)))
1215 (and tag
(org-element-interpret-data tag
))))
1216 ;; Compute indentation.
1217 (ind (make-string (length bullet
) 32))
1218 (item-starts-with-par-p
1219 (eq (org-element-type (car (org-element-contents item
)))
1224 (and counter
(format "[@%d] " counter
))
1229 (and tag
(format "%s :: " tag
))
1231 (let ((contents (replace-regexp-in-string
1232 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1233 (if item-starts-with-par-p
(org-trim contents
)
1234 (concat "\n" contents
)))))))
1239 (defun org-element--list-struct (limit)
1240 ;; Return structure of list at point. Internal function. See
1241 ;; `org-list-struct' for details.
1242 (let ((case-fold-search t
)
1244 (item-re (org-item-re))
1245 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1251 ;; At limit: end all items.
1254 (let ((end (progn (skip-chars-backward " \r\t\n")
1257 (dolist (item items
(sort (nconc items struct
)
1258 'car-less-than-car
))
1259 (setcar (nthcdr 6 item
) end
)))))
1260 ;; At list end: end all items.
1261 ((looking-at org-list-end-re
)
1262 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1263 'car-less-than-car
))
1264 (setcar (nthcdr 6 item
) (point)))))
1265 ;; At a new item: end previous sibling.
1266 ((looking-at item-re
)
1267 (let ((ind (save-excursion (skip-chars-forward " \t")
1269 (setq top-ind
(min top-ind ind
))
1270 (while (and items
(<= ind
(nth 1 (car items
))))
1271 (let ((item (pop items
)))
1272 (setcar (nthcdr 6 item
) (point))
1273 (push item struct
)))
1274 (push (progn (looking-at org-list-full-item-re
)
1275 (let ((bullet (match-string-no-properties 1)))
1279 (match-string-no-properties 2) ; counter
1280 (match-string-no-properties 3) ; checkbox
1282 (and (save-match-data
1283 (string-match "[-+*]" bullet
))
1284 (match-string-no-properties 4))
1285 ;; Ending position, unknown so far.
1289 ;; Skip empty lines.
1290 ((looking-at "^[ \t]*$") (forward-line))
1291 ;; Skip inline tasks and blank lines along the way.
1292 ((and inlinetask-re
(looking-at inlinetask-re
))
1294 (let ((origin (point)))
1295 (when (re-search-forward inlinetask-re limit t
)
1296 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1297 (goto-char origin
)))))
1298 ;; At some text line. Check if it ends any previous item.
1300 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1301 (when (<= ind top-ind
)
1302 (skip-chars-backward " \r\t\n")
1304 (while (<= ind
(nth 1 (car items
)))
1305 (let ((item (pop items
)))
1306 (setcar (nthcdr 6 item
) (line-beginning-position))
1309 (throw 'exit
(sort struct
'car-less-than-car
))))))
1310 ;; Skip blocks (any type) and drawers contents.
1312 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1314 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1316 ((and (looking-at org-drawer-regexp
)
1317 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1318 (forward-line))))))))
1320 (defun org-element-plain-list-parser (limit affiliated structure
)
1321 "Parse a plain list.
1323 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1324 the buffer position at the beginning of the first affiliated
1325 keyword and CDR is a plist of affiliated keywords along with
1326 their value. STRUCTURE is the structure of the plain list being
1329 Return a list whose CAR is `plain-list' and CDR is a plist
1330 containing `:type', `:begin', `:end', `:contents-begin' and
1331 `:contents-end', `:structure', `:post-blank' and
1332 `:post-affiliated' keywords.
1334 Assume point is at the beginning of the list."
1336 (let* ((struct (or structure
(org-element--list-struct limit
)))
1337 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1338 ((nth 5 (assq (point) struct
)) 'descriptive
)
1340 (contents-begin (point))
1341 (begin (car affiliated
))
1342 (contents-end (let* ((item (assq contents-begin struct
))
1345 (while (and (setq item
(assq pos struct
))
1346 (= (nth 1 item
) ind
))
1347 (setq pos
(nth 6 item
)))
1349 (end (progn (goto-char contents-end
)
1350 (skip-chars-forward " \r\t\n" limit
)
1351 (if (= (point) limit
) limit
(line-beginning-position)))))
1358 :contents-begin contents-begin
1359 :contents-end contents-end
1361 :post-blank
(count-lines contents-end end
)
1362 :post-affiliated contents-begin
)
1363 (cdr affiliated
))))))
1365 (defun org-element-plain-list-interpreter (plain-list contents
)
1366 "Interpret PLAIN-LIST element as Org syntax.
1367 CONTENTS is the contents of the element."
1370 (goto-char (point-min))
1375 ;;;; Property Drawer
1377 (defun org-element-property-drawer-parser (limit affiliated
)
1378 "Parse a property drawer.
1380 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1381 the buffer position at the beginning of the first affiliated
1382 keyword and CDR is a plist of affiliated keywords along with
1385 Return a list whose CAR is `property-drawer' and CDR is a plist
1386 containing `:begin', `:end', `:contents-begin', `:contents-end',
1387 `:post-blank' and `:post-affiliated' keywords.
1389 Assume point is at the beginning of the property drawer."
1391 (let ((case-fold-search t
))
1392 (if (not (save-excursion
1393 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1394 ;; Incomplete drawer: parse it as a paragraph.
1395 (org-element-paragraph-parser limit affiliated
)
1397 (let* ((drawer-end-line (match-beginning 0))
1398 (begin (car affiliated
))
1399 (post-affiliated (point))
1400 (contents-begin (progn (forward-line)
1401 (and (< (point) drawer-end-line
)
1403 (contents-end (and contents-begin drawer-end-line
))
1404 (pos-before-blank (progn (goto-char drawer-end-line
)
1407 (end (progn (skip-chars-forward " \r\t\n" limit
)
1408 (if (eobp) (point) (line-beginning-position)))))
1409 (list 'property-drawer
1413 :contents-begin contents-begin
1414 :contents-end contents-end
1415 :post-blank
(count-lines pos-before-blank end
)
1416 :post-affiliated post-affiliated
)
1417 (cdr affiliated
)))))))))
1419 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1420 "Interpret PROPERTY-DRAWER element as Org syntax.
1421 CONTENTS is the properties within the drawer."
1422 (format ":PROPERTIES:\n%s:END:" contents
))
1427 (defun org-element-quote-block-parser (limit affiliated
)
1428 "Parse a quote block.
1430 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1431 the buffer position at the beginning of the first affiliated
1432 keyword and CDR is a plist of affiliated keywords along with
1435 Return a list whose CAR is `quote-block' and CDR is a plist
1436 containing `:begin', `:end', `:contents-begin', `:contents-end',
1437 `:post-blank' and `:post-affiliated' keywords.
1439 Assume point is at the beginning of the block."
1440 (let ((case-fold-search t
))
1441 (if (not (save-excursion
1442 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1443 ;; Incomplete block: parse it as a paragraph.
1444 (org-element-paragraph-parser limit affiliated
)
1445 (let ((block-end-line (match-beginning 0)))
1447 (let* ((begin (car affiliated
))
1448 (post-affiliated (point))
1449 ;; Empty blocks have no contents.
1450 (contents-begin (progn (forward-line)
1451 (and (< (point) block-end-line
)
1453 (contents-end (and contents-begin block-end-line
))
1454 (pos-before-blank (progn (goto-char block-end-line
)
1457 (end (progn (skip-chars-forward " \r\t\n" limit
)
1458 (if (eobp) (point) (line-beginning-position)))))
1463 :contents-begin contents-begin
1464 :contents-end contents-end
1465 :post-blank
(count-lines pos-before-blank end
)
1466 :post-affiliated post-affiliated
)
1467 (cdr affiliated
)))))))))
1469 (defun org-element-quote-block-interpreter (quote-block contents
)
1470 "Interpret QUOTE-BLOCK element as Org syntax.
1471 CONTENTS is the contents of the element."
1472 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1477 (defun org-element-section-parser (limit)
1480 LIMIT bounds the search.
1482 Return a list whose CAR is `section' and CDR is a plist
1483 containing `:begin', `:end', `:contents-begin', `contents-end'
1484 and `:post-blank' keywords."
1486 ;; Beginning of section is the beginning of the first non-blank
1487 ;; line after previous headline.
1488 (let ((begin (point))
1489 (end (progn (org-with-limited-levels (outline-next-heading))
1491 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1497 :contents-begin begin
1498 :contents-end pos-before-blank
1499 :post-blank
(count-lines pos-before-blank end
))))))
1501 (defun org-element-section-interpreter (section contents
)
1502 "Interpret SECTION element as Org syntax.
1503 CONTENTS is the contents of the element."
1509 (defun org-element-special-block-parser (limit affiliated
)
1510 "Parse a special block.
1512 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1513 the buffer position at the beginning of the first affiliated
1514 keyword and CDR is a plist of affiliated keywords along with
1517 Return a list whose CAR is `special-block' and CDR is a plist
1518 containing `:type', `:begin', `:end', `:contents-begin',
1519 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1521 Assume point is at the beginning of the block."
1522 (let* ((case-fold-search t
)
1523 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1524 (upcase (match-string-no-properties 1)))))
1525 (if (not (save-excursion
1527 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1529 ;; Incomplete block: parse it as a paragraph.
1530 (org-element-paragraph-parser limit affiliated
)
1531 (let ((block-end-line (match-beginning 0)))
1533 (let* ((begin (car affiliated
))
1534 (post-affiliated (point))
1535 ;; Empty blocks have no contents.
1536 (contents-begin (progn (forward-line)
1537 (and (< (point) block-end-line
)
1539 (contents-end (and contents-begin block-end-line
))
1540 (pos-before-blank (progn (goto-char block-end-line
)
1543 (end (progn (skip-chars-forward " \r\t\n" limit
)
1544 (if (eobp) (point) (line-beginning-position)))))
1545 (list 'special-block
1550 :contents-begin contents-begin
1551 :contents-end contents-end
1552 :post-blank
(count-lines pos-before-blank end
)
1553 :post-affiliated post-affiliated
)
1554 (cdr affiliated
)))))))))
1556 (defun org-element-special-block-interpreter (special-block contents
)
1557 "Interpret SPECIAL-BLOCK element as Org syntax.
1558 CONTENTS is the contents of the element."
1559 (let ((block-type (org-element-property :type special-block
)))
1560 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1566 ;; For each element, a parser and an interpreter are also defined.
1567 ;; Both follow the same naming convention used for greater elements.
1569 ;; Also, as for greater elements, adding a new element type is done
1570 ;; through the following steps: implement a parser and an interpreter,
1571 ;; tweak `org-element--current-element' so that it recognizes the new
1572 ;; type and add that new type to `org-element-all-elements'.
1574 ;; As a special case, when the newly defined type is a block type,
1575 ;; `org-element-block-name-alist' has to be modified accordingly.
1580 (defun org-element-babel-call-parser (limit affiliated
)
1581 "Parse a babel call.
1583 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1584 the buffer position at the beginning of the first affiliated
1585 keyword and CDR is a plist of affiliated keywords along with
1588 Return a list whose CAR is `babel-call' and CDR is a plist
1589 containing `:begin', `:end', `:value', `:post-blank' and
1590 `:post-affiliated' as keywords."
1592 (let ((begin (car affiliated
))
1593 (post-affiliated (point))
1594 (value (progn (let ((case-fold-search t
))
1595 (re-search-forward "call:[ \t]*" nil t
))
1596 (buffer-substring-no-properties (point)
1597 (line-end-position))))
1598 (pos-before-blank (progn (forward-line) (point)))
1599 (end (progn (skip-chars-forward " \r\t\n" limit
)
1600 (if (eobp) (point) (line-beginning-position)))))
1606 :post-blank
(count-lines pos-before-blank end
)
1607 :post-affiliated post-affiliated
)
1608 (cdr affiliated
))))))
1610 (defun org-element-babel-call-interpreter (babel-call contents
)
1611 "Interpret BABEL-CALL element as Org syntax.
1613 (concat "#+CALL: " (org-element-property :value babel-call
)))
1618 (defun org-element-clock-parser (limit)
1621 LIMIT bounds the search.
1623 Return a list whose CAR is `clock' and CDR is a plist containing
1624 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1627 (let* ((case-fold-search nil
)
1629 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1630 (skip-chars-forward " \t")
1631 (org-element-timestamp-parser)))
1632 (duration (and (search-forward " => " (line-end-position) t
)
1633 (progn (skip-chars-forward " \t")
1634 (looking-at "\\(\\S-+\\)[ \t]*$"))
1635 (org-match-string-no-properties 1)))
1636 (status (if duration
'closed
'running
))
1637 (post-blank (let ((before-blank (progn (forward-line) (point))))
1638 (skip-chars-forward " \r\t\n" limit
)
1639 (skip-chars-backward " \t")
1640 (unless (bolp) (end-of-line))
1641 (count-lines before-blank
(point))))
1644 (list :status status
1649 :post-blank post-blank
)))))
1651 (defun org-element-clock-interpreter (clock contents
)
1652 "Interpret CLOCK element as Org syntax.
1654 (concat org-clock-string
" "
1655 (org-element-timestamp-interpreter
1656 (org-element-property :value clock
) nil
)
1657 (let ((duration (org-element-property :duration clock
)))
1662 (org-split-string duration
":")))))))
1667 (defun org-element-comment-parser (limit affiliated
)
1670 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1671 the buffer position at the beginning of the first affiliated
1672 keyword and CDR is a plist of affiliated keywords along with
1675 Return a list whose CAR is `comment' and CDR is a plist
1676 containing `:begin', `:end', `:value', `:post-blank',
1677 `:post-affiliated' keywords.
1679 Assume point is at comment beginning."
1681 (let* ((begin (car affiliated
))
1682 (post-affiliated (point))
1683 (value (prog2 (looking-at "[ \t]*# ?")
1684 (buffer-substring-no-properties
1685 (match-end 0) (line-end-position))
1688 ;; Get comments ending.
1690 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1691 ;; Accumulate lines without leading hash and first
1696 (buffer-substring-no-properties
1697 (match-end 0) (line-end-position))))
1700 (end (progn (goto-char com-end
)
1701 (skip-chars-forward " \r\t\n" limit
)
1702 (if (eobp) (point) (line-beginning-position)))))
1708 :post-blank
(count-lines com-end end
)
1709 :post-affiliated post-affiliated
)
1710 (cdr affiliated
))))))
1712 (defun org-element-comment-interpreter (comment contents
)
1713 "Interpret COMMENT element as Org syntax.
1715 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1720 (defun org-element-comment-block-parser (limit affiliated
)
1721 "Parse an export block.
1723 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1724 the buffer position at the beginning of the first affiliated
1725 keyword and CDR is a plist of affiliated keywords along with
1728 Return a list whose CAR is `comment-block' and CDR is a plist
1729 containing `:begin', `:end', `:value', `:post-blank' and
1730 `:post-affiliated' keywords.
1732 Assume point is at comment block beginning."
1733 (let ((case-fold-search t
))
1734 (if (not (save-excursion
1735 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1736 ;; Incomplete block: parse it as a paragraph.
1737 (org-element-paragraph-parser limit affiliated
)
1738 (let ((contents-end (match-beginning 0)))
1740 (let* ((begin (car affiliated
))
1741 (post-affiliated (point))
1742 (contents-begin (progn (forward-line) (point)))
1743 (pos-before-blank (progn (goto-char contents-end
)
1746 (end (progn (skip-chars-forward " \r\t\n" limit
)
1747 (if (eobp) (point) (line-beginning-position))))
1748 (value (buffer-substring-no-properties
1749 contents-begin contents-end
)))
1750 (list 'comment-block
1755 :post-blank
(count-lines pos-before-blank end
)
1756 :post-affiliated post-affiliated
)
1757 (cdr affiliated
)))))))))
1759 (defun org-element-comment-block-interpreter (comment-block contents
)
1760 "Interpret COMMENT-BLOCK element as Org syntax.
1762 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1763 (org-remove-indentation (org-element-property :value comment-block
))))
1768 (defun org-element-diary-sexp-parser (limit affiliated
)
1769 "Parse a diary sexp.
1771 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1772 the buffer position at the beginning of the first affiliated
1773 keyword and CDR is a plist of affiliated keywords along with
1776 Return a list whose CAR is `diary-sexp' and CDR is a plist
1777 containing `:begin', `:end', `:value', `:post-blank' and
1778 `:post-affiliated' keywords."
1780 (let ((begin (car affiliated
))
1781 (post-affiliated (point))
1782 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1783 (org-match-string-no-properties 1)))
1784 (pos-before-blank (progn (forward-line) (point)))
1785 (end (progn (skip-chars-forward " \r\t\n" limit
)
1786 (if (eobp) (point) (line-beginning-position)))))
1792 :post-blank
(count-lines pos-before-blank end
)
1793 :post-affiliated post-affiliated
)
1794 (cdr affiliated
))))))
1796 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1797 "Interpret DIARY-SEXP as Org syntax.
1799 (org-element-property :value diary-sexp
))
1804 (defun org-element-example-block-parser (limit affiliated
)
1805 "Parse an example block.
1807 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1808 the buffer position at the beginning of the first affiliated
1809 keyword and CDR is a plist of affiliated keywords along with
1812 Return a list whose CAR is `example-block' and CDR is a plist
1813 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1814 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1815 `:value', `:post-blank' and `:post-affiliated' keywords."
1816 (let ((case-fold-search t
))
1817 (if (not (save-excursion
1818 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1819 ;; Incomplete block: parse it as a paragraph.
1820 (org-element-paragraph-parser limit affiliated
)
1821 (let ((contents-end (match-beginning 0)))
1825 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1826 (org-match-string-no-properties 1)))
1827 ;; Switches analysis
1829 (cond ((not switches
) nil
)
1830 ((string-match "-n\\>" switches
) 'new
)
1831 ((string-match "+n\\>" switches
) 'continued
)))
1833 (and switches
(string-match "-i\\>" switches
)))
1834 ;; Should labels be retained in (or stripped from) example
1838 (not (string-match "-r\\>" switches
))
1839 (and number-lines
(string-match "-k\\>" switches
))))
1840 ;; What should code-references use - labels or
1845 (not (string-match "-k\\>" switches
)))))
1848 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1849 (match-string 1 switches
)))
1850 ;; Standard block parsing.
1851 (begin (car affiliated
))
1852 (post-affiliated (point))
1853 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1854 (contents-begin (progn (forward-line) (point)))
1855 (value (org-element-remove-indentation
1856 (org-unescape-code-in-string
1857 (buffer-substring-no-properties
1858 contents-begin contents-end
))
1860 (pos-before-blank (progn (goto-char contents-end
)
1863 (end (progn (skip-chars-forward " \r\t\n" limit
)
1864 (if (eobp) (point) (line-beginning-position)))))
1865 (list 'example-block
1871 :number-lines number-lines
1872 :preserve-indent preserve-indent
1873 :retain-labels retain-labels
1874 :use-labels use-labels
1875 :label-fmt label-fmt
1876 :post-blank
(count-lines pos-before-blank end
)
1877 :post-affiliated post-affiliated
)
1878 (cdr affiliated
)))))))))
1880 (defun org-element-example-block-interpreter (example-block contents
)
1881 "Interpret EXAMPLE-BLOCK element as Org syntax.
1883 (let ((switches (org-element-property :switches example-block
))
1884 (value (org-element-property :value example-block
)))
1885 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1886 (org-escape-code-in-string
1887 (if (or org-src-preserve-indentation
1888 (org-element-property :preserve-indent example-block
))
1890 (org-element-remove-indentation value
)))
1896 (defun org-element-export-block-parser (limit affiliated
)
1897 "Parse an export block.
1899 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1900 the buffer position at the beginning of the first affiliated
1901 keyword and CDR is a plist of affiliated keywords along with
1904 Return a list whose CAR is `export-block' and CDR is a plist
1905 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1906 `:post-affiliated' keywords.
1908 Assume point is at export-block beginning."
1909 (let* ((case-fold-search t
)
1910 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1911 (upcase (org-match-string-no-properties 1)))))
1912 (if (not (save-excursion
1914 (format "^[ \t]*#\\+END_%s[ \t]*$" type
) limit t
)))
1915 ;; Incomplete block: parse it as a paragraph.
1916 (org-element-paragraph-parser limit affiliated
)
1917 (let ((contents-end (match-beginning 0)))
1919 (let* ((begin (car affiliated
))
1920 (post-affiliated (point))
1921 (contents-begin (progn (forward-line) (point)))
1922 (pos-before-blank (progn (goto-char contents-end
)
1925 (end (progn (skip-chars-forward " \r\t\n" limit
)
1926 (if (eobp) (point) (line-beginning-position))))
1927 (value (buffer-substring-no-properties contents-begin
1935 :post-blank
(count-lines pos-before-blank end
)
1936 :post-affiliated post-affiliated
)
1937 (cdr affiliated
)))))))))
1939 (defun org-element-export-block-interpreter (export-block contents
)
1940 "Interpret EXPORT-BLOCK element as Org syntax.
1942 (let ((type (org-element-property :type export-block
)))
1943 (concat (format "#+BEGIN_%s\n" type
)
1944 (org-element-property :value export-block
)
1945 (format "#+END_%s" type
))))
1950 (defun org-element-fixed-width-parser (limit affiliated
)
1951 "Parse a fixed-width section.
1953 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1954 the buffer position at the beginning of the first affiliated
1955 keyword and CDR is a plist of affiliated keywords along with
1958 Return a list whose CAR is `fixed-width' and CDR is a plist
1959 containing `:begin', `:end', `:value', `:post-blank' and
1960 `:post-affiliated' keywords.
1962 Assume point is at the beginning of the fixed-width area."
1964 (let* ((begin (car affiliated
))
1965 (post-affiliated (point))
1969 (while (and (< (point) limit
)
1970 (looking-at "[ \t]*:\\( \\|$\\)"))
1971 ;; Accumulate text without starting colons.
1974 (buffer-substring-no-properties
1975 (match-end 0) (point-at-eol))
1979 (end (progn (skip-chars-forward " \r\t\n" limit
)
1980 (if (eobp) (point) (line-beginning-position)))))
1986 :post-blank
(count-lines end-area end
)
1987 :post-affiliated post-affiliated
)
1988 (cdr affiliated
))))))
1990 (defun org-element-fixed-width-interpreter (fixed-width contents
)
1991 "Interpret FIXED-WIDTH element as Org syntax.
1993 (let ((value (org-element-property :value fixed-width
)))
1995 (replace-regexp-in-string
1997 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
2000 ;;;; Horizontal Rule
2002 (defun org-element-horizontal-rule-parser (limit affiliated
)
2003 "Parse an horizontal rule.
2005 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2006 the buffer position at the beginning of the first affiliated
2007 keyword and CDR is a plist of affiliated keywords along with
2010 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2011 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2014 (let ((begin (car affiliated
))
2015 (post-affiliated (point))
2016 (post-hr (progn (forward-line) (point)))
2017 (end (progn (skip-chars-forward " \r\t\n" limit
)
2018 (if (eobp) (point) (line-beginning-position)))))
2019 (list 'horizontal-rule
2023 :post-blank
(count-lines post-hr end
)
2024 :post-affiliated post-affiliated
)
2025 (cdr affiliated
))))))
2027 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
2028 "Interpret HORIZONTAL-RULE element as Org syntax.
2035 (defun org-element-keyword-parser (limit affiliated
)
2036 "Parse a keyword at point.
2038 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2039 the buffer position at the beginning of the first affiliated
2040 keyword and CDR is a plist of affiliated keywords along with
2043 Return a list whose CAR is `keyword' and CDR is a plist
2044 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2045 `:post-affiliated' keywords."
2047 ;; An orphaned affiliated keyword is considered as a regular
2048 ;; keyword. In this case AFFILIATED is nil, so we take care of
2049 ;; this corner case.
2050 (let ((begin (or (car affiliated
) (point)))
2051 (post-affiliated (point))
2052 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2053 (upcase (org-match-string-no-properties 1))))
2054 (value (org-trim (buffer-substring-no-properties
2055 (match-end 0) (point-at-eol))))
2056 (pos-before-blank (progn (forward-line) (point)))
2057 (end (progn (skip-chars-forward " \r\t\n" limit
)
2058 (if (eobp) (point) (line-beginning-position)))))
2065 :post-blank
(count-lines pos-before-blank end
)
2066 :post-affiliated post-affiliated
)
2067 (cdr affiliated
))))))
2069 (defun org-element-keyword-interpreter (keyword contents
)
2070 "Interpret KEYWORD element as Org syntax.
2073 (org-element-property :key keyword
)
2074 (org-element-property :value keyword
)))
2077 ;;;; Latex Environment
2079 (defun org-element-latex-environment-parser (limit affiliated
)
2080 "Parse a LaTeX environment.
2082 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2083 the buffer position at the beginning of the first affiliated
2084 keyword and CDR is a plist of affiliated keywords along with
2087 Return a list whose CAR is `latex-environment' and CDR is a plist
2088 containing `:begin', `:end', `:value', `:post-blank' and
2089 `:post-affiliated' keywords.
2091 Assume point is at the beginning of the latex environment."
2093 (let ((case-fold-search t
)
2094 (code-begin (point)))
2095 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2096 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2097 (regexp-quote (match-string 1)))
2099 ;; Incomplete latex environment: parse it as a paragraph.
2100 (org-element-paragraph-parser limit affiliated
)
2101 (let* ((code-end (progn (forward-line) (point)))
2102 (begin (car affiliated
))
2103 (value (buffer-substring-no-properties code-begin code-end
))
2104 (end (progn (skip-chars-forward " \r\t\n" limit
)
2105 (if (eobp) (point) (line-beginning-position)))))
2106 (list 'latex-environment
2111 :post-blank
(count-lines code-end end
)
2112 :post-affiliated code-begin
)
2113 (cdr affiliated
))))))))
2115 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2116 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2118 (org-element-property :value latex-environment
))
2123 (defun org-element-node-property-parser (limit)
2124 "Parse a node-property at point.
2126 LIMIT bounds the search.
2128 Return a list whose CAR is `node-property' and CDR is a plist
2129 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2132 (looking-at org-property-re
)
2133 (let ((case-fold-search t
)
2135 (key (org-match-string-no-properties 2))
2136 (value (org-match-string-no-properties 3))
2137 (pos-before-blank (progn (forward-line) (point)))
2138 (end (progn (skip-chars-forward " \r\t\n" limit
)
2139 (if (eobp) (point) (point-at-bol)))))
2140 (list 'node-property
2145 :post-blank
(count-lines pos-before-blank end
))))))
2147 (defun org-element-node-property-interpreter (node-property contents
)
2148 "Interpret NODE-PROPERTY element as Org syntax.
2150 (format org-property-format
2151 (format ":%s:" (org-element-property :key node-property
))
2152 (org-element-property :value node-property
)))
2157 (defun org-element-paragraph-parser (limit affiliated
)
2160 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2161 the buffer position at the beginning of the first affiliated
2162 keyword and CDR is a plist of affiliated keywords along with
2165 Return a list whose CAR is `paragraph' and CDR is a plist
2166 containing `:begin', `:end', `:contents-begin' and
2167 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2169 Assume point is at the beginning of the paragraph."
2171 (let* ((begin (car affiliated
))
2172 (contents-begin (point))
2174 (let ((case-fold-search t
))
2176 (if (not (re-search-forward
2177 org-element-paragraph-separate limit
'm
))
2179 ;; A matching `org-element-paragraph-separate' is not
2180 ;; necessarily the end of the paragraph. In
2181 ;; particular, lines starting with # or : as a first
2182 ;; non-space character are ambiguous. We have to
2183 ;; check if they are valid Org syntax (e.g., not an
2184 ;; incomplete keyword).
2188 ;; There's no ambiguity for other symbols or
2189 ;; empty lines: stop here.
2190 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2191 ;; Stop at valid fixed-width areas.
2192 (looking-at "[ \t]*:\\(?: \\|$\\)")
2194 (and (looking-at org-drawer-regexp
)
2197 "^[ \t]*:END:[ \t]*$" limit t
)))
2198 ;; Stop at valid comments.
2199 (looking-at "[ \t]*#\\(?: \\|$\\)")
2200 ;; Stop at valid dynamic blocks.
2201 (and (looking-at org-dblock-start-re
)
2204 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2205 ;; Stop at valid blocks.
2206 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2209 (format "^[ \t]*#\\+END_%s[ \t]*$"
2211 (org-match-string-no-properties 1)))
2213 ;; Stop at valid latex environments.
2215 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2218 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2220 (org-match-string-no-properties 1)))
2222 ;; Stop at valid keywords.
2223 (looking-at "[ \t]*#\\+\\S-+:")
2224 ;; Skip everything else.
2228 (re-search-forward org-element-paragraph-separate
2230 (beginning-of-line)))
2231 (if (= (point) limit
) limit
2232 (goto-char (line-beginning-position)))))
2233 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2236 (end (progn (skip-chars-forward " \r\t\n" limit
)
2237 (if (eobp) (point) (line-beginning-position)))))
2242 :contents-begin contents-begin
2243 :contents-end contents-end
2244 :post-blank
(count-lines before-blank end
)
2245 :post-affiliated contents-begin
)
2246 (cdr affiliated
))))))
2248 (defun org-element-paragraph-interpreter (paragraph contents
)
2249 "Interpret PARAGRAPH element as Org syntax.
2250 CONTENTS is the contents of the element."
2256 (defun org-element-planning-parser (limit)
2259 LIMIT bounds the search.
2261 Return a list whose CAR is `planning' and CDR is a plist
2262 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2263 and `:post-blank' keywords."
2265 (let* ((case-fold-search nil
)
2267 (post-blank (let ((before-blank (progn (forward-line) (point))))
2268 (skip-chars-forward " \r\t\n" limit
)
2269 (skip-chars-backward " \t")
2270 (unless (bolp) (end-of-line))
2271 (count-lines before-blank
(point))))
2273 closed deadline scheduled
)
2275 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2276 (goto-char (match-end 1))
2277 (skip-chars-forward " \t" end
)
2278 (let ((keyword (match-string 1))
2279 (time (org-element-timestamp-parser)))
2280 (cond ((equal keyword org-closed-string
) (setq closed time
))
2281 ((equal keyword org-deadline-string
) (setq deadline time
))
2282 (t (setq scheduled time
)))))
2284 (list :closed closed
2286 :scheduled scheduled
2289 :post-blank post-blank
)))))
2291 (defun org-element-planning-interpreter (planning contents
)
2292 "Interpret PLANNING element as Org syntax.
2297 (list (let ((deadline (org-element-property :deadline planning
)))
2299 (concat org-deadline-string
" "
2300 (org-element-timestamp-interpreter deadline nil
))))
2301 (let ((scheduled (org-element-property :scheduled planning
)))
2303 (concat org-scheduled-string
" "
2304 (org-element-timestamp-interpreter scheduled nil
))))
2305 (let ((closed (org-element-property :closed planning
)))
2307 (concat org-closed-string
" "
2308 (org-element-timestamp-interpreter closed nil
))))))
2314 (defun org-element-src-block-parser (limit affiliated
)
2317 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2318 the buffer position at the beginning of the first affiliated
2319 keyword and CDR is a plist of affiliated keywords along with
2322 Return a list whose CAR is `src-block' and CDR is a plist
2323 containing `:language', `:switches', `:parameters', `:begin',
2324 `:end', `:number-lines', `:retain-labels', `:use-labels',
2325 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2326 `:post-affiliated' keywords.
2328 Assume point is at the beginning of the block."
2329 (let ((case-fold-search t
))
2330 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2332 ;; Incomplete block: parse it as a paragraph.
2333 (org-element-paragraph-parser limit affiliated
)
2334 (let ((contents-end (match-beginning 0)))
2336 (let* ((begin (car affiliated
))
2337 (post-affiliated (point))
2338 ;; Get language as a string.
2342 (concat "^[ \t]*#\\+BEGIN_SRC"
2343 "\\(?: +\\(\\S-+\\)\\)?"
2344 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2346 (org-match-string-no-properties 1)))
2348 (switches (org-match-string-no-properties 2))
2350 (parameters (org-match-string-no-properties 3))
2351 ;; Switches analysis
2353 (cond ((not switches
) nil
)
2354 ((string-match "-n\\>" switches
) 'new
)
2355 ((string-match "+n\\>" switches
) 'continued
)))
2356 (preserve-indent (and switches
2357 (string-match "-i\\>" switches
)))
2360 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2361 (match-string 1 switches
)))
2362 ;; Should labels be retained in (or stripped from)
2366 (not (string-match "-r\\>" switches
))
2367 (and number-lines
(string-match "-k\\>" switches
))))
2368 ;; What should code-references use - labels or
2373 (not (string-match "-k\\>" switches
)))))
2375 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2377 (value (org-element-remove-indentation
2378 (org-unescape-code-in-string
2379 (buffer-substring-no-properties
2380 (progn (forward-line) (point)) contents-end
))
2382 (pos-before-blank (progn (goto-char contents-end
)
2385 ;; Get position after ending blank lines.
2386 (end (progn (skip-chars-forward " \r\t\n" limit
)
2387 (if (eobp) (point) (line-beginning-position)))))
2390 (list :language language
2391 :switches
(and (org-string-nw-p switches
)
2392 (org-trim switches
))
2393 :parameters
(and (org-string-nw-p parameters
)
2394 (org-trim parameters
))
2397 :number-lines number-lines
2398 :preserve-indent preserve-indent
2399 :retain-labels retain-labels
2400 :use-labels use-labels
2401 :label-fmt label-fmt
2403 :post-blank
(count-lines pos-before-blank end
)
2404 :post-affiliated post-affiliated
)
2405 (cdr affiliated
)))))))))
2407 (defun org-element-src-block-interpreter (src-block contents
)
2408 "Interpret SRC-BLOCK element as Org syntax.
2410 (let ((lang (org-element-property :language src-block
))
2411 (switches (org-element-property :switches src-block
))
2412 (params (org-element-property :parameters src-block
))
2414 (let ((val (org-element-property :value src-block
)))
2416 ((or org-src-preserve-indentation
2417 (org-element-property :preserve-indent src-block
))
2419 ((zerop org-edit-src-content-indentation
) val
)
2421 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2422 (replace-regexp-in-string
2423 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2424 (concat (format "#+BEGIN_SRC%s\n"
2425 (concat (and lang
(concat " " lang
))
2426 (and switches
(concat " " switches
))
2427 (and params
(concat " " params
))))
2428 (org-escape-code-in-string value
)
2434 (defun org-element-table-parser (limit affiliated
)
2435 "Parse a table at point.
2437 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2438 the buffer position at the beginning of the first affiliated
2439 keyword and CDR is a plist of affiliated keywords along with
2442 Return a list whose CAR is `table' and CDR is a plist containing
2443 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2444 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2447 Assume point is at the beginning of the table."
2449 (let* ((case-fold-search t
)
2450 (table-begin (point))
2451 (type (if (org-at-table.el-p
) 'table.el
'org
))
2452 (begin (car affiliated
))
2454 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2455 (goto-char (match-beginning 0))
2458 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2459 (push (org-match-string-no-properties 1) acc
)
2462 (pos-before-blank (point))
2463 (end (progn (skip-chars-forward " \r\t\n" limit
)
2464 (if (eobp) (point) (line-beginning-position)))))
2471 ;; Only `org' tables have contents. `table.el' tables
2472 ;; use a `:value' property to store raw table as
2474 :contents-begin
(and (eq type
'org
) table-begin
)
2475 :contents-end
(and (eq type
'org
) table-end
)
2476 :value
(and (eq type
'table.el
)
2477 (buffer-substring-no-properties
2478 table-begin table-end
))
2479 :post-blank
(count-lines pos-before-blank end
)
2480 :post-affiliated table-begin
)
2481 (cdr affiliated
))))))
2483 (defun org-element-table-interpreter (table contents
)
2484 "Interpret TABLE element as Org syntax.
2486 (if (eq (org-element-property :type table
) 'table.el
)
2487 (org-remove-indentation (org-element-property :value table
))
2488 (concat (with-temp-buffer (insert contents
)
2491 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2492 (reverse (org-element-property :tblfm table
))
2498 (defun org-element-table-row-parser (limit)
2499 "Parse table row at point.
2501 LIMIT bounds the search.
2503 Return a list whose CAR is `table-row' and CDR is a plist
2504 containing `:begin', `:end', `:contents-begin', `:contents-end',
2505 `:type' and `:post-blank' keywords."
2507 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2509 ;; A table rule has no contents. In that case, ensure
2510 ;; CONTENTS-BEGIN matches CONTENTS-END.
2511 (contents-begin (and (eq type
'standard
)
2512 (search-forward "|")
2514 (contents-end (and (eq type
'standard
)
2517 (skip-chars-backward " \t")
2519 (end (progn (forward-line) (point))))
2524 :contents-begin contents-begin
2525 :contents-end contents-end
2528 (defun org-element-table-row-interpreter (table-row contents
)
2529 "Interpret TABLE-ROW element as Org syntax.
2530 CONTENTS is the contents of the table row."
2531 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2532 (concat "| " contents
)))
2537 (defun org-element-verse-block-parser (limit affiliated
)
2538 "Parse a verse block.
2540 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2541 the buffer position at the beginning of the first affiliated
2542 keyword and CDR is a plist of affiliated keywords along with
2545 Return a list whose CAR is `verse-block' and CDR is a plist
2546 containing `:begin', `:end', `:contents-begin', `:contents-end',
2547 `:post-blank' and `:post-affiliated' keywords.
2549 Assume point is at beginning of the block."
2550 (let ((case-fold-search t
))
2551 (if (not (save-excursion
2552 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2553 ;; Incomplete block: parse it as a paragraph.
2554 (org-element-paragraph-parser limit affiliated
)
2555 (let ((contents-end (match-beginning 0)))
2557 (let* ((begin (car affiliated
))
2558 (post-affiliated (point))
2559 (contents-begin (progn (forward-line) (point)))
2560 (pos-before-blank (progn (goto-char contents-end
)
2563 (end (progn (skip-chars-forward " \r\t\n" limit
)
2564 (if (eobp) (point) (line-beginning-position)))))
2569 :contents-begin contents-begin
2570 :contents-end contents-end
2571 :post-blank
(count-lines pos-before-blank end
)
2572 :post-affiliated post-affiliated
)
2573 (cdr affiliated
)))))))))
2575 (defun org-element-verse-block-interpreter (verse-block contents
)
2576 "Interpret VERSE-BLOCK element as Org syntax.
2577 CONTENTS is verse block contents."
2578 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2584 ;; Unlike to elements, raw text can be found between objects. Hence,
2585 ;; `org-element--object-lex' is provided to find the next object in
2588 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2589 ;; object types they can contain will be specified in
2590 ;; `org-element-object-restrictions'.
2592 ;; Creating a new type of object requires to alter
2593 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2594 ;; new type in `org-element-all-objects', and possibly add
2595 ;; restrictions in `org-element-object-restrictions'.
2599 (defun org-element-bold-parser ()
2600 "Parse bold object at point, if any.
2602 When at a bold object, return a list whose car is `bold' and cdr
2603 is a plist with `:begin', `:end', `:contents-begin' and
2604 `:contents-end' and `:post-blank' keywords. Otherwise, return
2607 Assume point is at the first star marker."
2609 (unless (bolp) (backward-char 1))
2610 (when (looking-at org-emph-re
)
2611 (let ((begin (match-beginning 2))
2612 (contents-begin (match-beginning 4))
2613 (contents-end (match-end 4))
2614 (post-blank (progn (goto-char (match-end 2))
2615 (skip-chars-forward " \t")))
2620 :contents-begin contents-begin
2621 :contents-end contents-end
2622 :post-blank post-blank
))))))
2624 (defun org-element-bold-interpreter (bold contents
)
2625 "Interpret BOLD object as Org syntax.
2626 CONTENTS is the contents of the object."
2627 (format "*%s*" contents
))
2632 (defun org-element-code-parser ()
2633 "Parse code object at point, if any.
2635 When at a code object, return a list whose car is `code' and cdr
2636 is a plist with `:value', `:begin', `:end' and `:post-blank'
2637 keywords. Otherwise, return nil.
2639 Assume point is at the first tilde marker."
2641 (unless (bolp) (backward-char 1))
2642 (when (looking-at org-emph-re
)
2643 (let ((begin (match-beginning 2))
2644 (value (org-match-string-no-properties 4))
2645 (post-blank (progn (goto-char (match-end 2))
2646 (skip-chars-forward " \t")))
2652 :post-blank post-blank
))))))
2654 (defun org-element-code-interpreter (code contents
)
2655 "Interpret CODE object as Org syntax.
2657 (format "~%s~" (org-element-property :value code
)))
2662 (defun org-element-entity-parser ()
2663 "Parse entity at point, if any.
2665 When at an entity, return a list whose car is `entity' and cdr
2666 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2667 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2668 `:post-blank' as keywords. Otherwise, return nil.
2670 Assume point is at the beginning of the entity."
2672 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2674 (let* ((value (or (org-entity-get (match-string 1))
2675 (throw 'no-object nil
)))
2676 (begin (match-beginning 0))
2677 (bracketsp (string= (match-string 2) "{}"))
2678 (post-blank (progn (goto-char (match-end 1))
2679 (when bracketsp
(forward-char 2))
2680 (skip-chars-forward " \t")))
2683 (list :name
(car value
)
2684 :latex
(nth 1 value
)
2685 :latex-math-p
(nth 2 value
)
2687 :ascii
(nth 4 value
)
2688 :latin1
(nth 5 value
)
2689 :utf-8
(nth 6 value
)
2692 :use-brackets-p bracketsp
2693 :post-blank post-blank
)))))))
2695 (defun org-element-entity-interpreter (entity contents
)
2696 "Interpret ENTITY object as Org syntax.
2699 (org-element-property :name entity
)
2700 (when (org-element-property :use-brackets-p entity
) "{}")))
2705 (defun org-element-export-snippet-parser ()
2706 "Parse export snippet at point.
2708 When at an export snippet, return a list whose car is
2709 `export-snippet' and cdr a plist with `:begin', `:end',
2710 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2713 Assume point is at the beginning of the snippet."
2716 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2718 (save-match-data (goto-char (match-end 0))
2719 (re-search-forward "@@" nil t
)
2720 (match-beginning 0))))
2721 (let* ((begin (match-beginning 0))
2722 (back-end (org-match-string-no-properties 1))
2723 (value (buffer-substring-no-properties
2724 (match-end 0) contents-end
))
2725 (post-blank (skip-chars-forward " \t"))
2727 (list 'export-snippet
2728 (list :back-end back-end
2732 :post-blank post-blank
)))))))
2734 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2735 "Interpret EXPORT-SNIPPET object as Org syntax.
2738 (org-element-property :back-end export-snippet
)
2739 (org-element-property :value export-snippet
)))
2742 ;;;; Footnote Reference
2744 (defun org-element-footnote-reference-parser ()
2745 "Parse footnote reference at point, if any.
2747 When at a footnote reference, return a list whose car is
2748 `footnote-reference' and cdr a plist with `:label', `:type',
2749 `:inline-definition', `:begin', `:end' and `:post-blank' as
2750 keywords. Otherwise, return nil."
2752 (when (looking-at org-footnote-re
)
2754 (let* ((begin (point))
2755 (label (or (org-match-string-no-properties 2)
2756 (org-match-string-no-properties 3)
2757 (and (match-string 1)
2758 (concat "fn:" (org-match-string-no-properties 1)))))
2759 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2760 (inner-begin (match-end 0))
2764 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2765 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2766 (unless (zerop count
) (throw 'no-object nil
))
2768 (post-blank (progn (goto-char (1+ inner-end
))
2769 (skip-chars-forward " \t")))
2772 (list 'footnote-reference
2777 :post-blank post-blank
))))
2778 (org-element-put-property
2779 footnote-reference
:inline-definition
2780 (and (eq type
'inline
)
2781 (org-element-parse-secondary-string
2782 (buffer-substring inner-begin inner-end
)
2783 (org-element-restriction 'footnote-reference
)
2784 footnote-reference
))))))))
2786 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2787 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2789 (let ((label (or (org-element-property :label footnote-reference
) "fn:"))
2792 (org-element-property :inline-definition footnote-reference
)))
2793 (if (not inline-def
) ""
2794 (concat ":" (org-element-interpret-data inline-def
))))))
2795 (format "[%s]" (concat label def
))))
2798 ;;;; Inline Babel Call
2800 (defun org-element-inline-babel-call-parser ()
2801 "Parse inline babel call at point, if any.
2803 When at an inline babel call, return a list whose car is
2804 `inline-babel-call' and cdr a plist with `:begin', `:end',
2805 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2807 Assume point is at the beginning of the babel call."
2809 (unless (bolp) (backward-char))
2810 (when (let ((case-fold-search t
))
2811 (looking-at org-babel-inline-lob-one-liner-regexp
))
2812 (let ((begin (match-end 1))
2813 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2814 (post-blank (progn (goto-char (match-end 0))
2815 (skip-chars-forward " \t")))
2817 (list 'inline-babel-call
2821 :post-blank post-blank
))))))
2823 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2824 "Interpret INLINE-BABEL-CALL object as Org syntax.
2826 (org-element-property :value inline-babel-call
))
2829 ;;;; Inline Src Block
2831 (defun org-element-inline-src-block-parser ()
2832 "Parse inline source block at point, if any.
2834 When at an inline source block, return a list whose car is
2835 `inline-src-block' and cdr a plist with `:begin', `:end',
2836 `:language', `:value', `:parameters' and `:post-blank' as
2837 keywords. Otherwise, return nil.
2839 Assume point is at the beginning of the inline src block."
2841 (unless (bolp) (backward-char))
2842 (when (looking-at org-babel-inline-src-block-regexp
)
2843 (let ((begin (match-beginning 1))
2844 (language (org-match-string-no-properties 2))
2845 (parameters (org-match-string-no-properties 4))
2846 (value (org-match-string-no-properties 5))
2847 (post-blank (progn (goto-char (match-end 0))
2848 (skip-chars-forward " \t")))
2850 (list 'inline-src-block
2851 (list :language language
2853 :parameters parameters
2856 :post-blank post-blank
))))))
2858 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2859 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2861 (let ((language (org-element-property :language inline-src-block
))
2862 (arguments (org-element-property :parameters inline-src-block
))
2863 (body (org-element-property :value inline-src-block
)))
2864 (format "src_%s%s{%s}"
2866 (if arguments
(format "[%s]" arguments
) "")
2871 (defun org-element-italic-parser ()
2872 "Parse italic object at point, if any.
2874 When at an italic object, return a list whose car is `italic' and
2875 cdr is a plist with `:begin', `:end', `:contents-begin' and
2876 `:contents-end' and `:post-blank' keywords. Otherwise, return
2879 Assume point is at the first slash marker."
2881 (unless (bolp) (backward-char 1))
2882 (when (looking-at org-emph-re
)
2883 (let ((begin (match-beginning 2))
2884 (contents-begin (match-beginning 4))
2885 (contents-end (match-end 4))
2886 (post-blank (progn (goto-char (match-end 2))
2887 (skip-chars-forward " \t")))
2892 :contents-begin contents-begin
2893 :contents-end contents-end
2894 :post-blank post-blank
))))))
2896 (defun org-element-italic-interpreter (italic contents
)
2897 "Interpret ITALIC object as Org syntax.
2898 CONTENTS is the contents of the object."
2899 (format "/%s/" contents
))
2904 (defun org-element-latex-fragment-parser ()
2905 "Parse LaTeX fragment at point, if any.
2907 When at a LaTeX fragment, return a list whose car is
2908 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2909 and `:post-blank' as keywords. Otherwise, return nil.
2911 Assume point is at the beginning of the LaTeX fragment."
2914 (let* ((begin (point))
2917 (dolist (e (cdr org-latex-regexps
))
2918 (let ((latex-regexp (nth 1 e
)))
2919 (when (or (looking-at latex-regexp
)
2923 (looking-at latex-regexp
))))
2924 (throw 'exit
(nth 2 e
))))))
2926 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2928 ;; No fragment found.
2929 (throw 'no-object nil
)))
2930 (value (org-match-string-no-properties substring-match
))
2931 (post-blank (progn (goto-char (match-end substring-match
))
2932 (skip-chars-forward " \t")))
2934 (list 'latex-fragment
2938 :post-blank post-blank
))))))
2940 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2941 "Interpret LATEX-FRAGMENT object as Org syntax.
2943 (org-element-property :value latex-fragment
))
2947 (defun org-element-line-break-parser ()
2948 "Parse line break at point, if any.
2950 When at a line break, return a list whose car is `line-break',
2951 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2952 Otherwise, return nil.
2954 Assume point is at the beginning of the line break."
2955 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2956 (not (eq (char-before) ?
\\)))
2958 (list :begin
(point)
2959 :end
(progn (forward-line) (point))
2962 (defun org-element-line-break-interpreter (line-break contents
)
2963 "Interpret LINE-BREAK object as Org syntax.
2970 (defun org-element-link-parser ()
2971 "Parse link at point, if any.
2973 When at a link, return a list whose car is `link' and cdr a plist
2974 with `:type', `:path', `:raw-link', `:application',
2975 `:search-option', `:begin', `:end', `:contents-begin',
2976 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2979 Assume point is at the beginning of the link."
2981 (let ((begin (point))
2982 end contents-begin contents-end link-end post-blank path type
2983 raw-link link search-option application
)
2985 ;; Type 1: Text targeted from a radio target.
2986 ((and org-target-link-regexp
2987 (save-excursion (or (bolp) (backward-char))
2988 (looking-at org-target-link-regexp
)))
2990 link-end
(match-end 1)
2991 path
(org-match-string-no-properties 1)
2992 contents-begin
(match-beginning 1)
2993 contents-end
(match-end 1)))
2994 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2995 ((looking-at org-bracket-link-regexp
)
2996 (setq contents-begin
(match-beginning 3)
2997 contents-end
(match-end 3)
2998 link-end
(match-end 0)
2999 ;; RAW-LINK is the original link. Expand any
3000 ;; abbreviation in it.
3001 raw-link
(org-translate-link
3002 (org-link-expand-abbrev
3003 (org-match-string-no-properties 1))))
3004 ;; Determine TYPE of link and set PATH accordingly.
3007 ((or (file-name-absolute-p raw-link
)
3008 (string-match "^\\.\\.?/" raw-link
))
3009 (setq type
"file" path raw-link
))
3010 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3011 ((string-match org-link-re-with-space3 raw-link
)
3012 (setq type
(match-string 1 raw-link
) path
(match-string 2 raw-link
)))
3013 ;; Id type: PATH is the id.
3014 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link
)
3015 (setq type
"id" path
(match-string 1 raw-link
)))
3016 ;; Code-ref type: PATH is the name of the reference.
3017 ((string-match "^(\\(.*\\))$" raw-link
)
3018 (setq type
"coderef" path
(match-string 1 raw-link
)))
3019 ;; Custom-id type: PATH is the name of the custom id.
3020 ((= (aref raw-link
0) ?
#)
3021 (setq type
"custom-id" path
(substring raw-link
1)))
3022 ;; Fuzzy type: Internal link either matches a target, an
3023 ;; headline name or nothing. PATH is the target or
3025 (t (setq type
"fuzzy" path raw-link
))))
3026 ;; Type 3: Plain link, e.g., http://orgmode.org
3027 ((looking-at org-plain-link-re
)
3028 (setq raw-link
(org-match-string-no-properties 0)
3029 type
(org-match-string-no-properties 1)
3030 link-end
(match-end 0)
3031 path
(org-match-string-no-properties 2)))
3032 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3033 ((looking-at org-angle-link-re
)
3034 (setq raw-link
(buffer-substring-no-properties
3035 (match-beginning 1) (match-end 2))
3036 type
(org-match-string-no-properties 1)
3037 link-end
(match-end 0)
3038 path
(org-match-string-no-properties 2)))
3039 (t (throw 'no-object nil
)))
3040 ;; In any case, deduce end point after trailing white space from
3041 ;; LINK-END variable.
3043 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3045 ;; Special "file" type link processing.
3046 (when (member type org-element-link-type-is-file
)
3047 ;; Extract opening application and search option.
3048 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3049 (setq application
(match-string 1 type
)))
3050 ((not (string-match "^file" type
))
3051 (setq application type
)))
3052 (when (string-match "::\\(.*\\)\\'" path
)
3053 (setq search-option
(match-string 1 path
)
3054 path
(replace-match "" nil nil path
)))
3056 (when (and (not (org-string-match-p "\\`//" path
))
3057 (file-name-absolute-p path
))
3058 (setq path
(concat "//" path
)))
3059 ;; Make sure TYPE always reports "file".
3064 :raw-link
(or raw-link path
)
3065 :application application
3066 :search-option search-option
3069 :contents-begin contents-begin
3070 :contents-end contents-end
3071 :post-blank post-blank
))))))
3073 (defun org-element-link-interpreter (link contents
)
3074 "Interpret LINK object as Org syntax.
3075 CONTENTS is the contents of the object, or nil."
3076 (let ((type (org-element-property :type link
))
3077 (raw-link (org-element-property :raw-link link
)))
3078 (if (string= type
"radio") raw-link
3081 (if contents
(format "[%s]" contents
) "")))))
3086 (defun org-element-macro-parser ()
3087 "Parse macro at point, if any.
3089 When at a macro, return a list whose car is `macro' and cdr
3090 a plist with `:key', `:args', `:begin', `:end', `:value' and
3091 `:post-blank' as keywords. Otherwise, return nil.
3093 Assume point is at the macro."
3095 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3096 (let ((begin (point))
3097 (key (downcase (org-match-string-no-properties 1)))
3098 (value (org-match-string-no-properties 0))
3099 (post-blank (progn (goto-char (match-end 0))
3100 (skip-chars-forward " \t")))
3102 (args (let ((args (org-match-string-no-properties 3)))
3104 ;; Do not use `org-split-string' since empty
3105 ;; strings are meaningful here.
3107 (replace-regexp-in-string
3108 "\\(\\\\*\\)\\(,\\)"
3110 (let ((len (length (match-string 1 str
))))
3111 (concat (make-string (/ len
2) ?
\\)
3112 (if (zerop (mod len
2)) "\000" ","))))
3121 :post-blank post-blank
))))))
3123 (defun org-element-macro-interpreter (macro contents
)
3124 "Interpret MACRO object as Org syntax.
3126 (org-element-property :value macro
))
3131 (defun org-element-radio-target-parser ()
3132 "Parse radio target at point, if any.
3134 When at a radio target, return a list whose car is `radio-target'
3135 and cdr a plist with `:begin', `:end', `:contents-begin',
3136 `:contents-end', `:value' and `:post-blank' as keywords.
3137 Otherwise, return nil.
3139 Assume point is at the radio target."
3141 (when (looking-at org-radio-target-regexp
)
3142 (let ((begin (point))
3143 (contents-begin (match-beginning 1))
3144 (contents-end (match-end 1))
3145 (value (org-match-string-no-properties 1))
3146 (post-blank (progn (goto-char (match-end 0))
3147 (skip-chars-forward " \t")))
3152 :contents-begin contents-begin
3153 :contents-end contents-end
3154 :post-blank post-blank
3157 (defun org-element-radio-target-interpreter (target contents
)
3158 "Interpret TARGET object as Org syntax.
3159 CONTENTS is the contents of the object."
3160 (concat "<<<" contents
">>>"))
3163 ;;;; Statistics Cookie
3165 (defun org-element-statistics-cookie-parser ()
3166 "Parse statistics cookie at point, if any.
3168 When at a statistics cookie, return a list whose car is
3169 `statistics-cookie', and cdr a plist with `:begin', `:end',
3170 `:value' and `:post-blank' keywords. Otherwise, return nil.
3172 Assume point is at the beginning of the statistics-cookie."
3174 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3175 (let* ((begin (point))
3176 (value (buffer-substring-no-properties
3177 (match-beginning 0) (match-end 0)))
3178 (post-blank (progn (goto-char (match-end 0))
3179 (skip-chars-forward " \t")))
3181 (list 'statistics-cookie
3185 :post-blank post-blank
))))))
3187 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3188 "Interpret STATISTICS-COOKIE object as Org syntax.
3190 (org-element-property :value statistics-cookie
))
3195 (defun org-element-strike-through-parser ()
3196 "Parse strike-through object at point, if any.
3198 When at a strike-through object, return a list whose car is
3199 `strike-through' and cdr is a plist with `:begin', `:end',
3200 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3201 Otherwise, return nil.
3203 Assume point is at the first plus sign marker."
3205 (unless (bolp) (backward-char 1))
3206 (when (looking-at org-emph-re
)
3207 (let ((begin (match-beginning 2))
3208 (contents-begin (match-beginning 4))
3209 (contents-end (match-end 4))
3210 (post-blank (progn (goto-char (match-end 2))
3211 (skip-chars-forward " \t")))
3213 (list 'strike-through
3216 :contents-begin contents-begin
3217 :contents-end contents-end
3218 :post-blank post-blank
))))))
3220 (defun org-element-strike-through-interpreter (strike-through contents
)
3221 "Interpret STRIKE-THROUGH object as Org syntax.
3222 CONTENTS is the contents of the object."
3223 (format "+%s+" contents
))
3228 (defun org-element-subscript-parser ()
3229 "Parse subscript at point, if any.
3231 When at a subscript object, return a list whose car is
3232 `subscript' and cdr a plist with `:begin', `:end',
3233 `:contents-begin', `:contents-end', `:use-brackets-p' and
3234 `:post-blank' as keywords. Otherwise, return nil.
3236 Assume point is at the underscore."
3238 (unless (bolp) (backward-char))
3239 (when (looking-at org-match-substring-regexp
)
3240 (let ((bracketsp (match-beginning 4))
3241 (begin (match-beginning 2))
3242 (contents-begin (or (match-beginning 4)
3243 (match-beginning 3)))
3244 (contents-end (or (match-end 4) (match-end 3)))
3245 (post-blank (progn (goto-char (match-end 0))
3246 (skip-chars-forward " \t")))
3251 :use-brackets-p bracketsp
3252 :contents-begin contents-begin
3253 :contents-end contents-end
3254 :post-blank post-blank
))))))
3256 (defun org-element-subscript-interpreter (subscript contents
)
3257 "Interpret SUBSCRIPT object as Org syntax.
3258 CONTENTS is the contents of the object."
3260 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3266 (defun org-element-superscript-parser ()
3267 "Parse superscript at point, if any.
3269 When at a superscript object, return a list whose car is
3270 `superscript' and cdr a plist with `:begin', `:end',
3271 `:contents-begin', `:contents-end', `:use-brackets-p' and
3272 `:post-blank' as keywords. Otherwise, return nil.
3274 Assume point is at the caret."
3276 (unless (bolp) (backward-char))
3277 (when (looking-at org-match-substring-regexp
)
3278 (let ((bracketsp (match-beginning 4))
3279 (begin (match-beginning 2))
3280 (contents-begin (or (match-beginning 4)
3281 (match-beginning 3)))
3282 (contents-end (or (match-end 4) (match-end 3)))
3283 (post-blank (progn (goto-char (match-end 0))
3284 (skip-chars-forward " \t")))
3289 :use-brackets-p bracketsp
3290 :contents-begin contents-begin
3291 :contents-end contents-end
3292 :post-blank post-blank
))))))
3294 (defun org-element-superscript-interpreter (superscript contents
)
3295 "Interpret SUPERSCRIPT object as Org syntax.
3296 CONTENTS is the contents of the object."
3298 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3304 (defun org-element-table-cell-parser ()
3305 "Parse table cell at point.
3306 Return a list whose car is `table-cell' and cdr is a plist
3307 containing `:begin', `:end', `:contents-begin', `:contents-end'
3308 and `:post-blank' keywords."
3309 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3310 (let* ((begin (match-beginning 0))
3312 (contents-begin (match-beginning 1))
3313 (contents-end (match-end 1)))
3317 :contents-begin contents-begin
3318 :contents-end contents-end
3321 (defun org-element-table-cell-interpreter (table-cell contents
)
3322 "Interpret TABLE-CELL element as Org syntax.
3323 CONTENTS is the contents of the cell, or nil."
3324 (concat " " contents
" |"))
3329 (defun org-element-target-parser ()
3330 "Parse target at point, if any.
3332 When at a target, return a list whose car is `target' and cdr
3333 a plist with `:begin', `:end', `:value' and `:post-blank' as
3334 keywords. Otherwise, return nil.
3336 Assume point is at the target."
3338 (when (looking-at org-target-regexp
)
3339 (let ((begin (point))
3340 (value (org-match-string-no-properties 1))
3341 (post-blank (progn (goto-char (match-end 0))
3342 (skip-chars-forward " \t")))
3348 :post-blank post-blank
))))))
3350 (defun org-element-target-interpreter (target contents
)
3351 "Interpret TARGET object as Org syntax.
3353 (format "<<%s>>" (org-element-property :value target
)))
3358 (defconst org-element--timestamp-regexp
3359 (concat org-ts-regexp-both
3361 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3363 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3364 "Regexp matching any timestamp type object.")
3366 (defun org-element-timestamp-parser ()
3367 "Parse time stamp at point, if any.
3369 When at a time stamp, return a list whose car is `timestamp', and
3370 cdr a plist with `:type', `:raw-value', `:year-start',
3371 `:month-start', `:day-start', `:hour-start', `:minute-start',
3372 `:year-end', `:month-end', `:day-end', `:hour-end',
3373 `:minute-end', `:repeater-type', `:repeater-value',
3374 `:repeater-unit', `:warning-type', `:warning-value',
3375 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3376 Otherwise, return nil.
3378 Assume point is at the beginning of the timestamp."
3379 (when (org-looking-at-p org-element--timestamp-regexp
)
3381 (let* ((begin (point))
3382 (activep (eq (char-after) ?
<))
3385 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3386 (match-string-no-properties 0)))
3387 (date-start (match-string-no-properties 1))
3388 (date-end (match-string 3))
3389 (diaryp (match-beginning 2))
3390 (post-blank (progn (goto-char (match-end 0))
3391 (skip-chars-forward " \t")))
3396 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3398 (cons (string-to-number (match-string 2 date-start
))
3399 (string-to-number (match-string 3 date-start
)))))
3400 (type (cond (diaryp 'diary
)
3401 ((and activep
(or date-end time-range
)) 'active-range
)
3403 ((or date-end time-range
) 'inactive-range
)
3407 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3411 (let ((type (match-string 1 raw-value
)))
3412 (cond ((equal "++" type
) 'catch-up
)
3413 ((equal ".+" type
) 'restart
)
3415 :repeater-value
(string-to-number (match-string 2 raw-value
))
3417 (case (string-to-char (match-string 3 raw-value
))
3418 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3421 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3423 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3424 :warning-value
(string-to-number (match-string 2 raw-value
))
3426 (case (string-to-char (match-string 3 raw-value
))
3427 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3428 year-start month-start day-start hour-start minute-start year-end
3429 month-end day-end hour-end minute-end
)
3430 ;; Parse date-start.
3432 (let ((date (org-parse-time-string date-start t
)))
3433 (setq year-start
(nth 5 date
)
3434 month-start
(nth 4 date
)
3435 day-start
(nth 3 date
)
3436 hour-start
(nth 2 date
)
3437 minute-start
(nth 1 date
))))
3438 ;; Compute date-end. It can be provided directly in time-stamp,
3439 ;; or extracted from time range. Otherwise, it defaults to the
3440 ;; same values as date-start.
3442 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3443 (setq year-end
(or (nth 5 date
) year-start
)
3444 month-end
(or (nth 4 date
) month-start
)
3445 day-end
(or (nth 3 date
) day-start
)
3446 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3447 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3449 (nconc (list :type type
3450 :raw-value raw-value
3451 :year-start year-start
3452 :month-start month-start
3453 :day-start day-start
3454 :hour-start hour-start
3455 :minute-start minute-start
3457 :month-end month-end
3460 :minute-end minute-end
3463 :post-blank post-blank
)
3467 (defun org-element-timestamp-interpreter (timestamp contents
)
3468 "Interpret TIMESTAMP object as Org syntax.
3470 (let* ((repeat-string
3472 (case (org-element-property :repeater-type timestamp
)
3473 (cumulate "+") (catch-up "++") (restart ".+"))
3474 (let ((val (org-element-property :repeater-value timestamp
)))
3475 (and val
(number-to-string val
)))
3476 (case (org-element-property :repeater-unit timestamp
)
3477 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3480 (case (org-element-property :warning-type timestamp
)
3483 (let ((val (org-element-property :warning-value timestamp
)))
3484 (and val
(number-to-string val
)))
3485 (case (org-element-property :warning-unit timestamp
)
3486 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3488 ;; Build an Org timestamp string from TIME. ACTIVEP is
3489 ;; non-nil when time stamp is active. If WITH-TIME-P is
3490 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3491 ;; specify a time range in the timestamp. REPEAT-STRING is
3492 ;; the repeater string, if any.
3493 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3494 (let ((ts (format-time-string
3495 (funcall (if with-time-p
'cdr
'car
)
3496 org-time-stamp-formats
)
3498 (when (and hour-end minute-end
)
3499 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3502 (format "\\&-%02d:%02d" hour-end minute-end
)
3504 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3505 (dolist (s (list repeat-string warning-string
))
3506 (when (org-string-nw-p s
)
3507 (setq ts
(concat (substring ts
0 -
1)
3510 (substring ts -
1)))))
3513 (type (org-element-property :type timestamp
)))
3516 (let* ((minute-start (org-element-property :minute-start timestamp
))
3517 (minute-end (org-element-property :minute-end timestamp
))
3518 (hour-start (org-element-property :hour-start timestamp
))
3519 (hour-end (org-element-property :hour-end timestamp
))
3520 (time-range-p (and hour-start hour-end minute-start minute-end
3521 (or (/= hour-start hour-end
)
3522 (/= minute-start minute-end
)))))
3528 (org-element-property :day-start timestamp
)
3529 (org-element-property :month-start timestamp
)
3530 (org-element-property :year-start timestamp
))
3532 (and hour-start minute-start
)
3533 (and time-range-p hour-end
)
3534 (and time-range-p minute-end
))))
3535 ((active-range inactive-range
)
3536 (let ((minute-start (org-element-property :minute-start timestamp
))
3537 (minute-end (org-element-property :minute-end timestamp
))
3538 (hour-start (org-element-property :hour-start timestamp
))
3539 (hour-end (org-element-property :hour-end timestamp
)))
3542 build-ts-string
(encode-time
3546 (org-element-property :day-start timestamp
)
3547 (org-element-property :month-start timestamp
)
3548 (org-element-property :year-start timestamp
))
3549 (eq type
'active-range
)
3550 (and hour-start minute-start
))
3552 (funcall build-ts-string
3556 (org-element-property :day-end timestamp
)
3557 (org-element-property :month-end timestamp
)
3558 (org-element-property :year-end timestamp
))
3559 (eq type
'active-range
)
3560 (and hour-end minute-end
))))))))
3565 (defun org-element-underline-parser ()
3566 "Parse underline object at point, if any.
3568 When at an underline object, return a list whose car is
3569 `underline' and cdr is a plist with `:begin', `:end',
3570 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3571 Otherwise, return nil.
3573 Assume point is at the first underscore marker."
3575 (unless (bolp) (backward-char 1))
3576 (when (looking-at org-emph-re
)
3577 (let ((begin (match-beginning 2))
3578 (contents-begin (match-beginning 4))
3579 (contents-end (match-end 4))
3580 (post-blank (progn (goto-char (match-end 2))
3581 (skip-chars-forward " \t")))
3586 :contents-begin contents-begin
3587 :contents-end contents-end
3588 :post-blank post-blank
))))))
3590 (defun org-element-underline-interpreter (underline contents
)
3591 "Interpret UNDERLINE object as Org syntax.
3592 CONTENTS is the contents of the object."
3593 (format "_%s_" contents
))
3598 (defun org-element-verbatim-parser ()
3599 "Parse verbatim object at point, if any.
3601 When at a verbatim object, return a list whose car is `verbatim'
3602 and cdr is a plist with `:value', `:begin', `:end' and
3603 `:post-blank' keywords. Otherwise, return nil.
3605 Assume point is at the first equal sign marker."
3607 (unless (bolp) (backward-char 1))
3608 (when (looking-at org-emph-re
)
3609 (let ((begin (match-beginning 2))
3610 (value (org-match-string-no-properties 4))
3611 (post-blank (progn (goto-char (match-end 2))
3612 (skip-chars-forward " \t")))
3618 :post-blank post-blank
))))))
3620 (defun org-element-verbatim-interpreter (verbatim contents
)
3621 "Interpret VERBATIM object as Org syntax.
3623 (format "=%s=" (org-element-property :value verbatim
)))
3627 ;;; Parsing Element Starting At Point
3629 ;; `org-element--current-element' is the core function of this section.
3630 ;; It returns the Lisp representation of the element starting at
3633 ;; `org-element--current-element' makes use of special modes. They
3634 ;; are activated for fixed element chaining (e.g., `plain-list' >
3635 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3636 ;; `section'). Special modes are: `first-section', `item',
3637 ;; `node-property', `section' and `table-row'.
3639 (defun org-element--current-element
3640 (limit &optional granularity special structure
)
3641 "Parse the element starting at point.
3643 Return value is a list like (TYPE PROPS) where TYPE is the type
3644 of the element and PROPS a plist of properties associated to the
3647 Possible types are defined in `org-element-all-elements'.
3649 LIMIT bounds the search.
3651 Optional argument GRANULARITY determines the depth of the
3652 recursion. Allowed values are `headline', `greater-element',
3653 `element', `object' or nil. When it is broader than `object' (or
3654 nil), secondary values will not be parsed, since they only
3657 Optional argument SPECIAL, when non-nil, can be either
3658 `first-section', `item', `node-property', `section', and
3661 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3664 This function assumes point is always at the beginning of the
3665 element it has to parse."
3667 (let ((case-fold-search t
)
3668 ;; Determine if parsing depth allows for secondary strings
3669 ;; parsing. It only applies to elements referenced in
3670 ;; `org-element-secondary-value-alist'.
3671 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3675 (org-element-item-parser limit structure raw-secondary-p
))
3677 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3679 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3681 ((org-with-limited-levels (org-at-heading-p))
3682 (org-element-headline-parser limit raw-secondary-p
))
3683 ;; Sections (must be checked after headline).
3684 ((eq special
'section
) (org-element-section-parser limit
))
3685 ((eq special
'first-section
)
3686 (org-element-section-parser
3687 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3689 ;; When not at bol, point is at the beginning of an item or
3690 ;; a footnote definition: next item is always a paragraph.
3691 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3692 ;; Planning and Clock.
3693 ((looking-at org-planning-or-clock-line-re
)
3694 (if (equal (match-string 1) org-clock-string
)
3695 (org-element-clock-parser limit
)
3696 (org-element-planning-parser limit
)))
3699 (org-element-inlinetask-parser limit raw-secondary-p
))
3700 ;; From there, elements can have affiliated keywords.
3701 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3703 ;; Jumping over affiliated keywords put point off-limits.
3704 ;; Parse them as regular keywords.
3705 ((and (cdr affiliated
) (>= (point) limit
))
3706 (goto-char (car affiliated
))
3707 (org-element-keyword-parser limit nil
))
3708 ;; LaTeX Environment.
3710 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3711 (org-element-latex-environment-parser limit affiliated
))
3712 ;; Drawer and Property Drawer.
3713 ((looking-at org-drawer-regexp
)
3714 (if (equal (match-string 1) "PROPERTIES")
3715 (org-element-property-drawer-parser limit affiliated
)
3716 (org-element-drawer-parser limit affiliated
)))
3718 ((looking-at "[ \t]*:\\( \\|$\\)")
3719 (org-element-fixed-width-parser limit affiliated
))
3720 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3722 ((looking-at "[ \t]*#")
3723 (goto-char (match-end 0))
3724 (cond ((looking-at "\\(?: \\|$\\)")
3726 (org-element-comment-parser limit affiliated
))
3727 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3729 (let ((parser (assoc (upcase (match-string 1))
3730 org-element-block-name-alist
)))
3731 (if parser
(funcall (cdr parser
) limit affiliated
)
3732 (org-element-special-block-parser limit affiliated
))))
3733 ((looking-at "\\+CALL:")
3735 (org-element-babel-call-parser limit affiliated
))
3736 ((looking-at "\\+BEGIN:? ")
3738 (org-element-dynamic-block-parser limit affiliated
))
3739 ((looking-at "\\+\\S-+:")
3741 (org-element-keyword-parser limit affiliated
))
3744 (org-element-paragraph-parser limit affiliated
))))
3745 ;; Footnote Definition.
3746 ((looking-at org-footnote-definition-re
)
3747 (org-element-footnote-definition-parser limit affiliated
))
3749 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3750 (org-element-horizontal-rule-parser limit affiliated
))
3753 (org-element-diary-sexp-parser limit affiliated
))
3755 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3757 ((looking-at (org-item-re))
3758 (org-element-plain-list-parser
3760 (or structure
(org-element--list-struct limit
))))
3761 ;; Default element: Paragraph.
3762 (t (org-element-paragraph-parser limit affiliated
)))))))))
3765 ;; Most elements can have affiliated keywords. When looking for an
3766 ;; element beginning, we want to move before them, as they belong to
3767 ;; that element, and, in the meantime, collect information they give
3768 ;; into appropriate properties. Hence the following function.
3770 (defun org-element--collect-affiliated-keywords (limit)
3771 "Collect affiliated keywords from point down to LIMIT.
3773 Return a list whose CAR is the position at the first of them and
3774 CDR a plist of keywords and values and move point to the
3775 beginning of the first line after them.
3777 As a special case, if element doesn't start at the beginning of
3778 the line (e.g., a paragraph starting an item), CAR is current
3779 position of point and CDR is nil."
3780 (if (not (bolp)) (list (point))
3781 (let ((case-fold-search t
)
3783 ;; RESTRICT is the list of objects allowed in parsed
3785 (restrict (org-element-restriction 'keyword
))
3787 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3788 (let* ((raw-kwd (upcase (match-string 1)))
3789 ;; Apply translation to RAW-KWD. From there, KWD is
3790 ;; the official keyword.
3791 (kwd (or (cdr (assoc raw-kwd
3792 org-element-keyword-translation-alist
))
3794 ;; Find main value for any keyword.
3798 (buffer-substring-no-properties
3799 (match-end 0) (point-at-eol)))))
3800 ;; PARSEDP is non-nil when keyword should have its
3802 (parsedp (member kwd org-element-parsed-keywords
))
3803 ;; If KWD is a dual keyword, find its secondary
3804 ;; value. Maybe parse it.
3805 (dualp (member kwd org-element-dual-keywords
))
3808 (let ((sec (org-match-string-no-properties 2)))
3809 (if (or (not sec
) (not parsedp
)) sec
3810 (org-element-parse-secondary-string sec restrict
)))))
3811 ;; Attribute a property name to KWD.
3812 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3813 ;; Now set final shape for VALUE.
3815 (setq value
(org-element-parse-secondary-string value restrict
)))
3817 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3818 (when (or (member kwd org-element-multiple-keywords
)
3819 ;; Attributes can always appear on multiple lines.
3820 (string-match "^ATTR_" kwd
))
3821 (setq value
(cons value
(plist-get output kwd-sym
))))
3822 ;; Eventually store the new value in OUTPUT.
3823 (setq output
(plist-put output kwd-sym value
))
3824 ;; Move to next keyword.
3826 ;; If affiliated keywords are orphaned: move back to first one.
3827 ;; They will be parsed as a paragraph.
3828 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3830 (cons origin output
))))
3836 ;; The two major functions here are `org-element-parse-buffer', which
3837 ;; parses Org syntax inside the current buffer, taking into account
3838 ;; region, narrowing, or even visibility if specified, and
3839 ;; `org-element-parse-secondary-string', which parses objects within
3842 ;; The (almost) almighty `org-element-map' allows to apply a function
3843 ;; on elements or objects matching some type, and accumulate the
3844 ;; resulting values. In an export situation, it also skips unneeded
3845 ;; parts of the parse tree.
3847 (defun org-element-parse-buffer (&optional granularity visible-only
)
3848 "Recursively parse the buffer and return structure.
3849 If narrowing is in effect, only parse the visible part of the
3852 Optional argument GRANULARITY determines the depth of the
3853 recursion. It can be set to the following symbols:
3855 `headline' Only parse headlines.
3856 `greater-element' Don't recurse into greater elements excepted
3857 headlines and sections. Thus, elements
3858 parsed are the top-level ones.
3859 `element' Parse everything but objects and plain text.
3860 `object' Parse the complete buffer (default).
3862 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3865 An element or an objects is represented as a list with the
3866 pattern (TYPE PROPERTIES CONTENTS), where :
3868 TYPE is a symbol describing the element or object. See
3869 `org-element-all-elements' and `org-element-all-objects' for an
3870 exhaustive list of such symbols. One can retrieve it with
3871 `org-element-type' function.
3873 PROPERTIES is the list of attributes attached to the element or
3874 object, as a plist. Although most of them are specific to the
3875 element or object type, all types share `:begin', `:end',
3876 `:post-blank' and `:parent' properties, which respectively
3877 refer to buffer position where the element or object starts,
3878 ends, the number of white spaces or blank lines after it, and
3879 the element or object containing it. Properties values can be
3880 obtained by using `org-element-property' function.
3882 CONTENTS is a list of elements, objects or raw strings
3883 contained in the current element or object, when applicable.
3884 One can access them with `org-element-contents' function.
3886 The Org buffer has `org-data' as type and nil as properties.
3887 `org-element-map' function can be used to find specific elements
3888 or objects within the parse tree.
3890 This function assumes that current major mode is `org-mode'."
3892 (goto-char (point-min))
3893 (org-skip-whitespace)
3894 (org-element--parse-elements
3895 (point-at-bol) (point-max)
3896 ;; Start in `first-section' mode so text before the first
3897 ;; headline belongs to a section.
3898 'first-section nil granularity visible-only
(list 'org-data nil
))))
3900 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3901 "Recursively parse objects in STRING and return structure.
3903 RESTRICTION is a symbol limiting the object types that will be
3906 Optional argument PARENT, when non-nil, is the element or object
3907 containing the secondary string. It is used to set correctly
3908 `:parent' property within the string."
3909 ;; Copy buffer-local variables listed in
3910 ;; `org-element-object-variables' into temporary buffer. This is
3911 ;; required since object parsing is dependent on these variables.
3912 (let ((pairs (delq nil
(mapcar (lambda (var)
3914 (cons var
(symbol-value var
))))
3915 org-element-object-variables
))))
3917 (mapc (lambda (pair) (org-set-local (car pair
) (cdr pair
))) pairs
)
3919 (let ((secondary (org-element--parse-objects
3920 (point-min) (point-max) nil restriction
)))
3922 (mapc (lambda (obj) (org-element-put-property obj
:parent parent
))
3926 (defun org-element-map
3927 (data types fun
&optional info first-match no-recursion with-affiliated
)
3928 "Map a function on selected elements or objects.
3930 DATA is a parse tree, an element, an object, a string, or a list
3931 of such constructs. TYPES is a symbol or list of symbols of
3932 elements or objects types (see `org-element-all-elements' and
3933 `org-element-all-objects' for a complete list of types). FUN is
3934 the function called on the matching element or object. It has to
3935 accept one argument: the element or object itself.
3937 When optional argument INFO is non-nil, it should be a plist
3938 holding export options. In that case, parts of the parse tree
3939 not exportable according to that property list will be skipped.
3941 When optional argument FIRST-MATCH is non-nil, stop at the first
3942 match for which FUN doesn't return nil, and return that value.
3944 Optional argument NO-RECURSION is a symbol or a list of symbols
3945 representing elements or objects types. `org-element-map' won't
3946 enter any recursive element or object whose type belongs to that
3947 list. Though, FUN can still be applied on them.
3949 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3950 apply to matching objects within parsed affiliated keywords (see
3951 `org-element-parsed-keywords').
3953 Nil values returned from FUN do not appear in the results.
3959 Assuming TREE is a variable containing an Org buffer parse tree,
3960 the following example will return a flat list of all `src-block'
3961 and `example-block' elements in it:
3963 \(org-element-map tree '(example-block src-block) 'identity)
3965 The following snippet will find the first headline with a level
3966 of 1 and a \"phone\" tag, and will return its beginning position:
3968 \(org-element-map tree 'headline
3970 \(and (= (org-element-property :level hl) 1)
3971 \(member \"phone\" (org-element-property :tags hl))
3972 \(org-element-property :begin hl)))
3975 The next example will return a flat list of all `plain-list' type
3976 elements in TREE that are not a sub-list themselves:
3978 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3980 Eventually, this example will return a flat list of all `bold'
3981 type objects containing a `latex-snippet' type object, even
3982 looking into captions:
3984 \(org-element-map tree 'bold
3986 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3988 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3989 (unless (listp types
) (setq types
(list types
)))
3990 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
3991 ;; Recursion depth is determined by --CATEGORY.
3994 (let ((category 'greater-elements
))
3995 (mapc (lambda (type)
3996 (cond ((or (memq type org-element-all-objects
)
3997 (eq type
'plain-text
))
3998 ;; If one object is found, the function
3999 ;; has to recurse into every object.
4000 (throw 'found
'objects
))
4001 ((not (memq type org-element-greater-elements
))
4002 ;; If one regular element is found, the
4003 ;; function has to recurse, at least,
4004 ;; into every element it encounters.
4005 (and (not (eq category
'elements
))
4006 (setq category
'elements
)))))
4009 ;; Compute properties for affiliated keywords if necessary.
4011 (and with-affiliated
4012 (mapcar (lambda (kwd)
4013 (cons kwd
(intern (concat ":" (downcase kwd
)))))
4014 org-element-affiliated-keywords
)))
4020 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4021 ;; holding contextual information.
4022 (let ((--type (org-element-type --data
)))
4025 ;; Ignored element in an export context.
4026 ((and info
(memq --data
(plist-get info
:ignore-list
))))
4027 ;; List of elements or objects.
4028 ((not --type
) (mapc --walk-tree --data
))
4029 ;; Unconditionally enter parse trees.
4030 ((eq --type
'org-data
)
4031 (mapc --walk-tree
(org-element-contents --data
)))
4033 ;; Check if TYPE is matching among TYPES. If so,
4034 ;; apply FUN to --DATA and accumulate return value
4035 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4036 (when (memq --type types
)
4037 (let ((result (funcall fun --data
)))
4038 (cond ((not result
))
4039 (first-match (throw '--map-first-match result
))
4040 (t (push result --acc
)))))
4041 ;; If --DATA has a secondary string that can contain
4042 ;; objects with their type among TYPES, look into it.
4043 (when (and (eq --category
'objects
) (not (stringp --data
)))
4045 (assq --type org-element-secondary-value-alist
)))
4047 (funcall --walk-tree
4048 (org-element-property (cdr sec-prop
) --data
)))))
4049 ;; If --DATA has any affiliated keywords and
4050 ;; WITH-AFFILIATED is non-nil, look for objects in
4052 (when (and with-affiliated
4053 (eq --category
'objects
)
4054 (memq --type org-element-all-elements
))
4055 (mapc (lambda (kwd-pair)
4056 (let ((kwd (car kwd-pair
))
4057 (value (org-element-property
4058 (cdr kwd-pair
) --data
)))
4059 ;; Pay attention to the type of value.
4060 ;; Preserve order for multiple keywords.
4063 ((and (member kwd org-element-multiple-keywords
)
4064 (member kwd org-element-dual-keywords
))
4065 (mapc (lambda (line)
4066 (funcall --walk-tree
(cdr line
))
4067 (funcall --walk-tree
(car line
)))
4069 ((member kwd org-element-multiple-keywords
)
4070 (mapc (lambda (line) (funcall --walk-tree line
))
4072 ((member kwd org-element-dual-keywords
)
4073 (funcall --walk-tree
(cdr value
))
4074 (funcall --walk-tree
(car value
)))
4075 (t (funcall --walk-tree value
)))))
4076 --affiliated-alist
))
4077 ;; Determine if a recursion into --DATA is possible.
4079 ;; --TYPE is explicitly removed from recursion.
4080 ((memq --type no-recursion
))
4081 ;; --DATA has no contents.
4082 ((not (org-element-contents --data
)))
4083 ;; Looking for greater elements but --DATA is simply
4084 ;; an element or an object.
4085 ((and (eq --category
'greater-elements
)
4086 (not (memq --type org-element-greater-elements
))))
4087 ;; Looking for elements but --DATA is an object.
4088 ((and (eq --category
'elements
)
4089 (memq --type org-element-all-objects
)))
4090 ;; In any other case, map contents.
4091 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4092 (catch '--map-first-match
4093 (funcall --walk-tree data
)
4094 ;; Return value in a proper order.
4096 (put 'org-element-map
'lisp-indent-function
2)
4098 ;; The following functions are internal parts of the parser.
4100 ;; The first one, `org-element--parse-elements' acts at the element's
4103 ;; The second one, `org-element--parse-objects' applies on all objects
4104 ;; of a paragraph or a secondary string.
4106 ;; More precisely, that function looks for every allowed object type
4107 ;; first. Then, it discards failed searches, keeps further matches,
4108 ;; and searches again types matched behind point, for subsequent
4109 ;; calls. Thus, searching for a given type fails only once, and every
4110 ;; object is searched only once at top level (but sometimes more for
4113 (defun org-element--parse-elements
4114 (beg end special structure granularity visible-only acc
)
4115 "Parse elements between BEG and END positions.
4117 SPECIAL prioritize some elements over the others. It can be set
4118 to `first-section', `section' `item' or `table-row'.
4120 When value is `item', STRUCTURE will be used as the current list
4123 GRANULARITY determines the depth of the recursion. See
4124 `org-element-parse-buffer' for more information.
4126 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4129 Elements are accumulated into ACC."
4132 ;; Visible only: skip invisible parts at the beginning of the
4134 (when (and visible-only
(org-invisible-p2))
4135 (goto-char (min (1+ (org-find-visible)) end
)))
4136 ;; When parsing only headlines, skip any text before first one.
4137 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4138 (org-with-limited-levels (outline-next-heading)))
4140 (while (< (point) end
)
4141 ;; Find current element's type and parse it accordingly to
4143 (let* ((element (org-element--current-element
4144 end granularity special structure
))
4145 (type (org-element-type element
))
4146 (cbeg (org-element-property :contents-begin element
)))
4147 (goto-char (org-element-property :end element
))
4148 ;; Visible only: skip invisible parts between siblings.
4149 (when (and visible-only
(org-invisible-p2))
4150 (goto-char (min (1+ (org-find-visible)) end
)))
4151 ;; Fill ELEMENT contents by side-effect.
4153 ;; If element has no contents, don't modify it.
4155 ;; Greater element: parse it between `contents-begin' and
4156 ;; `contents-end'. Make sure GRANULARITY allows the
4157 ;; recursion, or ELEMENT is a headline, in which case going
4158 ;; inside is mandatory, in order to get sub-level headings.
4159 ((and (memq type org-element-greater-elements
)
4160 (or (memq granularity
'(element object nil
))
4161 (and (eq granularity
'greater-element
)
4163 (eq type
'headline
)))
4164 (org-element--parse-elements
4165 cbeg
(org-element-property :contents-end element
)
4166 ;; Possibly switch to a special mode.
4170 (property-drawer 'node-property
)
4172 (and (memq type
'(item plain-list
))
4173 (org-element-property :structure element
))
4174 granularity visible-only element
))
4175 ;; ELEMENT has contents. Parse objects inside, if
4176 ;; GRANULARITY allows it.
4177 ((memq granularity
'(object nil
))
4178 (org-element--parse-objects
4179 cbeg
(org-element-property :contents-end element
) element
4180 (org-element-restriction type
))))
4181 (org-element-adopt-elements acc element
)))
4185 (defconst org-element--object-regexp
4186 (mapconcat #'identity
4187 (let ((link-types (regexp-opt org-link-types
)))
4190 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4191 ;; Bold, code, italic, strike-through, underline and
4194 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4196 (concat "\\<" link-types
":")
4197 ;; Objects starting with "[": regular link, footnote
4198 ;; reference, statistics cookie, timestamp (inactive).
4199 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4200 ;; Objects starting with "@": export snippets.
4202 ;; Objects starting with "{": macro.
4204 ;; Objects starting with "<" : timestamp (active,
4205 ;; diary), target, radio target and angular links.
4206 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4207 ;; Objects starting with "$": latex fragment.
4209 ;; Objects starting with "\": line break, entity,
4211 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4212 ;; Objects starting with raw text: inline Babel
4213 ;; source block, inline Babel call.
4214 "\\(?:call\\|src\\)_"))
4216 "Regexp possibly matching the beginning of an object.
4217 This regexp allows false positives. Dedicated parser (e.g.,
4218 `org-export-bold-parser') will take care of further filtering.
4219 Radio links are not matched by this regexp, as they are treated
4220 specially in `org-element--object-lex'.")
4222 (defun org-element--object-lex (restriction)
4223 "Return next object in current buffer or nil.
4224 RESTRICTION is a list of object types, as symbols, that should be
4225 looked after. This function assumes that the buffer is narrowed
4226 to an appropriate container (e.g., a paragraph)."
4227 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4229 (let ((limit (and org-target-link-regexp
4231 (or (bolp) (backward-char))
4232 (re-search-forward org-target-link-regexp nil t
))
4233 (match-beginning 1)))
4235 (while (and (not found
)
4236 (re-search-forward org-element--object-regexp limit t
))
4237 (goto-char (match-beginning 0))
4238 (let ((result (match-string 0)))
4241 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4242 (and (memq 'inline-babel-call restriction
)
4243 (org-element-inline-babel-call-parser)))
4244 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4245 (and (memq 'inline-src-block restriction
)
4246 (org-element-inline-src-block-parser)))
4249 (?^
(and (memq 'superscript restriction
)
4250 (org-element-superscript-parser)))
4251 (?_
(or (and (memq 'subscript restriction
)
4252 (org-element-subscript-parser))
4253 (and (memq 'underline restriction
)
4254 (org-element-underline-parser))))
4255 (?
* (and (memq 'bold restriction
)
4256 (org-element-bold-parser)))
4257 (?
/ (and (memq 'italic restriction
)
4258 (org-element-italic-parser)))
4259 (?~
(and (memq 'code restriction
)
4260 (org-element-code-parser)))
4261 (?
= (and (memq 'verbatim restriction
)
4262 (org-element-verbatim-parser)))
4263 (?
+ (and (memq 'strike-through restriction
)
4264 (org-element-strike-through-parser)))
4265 (?
@ (and (memq 'export-snippet restriction
)
4266 (org-element-export-snippet-parser)))
4267 (?
{ (and (memq 'macro restriction
)
4268 (org-element-macro-parser)))
4269 (?$
(and (memq 'latex-fragment restriction
)
4270 (org-element-latex-fragment-parser)))
4272 (if (eq (aref result
1) ?
<)
4273 (or (and (memq 'radio-target restriction
)
4274 (org-element-radio-target-parser))
4275 (and (memq 'target restriction
)
4276 (org-element-target-parser)))
4277 (or (and (memq 'timestamp restriction
)
4278 (org-element-timestamp-parser))
4279 (and (memq 'link restriction
)
4280 (org-element-link-parser)))))
4281 (?
\\ (or (and (memq 'line-break restriction
)
4282 (org-element-line-break-parser))
4283 (and (memq 'entity restriction
)
4284 (org-element-entity-parser))
4285 (and (memq 'latex-fragment restriction
)
4286 (org-element-latex-fragment-parser))))
4288 (if (eq (aref result
1) ?\
[)
4289 (and (memq 'link restriction
)
4290 (org-element-link-parser))
4291 (or (and (memq 'footnote-reference restriction
)
4292 (org-element-footnote-reference-parser))
4293 (and (memq 'timestamp restriction
)
4294 (org-element-timestamp-parser))
4295 (and (memq 'statistics-cookie restriction
)
4296 (org-element-statistics-cookie-parser)))))
4297 ;; This is probably a plain link.
4298 (otherwise (and (or (memq 'link restriction
)
4299 (memq 'plain-link restriction
))
4300 (org-element-link-parser)))))))
4301 (or (eobp) (forward-char))))
4304 ((and limit
(memq 'link restriction
))
4305 (goto-char limit
) (org-element-link-parser)))))))
4307 (defun org-element--parse-objects (beg end acc restriction
)
4308 "Parse objects between BEG and END and return recursive structure.
4310 Objects are accumulated in ACC.
4312 RESTRICTION is a list of object successors which are allowed in
4313 the current object."
4316 (narrow-to-region beg end
)
4317 (goto-char (point-min))
4319 (while (and (not (eobp))
4320 (setq next-object
(org-element--object-lex restriction
)))
4321 ;; 1. Text before any object. Untabify it.
4322 (let ((obj-beg (org-element-property :begin next-object
)))
4323 (unless (= (point) obj-beg
)
4325 (org-element-adopt-elements
4327 (replace-regexp-in-string
4328 "\t" (make-string tab-width ?
)
4329 (buffer-substring-no-properties (point) obj-beg
))))))
4331 (let ((obj-end (org-element-property :end next-object
))
4332 (cont-beg (org-element-property :contents-begin next-object
)))
4333 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4334 ;; a recursive type.
4336 (memq (car next-object
) org-element-recursive-objects
))
4337 (org-element--parse-objects
4338 cont-beg
(org-element-property :contents-end next-object
)
4339 next-object
(org-element-restriction next-object
)))
4340 (setq acc
(org-element-adopt-elements acc next-object
))
4341 (goto-char obj-end
))))
4342 ;; 3. Text after last object. Untabify it.
4345 (org-element-adopt-elements
4347 (replace-regexp-in-string
4348 "\t" (make-string tab-width ?
)
4349 (buffer-substring-no-properties (point) end
)))))
4355 ;;; Towards A Bijective Process
4357 ;; The parse tree obtained with `org-element-parse-buffer' is really
4358 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4359 ;; interpreted and expanded into a string with canonical Org syntax.
4360 ;; Hence `org-element-interpret-data'.
4362 ;; The function relies internally on
4363 ;; `org-element--interpret-affiliated-keywords'.
4366 (defun org-element-interpret-data (data &optional pseudo-objects
)
4367 "Interpret DATA as Org syntax.
4369 DATA is a parse tree, an element, an object or a secondary string
4372 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4373 new types that should be treated as objects. An unknown type not
4374 belonging to this list is seen as a pseudo-element instead. Both
4375 pseudo-objects and pseudo-elements are transparent entities, i.e.
4376 only their contents are interpreted.
4378 Return Org syntax as a string."
4379 (org-element--interpret-data-1 data nil pseudo-objects
))
4381 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4382 "Interpret DATA as Org syntax.
4384 DATA is a parse tree, an element, an object or a secondary string
4385 to interpret. PARENT is used for recursive calls. It contains
4386 the element or object containing data, or nil. PSEUDO-OBJECTS
4387 are list of symbols defining new element or object types.
4388 Unknown types that don't belong to this list are treated as
4389 pseudo-elements instead.
4391 Return Org syntax as a string."
4392 (let* ((type (org-element-type data
))
4393 ;; Find interpreter for current object or element. If it
4394 ;; doesn't exist (e.g. this is a pseudo object or element),
4395 ;; return contents, if any.
4397 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4398 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4401 ;; Secondary string.
4405 (org-element--interpret-data-1 obj parent pseudo-objects
))
4407 ;; Full Org document.
4408 ((eq type
'org-data
)
4411 (org-element--interpret-data-1 obj parent pseudo-objects
))
4412 (org-element-contents data
) ""))
4413 ;; Plain text: return it.
4414 ((stringp data
) data
)
4415 ;; Element or object without contents.
4416 ((not (org-element-contents data
)) (funcall interpret data nil
))
4417 ;; Element or object with contents.
4419 (funcall interpret data
4420 ;; Recursively interpret contents.
4423 (org-element--interpret-data-1 obj data pseudo-objects
))
4424 (org-element-contents
4425 (if (not (memq type
'(paragraph verse-block
)))
4427 ;; Fix indentation of elements containing
4428 ;; objects. We ignore `table-row' elements
4429 ;; as they are one line long anyway.
4430 (org-element-normalize-contents
4432 ;; When normalizing first paragraph of an
4433 ;; item or a footnote-definition, ignore
4434 ;; first line's indentation.
4435 (and (eq type
'paragraph
)
4436 (equal data
(car (org-element-contents parent
)))
4437 (memq (org-element-type parent
)
4438 '(footnote-definition item
))))))
4440 (if (memq type
'(org-data plain-text nil
)) results
4441 ;; Build white spaces. If no `:post-blank' property is
4442 ;; specified, assume its value is 0.
4443 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4444 (if (or (memq type org-element-all-objects
)
4445 (memq type pseudo-objects
))
4446 (concat results
(make-string post-blank ?\s
))
4448 (org-element--interpret-affiliated-keywords data
)
4449 (org-element-normalize-string results
)
4450 (make-string post-blank ?
\n)))))))
4452 (defun org-element--interpret-affiliated-keywords (element)
4453 "Return ELEMENT's affiliated keywords as Org syntax.
4454 If there is no affiliated keyword, return the empty string."
4455 (let ((keyword-to-org
4459 (when (member key org-element-dual-keywords
)
4460 (setq dual
(cdr value
) value
(car value
)))
4463 (format "[%s]" (org-element-interpret-data dual
)))
4465 (if (member key org-element-parsed-keywords
)
4466 (org-element-interpret-data value
)
4471 (let ((value (org-element-property prop element
))
4472 (keyword (upcase (substring (symbol-name prop
) 1))))
4474 (if (or (member keyword org-element-multiple-keywords
)
4475 ;; All attribute keywords can have multiple lines.
4476 (string-match "^ATTR_" keyword
))
4477 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4480 (funcall keyword-to-org keyword value
)))))
4481 ;; List all ELEMENT's properties matching an attribute line or an
4482 ;; affiliated keyword, but ignore translated keywords since they
4483 ;; cannot belong to the property list.
4484 (loop for prop in
(nth 1 element
) by
'cddr
4485 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4486 (or (string-match "^ATTR_" keyword
)
4488 (member keyword org-element-affiliated-keywords
)
4490 org-element-keyword-translation-alist
)))))
4494 ;; Because interpretation of the parse tree must return the same
4495 ;; number of blank lines between elements and the same number of white
4496 ;; space after objects, some special care must be given to white
4499 ;; The first function, `org-element-normalize-string', ensures any
4500 ;; string different from the empty string will end with a single
4501 ;; newline character.
4503 ;; The second function, `org-element-normalize-contents', removes
4504 ;; global indentation from the contents of the current element.
4506 (defun org-element-normalize-string (s)
4507 "Ensure string S ends with a single newline character.
4509 If S isn't a string return it unchanged. If S is the empty
4510 string, return it. Otherwise, return a new string with a single
4511 newline character at its end."
4513 ((not (stringp s
)) s
)
4515 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4516 (replace-match "\n" nil nil s
)))))
4518 (defun org-element-normalize-contents (element &optional ignore-first
)
4519 "Normalize plain text in ELEMENT's contents.
4521 ELEMENT must only contain plain text and objects.
4523 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4524 indentation to compute maximal common indentation.
4526 Return the normalized element that is element with global
4527 indentation removed from its contents. The function assumes that
4528 indentation is not done with TAB characters."
4529 (let* ((min-ind most-positive-fixnum
)
4530 find-min-ind
; For byte-compiler.
4533 ;; Return minimal common indentation within BLOB. This is
4534 ;; done by walking recursively BLOB and updating MIN-IND
4535 ;; along the way. FIRST-FLAG is non-nil when the first
4536 ;; string hasn't been seen yet. It is required as this
4537 ;; string is the only one whose indentation doesn't happen
4538 ;; after a newline character.
4539 (lambda (blob first-flag
)
4540 (dolist (object (org-element-contents blob
))
4541 (when (and first-flag
(stringp object
))
4542 (setq first-flag nil
)
4543 (string-match "\\`\\( *\\)" object
)
4544 (let ((len (length (match-string 1 object
))))
4545 ;; An indentation of zero means no string will be
4546 ;; modified. Quit the process.
4547 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4548 (setq min-ind
(min len min-ind
)))))
4551 (dolist (line (delq "" (cdr (org-split-string object
" *\n"))))
4552 (setq min-ind
(min (org-get-indentation line
) min-ind
))))
4553 ((memq (org-element-type object
) org-element-recursive-objects
)
4554 (funcall find-min-ind object first-flag
))))))))
4555 ;; Find minimal indentation in ELEMENT.
4556 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4557 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4558 ;; Build ELEMENT back, replacing each string with the same
4559 ;; string minus common indentation.
4560 (let* (build ; For byte compiler.
4563 (lambda (blob first-flag
)
4564 ;; Return BLOB with all its strings indentation
4565 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4566 ;; is non-nil when the first string hasn't been seen
4571 (when (and first-flag
(stringp object
))
4572 (setq first-flag nil
)
4574 (replace-regexp-in-string
4575 (format "\\` \\{%d\\}" min-ind
)
4579 (replace-regexp-in-string
4580 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4581 ((memq (org-element-type object
)
4582 org-element-recursive-objects
)
4583 (funcall build object first-flag
))
4585 (org-element-contents blob
)))
4587 (funcall build element
(not ignore-first
))))))
4593 ;; Implement a caching mechanism for `org-element-at-point' and
4594 ;; `org-element-context', which see.
4596 ;; A single public function is provided: `org-element-cache-reset'.
4598 ;; Cache is enabled by default, but can be disabled globally with
4599 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4600 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4601 ;; can be tweaked to control caching behaviour.
4603 ;; Internally, parsed elements are stored in an AVL tree,
4604 ;; `org-element--cache'. This tree is updated lazily: whenever
4605 ;; a change happens to the buffer, a synchronization request is
4606 ;; registered in `org-element--cache-sync-requests' (see
4607 ;; `org-element--cache-submit-request'). During idle time, requests
4608 ;; are processed by `org-element--cache-sync'. Synchronization also
4609 ;; happens when an element is required from the cache. In this case,
4610 ;; the process stops as soon as the needed element is up-to-date.
4612 ;; A synchronization request can only apply on a synchronized part of
4613 ;; the cache. Therefore, the cache is updated at least to the
4614 ;; location where the new request applies. Thus, requests are ordered
4615 ;; from left to right and all elements starting before the first
4616 ;; request are correct. This property is used by functions like
4617 ;; `org-element--cache-find' to retrieve elements in the part of the
4618 ;; cache that can be trusted.
4620 ;; A request applies to every element, starting from its original
4621 ;; location (or key, see below). When a request is processed, it
4622 ;; moves forward and may collide the next one. In this case, both
4623 ;; requests are merged into a new one that starts from that element.
4624 ;; As a consequence, the whole synchronization complexity does not
4625 ;; depend on the number of pending requests, but on the number of
4626 ;; elements the very first request will be applied on.
4628 ;; Elements cannot be accessed through their beginning position, which
4629 ;; may or may not be up-to-date. Instead, each element in the tree is
4630 ;; associated to a key, obtained with `org-element--cache-key'. This
4631 ;; mechanism is robust enough to preserve total order among elements
4632 ;; even when the tree is only partially synchronized.
4634 ;; Objects contained in an element are stored in a hash table,
4635 ;; `org-element--cache-objects'.
4638 (defvar org-element-use-cache t
4639 "Non nil when Org parser should cache its results.
4640 This is mostly for debugging purpose.")
4642 (defvar org-element-cache-sync-idle-time
0.4
4643 "Length, in seconds, of idle time before syncing cache.")
4645 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4646 "Maximum duration, as a time value, for a cache synchronization.
4647 If the synchronization is not over after this delay, the process
4648 pauses and resumes after `org-element-cache-sync-break'
4651 (defvar org-element-cache-sync-break
(seconds-to-time 0.2)
4652 "Duration, as a time value, of the pause between synchronizations.
4653 See `org-element-cache-sync-duration' for more information.")
4658 (defvar org-element--cache nil
4659 "AVL tree used to cache elements.
4660 Each node of the tree contains an element. Comparison is done
4661 with `org-element--cache-compare'. This cache is used in
4662 `org-element-at-point'.")
4664 (defvar org-element--cache-objects nil
4665 "Hash table used as to cache objects.
4666 Key is an element, as returned by `org-element-at-point', and
4667 value is an alist where each association is:
4669 \(PARENT COMPLETEP . OBJECTS)
4671 where PARENT is an element or object, COMPLETEP is a boolean,
4672 non-nil when all direct children of parent are already cached and
4673 OBJECTS is a list of such children, as objects, from farthest to
4676 In the following example, \\alpha, bold object and \\beta are
4677 contained within a paragraph
4681 If the paragraph is completely parsed, OBJECTS-DATA will be
4683 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4684 \(BOLD-OBJECT t ENTITY-OBJECT))
4686 whereas in a partially parsed paragraph, it could be
4688 \((PARAGRAPH nil ENTITY-OBJECT))
4690 This cache is used in `org-element-context'.")
4692 (defvar org-element--cache-sync-requests nil
4693 "List of pending synchronization requests.
4695 A request is a vector with the following pattern:
4697 \[NEXT BEG END OFFSET PARENT PHASE]
4699 Processing a synchronization request consists of three phases:
4701 0. Delete modified elements,
4702 1. Fill missing area in cache,
4703 2. Shift positions and re-parent elements after the changes.
4705 During phase 0, NEXT is the key of the first element to be
4706 removed, BEG and END is buffer position delimiting the
4707 modifications. Every element starting between these are removed.
4708 PARENT is an element to be removed. Every element contained in
4709 it will also be removed.
4711 During phase 1, NEXT is the key of the next known element in
4712 cache. Parse buffer between that element and the one before it
4713 in order to determine the parent of the next element. Set PARENT
4714 to the element containing NEXT.
4716 During phase 2, NEXT is the key of the next element to shift in
4717 the parse tree. All elements starting from this one have their
4718 properties relatives to buffer positions shifted by integer
4719 OFFSET and, if they belong to element PARENT, are adopted by it.
4721 PHASE specifies the phase number, as an integer.")
4723 (defvar org-element--cache-sync-timer nil
4724 "Timer used for cache synchronization.")
4726 (defvar org-element--cache-sync-keys nil
4727 "Hash table used to store keys during synchronization.
4728 See `org-element--cache-key' for more information.")
4730 (defsubst org-element--cache-key
(element)
4731 "Return a unique key for ELEMENT in cache tree.
4733 Keys are used to keep a total order among elements in the cache.
4734 Comparison is done with `org-element--cache-key-less-p'.
4736 When no synchronization is taking place, a key is simply the
4737 beginning position of the element, or that position plus one in
4738 the case of an first item (respectively row) in
4739 a list (respectively a table).
4741 During a synchronization, the key is the one the element had when
4742 the cache was synchronized for the last time. Elements added to
4743 cache during the synchronization get a new key generated with
4744 `org-element--cache-generate-key'.
4746 Such keys are stored in `org-element--cache-sync-keys'. The hash
4747 table is cleared once the synchronization is complete."
4748 (or (gethash element org-element--cache-sync-keys
)
4749 (let* ((begin (org-element-property :begin element
))
4750 ;; Increase beginning position of items (respectively
4751 ;; table rows) by one, so the first item can get
4752 ;; a different key from its parent list (respectively
4754 (key (if (memq (org-element-type element
) '(item table-row
))
4757 (if org-element--cache-sync-requests
4758 (puthash element key org-element--cache-sync-keys
)
4761 (defconst org-element--cache-default-key
(ash most-positive-fixnum -
1)
4762 "Default value for a new key level.
4763 See `org-element--cache-generate-key' for more information.")
4765 (defun org-element--cache-generate-key (lower upper
)
4766 "Generate a key between LOWER and UPPER.
4768 LOWER and UPPER are integers or lists, possibly empty.
4770 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4771 a unique key, as an integer or a list of integers, according to
4772 the following rules:
4774 - LOWER and UPPER are compared level-wise until values differ.
4776 - If, at a given level, LOWER and UPPER differ from more than
4777 2, the new key shares all the levels above with LOWER and
4778 gets a new level. Its value is the mean between LOWER and
4781 \(1 2) + (1 4) --> (1 3)
4783 - If LOWER has no value to compare with, it is assumed that its
4786 \(1 1) + (1 1 2) --> (1 1 1)
4788 Likewise, if UPPER is short of levels, the current value is
4789 `most-positive-fixnum'.
4791 - If they differ from only one, the new key inherits from
4792 current LOWER lever and has a new level at the value
4793 `org-element--cache-default-key'.
4795 \(1 2) + (1 3) --> (1 2 org-element--cache-default-key)
4797 - If the key is only one level long, it is returned as an
4800 \(1 2) + (3 2) --> 2"
4801 (if (equal lower upper
) lower
4802 (let ((lower (if (integerp lower
) (list lower
) lower
))
4803 (upper (if (integerp upper
) (list upper
) upper
))
4806 (while (and lower upper
)
4807 (let ((lower-level (car lower
))
4808 (upper-level (car upper
)))
4810 ((= lower-level upper-level
)
4811 (push lower-level key
)
4812 (setq lower
(cdr lower
) upper
(cdr upper
)))
4813 ((= (- upper-level lower-level
) 1)
4814 (push lower-level key
)
4815 (setq lower
(cdr lower
))
4816 (while (and lower
(= (car lower
) most-positive-fixnum
))
4817 (push most-positive-fixnum key
)
4818 (setq lower
(cdr lower
)))
4820 (let ((n (car lower
)))
4821 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4822 org-element--cache-default-key
))
4823 org-element--cache-default-key
)
4827 (push (let ((n (car lower
)))
4828 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4829 (ash (car upper
) -
1)))
4834 (while (and upper
(zerop (car upper
)))
4836 (setq upper
(cdr upper
)))
4837 ;; (n) is equivalent to (n 0 0 0 0 ...) so we forbid ending
4839 (cond ((not upper
) (push org-element--cache-default-key key
))
4842 (push org-element--cache-default-key key
))
4843 (t (push (ash (car upper
) -
1) key
))))
4845 (while (and lower
(= (car lower
) most-positive-fixnum
))
4846 (push most-positive-fixnum key
)
4847 (setq lower
(cdr lower
)))
4848 (push (if (not lower
) org-element--cache-default-key
4849 (let ((n (car lower
)))
4850 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4851 org-element--cache-default-key
)))
4853 ;; Ensure we don't return a list with a single element.
4854 (if (cdr key
) (nreverse key
) (car key
)))))
4856 (defsubst org-element--cache-key-less-p
(a b
)
4857 "Non-nil if key A is less than key B.
4858 A and B are either integers or lists of integers, as returned by
4859 `org-element--cache-key'."
4860 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4861 (if (integerp b
) (< (car a
) b
)
4864 (cond ((car-less-than-car a b
) (throw 'exit t
))
4865 ((car-less-than-car b a
) (throw 'exit nil
))
4866 (t (setq a
(cdr a
) b
(cdr b
)))))
4867 ;; If A is empty, either keys are equal (B is also empty) or
4868 ;; B is less than A (B is longer). Therefore return nil.
4870 ;; If A is not empty, B is necessarily empty and A is less
4871 ;; than B (A is longer). Therefore, return a non-nil value.
4874 (defun org-element--cache-compare (a b
)
4875 "Non-nil when element A is located before element B."
4876 (org-element--cache-key-less-p (org-element--cache-key a
)
4877 (org-element--cache-key b
)))
4879 (defsubst org-element--cache-root
()
4880 "Return root value in cache.
4881 This function assumes `org-element--cache' is a valid AVL tree."
4882 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4887 (defsubst org-element--cache-active-p
()
4888 "Non-nil when cache is active in current buffer."
4889 (and org-element-use-cache
4890 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4892 (defun org-element--cache-find (pos &optional side
)
4893 "Find element in cache starting at POS or before.
4895 POS refers to a buffer position.
4897 When optional argument SIDE is non-nil, the function checks for
4898 elements starting at or past POS instead. If SIDE is `both', the
4899 function returns a cons cell where car is the first element
4900 starting at or before POS and cdr the first element starting
4903 The function can only find elements in the synchronized part of
4905 (let ((limit (and org-element--cache-sync-requests
4906 (aref (car org-element--cache-sync-requests
) 0)))
4907 (node (org-element--cache-root))
4910 (let* ((element (avl-tree--node-data node
))
4911 (begin (org-element-property :begin element
)))
4914 (not (org-element--cache-key-less-p
4915 (org-element--cache-key element
) limit
)))
4916 (setq node
(avl-tree--node-left node
)))
4919 node
(avl-tree--node-left node
)))
4922 node
(avl-tree--node-right node
)))
4923 ;; We found an element in cache starting at POS. If `side'
4924 ;; is `both' we also want the next one in order to generate
4925 ;; a key in-between.
4927 ;; If the element is the first row or item in a table or
4928 ;; a plain list, we always return the table or the plain
4931 ;; In any other case, we return the element found.
4933 (setq lower element
)
4934 (setq node
(avl-tree--node-right node
)))
4935 ((and (memq (org-element-type element
) '(item table-row
))
4936 (let ((parent (org-element-property :parent element
)))
4937 (and (= (org-element-property :begin element
)
4938 (org-element-property :contents-begin parent
))
4947 (both (cons lower upper
))
4949 (otherwise upper
))))
4951 (defun org-element--cache-put (element &optional data
)
4952 "Store ELEMENT in current buffer's cache, if allowed.
4953 When optional argument DATA is non-nil, assume is it object data
4954 relative to ELEMENT and store it in the objects cache."
4955 (cond ((not (org-element--cache-active-p)) nil
)
4957 (when org-element--cache-sync-requests
4958 ;; During synchronization, first build an appropriate key
4959 ;; for the new element so `avl-tree-enter' can insert it at
4960 ;; the right spot in the cache.
4961 (let ((keys (org-element--cache-find
4962 (org-element-property :begin element
) 'both
)))
4964 (org-element--cache-generate-key
4965 (and (car keys
) (org-element--cache-key (car keys
)))
4966 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4967 (org-element--cache-sync-requests
4968 (aref (car org-element--cache-sync-requests
) 0))))
4969 org-element--cache-sync-keys
)))
4970 (avl-tree-enter org-element--cache element
))
4971 ;; Headlines are not stored in cache, so objects in titles are
4972 ;; not stored either.
4973 ((eq (org-element-type element
) 'headline
) nil
)
4974 (t (puthash element data org-element--cache-objects
))))
4976 (defsubst org-element--cache-remove
(element)
4977 "Remove ELEMENT from cache.
4978 Assume ELEMENT belongs to cache and that a cache is active."
4979 (avl-tree-delete org-element--cache element
)
4980 (remhash element org-element--cache-objects
))
4983 ;;;; Synchronization
4985 (defsubst org-element--cache-set-timer
(buffer)
4986 "Set idle timer for cache synchronization in BUFFER."
4987 (when org-element--cache-sync-timer
4988 (cancel-timer org-element--cache-sync-timer
))
4989 (setq org-element--cache-sync-timer
4990 (run-with-idle-timer
4991 (let ((idle (current-idle-time)))
4992 (if idle
(time-add idle org-element-cache-sync-break
)
4993 org-element-cache-sync-idle-time
))
4995 #'org-element--cache-sync
4998 (defsubst org-element--cache-interrupt-p
(time-limit)
4999 "Non-nil when synchronization process should be interrupted.
5000 TIME-LIMIT is a time value or nil."
5002 (or (input-pending-p)
5003 (time-less-p time-limit
(current-time)))))
5005 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
5006 "Shift ELEMENT properties relative to buffer positions by OFFSET.
5008 Properties containing buffer positions are `:begin', `:end',
5009 `:contents-begin', `:contents-end' and `:structure'. When
5010 optional argument PROPS is a list of keywords, only shift
5011 properties provided in that list.
5013 Properties are modified by side-effect."
5014 (let ((properties (nth 1 element
)))
5015 ;; Shift `:structure' property for the first plain list only: it
5016 ;; is the only one that really matters and it prevents from
5017 ;; shifting it more than once.
5018 (when (and (or (not props
) (memq :structure props
))
5019 (eq (org-element-type element
) 'plain-list
)
5020 (not (eq (org-element-type (plist-get properties
:parent
))
5022 (dolist (item (plist-get properties
:structure
))
5023 (incf (car item
) offset
)
5024 (incf (nth 6 item
) offset
)))
5025 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
5026 (let ((value (and (or (not props
) (memq key props
))
5027 (plist-get properties key
))))
5028 (and value
(plist-put properties key
(+ offset value
)))))))
5030 (defun org-element--cache-sync (buffer &optional threshold extra
)
5031 "Synchronize cache with recent modification in BUFFER.
5033 When optional argument THRESHOLD is non-nil, do the
5034 synchronization for all elements starting before or at threshold,
5035 then exit. Otherwise, synchronize cache for as long as
5036 `org-element-cache-sync-duration' or until Emacs leaves idle
5039 EXTRA, when non-nil, is an additional offset for changes not
5040 registered yet in the cache. It is used in
5041 `org-element--cache-submit-request', where cache is partially
5042 updated before current modification are actually submitted."
5043 (when (buffer-live-p buffer
)
5044 (with-current-buffer buffer
5045 (let ((inhibit-quit t
) request next
)
5046 (when org-element--cache-sync-timer
5047 (cancel-timer org-element--cache-sync-timer
))
5049 (while org-element--cache-sync-requests
5050 (setq request
(car org-element--cache-sync-requests
)
5051 next
(nth 1 org-element--cache-sync-requests
))
5052 (org-element--cache-process-request
5054 (and next
(aref next
0))
5056 (and (not threshold
)
5057 (time-add (current-time)
5058 org-element-cache-sync-duration
))
5060 ;; Request processed. Merge current and next offsets and
5061 ;; transfer phase number and ending position.
5063 (incf (aref next
3) (aref request
3))
5064 (aset next
2 (aref request
2))
5065 (aset next
5 (aref request
5)))
5066 (setq org-element--cache-sync-requests
5067 (cdr org-element--cache-sync-requests
))))
5068 ;; If more requests are awaiting, set idle timer accordingly.
5069 ;; Otherwise, reset keys.
5070 (if org-element--cache-sync-requests
5071 (org-element--cache-set-timer buffer
)
5072 (clrhash org-element--cache-sync-keys
))))))
5074 (defun org-element--cache-process-request
5075 (request next threshold time-limit extra
)
5076 "Process synchronization REQUEST for all entries before NEXT.
5078 REQUEST is a vector, built by `org-element--cache-submit-request'.
5080 NEXT is a cache key, as returned by `org-element--cache-key'.
5082 When non-nil, THRESHOLD is a buffer position. Synchronization
5083 stops as soon as a shifted element begins after it.
5085 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5086 after this time or when Emacs exits idle state.
5088 EXTRA is an additional offset taking into consideration changes
5089 not registered yet. See `org-element--cache-submit-request' for
5092 Throw `interrupt' if the process stops before completing the
5095 (when (= (aref request
5) 0)
5098 ;; Delete all elements starting after BEG, but not after buffer
5099 ;; position END or past element with key NEXT.
5101 ;; As an exception, also delete elements starting after
5102 ;; modifications but included in an element altered by
5103 ;; modifications (orphans).
5105 ;; At each iteration, we start again at tree root since
5106 ;; a deletion modifies structure of the balanced tree.
5108 (let ((beg (aref request
0))
5109 (end (aref request
2))
5110 (deleted-parent (aref request
4)))
5112 (when (org-element--cache-interrupt-p time-limit
)
5113 (aset request
4 deleted-parent
)
5114 (throw 'interrupt nil
))
5115 ;; Find first element in cache with key BEG or after it.
5116 ;; We don't use `org-element--cache-find' because it
5117 ;; couldn't reach orphaned elements past NEXT. Moreover,
5118 ;; BEG is a key, not a buffer position.
5119 (let ((node (org-element--cache-root)) data data-key
)
5121 (let* ((element (avl-tree--node-data node
))
5122 (key (org-element--cache-key element
)))
5124 ((org-element--cache-key-less-p key beg
)
5125 (setq node
(avl-tree--node-right node
)))
5126 ((org-element--cache-key-less-p beg key
)
5129 node
(avl-tree--node-left node
)))
5130 (t (setq data element
5133 (if (not data
) (throw 'quit t
)
5134 (let ((pos (org-element-property :begin data
)))
5136 ;; Remove orphaned elements.
5137 ((and deleted-parent
5140 (setq up
(org-element-property :parent up
))
5141 (not (eq up deleted-parent
))))
5143 (org-element--cache-remove data
))
5145 (not (org-element--cache-key-less-p data-key
5148 (aset request
0 data-key
)
5149 (aset request
2 pos
)
5151 (throw 'end-phase nil
))
5152 (t (org-element--cache-remove data
)
5153 (when (= (org-element-property :end data
) end
)
5154 (setq deleted-parent data
)))))))))))
5155 (when (= (aref request
5) 1)
5158 ;; Phase 1 left a hole in the parse tree. Some elements after
5159 ;; it could have parents within. For example, in the following
5171 ;; if we remove a blank line between "item" and "Paragraph1",
5172 ;; everything down to "Paragraph2" is removed from cache. But
5173 ;; the paragraph now belongs to the list, and its `:parent'
5174 ;; property no longer is accurate.
5176 ;; Therefore we need to parse again elements in the hole, or at
5177 ;; least in its last section, so that we can re-parent
5178 ;; subsequent elements, during phase 3.
5180 ;; Note that we only need to get the parent from the first
5181 ;; element in cache after the hole.
5183 ;; Also, this part can be delayed if we don't need to retrieve
5184 ;; an element after the hole.
5186 ;; Next element will start at its beginning position plus
5187 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5188 ;; contains the real beginning position of the first element
5189 ;; to shift and re-parent.
5190 (when (equal (aref request
0) next
) (throw 'quit t
))
5191 (let ((limit (+ (aref request
2) (aref request
3) extra
)))
5192 (when (and threshold
(< threshold limit
)) (throw 'interrupt nil
))
5193 (let ((parent (org-element--parse-to limit t time-limit
)))
5194 (aset request
4 parent
)
5196 (throw 'end-phase nil
)))))
5199 ;; Shift all elements starting from key START, but before NEXT, by
5200 ;; OFFSET, and re-parent them when appropriate.
5202 ;; Elements are modified by side-effect so the tree structure
5205 ;; Once THRESHOLD, if any, is reached, or once there is an input
5206 ;; pending, exit. Before leaving, the current synchronization
5207 ;; request is updated.
5208 (let ((start (aref request
0))
5209 (offset (aref request
3))
5210 (parent (aref request
4))
5211 (node (org-element--cache-root))
5215 ;; No re-parenting nor shifting planned: request is over.
5216 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5218 (let* ((data (avl-tree--node-data node
))
5219 (key (org-element--cache-key data
)))
5220 (if (and leftp
(avl-tree--node-left node
)
5221 (not (org-element--cache-key-less-p key start
)))
5222 (progn (push node stack
)
5223 (setq node
(avl-tree--node-left node
)))
5224 (unless (org-element--cache-key-less-p key start
)
5225 ;; We reached NEXT. Request is complete.
5226 (when (equal key next
) (throw 'quit t
))
5227 ;; Handle interruption request. Update current request.
5228 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5229 (aset request
0 key
)
5230 (aset request
4 parent
)
5231 (throw 'interrupt nil
))
5233 (unless (zerop offset
)
5234 (org-element--cache-shift-positions data offset
)
5235 ;; Shift associated objects data, if any.
5236 (dolist (object-data (gethash data org-element--cache-objects
))
5237 (dolist (object (cddr object-data
))
5238 (org-element--cache-shift-positions object offset
))))
5239 (let ((begin (org-element-property :begin data
)))
5242 (<= (org-element-property :end parent
) begin
))
5243 (setq parent
(org-element-property :parent parent
)))
5244 (cond (parent (org-element-put-property data
:parent parent
))
5245 ((zerop offset
) (throw 'quit t
)))
5246 ;; Cache is up-to-date past THRESHOLD. Request
5248 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5249 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5250 (avl-tree--node-right node
)
5252 ;; We reached end of tree: synchronization complete.
5255 (defun org-element--parse-to (pos &optional syncp time-limit
)
5256 "Parse elements in current section, down to POS.
5258 Start parsing from the closest between the last known element in
5259 cache or headline above. Return the smallest element containing
5262 When optional argument SYNCP is non-nil, return the parent of the
5263 element containing POS instead. In that case, it is also
5264 possible to provide TIME-LIMIT, which is a time value specifying
5265 when the parsing should stop. The function throws `interrupt' if
5266 the process stopped before finding the expected result."
5268 (org-with-wide-buffer
5270 (let* ((cached (and (org-element--cache-active-p)
5271 (org-element--cache-find pos nil
)))
5272 (begin (org-element-property :begin cached
))
5275 ;; Nothing in cache before point: start parsing from first
5276 ;; element following headline above, or first element in
5279 (when (org-with-limited-levels (outline-previous-heading))
5281 (skip-chars-forward " \r\t\n")
5282 (beginning-of-line))
5283 ;; Cache returned exact match: return it.
5285 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5286 ;; There's a headline between cached value and POS: cached
5287 ;; value is invalid. Start parsing from first element
5288 ;; following the headline.
5289 ((re-search-backward
5290 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5292 (skip-chars-forward " \r\t\n")
5293 (beginning-of-line))
5294 ;; Check if CACHED or any of its ancestors contain point.
5296 ;; If there is such an element, we inspect it in order to know
5297 ;; if we return it or if we need to parse its contents.
5298 ;; Otherwise, we just start parsing from current location,
5299 ;; which is right after the top-most element containing
5302 ;; As a special case, if POS is at the end of the buffer, we
5303 ;; want to return the innermost element ending there.
5305 ;; Also, if we find an ancestor and discover that we need to
5306 ;; parse its contents, make sure we don't start from
5307 ;; `:contents-begin', as we would otherwise go past CACHED
5308 ;; again. Instead, in that situation, we will resume parsing
5309 ;; from NEXT, which is located after CACHED or its higher
5310 ;; ancestor not containing point.
5313 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5314 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5315 (while (let ((end (org-element-property :end up
)))
5318 (setq up
(org-element-property :parent up
)))))
5320 ((eobp) (setq element up
))
5321 (t (setq element up next
(point)))))))
5322 ;; Parse successively each element until we reach POS.
5323 (let ((end (or (org-element-property :end element
)
5325 (org-with-limited-levels (outline-next-heading))
5331 (cond ((= (point) pos
) (throw 'exit parent
))
5332 ((org-element--cache-interrupt-p time-limit
)
5333 (throw 'interrupt nil
))))
5335 (setq element
(org-element--current-element
5336 end
'element special-flag
5337 (org-element-property :structure parent
)))
5338 (org-element-put-property element
:parent parent
)
5339 (org-element--cache-put element
))
5340 (let ((elem-end (org-element-property :end element
))
5341 (type (org-element-type element
)))
5343 ;; Skip any element ending before point. Also skip
5344 ;; element ending at point (unless it is also the end of
5345 ;; buffer) since we're sure that another element begins
5347 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5348 (goto-char elem-end
))
5349 ;; A non-greater element contains point: return it.
5350 ((not (memq type org-element-greater-elements
))
5351 (throw 'exit element
))
5352 ;; Otherwise, we have to decide if ELEMENT really
5353 ;; contains POS. In that case we start parsing from
5354 ;; contents' beginning.
5356 ;; If POS is at contents' beginning but it is also at
5357 ;; the beginning of the first item in a list or a table.
5358 ;; In that case, we need to create an anchor for that
5359 ;; list or table, so return it.
5361 ;; Also, if POS is at the end of the buffer, no element
5362 ;; can start after it, but more than one may end there.
5363 ;; Arbitrarily, we choose to return the innermost of
5365 ((let ((cbeg (org-element-property :contents-begin element
))
5366 (cend (org-element-property :contents-end element
)))
5371 (not (memq type
'(plain-list table
)))))
5373 (and (= cend pos
) (= (point-max) pos
)))))
5374 (goto-char (or next cbeg
))
5376 special-flag
(case type
5378 (property-drawer 'node-property
)
5382 ;; Otherwise, return ELEMENT as it is the smallest
5383 ;; element containing POS.
5384 (t (throw 'exit element
))))
5385 (setq element nil
)))))))
5388 ;;;; Staging Buffer Changes
5390 (defconst org-element--cache-opening-line
5391 (concat "^[ \t]*\\(?:"
5392 "#\\+BEGIN[:_]" "\\|"
5393 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
5396 "Regexp matching an element opening line.
5397 When such a line is modified, modifications may propagate after
5398 modified area. In that situation, every element between that
5399 area and next section is removed from cache.")
5401 (defconst org-element--cache-closing-line
5402 (concat "^[ \t]*\\(?:"
5403 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
5404 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
5407 "Regexp matching an element closing line.
5408 When such a line is modified, modifications may propagate before
5409 modified area. In that situation, every element between that
5410 area and previous section is removed from cache.")
5412 (defvar org-element--cache-change-warning nil
5413 "Non-nil when a sensitive line is about to be changed.
5414 It is a symbol among nil, t and `headline'.")
5416 (defun org-element--cache-before-change (beg end
)
5417 "Request extension of area going to be modified if needed.
5418 BEG and END are the beginning and end of the range of changed
5419 text. See `before-change-functions' for more information."
5420 (let ((inhibit-quit t
))
5422 (org-with-wide-buffer
5426 (bottom (save-excursion (goto-char end
) (line-end-position)))
5428 ;; A sensitive line is a headline or a block (or drawer,
5429 ;; or latex-environment) boundary. Inserting one can
5430 ;; modify buffer drastically both above and below that
5431 ;; line, possibly making cache invalid. Therefore, we
5432 ;; need to pay attention to changes happening to them.
5434 "\\(" (org-with-limited-levels org-outline-regexp-bol
) "\\)" "\\|"
5435 org-element--cache-closing-line
"\\|"
5436 org-element--cache-opening-line
)))
5437 (setq org-element--cache-change-warning
5438 (cond ((not (re-search-forward sensitive-re bottom t
)) nil
)
5439 ((and (match-beginning 1)
5440 (progn (goto-char bottom
)
5441 (or (not (re-search-backward sensitive-re
5443 (match-beginning 1))))
5447 (defun org-element--cache-after-change (beg end pre
)
5448 "Update buffer modifications for current buffer.
5449 BEG and END are the beginning and end of the range of changed
5450 text, and the length in bytes of the pre-change text replaced by
5451 that range. See `after-change-functions' for more information."
5452 (let ((inhibit-quit t
))
5453 (when (org-element--cache-active-p)
5454 (org-with-wide-buffer
5458 (bottom (save-excursion (goto-char end
) (line-end-position))))
5459 (org-with-limited-levels
5461 ;; Determine if modified area needs to be extended,
5462 ;; according to both previous and current state. We make
5463 ;; a special case for headline editing: if a headline is
5464 ;; modified but not removed, do not extend.
5465 (when (let ((previous-state org-element--cache-change-warning
)
5467 (concat "\\(" org-outline-regexp-bol
"\\)" "\\|"
5468 org-element--cache-closing-line
"\\|"
5469 org-element--cache-opening-line
))
5470 (case-fold-search t
))
5471 (cond ((eq previous-state t
))
5472 ((not (re-search-forward sensitive-re bottom t
))
5473 (eq previous-state
'headline
))
5474 ((match-beginning 1)
5475 (or (not (eq previous-state
'headline
))
5476 (and (progn (goto-char bottom
)
5478 sensitive-re
(match-end 1) t
))
5479 (not (match-beginning 1)))))
5481 ;; Effectively extend modified area.
5482 (setq top
(progn (goto-char top
)
5483 (when (outline-previous-heading) (forward-line))
5485 (setq bottom
(progn (goto-char bottom
)
5486 (if (outline-next-heading) (1- (point))
5488 ;; Store synchronization request.
5489 (let ((offset (- end beg pre
)))
5490 (org-element--cache-submit-request top
(- bottom offset
) offset
))))
5491 ;; Activate a timer to process the request during idle time.
5492 (org-element--cache-set-timer (current-buffer)))))
5494 (defun org-element--cache-submit-request (beg end offset
)
5495 "Submit a new cache synchronization request for current buffer.
5496 BEG and END are buffer positions delimiting the minimal area
5497 where cache data should be removed. OFFSET is the size of the
5498 change, as an integer."
5499 ;; Make sure buffer positions in cache are correct until END. This
5500 ;; also ensures that pending cache requests have their phases
5501 ;; properly ordered. We need to provide OFFSET as optional
5502 ;; parameter since current modifications are not known yet to the
5503 ;; otherwise correct part of the cache (i.e, before the first
5505 (org-element--cache-sync (current-buffer) end offset
)
5506 (let ((first-element
5507 ;; Find the position of the first element in cache to remove.
5509 ;; Partially modified elements will be removed during request
5510 ;; processing. As an exception, greater elements around the
5511 ;; changes that are robust to contents modifications are
5514 ;; We look just before BEG because an element ending at BEG
5515 ;; needs to be removed too.
5516 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5517 (before (car elements
))
5518 (after (cdr elements
)))
5519 (if (not before
) after
5521 (while (setq up
(org-element-property :parent up
))
5522 (if (and (memq (org-element-type up
)
5524 drawer dynamic-block inlinetask
5525 property-drawer quote-block special-block
))
5526 (<= (org-element-property :contents-begin up
) beg
)
5527 (> (org-element-property :contents-end up
) end
))
5528 ;; UP is a greater element that is wrapped around
5529 ;; the changes. We only need to extend its
5530 ;; ending boundaries and those of all its
5533 (org-element--cache-shift-positions
5534 up offset
'(:contents-end
:end
))
5535 (setq up
(org-element-property :parent up
)))
5537 ;; We're at top level element containing ELEMENT: if
5538 ;; it's altered by buffer modifications, it is first
5539 ;; element in cache to be removed. Otherwise, that
5540 ;; first element is the following one.
5541 (if (< (org-element-property :end before
) beg
) after before
))))))
5543 ;; Changes happened before the first known element. Shift the
5544 ;; rest of the cache.
5545 ((and first-element
(> (org-element-property :begin first-element
) end
))
5546 (push (vector (org-element--cache-key first-element
) nil nil offset nil
2)
5547 org-element--cache-sync-requests
))
5548 ;; There is at least an element to remove. Find position past
5549 ;; every element containing END.
5551 (if (> (org-element-property :end first-element
) end
)
5552 (setq end
(org-element-property :end first-element
))
5553 (let ((element (org-element--cache-find end
)))
5554 (setq end
(org-element-property :end element
))
5556 (while (and (setq up
(org-element-property :parent up
))
5557 (>= (org-element-property :begin up
) beg
))
5558 (setq end
(org-element-property :end up
))))))
5559 (push (vector (org-element--cache-key first-element
)
5560 (org-element-property :begin first-element
)
5562 org-element--cache-sync-requests
))
5563 ;; No element to remove. No need to re-parent either. Simply
5564 ;; shift additional elements, if any, by OFFSET.
5565 (org-element--cache-sync-requests
5566 (incf (aref (car org-element--cache-sync-requests
) 2) offset
)))))
5569 ;;;; Public Functions
5572 (defun org-element-cache-reset (&optional all
)
5573 "Reset cache in current buffer.
5574 When optional argument ALL is non-nil, reset cache in all Org
5577 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5578 (with-current-buffer buffer
5579 (when (org-element--cache-active-p)
5580 (org-set-local 'org-element--cache
5581 (avl-tree-create #'org-element--cache-compare
))
5582 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5583 (org-set-local 'org-element--cache-sync-keys
5584 (make-hash-table :weakness
'key
:test
#'eq
))
5585 (org-set-local 'org-element--cache-change-warning nil
)
5586 (org-set-local 'org-element--cache-sync-requests nil
)
5587 (org-set-local 'org-element--cache-sync-timer nil
)
5588 (add-hook 'before-change-functions
5589 #'org-element--cache-before-change nil t
)
5590 (add-hook 'after-change-functions
5591 #'org-element--cache-after-change nil t
)))))
5594 (defun org-element-cache-refresh (pos)
5595 "Refresh cache at position POS."
5596 (when (org-element--cache-active-p)
5597 (org-element--cache-sync (current-buffer) pos
)
5598 (org-element--cache-submit-request pos pos
0)
5599 (org-element--cache-set-timer (current-buffer))))
5605 ;; The first move is to implement a way to obtain the smallest element
5606 ;; containing point. This is the job of `org-element-at-point'. It
5607 ;; basically jumps back to the beginning of section containing point
5608 ;; and proceed, one element after the other, with
5609 ;; `org-element--current-element' until the container is found. Note:
5610 ;; When using `org-element-at-point', secondary values are never
5611 ;; parsed since the function focuses on elements, not on objects.
5613 ;; At a deeper level, `org-element-context' lists all elements and
5614 ;; objects containing point.
5616 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5617 ;; internally by navigation and manipulation tools.
5621 (defun org-element-at-point ()
5622 "Determine closest element around point.
5624 Return value is a list like (TYPE PROPS) where TYPE is the type
5625 of the element and PROPS a plist of properties associated to the
5628 Possible types are defined in `org-element-all-elements'.
5629 Properties depend on element or object type, but always include
5630 `:begin', `:end', `:parent' and `:post-blank' properties.
5632 As a special case, if point is at the very beginning of the first
5633 item in a list or sub-list, returned element will be that list
5634 instead of the item. Likewise, if point is at the beginning of
5635 the first row of a table, returned element will be the table
5636 instead of the first row.
5638 When point is at the end of the buffer, return the innermost
5639 element ending there."
5640 (org-with-wide-buffer
5641 (let ((origin (point)))
5643 (skip-chars-backward " \r\t\n")
5645 ;; Within blank lines at the beginning of buffer, return nil.
5647 ;; Within blank lines right after a headline, return that
5649 ((org-with-limited-levels (org-at-heading-p))
5651 (org-element-headline-parser (point-max) t
))
5652 ;; Otherwise parse until we find element containing ORIGIN.
5654 (when (org-element--cache-active-p)
5655 (if (not org-element--cache
) (org-element-cache-reset)
5656 (org-element--cache-sync (current-buffer) origin
)))
5657 (org-element--parse-to origin
))))))
5660 (defun org-element-context (&optional element
)
5661 "Return smallest element or object around point.
5663 Return value is a list like (TYPE PROPS) where TYPE is the type
5664 of the element or object and PROPS a plist of properties
5667 Possible types are defined in `org-element-all-elements' and
5668 `org-element-all-objects'. Properties depend on element or
5669 object type, but always include `:begin', `:end', `:parent' and
5672 As a special case, if point is right after an object and not at
5673 the beginning of any other object, return that object.
5675 Optional argument ELEMENT, when non-nil, is the closest element
5676 containing point, as returned by `org-element-at-point'.
5677 Providing it allows for quicker computation."
5678 (catch 'objects-forbidden
5679 (org-with-wide-buffer
5680 (let* ((pos (point))
5681 (element (or element
(org-element-at-point)))
5682 (type (org-element-type element
)))
5683 ;; If point is inside an element containing objects or
5684 ;; a secondary string, narrow buffer to the container and
5685 ;; proceed with parsing. Otherwise, return ELEMENT.
5687 ;; At a parsed affiliated keyword, check if we're inside main
5689 ((let ((post (org-element-property :post-affiliated element
)))
5690 (and post
(< pos post
)))
5692 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5694 ((not (member-ignore-case (match-string 1)
5695 org-element-parsed-keywords
))
5696 (throw 'objects-forbidden element
))
5697 ((< (match-end 0) pos
)
5698 (narrow-to-region (match-end 0) (line-end-position)))
5699 ((and (match-beginning 2)
5700 (>= pos
(match-beginning 2))
5701 (< pos
(match-end 2)))
5702 (narrow-to-region (match-beginning 2) (match-end 2)))
5703 (t (throw 'objects-forbidden element
)))
5704 ;; Also change type to retrieve correct restrictions.
5705 (setq type
'keyword
))
5706 ;; At an item, objects can only be located within tag, if any.
5708 (let ((tag (org-element-property :tag element
)))
5709 (if (not tag
) (throw 'objects-forbidden element
)
5711 (search-forward tag
(line-end-position))
5712 (goto-char (match-beginning 0))
5713 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5714 (narrow-to-region (point) (match-end 0))
5715 (throw 'objects-forbidden element
)))))
5716 ;; At an headline or inlinetask, objects are in title.
5717 ((memq type
'(headline inlinetask
))
5718 (goto-char (org-element-property :begin element
))
5719 (skip-chars-forward "*")
5720 (if (and (> pos
(point)) (< pos
(line-end-position)))
5721 (narrow-to-region (point) (line-end-position))
5722 (throw 'objects-forbidden element
)))
5723 ;; At a paragraph, a table-row or a verse block, objects are
5724 ;; located within their contents.
5725 ((memq type
'(paragraph table-row verse-block
))
5726 (let ((cbeg (org-element-property :contents-begin element
))
5727 (cend (org-element-property :contents-end element
)))
5728 ;; CBEG is nil for table rules.
5729 (if (and cbeg cend
(>= pos cbeg
)
5730 (or (< pos cend
) (and (= pos cend
) (eobp))))
5731 (narrow-to-region cbeg cend
)
5732 (throw 'objects-forbidden element
))))
5733 ;; At a parsed keyword, objects are located within value.
5735 (if (not (member (org-element-property :key element
)
5736 org-element-document-properties
))
5737 (throw 'objects-forbidden element
)
5739 (search-forward ":")
5740 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5741 (narrow-to-region (point) (line-end-position))
5742 (throw 'objects-forbidden element
))))
5743 ;; At a planning line, if point is at a timestamp, return it,
5744 ;; otherwise, return element.
5745 ((eq type
'planning
)
5746 (dolist (p '(:closed
:deadline
:scheduled
))
5747 (let ((timestamp (org-element-property p element
)))
5748 (when (and timestamp
5749 (<= (org-element-property :begin timestamp
) pos
)
5750 (> (org-element-property :end timestamp
) pos
))
5751 (throw 'objects-forbidden timestamp
))))
5752 ;; All other locations cannot contain objects: bail out.
5753 (throw 'objects-forbidden element
))
5754 (t (throw 'objects-forbidden element
)))
5755 (goto-char (point-min))
5756 (let ((restriction (org-element-restriction type
))
5758 (cache (cond ((not (org-element--cache-active-p)) nil
)
5759 (org-element--cache-objects
5760 (gethash element org-element--cache-objects
))
5761 (t (org-element-cache-reset) nil
)))
5762 next object-data last
)
5766 ;; When entering PARENT for the first time, get list
5767 ;; of objects within known so far. Store it in
5770 (let ((data (assq parent cache
)))
5771 (if data
(setq object-data data
)
5772 (push (setq object-data
(list parent nil
)) cache
))))
5773 ;; Find NEXT object for analysis.
5775 ;; If NEXT is non-nil, we already exhausted the
5776 ;; cache so we can parse buffer to find the object
5778 (if next
(setq next
(org-element--object-lex restriction
))
5779 ;; Otherwise, check if cache can help us.
5780 (let ((objects (cddr object-data
))
5781 (completep (nth 1 object-data
)))
5783 ((and (not objects
) completep
) (throw 'exit parent
))
5785 (setq next
(org-element--object-lex restriction
)))
5788 (org-element-property :end
(car objects
))))
5789 (if (>= cache-limit pos
)
5790 ;; Cache contains the information needed.
5791 (dolist (object objects
(throw 'exit parent
))
5792 (when (<= (org-element-property :begin object
)
5794 (if (>= (org-element-property :end object
)
5796 (throw 'found
(setq next object
))
5797 (throw 'exit parent
))))
5798 (goto-char cache-limit
)
5800 (org-element--object-lex restriction
))))))))
5801 ;; If we have a new object to analyze, store it in
5802 ;; cache. Otherwise record that there is nothing
5803 ;; more to parse in this element at this depth.
5805 (progn (org-element-put-property next
:parent parent
)
5806 (push next
(cddr object-data
)))
5807 (setcar (cdr object-data
) t
)))
5808 ;; Process NEXT, if any, in order to know if we need
5809 ;; to skip it, return it or move into it.
5810 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5811 (throw 'exit
(or last parent
))
5812 (let ((end (org-element-property :end next
))
5813 (cbeg (org-element-property :contents-begin next
))
5814 (cend (org-element-property :contents-end next
)))
5816 ;; Skip objects ending before point. Also skip
5817 ;; objects ending at point unless it is also the
5818 ;; end of buffer, since we want to return the
5819 ;; innermost object.
5820 ((and (<= end pos
) (/= (point-max) end
))
5822 ;; For convenience, when object ends at POS,
5823 ;; without any space, store it in LAST, as we
5824 ;; will return it if no object starts here.
5825 (when (and (= end pos
)
5826 (not (memq (char-before) '(?\s ?
\t))))
5828 ;; If POS is within a container object, move
5829 ;; into that object.
5833 ;; At contents' end, if there is no
5834 ;; space before point, also move into
5835 ;; object, for consistency with
5836 ;; convenience feature above.
5838 (or (= (point-max) pos
)
5839 (not (memq (char-before pos
)
5842 (narrow-to-region (point) cend
)
5844 restriction
(org-element-restriction next
)
5847 ;; Otherwise, return NEXT.
5848 (t (throw 'exit next
)))))))
5849 ;; Store results in cache, if applicable.
5850 (org-element--cache-put element cache
)))))))
5852 (defun org-element-nested-p (elem-A elem-B
)
5853 "Non-nil when elements ELEM-A and ELEM-B are nested."
5854 (let ((beg-A (org-element-property :begin elem-A
))
5855 (beg-B (org-element-property :begin elem-B
))
5856 (end-A (org-element-property :end elem-A
))
5857 (end-B (org-element-property :end elem-B
)))
5858 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5859 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5861 (defun org-element-swap-A-B (elem-A elem-B
)
5862 "Swap elements ELEM-A and ELEM-B.
5863 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5865 (goto-char (org-element-property :begin elem-A
))
5866 ;; There are two special cases when an element doesn't start at bol:
5867 ;; the first paragraph in an item or in a footnote definition.
5868 (let ((specialp (not (bolp))))
5869 ;; Only a paragraph without any affiliated keyword can be moved at
5870 ;; ELEM-A position in such a situation. Note that the case of
5871 ;; a footnote definition is impossible: it cannot contain two
5872 ;; paragraphs in a row because it cannot contain a blank line.
5874 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5875 (/= (org-element-property :begin elem-B
)
5876 (org-element-property :contents-begin elem-B
))))
5877 (error "Cannot swap elements"))
5878 ;; In a special situation, ELEM-A will have no indentation. We'll
5879 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5880 (let* ((ind-B (when specialp
5881 (goto-char (org-element-property :begin elem-B
))
5882 (org-get-indentation)))
5883 (beg-A (org-element-property :begin elem-A
))
5884 (end-A (save-excursion
5885 (goto-char (org-element-property :end elem-A
))
5886 (skip-chars-backward " \r\t\n")
5888 (beg-B (org-element-property :begin elem-B
))
5889 (end-B (save-excursion
5890 (goto-char (org-element-property :end elem-B
))
5891 (skip-chars-backward " \r\t\n")
5893 ;; Store overlays responsible for visibility status. We
5894 ;; also need to store their boundaries as they will be
5895 ;; removed from buffer.
5898 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5899 (overlays-in beg-A end-A
))
5900 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5901 (overlays-in beg-B end-B
))))
5903 (body-A (buffer-substring beg-A end-A
))
5904 (body-B (delete-and-extract-region beg-B end-B
)))
5907 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5908 (org-indent-to-column ind-B
))
5910 ;; Restore ex ELEM-A overlays.
5911 (let ((offset (- beg-B beg-A
)))
5914 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5917 (delete-region beg-A end-A
)
5919 ;; Restore ex ELEM-B overlays.
5922 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5924 (goto-char (org-element-property :end elem-B
)))))
5926 (defun org-element-remove-indentation (s &optional n
)
5927 "Remove maximum common indentation in string S and return it.
5928 When optional argument N is a positive integer, remove exactly
5929 that much characters from indentation, if possible, or return
5930 S as-is otherwise. Unlike to `org-remove-indentation', this
5931 function doesn't call `untabify' on S."
5935 (goto-char (point-min))
5936 ;; Find maximum common indentation, if not specified.
5938 (let ((min-ind (point-max)))
5940 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5941 (let ((ind (1- (current-column))))
5942 (if (zerop ind
) (throw 'exit s
)
5943 (setq min-ind
(min min-ind ind
))))))
5946 ;; Remove exactly N indentation, but give up if not possible.
5948 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5949 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5950 ((< ind n
) (throw 'exit s
))
5951 (t (org-indent-line-to (- ind n
))))
5957 (provide 'org-element
)
5960 ;; generated-autoload-file: "org-loaddefs.el"
5963 ;;; org-element.el ends here