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', `fixed-width',
49 ;; `horizontal-rule', `keyword', `latex-environment', `node-property',
50 ;; `paragraph', `planning', `src-block', `table', `table-row' and
51 ;; `verse-block'. Among them, `paragraph' and `verse-block' types can
52 ;; contain Org objects and plain text.
54 ;; Objects are related to document's contents. Some of them are
55 ;; recursive. Associated types are of the following: `bold', `code',
56 ;; `entity', `export-snippet', `footnote-reference',
57 ;; `inline-babel-call', `inline-src-block', `italic',
58 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
59 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
60 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
62 ;; Some elements also have special properties whose value can hold
63 ;; objects themselves (e.g. an item tag or a headline name). Such
64 ;; values are called "secondary strings". Any object belongs to
65 ;; either an element or a secondary string.
67 ;; Notwithstanding affiliated keywords, each greater element, element
68 ;; and object has a fixed set of properties attached to it. Among
69 ;; them, four are shared by all types: `:begin' and `:end', which
70 ;; refer to the beginning and ending buffer positions of the
71 ;; considered element or object, `:post-blank', which holds the number
72 ;; of blank lines, or white spaces, at its end and `:parent' which
73 ;; refers to the element or object containing it. Greater elements,
74 ;; elements and objects containing objects will also have
75 ;; `:contents-begin' and `:contents-end' properties to delimit
76 ;; contents. Eventually, All elements have a `:post-affiliated'
77 ;; property referring to the buffer position after all affiliated
78 ;; keywords, if any, or to their beginning position otherwise.
80 ;; At the lowest level, a `:parent' property is also attached to any
81 ;; string, as a text property.
83 ;; Lisp-wise, an element or an object can be represented as a list.
84 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
85 ;; TYPE is a symbol describing the Org element or object.
86 ;; PROPERTIES is the property list attached to it. See docstring of
87 ;; appropriate parsing function to get an exhaustive
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 fixed-width footnote-definition
177 headline horizontal-rule inlinetask item keyword
178 latex-environment node-property paragraph plain-list
179 planning property-drawer quote-block section special-block
180 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 footnote-reference italic link subscript radio-target strike-through
198 superscript table-cell underline
)
199 "List of recursive object types.")
201 (defconst 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 "Alist between element types and location of secondary value.")
349 ;;; Accessors and Setters
351 ;; Provide four accessors: `org-element-type', `org-element-property'
352 ;; `org-element-contents' and `org-element-restriction'.
354 ;; Setter functions allow to modify elements by side effect. There is
355 ;; `org-element-put-property', `org-element-set-contents'. These
356 ;; low-level functions are useful to build a parse tree.
358 ;; `org-element-adopt-element', `org-element-set-element',
359 ;; `org-element-extract-element' and `org-element-insert-before' are
360 ;; high-level functions useful to modify a parse tree.
362 ;; `org-element-secondary-p' is a predicate used to know if a given
363 ;; object belongs to a secondary string.
365 (defsubst org-element-type
(element)
366 "Return type of ELEMENT.
368 The function returns the type of the element or object provided.
369 It can also return the following special value:
370 `plain-text' for a string
371 `org-data' for a complete document
372 nil in any other case."
374 ((not (consp element
)) (and (stringp element
) 'plain-text
))
375 ((symbolp (car element
)) (car element
))))
377 (defsubst org-element-property
(property element
)
378 "Extract the value from the PROPERTY of an ELEMENT."
379 (if (stringp element
) (get-text-property 0 property element
)
380 (plist-get (nth 1 element
) property
)))
382 (defsubst org-element-contents
(element)
383 "Extract contents from an ELEMENT."
384 (cond ((not (consp element
)) nil
)
385 ((symbolp (car element
)) (nthcdr 2 element
))
388 (defsubst org-element-restriction
(element)
389 "Return restriction associated to ELEMENT.
390 ELEMENT can be an element, an object or a symbol representing an
391 element or object type."
392 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
393 org-element-object-restrictions
)))
395 (defsubst org-element-put-property
(element property value
)
396 "In ELEMENT set PROPERTY to VALUE.
397 Return modified element."
398 (if (stringp element
) (org-add-props element nil property value
)
399 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
402 (defsubst org-element-set-contents
(element &rest contents
)
403 "Set ELEMENT contents to CONTENTS.
404 Return modified element."
405 (cond ((not element
) (list contents
))
406 ((not (symbolp (car element
))) contents
)
407 ((cdr element
) (setcdr (cdr element
) contents
))
408 (t (nconc element contents
))))
410 (defun org-element-secondary-p (object)
411 "Non-nil when OBJECT belongs to a secondary string.
412 Return value is the property name, as a keyword, or nil."
413 (let* ((parent (org-element-property :parent object
))
414 (property (cdr (assq (org-element-type parent
)
415 org-element-secondary-value-alist
))))
417 (memq object
(org-element-property property parent
))
420 (defsubst org-element-adopt-elements
(parent &rest children
)
421 "Append elements to the contents of another element.
423 PARENT is an element or object. CHILDREN can be elements,
424 objects, or a strings.
426 The function takes care of setting `:parent' property for CHILD.
427 Return parent element."
428 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
429 ;; string: parent is the list itself.
430 (mapc (lambda (child)
431 (org-element-put-property child
:parent
(or parent children
)))
433 ;; Add CHILDREN at the end of PARENT contents.
435 (apply 'org-element-set-contents
437 (nconc (org-element-contents parent
) children
)))
438 ;; Return modified PARENT element.
439 (or parent children
))
441 (defun org-element-extract-element (element)
442 "Extract ELEMENT from parse tree.
443 Remove element from the parse tree by side-effect, and return it
444 with its `:parent' property stripped out."
445 (let ((parent (org-element-property :parent element
))
446 (secondary (org-element-secondary-p element
)))
448 (org-element-put-property
450 (delq element
(org-element-property secondary parent
)))
451 (apply #'org-element-set-contents
453 (delq element
(org-element-contents parent
))))
454 ;; Return ELEMENT with its :parent removed.
455 (org-element-put-property element
:parent nil
)))
457 (defun org-element-insert-before (element location
)
458 "Insert ELEMENT before LOCATION in parse tree.
459 LOCATION is an element, object or string within the parse tree.
460 Parse tree is modified by side effect."
461 (let* ((parent (org-element-property :parent location
))
462 (property (org-element-secondary-p location
))
463 (siblings (if property
(org-element-property property parent
)
464 (org-element-contents parent
)))
465 ;; Special case: LOCATION is the first element of an
466 ;; independent secondary string (e.g. :title property). Add
468 (specialp (and (not property
)
470 (eq (car parent
) location
))))
471 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
473 ((or (null siblings
) (eq (car siblings
) location
))
474 (push element siblings
))
475 ((null location
) (nconc siblings
(list element
)))
476 (t (let ((previous (cadr (memq location
(reverse siblings
)))))
478 (error "No location found to insert element")
479 (let ((next (memq previous siblings
)))
480 (setcdr next
(cons element
(cdr next
))))))))
481 ;; Store SIBLINGS at appropriate place in parse tree.
483 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
484 (property (org-element-put-property parent property siblings
))
485 (t (apply #'org-element-set-contents parent siblings
)))
486 ;; Set appropriate :parent property.
487 (org-element-put-property element
:parent parent
)))
489 (defun org-element-set-element (old new
)
490 "Replace element or object OLD with element or object NEW.
491 The function takes care of setting `:parent' property for NEW."
492 ;; Ensure OLD and NEW have the same parent.
493 (org-element-put-property new
:parent
(org-element-property :parent old
))
494 (if (or (memq (org-element-type old
) '(plain-text nil
))
495 (memq (org-element-type new
) '(plain-text nil
)))
496 ;; We cannot replace OLD with NEW since one of them is not an
497 ;; object or element. We take the long path.
498 (progn (org-element-insert-before new old
)
499 (org-element-extract-element old
))
500 ;; Since OLD is going to be changed into NEW by side-effect, first
501 ;; make sure that every element or object within NEW has OLD as
503 (dolist (blob (org-element-contents new
))
504 (org-element-put-property blob
:parent old
))
505 ;; Transfer contents.
506 (apply #'org-element-set-contents old
(org-element-contents new
))
507 ;; Overwrite OLD's properties with NEW's.
508 (setcar (cdr old
) (nth 1 new
))
510 (setcar old
(car new
))))
516 ;; For each greater element type, we define a parser and an
519 ;; A parser returns the element or object as the list described above.
520 ;; Most of them accepts no argument. Though, exceptions exist. Hence
521 ;; every element containing a secondary string (see
522 ;; `org-element-secondary-value-alist') will accept an optional
523 ;; argument to toggle parsing of that secondary string. Moreover,
524 ;; `item' parser requires current list's structure as its first
527 ;; An interpreter accepts two arguments: the list representation of
528 ;; the element or object, and its contents. The latter may be nil,
529 ;; depending on the element or object considered. It returns the
530 ;; appropriate Org syntax, as a string.
532 ;; Parsing functions must follow the naming convention:
533 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
534 ;; defined in `org-element-greater-elements'.
536 ;; Similarly, interpreting functions must follow the naming
537 ;; convention: org-element-TYPE-interpreter.
539 ;; With the exception of `headline' and `item' types, greater elements
540 ;; cannot contain other greater elements of their own type.
542 ;; Beside implementing a parser and an interpreter, adding a new
543 ;; greater element requires to tweak `org-element--current-element'.
544 ;; Moreover, the newly defined type must be added to both
545 ;; `org-element-all-elements' and `org-element-greater-elements'.
550 (defun org-element-center-block-parser (limit affiliated
)
551 "Parse a center block.
553 LIMIT bounds the search. AFFILIATED is a list of which CAR is
554 the buffer position at the beginning of the first affiliated
555 keyword and CDR is a plist of affiliated keywords along with
558 Return a list whose CAR is `center-block' and CDR is a plist
559 containing `:begin', `:end', `:contents-begin', `:contents-end',
560 `:post-blank' and `:post-affiliated' keywords.
562 Assume point is at the beginning of the block."
563 (let ((case-fold-search t
))
564 (if (not (save-excursion
565 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
566 ;; Incomplete block: parse it as a paragraph.
567 (org-element-paragraph-parser limit affiliated
)
568 (let ((block-end-line (match-beginning 0)))
569 (let* ((begin (car affiliated
))
570 (post-affiliated (point))
571 ;; Empty blocks have no contents.
572 (contents-begin (progn (forward-line)
573 (and (< (point) block-end-line
)
575 (contents-end (and contents-begin block-end-line
))
576 (pos-before-blank (progn (goto-char block-end-line
)
580 (skip-chars-forward " \r\t\n" limit
)
581 (if (eobp) (point) (line-beginning-position)))))
586 :contents-begin contents-begin
587 :contents-end contents-end
588 :post-blank
(count-lines pos-before-blank end
)
589 :post-affiliated post-affiliated
)
590 (cdr affiliated
))))))))
592 (defun org-element-center-block-interpreter (center-block contents
)
593 "Interpret CENTER-BLOCK element as Org syntax.
594 CONTENTS is the contents of the element."
595 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
600 (defun org-element-drawer-parser (limit affiliated
)
603 LIMIT bounds the search. AFFILIATED is a list of which CAR is
604 the buffer position at the beginning of the first affiliated
605 keyword and CDR is a plist of affiliated keywords along with
608 Return a list whose CAR is `drawer' and CDR is a plist containing
609 `:drawer-name', `:begin', `:end', `:contents-begin',
610 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
612 Assume point is at beginning of drawer."
613 (let ((case-fold-search t
))
614 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
615 ;; Incomplete drawer: parse it as a paragraph.
616 (org-element-paragraph-parser limit affiliated
)
618 (let* ((drawer-end-line (match-beginning 0))
619 (name (progn (looking-at org-drawer-regexp
)
620 (org-match-string-no-properties 1)))
621 (begin (car affiliated
))
622 (post-affiliated (point))
623 ;; Empty drawers have no contents.
624 (contents-begin (progn (forward-line)
625 (and (< (point) drawer-end-line
)
627 (contents-end (and contents-begin drawer-end-line
))
628 (pos-before-blank (progn (goto-char drawer-end-line
)
631 (end (progn (skip-chars-forward " \r\t\n" limit
)
632 (if (eobp) (point) (line-beginning-position)))))
638 :contents-begin contents-begin
639 :contents-end contents-end
640 :post-blank
(count-lines pos-before-blank end
)
641 :post-affiliated post-affiliated
)
642 (cdr affiliated
))))))))
644 (defun org-element-drawer-interpreter (drawer contents
)
645 "Interpret DRAWER element as Org syntax.
646 CONTENTS is the contents of the element."
647 (format ":%s:\n%s:END:"
648 (org-element-property :drawer-name drawer
)
654 (defun org-element-dynamic-block-parser (limit affiliated
)
655 "Parse a dynamic block.
657 LIMIT bounds the search. AFFILIATED is a list of which CAR is
658 the buffer position at the beginning of the first affiliated
659 keyword and CDR is a plist of affiliated keywords along with
662 Return a list whose CAR is `dynamic-block' and CDR is a plist
663 containing `:block-name', `:begin', `:end', `:contents-begin',
664 `:contents-end', `:arguments', `:post-blank' and
665 `:post-affiliated' keywords.
667 Assume point is at beginning of dynamic block."
668 (let ((case-fold-search t
))
669 (if (not (save-excursion
670 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
671 ;; Incomplete block: parse it as a paragraph.
672 (org-element-paragraph-parser limit affiliated
)
673 (let ((block-end-line (match-beginning 0)))
675 (let* ((name (progn (looking-at org-dblock-start-re
)
676 (org-match-string-no-properties 1)))
677 (arguments (org-match-string-no-properties 3))
678 (begin (car affiliated
))
679 (post-affiliated (point))
680 ;; Empty blocks have no contents.
681 (contents-begin (progn (forward-line)
682 (and (< (point) block-end-line
)
684 (contents-end (and contents-begin block-end-line
))
685 (pos-before-blank (progn (goto-char block-end-line
)
688 (end (progn (skip-chars-forward " \r\t\n" limit
)
689 (if (eobp) (point) (line-beginning-position)))))
696 :contents-begin contents-begin
697 :contents-end contents-end
698 :post-blank
(count-lines pos-before-blank end
)
699 :post-affiliated post-affiliated
)
700 (cdr affiliated
)))))))))
702 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
703 "Interpret DYNAMIC-BLOCK element as Org syntax.
704 CONTENTS is the contents of the element."
705 (format "#+BEGIN: %s%s\n%s#+END:"
706 (org-element-property :block-name dynamic-block
)
707 (let ((args (org-element-property :arguments dynamic-block
)))
708 (and args
(concat " " args
)))
712 ;;;; Footnote Definition
714 (defun org-element-footnote-definition-parser (limit affiliated
)
715 "Parse a footnote definition.
717 LIMIT bounds the search. AFFILIATED is a list of which CAR is
718 the buffer position at the beginning of the first affiliated
719 keyword and CDR is a plist of affiliated keywords along with
722 Return a list whose CAR is `footnote-definition' and CDR is
723 a plist containing `:label', `:begin' `:end', `:contents-begin',
724 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
726 Assume point is at the beginning of the footnote definition."
728 (let* ((label (progn (looking-at org-footnote-definition-re
)
729 (org-match-string-no-properties 1)))
730 (begin (car affiliated
))
731 (post-affiliated (point))
732 (ending (save-excursion
736 (concat org-outline-regexp-bol
"\\|"
737 org-footnote-definition-re
"\\|"
738 "^\\([ \t]*\n\\)\\{2,\\}") limit
'move
))
741 (contents-begin (progn
743 (skip-chars-forward " \r\t\n" ending
)
744 (cond ((= (point) ending
) nil
)
745 ((= (line-beginning-position) begin
) (point))
746 (t (line-beginning-position)))))
747 (contents-end (and contents-begin ending
))
748 (end (progn (goto-char ending
)
749 (skip-chars-forward " \r\t\n" limit
)
750 (if (eobp) (point) (line-beginning-position)))))
751 (list 'footnote-definition
756 :contents-begin contents-begin
757 :contents-end contents-end
758 :post-blank
(count-lines ending end
)
759 :post-affiliated post-affiliated
)
760 (cdr affiliated
))))))
762 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
763 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
764 CONTENTS is the contents of the footnote-definition."
765 (concat (format "[%s]" (org-element-property :label footnote-definition
))
772 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
775 Return a list whose CAR is `headline' and CDR is a plist
776 containing `:raw-value', `:title', `:alt-title', `:begin',
777 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
778 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
779 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
780 `:footnote-section-p', `:post-blank' and `:post-affiliated'
783 The plist also contains any property set in the property drawer,
784 with its name in upper cases and colons added at the
785 beginning (e.g., `:CUSTOM_ID').
787 LIMIT is a buffer position bounding the search.
789 When RAW-SECONDARY-P is non-nil, headline's title will not be
790 parsed as a secondary string, but as a plain string instead.
792 Assume point is at beginning of the headline."
794 (let* ((components (org-heading-components))
795 (level (nth 1 components
))
796 (todo (nth 2 components
))
798 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
799 (tags (let ((raw-tags (nth 5 components
)))
800 (and raw-tags
(org-split-string raw-tags
":"))))
801 (raw-value (or (nth 4 components
) ""))
803 (let ((case-fold-search nil
))
804 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
806 (archivedp (member org-archive-tag tags
))
807 (footnote-section-p (and org-footnote-section
808 (string= org-footnote-section raw-value
)))
810 ;; Find property drawer associated to current headline and
811 ;; extract properties.
813 ;; Upcase property names. It avoids confusion between
814 ;; properties obtained through property drawer and default
815 ;; properties from the parser (e.g. `:end' and :END:)
816 (let ((end (save-excursion
817 (org-with-limited-levels (outline-next-heading))
821 (while (and (null plist
)
822 (re-search-forward org-property-start-re end t
))
823 (let ((drawer (org-element-at-point)))
824 (when (and (eq (org-element-type drawer
) 'property-drawer
)
825 ;; Make sure drawer is not associated
828 (while (and (setq p
(org-element-property
830 (not (eq (org-element-type p
)
833 (let ((end (org-element-property :contents-end drawer
)))
836 (while (< (point) end
)
837 (when (looking-at org-property-re
)
842 (concat ":" (upcase (match-string 2))))
843 (org-match-string-no-properties 3))))
847 ;; Read time properties on the line below the headline.
850 (when (looking-at org-planning-or-clock-line-re
)
851 (let ((end (line-end-position)) plist
)
852 (while (re-search-forward
853 org-keyword-time-not-clock-regexp end t
)
854 (goto-char (match-end 1))
855 (skip-chars-forward " \t")
856 (let ((keyword (match-string 1))
857 (time (org-element-timestamp-parser)))
858 (cond ((equal keyword org-scheduled-string
)
859 (setq plist
(plist-put plist
:scheduled time
)))
860 ((equal keyword org-deadline-string
)
861 (setq plist
(plist-put plist
:deadline time
)))
862 (t (setq plist
(plist-put plist
:closed time
))))))
865 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
866 (pos-after-head (progn (forward-line) (point)))
867 (contents-begin (save-excursion
868 (skip-chars-forward " \r\t\n" end
)
869 (and (/= (point) end
) (line-beginning-position))))
870 (contents-end (and contents-begin
871 (progn (goto-char end
)
872 (skip-chars-backward " \r\t\n")
875 ;; Clean RAW-VALUE from any comment string.
877 (let ((case-fold-search nil
))
879 (replace-regexp-in-string
880 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
883 ;; Clean TAGS from archive tag, if any.
884 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
888 (list :raw-value raw-value
892 (if (not contents-begin
) 0
893 (count-lines pos-after-head contents-begin
))
894 :contents-begin contents-begin
895 :contents-end contents-end
897 :priority
(nth 3 components
)
901 :post-blank
(count-lines
902 (or contents-end pos-after-head
)
904 :footnote-section-p footnote-section-p
906 :commentedp commentedp
907 :post-affiliated begin
)
910 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
912 (org-element-put-property
914 (if raw-secondary-p alt-title
915 (org-element-parse-secondary-string
916 alt-title
(org-element-restriction 'headline
) headline
)))))
917 (org-element-put-property
919 (if raw-secondary-p raw-value
920 (org-element-parse-secondary-string
921 raw-value
(org-element-restriction 'headline
) headline
)))))))
923 (defun org-element-headline-interpreter (headline contents
)
924 "Interpret HEADLINE element as Org syntax.
925 CONTENTS is the contents of the element."
926 (let* ((level (org-element-property :level headline
))
927 (todo (org-element-property :todo-keyword headline
))
928 (priority (org-element-property :priority headline
))
929 (title (org-element-interpret-data
930 (org-element-property :title headline
)))
931 (tags (let ((tag-list (if (org-element-property :archivedp headline
)
932 (cons org-archive-tag
933 (org-element-property :tags headline
))
934 (org-element-property :tags headline
))))
936 (format ":%s:" (mapconcat #'identity tag-list
":")))))
937 (commentedp (org-element-property :commentedp headline
))
938 (pre-blank (or (org-element-property :pre-blank headline
) 0))
940 (concat (make-string (if org-odd-levels-only
(1- (* level
2)) level
)
942 (and todo
(concat " " todo
))
943 (and commentedp
(concat " " org-comment-string
))
944 (and priority
(format " [#%s]" (char-to-string priority
)))
946 (if (and org-footnote-section
947 (org-element-property :footnote-section-p headline
))
955 ((zerop org-tags-column
) (format " %s" tags
))
956 ((< org-tags-column
0)
959 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
964 (make-string (max (- org-tags-column
(length heading
)) 1) ?\s
)
966 (make-string (1+ pre-blank
) ?
\n)
972 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
973 "Parse an inline task.
975 Return a list whose CAR is `inlinetask' and CDR is a plist
976 containing `:title', `:begin', `:end', `:contents-begin' and
977 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
978 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
979 `:closed', `:post-blank' and `:post-affiliated' keywords.
981 The plist also contains any property set in the property drawer,
982 with its name in upper cases and colons added at the
983 beginning (e.g., `:CUSTOM_ID').
985 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
986 title will not be parsed as a secondary string, but as a plain
989 Assume point is at beginning of the inline task."
991 (let* ((begin (point))
992 (components (org-heading-components))
993 (todo (nth 2 components
))
995 (if (member todo org-done-keywords
) 'done
'todo
)))
996 (tags (let ((raw-tags (nth 5 components
)))
997 (and raw-tags
(org-split-string raw-tags
":"))))
998 (raw-value (or (nth 4 components
) ""))
999 (task-end (save-excursion
1001 (and (re-search-forward org-outline-regexp-bol limit t
)
1002 (org-looking-at-p "END[ \t]*$")
1003 (line-beginning-position))))
1005 ;; Read time properties on the line below the inlinetask
1009 (when (progn (forward-line)
1010 (looking-at org-planning-or-clock-line-re
))
1011 (let ((end (line-end-position)) plist
)
1012 (while (re-search-forward
1013 org-keyword-time-not-clock-regexp end t
)
1014 (goto-char (match-end 1))
1015 (skip-chars-forward " \t")
1016 (let ((keyword (match-string 1))
1017 (time (org-element-timestamp-parser)))
1018 (cond ((equal keyword org-scheduled-string
)
1019 (setq plist
(plist-put plist
:scheduled time
)))
1020 ((equal keyword org-deadline-string
)
1021 (setq plist
(plist-put plist
:deadline time
)))
1022 (t (setq plist
(plist-put plist
:closed time
))))))
1024 (contents-begin (progn (forward-line)
1025 (and task-end
(< (point) task-end
) (point))))
1026 (contents-end (and contents-begin task-end
))
1027 (before-blank (if (not task-end
) (point)
1028 (goto-char task-end
)
1031 (end (progn (skip-chars-forward " \r\t\n" limit
)
1032 (if (eobp) (point) (line-beginning-position))))
1034 ;; Find property drawer associated to current inlinetask
1035 ;; and extract properties.
1037 ;; HACK: Calling `org-element-at-point' triggers a parsing
1038 ;; of this inlinetask and, thus, an infloop. To avoid the
1039 ;; problem, we extract contents of the inlinetask and
1040 ;; parse them in a new buffer.
1042 ;; Upcase property names. It avoids confusion between
1043 ;; properties obtained through property drawer and default
1044 ;; properties from the parser (e.g. `:end' and :END:)
1045 (when contents-begin
1046 (let ((contents (buffer-substring contents-begin contents-end
))
1049 (let ((org-inhibit-startup t
)) (org-mode))
1051 (goto-char (point-min))
1052 (while (and (null plist
)
1054 org-property-start-re task-end t
))
1055 (let ((d (org-element-at-point)))
1056 (when (eq (org-element-type d
) 'property-drawer
)
1057 (let ((end (org-element-property :contents-end d
)))
1060 (while (< (point) end
)
1061 (when (looking-at org-property-re
)
1066 (concat ":" (upcase (match-string 2))))
1067 (org-match-string-no-properties 3))))
1068 (forward-line))))))))
1073 (list :raw-value raw-value
1076 :contents-begin contents-begin
1077 :contents-end contents-end
1078 :level
(nth 1 components
)
1079 :priority
(nth 3 components
)
1082 :todo-type todo-type
1083 :post-blank
(count-lines before-blank end
)
1084 :post-affiliated begin
)
1087 (org-element-put-property
1089 (if raw-secondary-p raw-value
1090 (org-element-parse-secondary-string
1092 (org-element-restriction 'inlinetask
)
1095 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1096 "Interpret INLINETASK element as Org syntax.
1097 CONTENTS is the contents of inlinetask."
1098 (let* ((level (org-element-property :level inlinetask
))
1099 (todo (org-element-property :todo-keyword inlinetask
))
1100 (priority (org-element-property :priority inlinetask
))
1101 (title (org-element-interpret-data
1102 (org-element-property :title inlinetask
)))
1103 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1105 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1106 (task (concat (make-string level ?
*)
1107 (and todo
(concat " " todo
))
1109 (format " [#%s]" (char-to-string priority
)))
1110 (and title
(concat " " title
)))))
1115 ((zerop org-tags-column
) (format " %s" tags
))
1116 ((< org-tags-column
0)
1119 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1124 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1126 ;; Prefer degenerate inlinetasks when there are no
1131 (make-string level ?
*) " END")))))
1136 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1139 STRUCT is the structure of the plain list.
1141 Return a list whose CAR is `item' and CDR is a plist containing
1142 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1143 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1144 `:post-affiliated' keywords.
1146 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1147 any, will not be parsed as a secondary string, but as a plain
1150 Assume point is at the beginning of the item."
1153 (looking-at org-list-full-item-re
)
1154 (let* ((begin (point))
1155 (bullet (org-match-string-no-properties 1))
1156 (checkbox (let ((box (org-match-string-no-properties 3)))
1157 (cond ((equal "[ ]" box
) 'off
)
1158 ((equal "[X]" box
) 'on
)
1159 ((equal "[-]" box
) 'trans
))))
1160 (counter (let ((c (org-match-string-no-properties 2)))
1164 ((string-match "[A-Za-z]" c
)
1165 (- (string-to-char (upcase (match-string 0 c
)))
1167 ((string-match "[0-9]+" c
)
1168 (string-to-number (match-string 0 c
)))))))
1169 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1170 (unless (bolp) (forward-line))
1174 ;; Ignore tags in un-ordered lists: they are just
1175 ;; a part of item's body.
1176 (if (and (match-beginning 4)
1177 (save-match-data (string-match "[.)]" bullet
)))
1180 (skip-chars-forward " \r\t\n" limit
)
1181 ;; If first line isn't empty, contents really start
1182 ;; at the text after item's meta-data.
1183 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1184 (contents-end (progn (goto-char end
)
1185 (skip-chars-backward " \r\t\n")
1190 (list :bullet bullet
1193 ;; CONTENTS-BEGIN and CONTENTS-END may be
1194 ;; mixed up in the case of an empty item
1195 ;; separated from the next by a blank line.
1196 ;; Thus ensure the former is always the
1198 :contents-begin
(min contents-begin contents-end
)
1199 :contents-end
(max contents-begin contents-end
)
1203 :post-blank
(count-lines contents-end end
)
1204 :post-affiliated begin
))))
1205 (org-element-put-property
1207 (let ((raw-tag (org-list-get-tag begin struct
)))
1209 (if raw-secondary-p raw-tag
1210 (org-element-parse-secondary-string
1211 raw-tag
(org-element-restriction 'item
) item
))))))))
1213 (defun org-element-item-interpreter (item contents
)
1214 "Interpret ITEM element as Org syntax.
1215 CONTENTS is the contents of the element."
1216 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1217 (org-list-bullet-string
1218 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1219 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1221 (checkbox (org-element-property :checkbox item
))
1222 (counter (org-element-property :counter item
))
1223 (tag (let ((tag (org-element-property :tag item
)))
1224 (and tag
(org-element-interpret-data tag
))))
1225 ;; Compute indentation.
1226 (ind (make-string (length bullet
) 32))
1227 (item-starts-with-par-p
1228 (eq (org-element-type (car (org-element-contents item
)))
1233 (and counter
(format "[@%d] " counter
))
1238 (and tag
(format "%s :: " tag
))
1240 (let ((contents (replace-regexp-in-string
1241 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1242 (if item-starts-with-par-p
(org-trim contents
)
1243 (concat "\n" contents
)))))))
1248 (defun org-element--list-struct (limit)
1249 ;; Return structure of list at point. Internal function. See
1250 ;; `org-list-struct' for details.
1251 (let ((case-fold-search t
)
1253 (item-re (org-item-re))
1254 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1260 ;; At limit: end all items.
1263 (let ((end (progn (skip-chars-backward " \r\t\n")
1266 (dolist (item items
(sort (nconc items struct
)
1267 'car-less-than-car
))
1268 (setcar (nthcdr 6 item
) end
)))))
1269 ;; At list end: end all items.
1270 ((looking-at org-list-end-re
)
1271 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1272 'car-less-than-car
))
1273 (setcar (nthcdr 6 item
) (point)))))
1274 ;; At a new item: end previous sibling.
1275 ((looking-at item-re
)
1276 (let ((ind (save-excursion (skip-chars-forward " \t")
1278 (setq top-ind
(min top-ind ind
))
1279 (while (and items
(<= ind
(nth 1 (car items
))))
1280 (let ((item (pop items
)))
1281 (setcar (nthcdr 6 item
) (point))
1282 (push item struct
)))
1283 (push (progn (looking-at org-list-full-item-re
)
1284 (let ((bullet (match-string-no-properties 1)))
1288 (match-string-no-properties 2) ; counter
1289 (match-string-no-properties 3) ; checkbox
1291 (and (save-match-data
1292 (string-match "[-+*]" bullet
))
1293 (match-string-no-properties 4))
1294 ;; Ending position, unknown so far.
1298 ;; Skip empty lines.
1299 ((looking-at "^[ \t]*$") (forward-line))
1300 ;; Skip inline tasks and blank lines along the way.
1301 ((and inlinetask-re
(looking-at inlinetask-re
))
1303 (let ((origin (point)))
1304 (when (re-search-forward inlinetask-re limit t
)
1305 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1306 (goto-char origin
)))))
1307 ;; At some text line. Check if it ends any previous item.
1309 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1310 (when (<= ind top-ind
)
1311 (skip-chars-backward " \r\t\n")
1313 (while (<= ind
(nth 1 (car items
)))
1314 (let ((item (pop items
)))
1315 (setcar (nthcdr 6 item
) (line-beginning-position))
1318 (throw 'exit
(sort struct
'car-less-than-car
))))))
1319 ;; Skip blocks (any type) and drawers contents.
1321 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1323 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1325 ((and (looking-at org-drawer-regexp
)
1326 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1327 (forward-line))))))))
1329 (defun org-element-plain-list-parser (limit affiliated structure
)
1330 "Parse a plain list.
1332 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1333 the buffer position at the beginning of the first affiliated
1334 keyword and CDR is a plist of affiliated keywords along with
1335 their value. STRUCTURE is the structure of the plain list being
1338 Return a list whose CAR is `plain-list' and CDR is a plist
1339 containing `:type', `:begin', `:end', `:contents-begin' and
1340 `:contents-end', `:structure', `:post-blank' and
1341 `:post-affiliated' keywords.
1343 Assume point is at the beginning of the list."
1345 (let* ((struct (or structure
(org-element--list-struct limit
)))
1346 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1347 ((nth 5 (assq (point) struct
)) 'descriptive
)
1349 (contents-begin (point))
1350 (begin (car affiliated
))
1351 (contents-end (let* ((item (assq contents-begin struct
))
1354 (while (and (setq item
(assq pos struct
))
1355 (= (nth 1 item
) ind
))
1356 (setq pos
(nth 6 item
)))
1358 (end (progn (goto-char contents-end
)
1359 (skip-chars-forward " \r\t\n" limit
)
1360 (if (= (point) limit
) limit
(line-beginning-position)))))
1367 :contents-begin contents-begin
1368 :contents-end contents-end
1370 :post-blank
(count-lines contents-end end
)
1371 :post-affiliated contents-begin
)
1372 (cdr affiliated
))))))
1374 (defun org-element-plain-list-interpreter (plain-list contents
)
1375 "Interpret PLAIN-LIST element as Org syntax.
1376 CONTENTS is the contents of the element."
1379 (goto-char (point-min))
1384 ;;;; Property Drawer
1386 (defun org-element-property-drawer-parser (limit affiliated
)
1387 "Parse a property drawer.
1389 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1390 the buffer position at the beginning of the first affiliated
1391 keyword and CDR is a plist of affiliated keywords along with
1394 Return a list whose CAR is `property-drawer' and CDR is a plist
1395 containing `:begin', `:end', `:contents-begin', `:contents-end',
1396 `:post-blank' and `:post-affiliated' keywords.
1398 Assume point is at the beginning of the property drawer."
1400 (let ((case-fold-search t
))
1401 (if (not (save-excursion
1402 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1403 ;; Incomplete drawer: parse it as a paragraph.
1404 (org-element-paragraph-parser limit affiliated
)
1406 (let* ((drawer-end-line (match-beginning 0))
1407 (begin (car affiliated
))
1408 (post-affiliated (point))
1409 (contents-begin (progn (forward-line)
1410 (and (< (point) drawer-end-line
)
1412 (contents-end (and contents-begin drawer-end-line
))
1413 (pos-before-blank (progn (goto-char drawer-end-line
)
1416 (end (progn (skip-chars-forward " \r\t\n" limit
)
1417 (if (eobp) (point) (line-beginning-position)))))
1418 (list 'property-drawer
1422 :contents-begin contents-begin
1423 :contents-end contents-end
1424 :post-blank
(count-lines pos-before-blank end
)
1425 :post-affiliated post-affiliated
)
1426 (cdr affiliated
)))))))))
1428 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1429 "Interpret PROPERTY-DRAWER element as Org syntax.
1430 CONTENTS is the properties within the drawer."
1431 (format ":PROPERTIES:\n%s:END:" contents
))
1436 (defun org-element-quote-block-parser (limit affiliated
)
1437 "Parse a quote block.
1439 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1440 the buffer position at the beginning of the first affiliated
1441 keyword and CDR is a plist of affiliated keywords along with
1444 Return a list whose CAR is `quote-block' and CDR is a plist
1445 containing `:begin', `:end', `:contents-begin', `:contents-end',
1446 `:post-blank' and `:post-affiliated' keywords.
1448 Assume point is at the beginning of the block."
1449 (let ((case-fold-search t
))
1450 (if (not (save-excursion
1451 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1452 ;; Incomplete block: parse it as a paragraph.
1453 (org-element-paragraph-parser limit affiliated
)
1454 (let ((block-end-line (match-beginning 0)))
1456 (let* ((begin (car affiliated
))
1457 (post-affiliated (point))
1458 ;; Empty blocks have no contents.
1459 (contents-begin (progn (forward-line)
1460 (and (< (point) block-end-line
)
1462 (contents-end (and contents-begin block-end-line
))
1463 (pos-before-blank (progn (goto-char block-end-line
)
1466 (end (progn (skip-chars-forward " \r\t\n" limit
)
1467 (if (eobp) (point) (line-beginning-position)))))
1472 :contents-begin contents-begin
1473 :contents-end contents-end
1474 :post-blank
(count-lines pos-before-blank end
)
1475 :post-affiliated post-affiliated
)
1476 (cdr affiliated
)))))))))
1478 (defun org-element-quote-block-interpreter (quote-block contents
)
1479 "Interpret QUOTE-BLOCK element as Org syntax.
1480 CONTENTS is the contents of the element."
1481 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1486 (defun org-element-section-parser (limit)
1489 LIMIT bounds the search.
1491 Return a list whose CAR is `section' and CDR is a plist
1492 containing `:begin', `:end', `:contents-begin', `contents-end',
1493 `:post-blank' and `:post-affiliated' keywords."
1495 ;; Beginning of section is the beginning of the first non-blank
1496 ;; line after previous headline.
1497 (let ((begin (point))
1498 (end (progn (org-with-limited-levels (outline-next-heading))
1500 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1506 :contents-begin begin
1507 :contents-end pos-before-blank
1508 :post-blank
(count-lines pos-before-blank end
)
1509 :post-affiliated begin
)))))
1511 (defun org-element-section-interpreter (section contents
)
1512 "Interpret SECTION element as Org syntax.
1513 CONTENTS is the contents of the element."
1519 (defun org-element-special-block-parser (limit affiliated
)
1520 "Parse a special block.
1522 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1523 the buffer position at the beginning of the first affiliated
1524 keyword and CDR is a plist of affiliated keywords along with
1527 Return a list whose CAR is `special-block' and CDR is a plist
1528 containing `:type', `:raw-value', `:begin', `:end',
1529 `:contents-begin', `:contents-end', `:post-blank' and
1530 `:post-affiliated' keywords.
1532 Assume point is at the beginning of the block."
1533 (let* ((case-fold-search t
)
1534 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1535 (upcase (match-string-no-properties 1)))))
1536 (if (not (save-excursion
1538 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1540 ;; Incomplete block: parse it as a paragraph.
1541 (org-element-paragraph-parser limit affiliated
)
1542 (let ((block-end-line (match-beginning 0)))
1544 (let* ((begin (car affiliated
))
1545 (post-affiliated (point))
1546 ;; Empty blocks have no contents.
1547 (contents-begin (progn (forward-line)
1548 (and (< (point) block-end-line
)
1550 (contents-end (and contents-begin block-end-line
))
1551 (pos-before-blank (progn (goto-char block-end-line
)
1554 (end (progn (skip-chars-forward " \r\t\n" limit
)
1555 (if (eobp) (point) (line-beginning-position)))))
1556 (list 'special-block
1561 (buffer-substring-no-properties
1562 contents-begin contents-end
))
1565 :contents-begin contents-begin
1566 :contents-end contents-end
1567 :post-blank
(count-lines pos-before-blank end
)
1568 :post-affiliated post-affiliated
)
1569 (cdr affiliated
)))))))))
1571 (defun org-element-special-block-interpreter (special-block contents
)
1572 "Interpret SPECIAL-BLOCK element as Org syntax.
1573 CONTENTS is the contents of the element."
1574 (let ((block-type (org-element-property :type special-block
)))
1575 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1581 ;; For each element, a parser and an interpreter are also defined.
1582 ;; Both follow the same naming convention used for greater elements.
1584 ;; Also, as for greater elements, adding a new element type is done
1585 ;; through the following steps: implement a parser and an interpreter,
1586 ;; tweak `org-element--current-element' so that it recognizes the new
1587 ;; type and add that new type to `org-element-all-elements'.
1589 ;; As a special case, when the newly defined type is a block type,
1590 ;; `org-element-block-name-alist' has to be modified accordingly.
1595 (defun org-element-babel-call-parser (limit affiliated
)
1596 "Parse a babel call.
1598 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1599 the buffer position at the beginning of the first affiliated
1600 keyword and CDR is a plist of affiliated keywords along with
1603 Return a list whose CAR is `babel-call' and CDR is a plist
1604 containing `:begin', `:end', `:value', `:post-blank' and
1605 `:post-affiliated' as keywords."
1607 (let ((begin (car affiliated
))
1608 (post-affiliated (point))
1609 (value (progn (let ((case-fold-search t
))
1610 (re-search-forward "call:[ \t]*" nil t
))
1611 (buffer-substring-no-properties (point)
1612 (line-end-position))))
1613 (pos-before-blank (progn (forward-line) (point)))
1614 (end (progn (skip-chars-forward " \r\t\n" limit
)
1615 (if (eobp) (point) (line-beginning-position)))))
1621 :post-blank
(count-lines pos-before-blank end
)
1622 :post-affiliated post-affiliated
)
1623 (cdr affiliated
))))))
1625 (defun org-element-babel-call-interpreter (babel-call contents
)
1626 "Interpret BABEL-CALL element as Org syntax.
1628 (concat "#+CALL: " (org-element-property :value babel-call
)))
1633 (defun org-element-clock-parser (limit)
1636 LIMIT bounds the search.
1638 Return a list whose CAR is `clock' and CDR is a plist containing
1639 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1640 `:post-affiliated' as keywords."
1642 (let* ((case-fold-search nil
)
1644 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1645 (skip-chars-forward " \t")
1646 (org-element-timestamp-parser)))
1647 (duration (and (search-forward " => " (line-end-position) t
)
1648 (progn (skip-chars-forward " \t")
1649 (looking-at "\\(\\S-+\\)[ \t]*$"))
1650 (org-match-string-no-properties 1)))
1651 (status (if duration
'closed
'running
))
1652 (post-blank (let ((before-blank (progn (forward-line) (point))))
1653 (skip-chars-forward " \r\t\n" limit
)
1654 (skip-chars-backward " \t")
1655 (unless (bolp) (end-of-line))
1656 (count-lines before-blank
(point))))
1659 (list :status status
1664 :post-blank post-blank
1665 :post-affiliated begin
)))))
1667 (defun org-element-clock-interpreter (clock contents
)
1668 "Interpret CLOCK element as Org syntax.
1670 (concat org-clock-string
" "
1671 (org-element-timestamp-interpreter
1672 (org-element-property :value clock
) nil
)
1673 (let ((duration (org-element-property :duration clock
)))
1678 (org-split-string duration
":")))))))
1683 (defun org-element-comment-parser (limit affiliated
)
1686 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1687 the buffer position at the beginning of the first affiliated
1688 keyword and CDR is a plist of affiliated keywords along with
1691 Return a list whose CAR is `comment' and CDR is a plist
1692 containing `:begin', `:end', `:value', `:post-blank',
1693 `:post-affiliated' keywords.
1695 Assume point is at comment beginning."
1697 (let* ((begin (car affiliated
))
1698 (post-affiliated (point))
1699 (value (prog2 (looking-at "[ \t]*# ?")
1700 (buffer-substring-no-properties
1701 (match-end 0) (line-end-position))
1704 ;; Get comments ending.
1706 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1707 ;; Accumulate lines without leading hash and first
1712 (buffer-substring-no-properties
1713 (match-end 0) (line-end-position))))
1716 (end (progn (goto-char com-end
)
1717 (skip-chars-forward " \r\t\n" limit
)
1718 (if (eobp) (point) (line-beginning-position)))))
1724 :post-blank
(count-lines com-end end
)
1725 :post-affiliated post-affiliated
)
1726 (cdr affiliated
))))))
1728 (defun org-element-comment-interpreter (comment contents
)
1729 "Interpret COMMENT element as Org syntax.
1731 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1736 (defun org-element-comment-block-parser (limit affiliated
)
1737 "Parse an export block.
1739 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1740 the buffer position at the beginning of the first affiliated
1741 keyword and CDR is a plist of affiliated keywords along with
1744 Return a list whose CAR is `comment-block' and CDR is a plist
1745 containing `:begin', `:end', `:value', `:post-blank' and
1746 `:post-affiliated' keywords.
1748 Assume point is at comment block beginning."
1749 (let ((case-fold-search t
))
1750 (if (not (save-excursion
1751 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1752 ;; Incomplete block: parse it as a paragraph.
1753 (org-element-paragraph-parser limit affiliated
)
1754 (let ((contents-end (match-beginning 0)))
1756 (let* ((begin (car affiliated
))
1757 (post-affiliated (point))
1758 (contents-begin (progn (forward-line) (point)))
1759 (pos-before-blank (progn (goto-char contents-end
)
1762 (end (progn (skip-chars-forward " \r\t\n" limit
)
1763 (if (eobp) (point) (line-beginning-position))))
1764 (value (buffer-substring-no-properties
1765 contents-begin contents-end
)))
1766 (list 'comment-block
1771 :post-blank
(count-lines pos-before-blank end
)
1772 :post-affiliated post-affiliated
)
1773 (cdr affiliated
)))))))))
1775 (defun org-element-comment-block-interpreter (comment-block contents
)
1776 "Interpret COMMENT-BLOCK element as Org syntax.
1778 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1779 (org-element-normalize-string
1780 (org-remove-indentation
1781 (org-element-property :value comment-block
)))))
1786 (defun org-element-diary-sexp-parser (limit affiliated
)
1787 "Parse a diary sexp.
1789 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1790 the buffer position at the beginning of the first affiliated
1791 keyword and CDR is a plist of affiliated keywords along with
1794 Return a list whose CAR is `diary-sexp' and CDR is a plist
1795 containing `:begin', `:end', `:value', `:post-blank' and
1796 `:post-affiliated' keywords."
1798 (let ((begin (car affiliated
))
1799 (post-affiliated (point))
1800 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1801 (org-match-string-no-properties 1)))
1802 (pos-before-blank (progn (forward-line) (point)))
1803 (end (progn (skip-chars-forward " \r\t\n" limit
)
1804 (if (eobp) (point) (line-beginning-position)))))
1810 :post-blank
(count-lines pos-before-blank end
)
1811 :post-affiliated post-affiliated
)
1812 (cdr affiliated
))))))
1814 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1815 "Interpret DIARY-SEXP as Org syntax.
1817 (org-element-property :value diary-sexp
))
1822 (defun org-element-example-block-parser (limit affiliated
)
1823 "Parse an example block.
1825 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1826 the buffer position at the beginning of the first affiliated
1827 keyword and CDR is a plist of affiliated keywords along with
1830 Return a list whose CAR is `example-block' and CDR is a plist
1831 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1832 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1833 `:value', `:post-blank' and `:post-affiliated' keywords."
1834 (let ((case-fold-search t
))
1835 (if (not (save-excursion
1836 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1837 ;; Incomplete block: parse it as a paragraph.
1838 (org-element-paragraph-parser limit affiliated
)
1839 (let ((contents-end (match-beginning 0)))
1843 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1844 (org-match-string-no-properties 1)))
1845 ;; Switches analysis
1847 (cond ((not switches
) nil
)
1848 ((string-match "-n\\>" switches
) 'new
)
1849 ((string-match "+n\\>" switches
) 'continued
)))
1851 (and switches
(string-match "-i\\>" switches
)))
1852 ;; Should labels be retained in (or stripped from) example
1856 (not (string-match "-r\\>" switches
))
1857 (and number-lines
(string-match "-k\\>" switches
))))
1858 ;; What should code-references use - labels or
1863 (not (string-match "-k\\>" switches
)))))
1866 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1867 (match-string 1 switches
)))
1868 ;; Standard block parsing.
1869 (begin (car affiliated
))
1870 (post-affiliated (point))
1871 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1872 (contents-begin (progn (forward-line) (point)))
1873 (value (org-element-remove-indentation
1874 (org-unescape-code-in-string
1875 (buffer-substring-no-properties
1876 contents-begin contents-end
))
1878 (pos-before-blank (progn (goto-char contents-end
)
1881 (end (progn (skip-chars-forward " \r\t\n" limit
)
1882 (if (eobp) (point) (line-beginning-position)))))
1883 (list 'example-block
1889 :number-lines number-lines
1890 :preserve-indent preserve-indent
1891 :retain-labels retain-labels
1892 :use-labels use-labels
1893 :label-fmt label-fmt
1894 :post-blank
(count-lines pos-before-blank end
)
1895 :post-affiliated post-affiliated
)
1896 (cdr affiliated
)))))))))
1898 (defun org-element-example-block-interpreter (example-block contents
)
1899 "Interpret EXAMPLE-BLOCK element as Org syntax.
1901 (let ((switches (org-element-property :switches example-block
))
1902 (value (org-element-property :value example-block
)))
1903 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1904 (org-element-normalize-string
1905 (org-escape-code-in-string
1906 (if (or org-src-preserve-indentation
1907 (org-element-property :preserve-indent example-block
))
1909 (org-element-remove-indentation value
))))
1915 (defun org-element-fixed-width-parser (limit affiliated
)
1916 "Parse a fixed-width section.
1918 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1919 the buffer position at the beginning of the first affiliated
1920 keyword and CDR is a plist of affiliated keywords along with
1923 Return a list whose CAR is `fixed-width' and CDR is a plist
1924 containing `:begin', `:end', `:value', `:post-blank' and
1925 `:post-affiliated' keywords.
1927 Assume point is at the beginning of the fixed-width area."
1929 (let* ((begin (car affiliated
))
1930 (post-affiliated (point))
1934 (while (and (< (point) limit
)
1935 (looking-at "[ \t]*:\\( \\|$\\)"))
1936 ;; Accumulate text without starting colons.
1939 (buffer-substring-no-properties
1940 (match-end 0) (point-at-eol))
1944 (end (progn (skip-chars-forward " \r\t\n" limit
)
1945 (if (eobp) (point) (line-beginning-position)))))
1951 :post-blank
(count-lines end-area end
)
1952 :post-affiliated post-affiliated
)
1953 (cdr affiliated
))))))
1955 (defun org-element-fixed-width-interpreter (fixed-width contents
)
1956 "Interpret FIXED-WIDTH element as Org syntax.
1958 (let ((value (org-element-property :value fixed-width
)))
1960 (replace-regexp-in-string
1962 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
1965 ;;;; Horizontal Rule
1967 (defun org-element-horizontal-rule-parser (limit affiliated
)
1968 "Parse an horizontal rule.
1970 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1971 the buffer position at the beginning of the first affiliated
1972 keyword and CDR is a plist of affiliated keywords along with
1975 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1976 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1979 (let ((begin (car affiliated
))
1980 (post-affiliated (point))
1981 (post-hr (progn (forward-line) (point)))
1982 (end (progn (skip-chars-forward " \r\t\n" limit
)
1983 (if (eobp) (point) (line-beginning-position)))))
1984 (list 'horizontal-rule
1988 :post-blank
(count-lines post-hr end
)
1989 :post-affiliated post-affiliated
)
1990 (cdr affiliated
))))))
1992 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
1993 "Interpret HORIZONTAL-RULE element as Org syntax.
2000 (defun org-element-keyword-parser (limit affiliated
)
2001 "Parse a keyword at point.
2003 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2004 the buffer position at the beginning of the first affiliated
2005 keyword and CDR is a plist of affiliated keywords along with
2008 Return a list whose CAR is `keyword' and CDR is a plist
2009 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2010 `:post-affiliated' keywords."
2012 ;; An orphaned affiliated keyword is considered as a regular
2013 ;; keyword. In this case AFFILIATED is nil, so we take care of
2014 ;; this corner case.
2015 (let ((begin (or (car affiliated
) (point)))
2016 (post-affiliated (point))
2017 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2018 (upcase (org-match-string-no-properties 1))))
2019 (value (org-trim (buffer-substring-no-properties
2020 (match-end 0) (point-at-eol))))
2021 (pos-before-blank (progn (forward-line) (point)))
2022 (end (progn (skip-chars-forward " \r\t\n" limit
)
2023 (if (eobp) (point) (line-beginning-position)))))
2030 :post-blank
(count-lines pos-before-blank end
)
2031 :post-affiliated post-affiliated
)
2032 (cdr affiliated
))))))
2034 (defun org-element-keyword-interpreter (keyword contents
)
2035 "Interpret KEYWORD element as Org syntax.
2038 (org-element-property :key keyword
)
2039 (org-element-property :value keyword
)))
2042 ;;;; Latex Environment
2044 (defconst org-element--latex-begin-environment
2045 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2046 "Regexp matching the beginning of a LaTeX environment.
2047 The environment is captured by the first group.
2049 See also `org-element--latex-end-environment'.")
2051 (defconst org-element--latex-end-environment
2052 "\\\\end{%s}[ \t]*$"
2053 "Format string matching the ending of a LaTeX environment.
2054 See also `org-element--latex-begin-environment'.")
2056 (defun org-element-latex-environment-parser (limit affiliated
)
2057 "Parse a LaTeX environment.
2059 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2060 the buffer position at the beginning of the first affiliated
2061 keyword and CDR is a plist of affiliated keywords along with
2064 Return a list whose CAR is `latex-environment' and CDR is a plist
2065 containing `:begin', `:end', `:value', `:post-blank' and
2066 `:post-affiliated' keywords.
2068 Assume point is at the beginning of the latex environment."
2070 (let ((case-fold-search t
)
2071 (code-begin (point)))
2072 (looking-at org-element--latex-begin-environment
)
2073 (if (not (re-search-forward (format org-element--latex-end-environment
2074 (regexp-quote (match-string 1)))
2076 ;; Incomplete latex environment: parse it as a paragraph.
2077 (org-element-paragraph-parser limit affiliated
)
2078 (let* ((code-end (progn (forward-line) (point)))
2079 (begin (car affiliated
))
2080 (value (buffer-substring-no-properties code-begin code-end
))
2081 (end (progn (skip-chars-forward " \r\t\n" limit
)
2082 (if (eobp) (point) (line-beginning-position)))))
2083 (list 'latex-environment
2088 :post-blank
(count-lines code-end end
)
2089 :post-affiliated code-begin
)
2090 (cdr affiliated
))))))))
2092 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2093 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2095 (org-element-property :value latex-environment
))
2100 (defun org-element-node-property-parser (limit)
2101 "Parse a node-property at point.
2103 LIMIT bounds the search.
2105 Return a list whose CAR is `node-property' and CDR is a plist
2106 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2107 `:post-affiliated' keywords."
2109 (looking-at org-property-re
)
2110 (let ((case-fold-search t
)
2112 (key (org-match-string-no-properties 2))
2113 (value (org-match-string-no-properties 3))
2114 (pos-before-blank (progn (forward-line) (point)))
2115 (end (progn (skip-chars-forward " \r\t\n" limit
)
2116 (if (eobp) (point) (point-at-bol)))))
2117 (list 'node-property
2122 :post-blank
(count-lines pos-before-blank end
)
2123 :post-affiliated begin
)))))
2125 (defun org-element-node-property-interpreter (node-property contents
)
2126 "Interpret NODE-PROPERTY element as Org syntax.
2128 (format org-property-format
2129 (format ":%s:" (org-element-property :key node-property
))
2130 (org-element-property :value node-property
)))
2135 (defun org-element-paragraph-parser (limit affiliated
)
2138 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2139 the buffer position at the beginning of the first affiliated
2140 keyword and CDR is a plist of affiliated keywords along with
2143 Return a list whose CAR is `paragraph' and CDR is a plist
2144 containing `:begin', `:end', `:contents-begin' and
2145 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2147 Assume point is at the beginning of the paragraph."
2149 (let* ((begin (car affiliated
))
2150 (contents-begin (point))
2152 (let ((case-fold-search t
))
2154 (if (not (re-search-forward
2155 org-element-paragraph-separate limit
'm
))
2157 ;; A matching `org-element-paragraph-separate' is not
2158 ;; necessarily the end of the paragraph. In
2159 ;; particular, lines starting with # or : as a first
2160 ;; non-space character are ambiguous. We have to
2161 ;; check if they are valid Org syntax (e.g., not an
2162 ;; incomplete keyword).
2166 ;; There's no ambiguity for other symbols or
2167 ;; empty lines: stop here.
2168 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2169 ;; Stop at valid fixed-width areas.
2170 (looking-at "[ \t]*:\\(?: \\|$\\)")
2172 (and (looking-at org-drawer-regexp
)
2175 "^[ \t]*:END:[ \t]*$" limit t
)))
2176 ;; Stop at valid comments.
2177 (looking-at "[ \t]*#\\(?: \\|$\\)")
2178 ;; Stop at valid dynamic blocks.
2179 (and (looking-at org-dblock-start-re
)
2182 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2183 ;; Stop at valid blocks.
2184 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2187 (format "^[ \t]*#\\+END_%s[ \t]*$"
2189 (org-match-string-no-properties 1)))
2191 ;; Stop at valid latex environments.
2192 (and (looking-at org-element--latex-begin-environment
)
2195 (format org-element--latex-end-environment
2197 (org-match-string-no-properties 1)))
2199 ;; Stop at valid keywords.
2200 (looking-at "[ \t]*#\\+\\S-+:")
2201 ;; Skip everything else.
2205 (re-search-forward org-element-paragraph-separate
2207 (beginning-of-line)))
2208 (if (= (point) limit
) limit
2209 (goto-char (line-beginning-position)))))
2210 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2213 (end (progn (skip-chars-forward " \r\t\n" limit
)
2214 (if (eobp) (point) (line-beginning-position)))))
2219 :contents-begin contents-begin
2220 :contents-end contents-end
2221 :post-blank
(count-lines before-blank end
)
2222 :post-affiliated contents-begin
)
2223 (cdr affiliated
))))))
2225 (defun org-element-paragraph-interpreter (paragraph contents
)
2226 "Interpret PARAGRAPH element as Org syntax.
2227 CONTENTS is the contents of the element."
2233 (defun org-element-planning-parser (limit)
2236 LIMIT bounds the search.
2238 Return a list whose CAR is `planning' and CDR is a plist
2239 containing `:closed', `:deadline', `:scheduled', `:begin',
2240 `:end', `:post-blank' and `:post-affiliated' keywords."
2242 (let* ((case-fold-search nil
)
2244 (post-blank (let ((before-blank (progn (forward-line) (point))))
2245 (skip-chars-forward " \r\t\n" limit
)
2246 (skip-chars-backward " \t")
2247 (unless (bolp) (end-of-line))
2248 (count-lines before-blank
(point))))
2250 closed deadline scheduled
)
2252 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2253 (goto-char (match-end 1))
2254 (skip-chars-forward " \t" end
)
2255 (let ((keyword (match-string 1))
2256 (time (org-element-timestamp-parser)))
2257 (cond ((equal keyword org-closed-string
) (setq closed time
))
2258 ((equal keyword org-deadline-string
) (setq deadline time
))
2259 (t (setq scheduled time
)))))
2261 (list :closed closed
2263 :scheduled scheduled
2266 :post-blank post-blank
2267 :post-affiliated begin
)))))
2269 (defun org-element-planning-interpreter (planning contents
)
2270 "Interpret PLANNING element as Org syntax.
2275 (list (let ((deadline (org-element-property :deadline planning
)))
2277 (concat org-deadline-string
" "
2278 (org-element-timestamp-interpreter deadline nil
))))
2279 (let ((scheduled (org-element-property :scheduled planning
)))
2281 (concat org-scheduled-string
" "
2282 (org-element-timestamp-interpreter scheduled nil
))))
2283 (let ((closed (org-element-property :closed planning
)))
2285 (concat org-closed-string
" "
2286 (org-element-timestamp-interpreter closed nil
))))))
2292 (defun org-element-src-block-parser (limit affiliated
)
2295 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2296 the buffer position at the beginning of the first affiliated
2297 keyword and CDR is a plist of affiliated keywords along with
2300 Return a list whose CAR is `src-block' and CDR is a plist
2301 containing `:language', `:switches', `:parameters', `:begin',
2302 `:end', `:number-lines', `:retain-labels', `:use-labels',
2303 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2304 `:post-affiliated' keywords.
2306 Assume point is at the beginning of the block."
2307 (let ((case-fold-search t
))
2308 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2310 ;; Incomplete block: parse it as a paragraph.
2311 (org-element-paragraph-parser limit affiliated
)
2312 (let ((contents-end (match-beginning 0)))
2314 (let* ((begin (car affiliated
))
2315 (post-affiliated (point))
2316 ;; Get language as a string.
2320 (concat "^[ \t]*#\\+BEGIN_SRC"
2321 "\\(?: +\\(\\S-+\\)\\)?"
2322 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2324 (org-match-string-no-properties 1)))
2326 (switches (org-match-string-no-properties 2))
2328 (parameters (org-match-string-no-properties 3))
2329 ;; Switches analysis
2331 (cond ((not switches
) nil
)
2332 ((string-match "-n\\>" switches
) 'new
)
2333 ((string-match "+n\\>" switches
) 'continued
)))
2334 (preserve-indent (and switches
2335 (string-match "-i\\>" switches
)))
2338 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2339 (match-string 1 switches
)))
2340 ;; Should labels be retained in (or stripped from)
2344 (not (string-match "-r\\>" switches
))
2345 (and number-lines
(string-match "-k\\>" switches
))))
2346 ;; What should code-references use - labels or
2351 (not (string-match "-k\\>" switches
)))))
2353 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2355 (value (org-element-remove-indentation
2356 (org-unescape-code-in-string
2357 (buffer-substring-no-properties
2358 (progn (forward-line) (point)) contents-end
))
2360 (pos-before-blank (progn (goto-char contents-end
)
2363 ;; Get position after ending blank lines.
2364 (end (progn (skip-chars-forward " \r\t\n" limit
)
2365 (if (eobp) (point) (line-beginning-position)))))
2368 (list :language language
2369 :switches
(and (org-string-nw-p switches
)
2370 (org-trim switches
))
2371 :parameters
(and (org-string-nw-p parameters
)
2372 (org-trim parameters
))
2375 :number-lines number-lines
2376 :preserve-indent preserve-indent
2377 :retain-labels retain-labels
2378 :use-labels use-labels
2379 :label-fmt label-fmt
2381 :post-blank
(count-lines pos-before-blank end
)
2382 :post-affiliated post-affiliated
)
2383 (cdr affiliated
)))))))))
2385 (defun org-element-src-block-interpreter (src-block contents
)
2386 "Interpret SRC-BLOCK element as Org syntax.
2388 (let ((lang (org-element-property :language src-block
))
2389 (switches (org-element-property :switches src-block
))
2390 (params (org-element-property :parameters src-block
))
2392 (let ((val (org-element-property :value src-block
)))
2394 ((or org-src-preserve-indentation
2395 (org-element-property :preserve-indent src-block
))
2397 ((zerop org-edit-src-content-indentation
) val
)
2399 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2400 (replace-regexp-in-string
2401 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2402 (concat (format "#+BEGIN_SRC%s\n"
2403 (concat (and lang
(concat " " lang
))
2404 (and switches
(concat " " switches
))
2405 (and params
(concat " " params
))))
2406 (org-element-normalize-string (org-escape-code-in-string value
))
2412 (defun org-element-table-parser (limit affiliated
)
2413 "Parse a table at point.
2415 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2416 the buffer position at the beginning of the first affiliated
2417 keyword and CDR is a plist of affiliated keywords along with
2420 Return a list whose CAR is `table' and CDR is a plist containing
2421 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2422 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2425 Assume point is at the beginning of the table."
2427 (let* ((case-fold-search t
)
2428 (table-begin (point))
2429 (type (if (org-at-table.el-p
) 'table.el
'org
))
2430 (begin (car affiliated
))
2432 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2433 (goto-char (match-beginning 0))
2436 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2437 (push (org-match-string-no-properties 1) acc
)
2440 (pos-before-blank (point))
2441 (end (progn (skip-chars-forward " \r\t\n" limit
)
2442 (if (eobp) (point) (line-beginning-position)))))
2449 ;; Only `org' tables have contents. `table.el' tables
2450 ;; use a `:value' property to store raw table as
2452 :contents-begin
(and (eq type
'org
) table-begin
)
2453 :contents-end
(and (eq type
'org
) table-end
)
2454 :value
(and (eq type
'table.el
)
2455 (buffer-substring-no-properties
2456 table-begin table-end
))
2457 :post-blank
(count-lines pos-before-blank end
)
2458 :post-affiliated table-begin
)
2459 (cdr affiliated
))))))
2461 (defun org-element-table-interpreter (table contents
)
2462 "Interpret TABLE element as Org syntax.
2463 CONTENTS is a string, if table's type is `org', or nil."
2464 (if (eq (org-element-property :type table
) 'table.el
)
2465 (org-remove-indentation (org-element-property :value table
))
2466 (concat (with-temp-buffer (insert contents
)
2469 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2470 (reverse (org-element-property :tblfm table
))
2476 (defun org-element-table-row-parser (limit)
2477 "Parse table row at point.
2479 LIMIT bounds the search.
2481 Return a list whose CAR is `table-row' and CDR is a plist
2482 containing `:begin', `:end', `:contents-begin', `:contents-end',
2483 `:type', `:post-blank' and `:post-affiliated' keywords."
2485 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2487 ;; A table rule has no contents. In that case, ensure
2488 ;; CONTENTS-BEGIN matches CONTENTS-END.
2489 (contents-begin (and (eq type
'standard
)
2490 (search-forward "|")
2492 (contents-end (and (eq type
'standard
)
2495 (skip-chars-backward " \t")
2497 (end (progn (forward-line) (point))))
2502 :contents-begin contents-begin
2503 :contents-end contents-end
2505 :post-affiliated begin
)))))
2507 (defun org-element-table-row-interpreter (table-row contents
)
2508 "Interpret TABLE-ROW element as Org syntax.
2509 CONTENTS is the contents of the table row."
2510 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2511 (concat "| " contents
)))
2516 (defun org-element-verse-block-parser (limit affiliated
)
2517 "Parse a verse block.
2519 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2520 the buffer position at the beginning of the first affiliated
2521 keyword and CDR is a plist of affiliated keywords along with
2524 Return a list whose CAR is `verse-block' and CDR is a plist
2525 containing `:begin', `:end', `:contents-begin', `:contents-end',
2526 `:post-blank' and `:post-affiliated' keywords.
2528 Assume point is at beginning of the block."
2529 (let ((case-fold-search t
))
2530 (if (not (save-excursion
2531 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2532 ;; Incomplete block: parse it as a paragraph.
2533 (org-element-paragraph-parser limit affiliated
)
2534 (let ((contents-end (match-beginning 0)))
2536 (let* ((begin (car affiliated
))
2537 (post-affiliated (point))
2538 (contents-begin (progn (forward-line) (point)))
2539 (pos-before-blank (progn (goto-char contents-end
)
2542 (end (progn (skip-chars-forward " \r\t\n" limit
)
2543 (if (eobp) (point) (line-beginning-position)))))
2548 :contents-begin contents-begin
2549 :contents-end contents-end
2550 :post-blank
(count-lines pos-before-blank end
)
2551 :post-affiliated post-affiliated
)
2552 (cdr affiliated
)))))))))
2554 (defun org-element-verse-block-interpreter (verse-block contents
)
2555 "Interpret VERSE-BLOCK element as Org syntax.
2556 CONTENTS is verse block contents."
2557 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2563 ;; Unlike to elements, raw text can be found between objects. Hence,
2564 ;; `org-element--object-lex' is provided to find the next object in
2567 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2568 ;; object types they can contain will be specified in
2569 ;; `org-element-object-restrictions'.
2571 ;; Creating a new type of object requires to alter
2572 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2573 ;; new type in `org-element-all-objects', and possibly add
2574 ;; restrictions in `org-element-object-restrictions'.
2578 (defun org-element-bold-parser ()
2579 "Parse bold object at point, if any.
2581 When at a bold object, return a list whose car is `bold' and cdr
2582 is a plist with `:begin', `:end', `:contents-begin' and
2583 `:contents-end' and `:post-blank' keywords. Otherwise, return
2586 Assume point is at the first star marker."
2588 (unless (bolp) (backward-char 1))
2589 (when (looking-at org-emph-re
)
2590 (let ((begin (match-beginning 2))
2591 (contents-begin (match-beginning 4))
2592 (contents-end (match-end 4))
2593 (post-blank (progn (goto-char (match-end 2))
2594 (skip-chars-forward " \t")))
2599 :contents-begin contents-begin
2600 :contents-end contents-end
2601 :post-blank post-blank
))))))
2603 (defun org-element-bold-interpreter (bold contents
)
2604 "Interpret BOLD object as Org syntax.
2605 CONTENTS is the contents of the object."
2606 (format "*%s*" contents
))
2611 (defun org-element-code-parser ()
2612 "Parse code object at point, if any.
2614 When at a code object, return a list whose car is `code' and cdr
2615 is a plist with `:value', `:begin', `:end' and `:post-blank'
2616 keywords. Otherwise, return nil.
2618 Assume point is at the first tilde marker."
2620 (unless (bolp) (backward-char 1))
2621 (when (looking-at org-emph-re
)
2622 (let ((begin (match-beginning 2))
2623 (value (org-match-string-no-properties 4))
2624 (post-blank (progn (goto-char (match-end 2))
2625 (skip-chars-forward " \t")))
2631 :post-blank post-blank
))))))
2633 (defun org-element-code-interpreter (code contents
)
2634 "Interpret CODE object as Org syntax.
2636 (format "~%s~" (org-element-property :value code
)))
2641 (defun org-element-entity-parser ()
2642 "Parse entity at point, if any.
2644 When at an entity, return a list whose car is `entity' and cdr
2645 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2646 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2647 `:post-blank' as keywords. Otherwise, return nil.
2649 Assume point is at the beginning of the entity."
2651 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2653 (let* ((value (or (org-entity-get (match-string 1))
2654 (throw 'no-object nil
)))
2655 (begin (match-beginning 0))
2656 (bracketsp (string= (match-string 2) "{}"))
2657 (post-blank (progn (goto-char (match-end 1))
2658 (when bracketsp
(forward-char 2))
2659 (skip-chars-forward " \t")))
2662 (list :name
(car value
)
2663 :latex
(nth 1 value
)
2664 :latex-math-p
(nth 2 value
)
2666 :ascii
(nth 4 value
)
2667 :latin1
(nth 5 value
)
2668 :utf-8
(nth 6 value
)
2671 :use-brackets-p bracketsp
2672 :post-blank post-blank
)))))))
2674 (defun org-element-entity-interpreter (entity contents
)
2675 "Interpret ENTITY object as Org syntax.
2678 (org-element-property :name entity
)
2679 (when (org-element-property :use-brackets-p entity
) "{}")))
2684 (defun org-element-export-snippet-parser ()
2685 "Parse export snippet at point.
2687 When at an export snippet, return a list whose car is
2688 `export-snippet' and cdr a plist with `:begin', `:end',
2689 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2692 Assume point is at the beginning of the snippet."
2695 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2697 (save-match-data (goto-char (match-end 0))
2698 (re-search-forward "@@" nil t
)
2699 (match-beginning 0))))
2700 (let* ((begin (match-beginning 0))
2701 (back-end (org-match-string-no-properties 1))
2702 (value (buffer-substring-no-properties
2703 (match-end 0) contents-end
))
2704 (post-blank (skip-chars-forward " \t"))
2706 (list 'export-snippet
2707 (list :back-end back-end
2711 :post-blank post-blank
)))))))
2713 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2714 "Interpret EXPORT-SNIPPET object as Org syntax.
2717 (org-element-property :back-end export-snippet
)
2718 (org-element-property :value export-snippet
)))
2721 ;;;; Footnote Reference
2723 (defun org-element-footnote-reference-parser ()
2724 "Parse footnote reference at point, if any.
2726 When at a footnote reference, return a list whose car is
2727 `footnote-reference' and cdr a plist with `:label', `:type',
2728 `:begin', `:end', `:content-begin', `:contents-end' and
2729 `:post-blank' as keywords. Otherwise, return nil."
2731 (when (looking-at org-footnote-re
)
2733 (let* ((begin (point))
2735 (or (org-match-string-no-properties 2)
2736 (org-match-string-no-properties 3)
2737 (and (match-string 1)
2738 (concat "fn:" (org-match-string-no-properties 1)))))
2739 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2740 (inner-begin (match-end 0))
2744 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2745 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2746 (unless (zerop count
) (throw 'no-object nil
))
2748 (post-blank (progn (goto-char (1+ inner-end
))
2749 (skip-chars-forward " \t")))
2751 (list 'footnote-reference
2756 :contents-begin
(and (eq type
'inline
) inner-begin
)
2757 :contents-end
(and (eq type
'inline
) inner-end
)
2758 :post-blank post-blank
)))))))
2760 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2761 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2762 CONTENTS is its definition, when inline, or nil."
2764 (concat (or (org-element-property :label footnote-reference
) "fn:")
2765 (and contents
(concat ":" contents
)))))
2768 ;;;; Inline Babel Call
2770 (defun org-element-inline-babel-call-parser ()
2771 "Parse inline babel call at point, if any.
2773 When at an inline babel call, return a list whose car is
2774 `inline-babel-call' and cdr a plist with `:begin', `:end',
2775 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2777 Assume point is at the beginning of the babel call."
2779 (unless (bolp) (backward-char))
2780 (when (let ((case-fold-search t
))
2781 (looking-at org-babel-inline-lob-one-liner-regexp
))
2782 (let ((begin (match-end 1))
2783 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2784 (post-blank (progn (goto-char (match-end 0))
2785 (skip-chars-forward " \t")))
2787 (list 'inline-babel-call
2791 :post-blank post-blank
))))))
2793 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2794 "Interpret INLINE-BABEL-CALL object as Org syntax.
2796 (org-element-property :value inline-babel-call
))
2799 ;;;; Inline Src Block
2801 (defun org-element-inline-src-block-parser ()
2802 "Parse inline source block at point, if any.
2804 When at an inline source block, return a list whose car is
2805 `inline-src-block' and cdr a plist with `:begin', `:end',
2806 `:language', `:value', `:parameters' and `:post-blank' as
2807 keywords. Otherwise, return nil.
2809 Assume point is at the beginning of the inline src block."
2811 (unless (bolp) (backward-char))
2812 (when (looking-at org-babel-inline-src-block-regexp
)
2813 (let ((begin (match-beginning 1))
2814 (language (org-match-string-no-properties 2))
2815 (parameters (org-match-string-no-properties 4))
2816 (value (org-match-string-no-properties 5))
2817 (post-blank (progn (goto-char (match-end 0))
2818 (skip-chars-forward " \t")))
2820 (list 'inline-src-block
2821 (list :language language
2823 :parameters parameters
2826 :post-blank post-blank
))))))
2828 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2829 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2831 (let ((language (org-element-property :language inline-src-block
))
2832 (arguments (org-element-property :parameters inline-src-block
))
2833 (body (org-element-property :value inline-src-block
)))
2834 (format "src_%s%s{%s}"
2836 (if arguments
(format "[%s]" arguments
) "")
2841 (defun org-element-italic-parser ()
2842 "Parse italic object at point, if any.
2844 When at an italic object, return a list whose car is `italic' and
2845 cdr is a plist with `:begin', `:end', `:contents-begin' and
2846 `:contents-end' and `:post-blank' keywords. Otherwise, return
2849 Assume point is at the first slash marker."
2851 (unless (bolp) (backward-char 1))
2852 (when (looking-at org-emph-re
)
2853 (let ((begin (match-beginning 2))
2854 (contents-begin (match-beginning 4))
2855 (contents-end (match-end 4))
2856 (post-blank (progn (goto-char (match-end 2))
2857 (skip-chars-forward " \t")))
2862 :contents-begin contents-begin
2863 :contents-end contents-end
2864 :post-blank post-blank
))))))
2866 (defun org-element-italic-interpreter (italic contents
)
2867 "Interpret ITALIC object as Org syntax.
2868 CONTENTS is the contents of the object."
2869 (format "/%s/" contents
))
2874 (defun org-element-latex-fragment-parser ()
2875 "Parse LaTeX fragment at point, if any.
2877 When at a LaTeX fragment, return a list whose car is
2878 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2879 and `:post-blank' as keywords. Otherwise, return nil.
2881 Assume point is at the beginning of the LaTeX fragment."
2884 (let* ((begin (point))
2886 (if (eq (char-after) ?$
)
2887 (if (eq (char-after (1+ (point))) ?$
)
2888 (search-forward "$$" nil t
2)
2889 (and (not (eq (char-before) ?$
))
2890 (search-forward "$" nil t
2)
2891 (not (memq (char-before (match-beginning 0))
2892 '(?\s ?
\t ?
\n ?
, ?.
)))
2893 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2895 (case (char-after (1+ (point)))
2896 (?\
( (search-forward "\\)" nil t
))
2897 (?\
[ (search-forward "\\]" nil t
))
2900 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2902 (post-blank (if (not after-fragment
) (throw 'no-object nil
)
2903 (goto-char after-fragment
)
2904 (skip-chars-forward " \t")))
2906 (list 'latex-fragment
2907 (list :value
(buffer-substring-no-properties begin after-fragment
)
2910 :post-blank post-blank
))))))
2912 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2913 "Interpret LATEX-FRAGMENT object as Org syntax.
2915 (org-element-property :value latex-fragment
))
2919 (defun org-element-line-break-parser ()
2920 "Parse line break at point, if any.
2922 When at a line break, return a list whose car is `line-break',
2923 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2924 Otherwise, return nil.
2926 Assume point is at the beginning of the line break."
2927 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2928 (not (eq (char-before) ?
\\)))
2930 (list :begin
(point)
2931 :end
(progn (forward-line) (point))
2934 (defun org-element-line-break-interpreter (line-break contents
)
2935 "Interpret LINE-BREAK object as Org syntax.
2942 (defun org-element-link-parser ()
2943 "Parse link at point, if any.
2945 When at a link, return a list whose car is `link' and cdr a plist
2946 with `:type', `:path', `:raw-link', `:application',
2947 `:search-option', `:begin', `:end', `:contents-begin',
2948 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2951 Assume point is at the beginning of the link."
2953 (let ((begin (point))
2954 end contents-begin contents-end link-end post-blank path type
2955 raw-link link search-option application
)
2957 ;; Type 1: Text targeted from a radio target.
2958 ((and org-target-link-regexp
2959 (save-excursion (or (bolp) (backward-char))
2960 (looking-at org-target-link-regexp
)))
2962 link-end
(match-end 1)
2963 path
(org-match-string-no-properties 1)
2964 contents-begin
(match-beginning 1)
2965 contents-end
(match-end 1)))
2966 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2967 ((looking-at org-bracket-link-regexp
)
2968 (setq contents-begin
(match-beginning 3)
2969 contents-end
(match-end 3)
2970 link-end
(match-end 0)
2971 ;; RAW-LINK is the original link. Expand any
2972 ;; abbreviation in it.
2973 raw-link
(org-translate-link
2974 (org-link-expand-abbrev
2975 (org-match-string-no-properties 1))))
2976 ;; Determine TYPE of link and set PATH accordingly.
2979 ((or (file-name-absolute-p raw-link
)
2980 (string-match "\\`\\.\\.?/" raw-link
))
2981 (setq type
"file" path raw-link
))
2982 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2983 ((string-match org-link-types-re raw-link
)
2984 (setq type
(match-string 1 raw-link
)
2985 ;; According to RFC 3986, extra whitespace should be
2986 ;; ignored when a URI is extracted.
2987 path
(replace-regexp-in-string
2988 "[ \t]*\n[ \t]*" "" (substring raw-link
(match-end 0)))))
2989 ;; Id type: PATH is the id.
2990 ((string-match "\\`id:\\([-a-f0-9]+\\)" raw-link
)
2991 (setq type
"id" path
(match-string 1 raw-link
)))
2992 ;; Code-ref type: PATH is the name of the reference.
2993 ((string-match "\\`(\\(.*\\))\\'" raw-link
)
2994 (setq type
"coderef" path
(match-string 1 raw-link
)))
2995 ;; Custom-id type: PATH is the name of the custom id.
2996 ((= (aref raw-link
0) ?
#)
2997 (setq type
"custom-id" path
(substring raw-link
1)))
2998 ;; Fuzzy type: Internal link either matches a target, an
2999 ;; headline name or nothing. PATH is the target or
3001 (t (setq type
"fuzzy" path raw-link
))))
3002 ;; Type 3: Plain link, e.g., http://orgmode.org
3003 ((looking-at org-plain-link-re
)
3004 (setq raw-link
(org-match-string-no-properties 0)
3005 type
(org-match-string-no-properties 1)
3006 link-end
(match-end 0)
3007 path
(org-match-string-no-properties 2)))
3008 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3009 ((looking-at org-angle-link-re
)
3010 (setq raw-link
(buffer-substring-no-properties
3011 (match-beginning 1) (match-end 2))
3012 type
(org-match-string-no-properties 1)
3013 link-end
(match-end 0)
3014 path
(org-match-string-no-properties 2)))
3015 (t (throw 'no-object nil
)))
3016 ;; In any case, deduce end point after trailing white space from
3017 ;; LINK-END variable.
3019 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3021 ;; Special "file" type link processing.
3022 (when (member type org-element-link-type-is-file
)
3023 ;; Extract opening application and search option.
3024 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3025 (setq application
(match-string 1 type
)))
3026 ((not (string-match "^file" type
))
3027 (setq application type
)))
3028 (when (string-match "::\\(.*\\)\\'" path
)
3029 (setq search-option
(match-string 1 path
)
3030 path
(replace-match "" nil nil path
)))
3032 (when (and (file-name-absolute-p path
)
3033 (not (org-string-match-p "\\`[/~]/" path
)))
3034 (setq path
(concat "//" path
)))
3035 ;; Make sure TYPE always reports "file".
3040 :raw-link
(or raw-link path
)
3041 :application application
3042 :search-option search-option
3045 :contents-begin contents-begin
3046 :contents-end contents-end
3047 :post-blank post-blank
))))))
3049 (defun org-element-link-interpreter (link contents
)
3050 "Interpret LINK object as Org syntax.
3051 CONTENTS is the contents of the object, or nil."
3052 (let ((type (org-element-property :type link
))
3053 (raw-link (org-element-property :raw-link link
)))
3054 (if (string= type
"radio") raw-link
3057 (if contents
(format "[%s]" contents
) "")))))
3062 (defun org-element-macro-parser ()
3063 "Parse macro at point, if any.
3065 When at a macro, return a list whose car is `macro' and cdr
3066 a plist with `:key', `:args', `:begin', `:end', `:value' and
3067 `:post-blank' as keywords. Otherwise, return nil.
3069 Assume point is at the macro."
3071 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3072 (let ((begin (point))
3073 (key (downcase (org-match-string-no-properties 1)))
3074 (value (org-match-string-no-properties 0))
3075 (post-blank (progn (goto-char (match-end 0))
3076 (skip-chars-forward " \t")))
3078 (args (let ((args (org-match-string-no-properties 3)))
3080 ;; Do not use `org-split-string' since empty
3081 ;; strings are meaningful here.
3083 (replace-regexp-in-string
3084 "\\(\\\\*\\)\\(,\\)"
3086 (let ((len (length (match-string 1 str
))))
3087 (concat (make-string (/ len
2) ?
\\)
3088 (if (zerop (mod len
2)) "\000" ","))))
3097 :post-blank post-blank
))))))
3099 (defun org-element-macro-interpreter (macro contents
)
3100 "Interpret MACRO object as Org syntax.
3102 (org-element-property :value macro
))
3107 (defun org-element-radio-target-parser ()
3108 "Parse radio target at point, if any.
3110 When at a radio target, return a list whose car is `radio-target'
3111 and cdr a plist with `:begin', `:end', `:contents-begin',
3112 `:contents-end', `:value' and `:post-blank' as keywords.
3113 Otherwise, return nil.
3115 Assume point is at the radio target."
3117 (when (looking-at org-radio-target-regexp
)
3118 (let ((begin (point))
3119 (contents-begin (match-beginning 1))
3120 (contents-end (match-end 1))
3121 (value (org-match-string-no-properties 1))
3122 (post-blank (progn (goto-char (match-end 0))
3123 (skip-chars-forward " \t")))
3128 :contents-begin contents-begin
3129 :contents-end contents-end
3130 :post-blank post-blank
3133 (defun org-element-radio-target-interpreter (target contents
)
3134 "Interpret TARGET object as Org syntax.
3135 CONTENTS is the contents of the object."
3136 (concat "<<<" contents
">>>"))
3139 ;;;; Statistics Cookie
3141 (defun org-element-statistics-cookie-parser ()
3142 "Parse statistics cookie at point, if any.
3144 When at a statistics cookie, return a list whose car is
3145 `statistics-cookie', and cdr a plist with `:begin', `:end',
3146 `:value' and `:post-blank' keywords. Otherwise, return nil.
3148 Assume point is at the beginning of the statistics-cookie."
3150 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3151 (let* ((begin (point))
3152 (value (buffer-substring-no-properties
3153 (match-beginning 0) (match-end 0)))
3154 (post-blank (progn (goto-char (match-end 0))
3155 (skip-chars-forward " \t")))
3157 (list 'statistics-cookie
3161 :post-blank post-blank
))))))
3163 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3164 "Interpret STATISTICS-COOKIE object as Org syntax.
3166 (org-element-property :value statistics-cookie
))
3171 (defun org-element-strike-through-parser ()
3172 "Parse strike-through object at point, if any.
3174 When at a strike-through object, return a list whose car is
3175 `strike-through' and cdr is a plist with `:begin', `:end',
3176 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3177 Otherwise, return nil.
3179 Assume point is at the first plus sign marker."
3181 (unless (bolp) (backward-char 1))
3182 (when (looking-at org-emph-re
)
3183 (let ((begin (match-beginning 2))
3184 (contents-begin (match-beginning 4))
3185 (contents-end (match-end 4))
3186 (post-blank (progn (goto-char (match-end 2))
3187 (skip-chars-forward " \t")))
3189 (list 'strike-through
3192 :contents-begin contents-begin
3193 :contents-end contents-end
3194 :post-blank post-blank
))))))
3196 (defun org-element-strike-through-interpreter (strike-through contents
)
3197 "Interpret STRIKE-THROUGH object as Org syntax.
3198 CONTENTS is the contents of the object."
3199 (format "+%s+" contents
))
3204 (defun org-element-subscript-parser ()
3205 "Parse subscript at point, if any.
3207 When at a subscript object, return a list whose car is
3208 `subscript' and cdr a plist with `:begin', `:end',
3209 `:contents-begin', `:contents-end', `:use-brackets-p' and
3210 `:post-blank' as keywords. Otherwise, return nil.
3212 Assume point is at the underscore."
3214 (unless (bolp) (backward-char))
3215 (when (looking-at org-match-substring-regexp
)
3216 (let ((bracketsp (match-beginning 4))
3217 (begin (match-beginning 2))
3218 (contents-begin (or (match-beginning 4)
3219 (match-beginning 3)))
3220 (contents-end (or (match-end 4) (match-end 3)))
3221 (post-blank (progn (goto-char (match-end 0))
3222 (skip-chars-forward " \t")))
3227 :use-brackets-p bracketsp
3228 :contents-begin contents-begin
3229 :contents-end contents-end
3230 :post-blank post-blank
))))))
3232 (defun org-element-subscript-interpreter (subscript contents
)
3233 "Interpret SUBSCRIPT object as Org syntax.
3234 CONTENTS is the contents of the object."
3236 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3242 (defun org-element-superscript-parser ()
3243 "Parse superscript at point, if any.
3245 When at a superscript object, return a list whose car is
3246 `superscript' and cdr a plist with `:begin', `:end',
3247 `:contents-begin', `:contents-end', `:use-brackets-p' and
3248 `:post-blank' as keywords. Otherwise, return nil.
3250 Assume point is at the caret."
3252 (unless (bolp) (backward-char))
3253 (when (looking-at org-match-substring-regexp
)
3254 (let ((bracketsp (match-beginning 4))
3255 (begin (match-beginning 2))
3256 (contents-begin (or (match-beginning 4)
3257 (match-beginning 3)))
3258 (contents-end (or (match-end 4) (match-end 3)))
3259 (post-blank (progn (goto-char (match-end 0))
3260 (skip-chars-forward " \t")))
3265 :use-brackets-p bracketsp
3266 :contents-begin contents-begin
3267 :contents-end contents-end
3268 :post-blank post-blank
))))))
3270 (defun org-element-superscript-interpreter (superscript contents
)
3271 "Interpret SUPERSCRIPT object as Org syntax.
3272 CONTENTS is the contents of the object."
3274 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3280 (defun org-element-table-cell-parser ()
3281 "Parse table cell at point.
3282 Return a list whose car is `table-cell' and cdr is a plist
3283 containing `:begin', `:end', `:contents-begin', `:contents-end'
3284 and `:post-blank' keywords."
3285 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3286 (let* ((begin (match-beginning 0))
3288 (contents-begin (match-beginning 1))
3289 (contents-end (match-end 1)))
3293 :contents-begin contents-begin
3294 :contents-end contents-end
3297 (defun org-element-table-cell-interpreter (table-cell contents
)
3298 "Interpret TABLE-CELL element as Org syntax.
3299 CONTENTS is the contents of the cell, or nil."
3300 (concat " " contents
" |"))
3305 (defun org-element-target-parser ()
3306 "Parse target at point, if any.
3308 When at a target, return a list whose car is `target' and cdr
3309 a plist with `:begin', `:end', `:value' and `:post-blank' as
3310 keywords. Otherwise, return nil.
3312 Assume point is at the target."
3314 (when (looking-at org-target-regexp
)
3315 (let ((begin (point))
3316 (value (org-match-string-no-properties 1))
3317 (post-blank (progn (goto-char (match-end 0))
3318 (skip-chars-forward " \t")))
3324 :post-blank post-blank
))))))
3326 (defun org-element-target-interpreter (target contents
)
3327 "Interpret TARGET object as Org syntax.
3329 (format "<<%s>>" (org-element-property :value target
)))
3334 (defconst org-element--timestamp-regexp
3335 (concat org-ts-regexp-both
3337 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3339 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3340 "Regexp matching any timestamp type object.")
3342 (defun org-element-timestamp-parser ()
3343 "Parse time stamp at point, if any.
3345 When at a time stamp, return a list whose car is `timestamp', and
3346 cdr a plist with `:type', `:raw-value', `:year-start',
3347 `:month-start', `:day-start', `:hour-start', `:minute-start',
3348 `:year-end', `:month-end', `:day-end', `:hour-end',
3349 `:minute-end', `:repeater-type', `:repeater-value',
3350 `:repeater-unit', `:warning-type', `:warning-value',
3351 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3352 Otherwise, return nil.
3354 Assume point is at the beginning of the timestamp."
3355 (when (org-looking-at-p org-element--timestamp-regexp
)
3357 (let* ((begin (point))
3358 (activep (eq (char-after) ?
<))
3361 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3362 (match-string-no-properties 0)))
3363 (date-start (match-string-no-properties 1))
3364 (date-end (match-string 3))
3365 (diaryp (match-beginning 2))
3366 (post-blank (progn (goto-char (match-end 0))
3367 (skip-chars-forward " \t")))
3372 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3374 (cons (string-to-number (match-string 2 date-start
))
3375 (string-to-number (match-string 3 date-start
)))))
3376 (type (cond (diaryp 'diary
)
3377 ((and activep
(or date-end time-range
)) 'active-range
)
3379 ((or date-end time-range
) 'inactive-range
)
3383 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3387 (let ((type (match-string 1 raw-value
)))
3388 (cond ((equal "++" type
) 'catch-up
)
3389 ((equal ".+" type
) 'restart
)
3391 :repeater-value
(string-to-number (match-string 2 raw-value
))
3393 (case (string-to-char (match-string 3 raw-value
))
3394 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3397 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3399 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3400 :warning-value
(string-to-number (match-string 2 raw-value
))
3402 (case (string-to-char (match-string 3 raw-value
))
3403 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3404 year-start month-start day-start hour-start minute-start year-end
3405 month-end day-end hour-end minute-end
)
3406 ;; Parse date-start.
3408 (let ((date (org-parse-time-string date-start t
)))
3409 (setq year-start
(nth 5 date
)
3410 month-start
(nth 4 date
)
3411 day-start
(nth 3 date
)
3412 hour-start
(nth 2 date
)
3413 minute-start
(nth 1 date
))))
3414 ;; Compute date-end. It can be provided directly in time-stamp,
3415 ;; or extracted from time range. Otherwise, it defaults to the
3416 ;; same values as date-start.
3418 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3419 (setq year-end
(or (nth 5 date
) year-start
)
3420 month-end
(or (nth 4 date
) month-start
)
3421 day-end
(or (nth 3 date
) day-start
)
3422 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3423 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3425 (nconc (list :type type
3426 :raw-value raw-value
3427 :year-start year-start
3428 :month-start month-start
3429 :day-start day-start
3430 :hour-start hour-start
3431 :minute-start minute-start
3433 :month-end month-end
3436 :minute-end minute-end
3439 :post-blank post-blank
)
3443 (defun org-element-timestamp-interpreter (timestamp contents
)
3444 "Interpret TIMESTAMP object as Org syntax.
3446 (let* ((repeat-string
3448 (case (org-element-property :repeater-type timestamp
)
3449 (cumulate "+") (catch-up "++") (restart ".+"))
3450 (let ((val (org-element-property :repeater-value timestamp
)))
3451 (and val
(number-to-string val
)))
3452 (case (org-element-property :repeater-unit timestamp
)
3453 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3456 (case (org-element-property :warning-type timestamp
)
3459 (let ((val (org-element-property :warning-value timestamp
)))
3460 (and val
(number-to-string val
)))
3461 (case (org-element-property :warning-unit timestamp
)
3462 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3464 ;; Build an Org timestamp string from TIME. ACTIVEP is
3465 ;; non-nil when time stamp is active. If WITH-TIME-P is
3466 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3467 ;; specify a time range in the timestamp. REPEAT-STRING is
3468 ;; the repeater string, if any.
3469 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3470 (let ((ts (format-time-string
3471 (funcall (if with-time-p
'cdr
'car
)
3472 org-time-stamp-formats
)
3474 (when (and hour-end minute-end
)
3475 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3478 (format "\\&-%02d:%02d" hour-end minute-end
)
3480 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3481 (dolist (s (list repeat-string warning-string
))
3482 (when (org-string-nw-p s
)
3483 (setq ts
(concat (substring ts
0 -
1)
3486 (substring ts -
1)))))
3489 (type (org-element-property :type timestamp
)))
3492 (let* ((minute-start (org-element-property :minute-start timestamp
))
3493 (minute-end (org-element-property :minute-end timestamp
))
3494 (hour-start (org-element-property :hour-start timestamp
))
3495 (hour-end (org-element-property :hour-end timestamp
))
3496 (time-range-p (and hour-start hour-end minute-start minute-end
3497 (or (/= hour-start hour-end
)
3498 (/= minute-start minute-end
)))))
3504 (org-element-property :day-start timestamp
)
3505 (org-element-property :month-start timestamp
)
3506 (org-element-property :year-start timestamp
))
3508 (and hour-start minute-start
)
3509 (and time-range-p hour-end
)
3510 (and time-range-p minute-end
))))
3511 ((active-range inactive-range
)
3512 (let ((minute-start (org-element-property :minute-start timestamp
))
3513 (minute-end (org-element-property :minute-end timestamp
))
3514 (hour-start (org-element-property :hour-start timestamp
))
3515 (hour-end (org-element-property :hour-end timestamp
)))
3518 build-ts-string
(encode-time
3522 (org-element-property :day-start timestamp
)
3523 (org-element-property :month-start timestamp
)
3524 (org-element-property :year-start timestamp
))
3525 (eq type
'active-range
)
3526 (and hour-start minute-start
))
3528 (funcall build-ts-string
3532 (org-element-property :day-end timestamp
)
3533 (org-element-property :month-end timestamp
)
3534 (org-element-property :year-end timestamp
))
3535 (eq type
'active-range
)
3536 (and hour-end minute-end
))))))))
3541 (defun org-element-underline-parser ()
3542 "Parse underline object at point, if any.
3544 When at an underline object, return a list whose car is
3545 `underline' and cdr is a plist with `:begin', `:end',
3546 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3547 Otherwise, return nil.
3549 Assume point is at the first underscore marker."
3551 (unless (bolp) (backward-char 1))
3552 (when (looking-at org-emph-re
)
3553 (let ((begin (match-beginning 2))
3554 (contents-begin (match-beginning 4))
3555 (contents-end (match-end 4))
3556 (post-blank (progn (goto-char (match-end 2))
3557 (skip-chars-forward " \t")))
3562 :contents-begin contents-begin
3563 :contents-end contents-end
3564 :post-blank post-blank
))))))
3566 (defun org-element-underline-interpreter (underline contents
)
3567 "Interpret UNDERLINE object as Org syntax.
3568 CONTENTS is the contents of the object."
3569 (format "_%s_" contents
))
3574 (defun org-element-verbatim-parser ()
3575 "Parse verbatim object at point, if any.
3577 When at a verbatim object, return a list whose car is `verbatim'
3578 and cdr is a plist with `:value', `:begin', `:end' and
3579 `:post-blank' keywords. Otherwise, return nil.
3581 Assume point is at the first equal sign marker."
3583 (unless (bolp) (backward-char 1))
3584 (when (looking-at org-emph-re
)
3585 (let ((begin (match-beginning 2))
3586 (value (org-match-string-no-properties 4))
3587 (post-blank (progn (goto-char (match-end 2))
3588 (skip-chars-forward " \t")))
3594 :post-blank post-blank
))))))
3596 (defun org-element-verbatim-interpreter (verbatim contents
)
3597 "Interpret VERBATIM object as Org syntax.
3599 (format "=%s=" (org-element-property :value verbatim
)))
3603 ;;; Parsing Element Starting At Point
3605 ;; `org-element--current-element' is the core function of this section.
3606 ;; It returns the Lisp representation of the element starting at
3609 ;; `org-element--current-element' makes use of special modes. They
3610 ;; are activated for fixed element chaining (e.g., `plain-list' >
3611 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3612 ;; `section'). Special modes are: `first-section', `item',
3613 ;; `node-property', `section' and `table-row'.
3615 (defun org-element--current-element
3616 (limit &optional granularity special structure
)
3617 "Parse the element starting at point.
3619 Return value is a list like (TYPE PROPS) where TYPE is the type
3620 of the element and PROPS a plist of properties associated to the
3623 Possible types are defined in `org-element-all-elements'.
3625 LIMIT bounds the search.
3627 Optional argument GRANULARITY determines the depth of the
3628 recursion. Allowed values are `headline', `greater-element',
3629 `element', `object' or nil. When it is broader than `object' (or
3630 nil), secondary values will not be parsed, since they only
3633 Optional argument SPECIAL, when non-nil, can be either
3634 `first-section', `item', `node-property', `section', and
3637 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3640 This function assumes point is always at the beginning of the
3641 element it has to parse."
3643 (let ((case-fold-search t
)
3644 ;; Determine if parsing depth allows for secondary strings
3645 ;; parsing. It only applies to elements referenced in
3646 ;; `org-element-secondary-value-alist'.
3647 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3651 (org-element-item-parser limit structure raw-secondary-p
))
3653 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3655 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3657 ((org-with-limited-levels (org-at-heading-p))
3658 (org-element-headline-parser limit raw-secondary-p
))
3659 ;; Sections (must be checked after headline).
3660 ((eq special
'section
) (org-element-section-parser limit
))
3661 ((eq special
'first-section
)
3662 (org-element-section-parser
3663 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3665 ;; When not at bol, point is at the beginning of an item or
3666 ;; a footnote definition: next item is always a paragraph.
3667 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3668 ;; Planning and Clock.
3669 ((looking-at org-planning-or-clock-line-re
)
3670 (if (equal (match-string 1) org-clock-string
)
3671 (org-element-clock-parser limit
)
3672 (org-element-planning-parser limit
)))
3675 (org-element-inlinetask-parser limit raw-secondary-p
))
3676 ;; From there, elements can have affiliated keywords.
3677 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3679 ;; Jumping over affiliated keywords put point off-limits.
3680 ;; Parse them as regular keywords.
3681 ((and (cdr affiliated
) (>= (point) limit
))
3682 (goto-char (car affiliated
))
3683 (org-element-keyword-parser limit nil
))
3684 ;; LaTeX Environment.
3685 ((looking-at org-element--latex-begin-environment
)
3686 (org-element-latex-environment-parser limit affiliated
))
3687 ;; Drawer and Property Drawer.
3688 ((looking-at org-drawer-regexp
)
3689 (if (equal (match-string 1) "PROPERTIES")
3690 (org-element-property-drawer-parser limit affiliated
)
3691 (org-element-drawer-parser limit affiliated
)))
3693 ((looking-at "[ \t]*:\\( \\|$\\)")
3694 (org-element-fixed-width-parser limit affiliated
))
3695 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3697 ((looking-at "[ \t]*#")
3698 (goto-char (match-end 0))
3699 (cond ((looking-at "\\(?: \\|$\\)")
3701 (org-element-comment-parser limit affiliated
))
3702 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3704 (let ((parser (assoc (upcase (match-string 1))
3705 org-element-block-name-alist
)))
3706 (if parser
(funcall (cdr parser
) limit affiliated
)
3707 (org-element-special-block-parser limit affiliated
))))
3708 ((looking-at "\\+CALL:")
3710 (org-element-babel-call-parser limit affiliated
))
3711 ((looking-at "\\+BEGIN:? ")
3713 (org-element-dynamic-block-parser limit affiliated
))
3714 ((looking-at "\\+\\S-+:")
3716 (org-element-keyword-parser limit affiliated
))
3719 (org-element-paragraph-parser limit affiliated
))))
3720 ;; Footnote Definition.
3721 ((looking-at org-footnote-definition-re
)
3722 (org-element-footnote-definition-parser limit affiliated
))
3724 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3725 (org-element-horizontal-rule-parser limit affiliated
))
3728 (org-element-diary-sexp-parser limit affiliated
))
3730 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3732 ((looking-at (org-item-re))
3733 (org-element-plain-list-parser
3735 (or structure
(org-element--list-struct limit
))))
3736 ;; Default element: Paragraph.
3737 (t (org-element-paragraph-parser limit affiliated
)))))))))
3740 ;; Most elements can have affiliated keywords. When looking for an
3741 ;; element beginning, we want to move before them, as they belong to
3742 ;; that element, and, in the meantime, collect information they give
3743 ;; into appropriate properties. Hence the following function.
3745 (defun org-element--collect-affiliated-keywords (limit)
3746 "Collect affiliated keywords from point down to LIMIT.
3748 Return a list whose CAR is the position at the first of them and
3749 CDR a plist of keywords and values and move point to the
3750 beginning of the first line after them.
3752 As a special case, if element doesn't start at the beginning of
3753 the line (e.g., a paragraph starting an item), CAR is current
3754 position of point and CDR is nil."
3755 (if (not (bolp)) (list (point))
3756 (let ((case-fold-search t
)
3758 ;; RESTRICT is the list of objects allowed in parsed
3760 (restrict (org-element-restriction 'keyword
))
3762 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3763 (let* ((raw-kwd (upcase (match-string 1)))
3764 ;; Apply translation to RAW-KWD. From there, KWD is
3765 ;; the official keyword.
3766 (kwd (or (cdr (assoc raw-kwd
3767 org-element-keyword-translation-alist
))
3769 ;; Find main value for any keyword.
3773 (buffer-substring-no-properties
3774 (match-end 0) (point-at-eol)))))
3775 ;; PARSEDP is non-nil when keyword should have its
3777 (parsedp (member kwd org-element-parsed-keywords
))
3778 ;; If KWD is a dual keyword, find its secondary
3779 ;; value. Maybe parse it.
3780 (dualp (member kwd org-element-dual-keywords
))
3783 (let ((sec (org-match-string-no-properties 2)))
3784 (if (or (not sec
) (not parsedp
)) sec
3785 (org-element-parse-secondary-string sec restrict
)))))
3786 ;; Attribute a property name to KWD.
3787 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3788 ;; Now set final shape for VALUE.
3790 (setq value
(org-element-parse-secondary-string value restrict
)))
3792 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3793 (when (or (member kwd org-element-multiple-keywords
)
3794 ;; Attributes can always appear on multiple lines.
3795 (string-match "^ATTR_" kwd
))
3796 (setq value
(cons value
(plist-get output kwd-sym
))))
3797 ;; Eventually store the new value in OUTPUT.
3798 (setq output
(plist-put output kwd-sym value
))
3799 ;; Move to next keyword.
3801 ;; If affiliated keywords are orphaned: move back to first one.
3802 ;; They will be parsed as a paragraph.
3803 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3805 (cons origin output
))))
3811 ;; The two major functions here are `org-element-parse-buffer', which
3812 ;; parses Org syntax inside the current buffer, taking into account
3813 ;; region, narrowing, or even visibility if specified, and
3814 ;; `org-element-parse-secondary-string', which parses objects within
3817 ;; The (almost) almighty `org-element-map' allows to apply a function
3818 ;; on elements or objects matching some type, and accumulate the
3819 ;; resulting values. In an export situation, it also skips unneeded
3820 ;; parts of the parse tree.
3822 (defun org-element-parse-buffer (&optional granularity visible-only
)
3823 "Recursively parse the buffer and return structure.
3824 If narrowing is in effect, only parse the visible part of the
3827 Optional argument GRANULARITY determines the depth of the
3828 recursion. It can be set to the following symbols:
3830 `headline' Only parse headlines.
3831 `greater-element' Don't recurse into greater elements excepted
3832 headlines and sections. Thus, elements
3833 parsed are the top-level ones.
3834 `element' Parse everything but objects and plain text.
3835 `object' Parse the complete buffer (default).
3837 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3840 An element or an objects is represented as a list with the
3841 pattern (TYPE PROPERTIES CONTENTS), where :
3843 TYPE is a symbol describing the element or object. See
3844 `org-element-all-elements' and `org-element-all-objects' for an
3845 exhaustive list of such symbols. One can retrieve it with
3846 `org-element-type' function.
3848 PROPERTIES is the list of attributes attached to the element or
3849 object, as a plist. Although most of them are specific to the
3850 element or object type, all types share `:begin', `:end',
3851 `:post-blank' and `:parent' properties, which respectively
3852 refer to buffer position where the element or object starts,
3853 ends, the number of white spaces or blank lines after it, and
3854 the element or object containing it. Properties values can be
3855 obtained by using `org-element-property' function.
3857 CONTENTS is a list of elements, objects or raw strings
3858 contained in the current element or object, when applicable.
3859 One can access them with `org-element-contents' function.
3861 The Org buffer has `org-data' as type and nil as properties.
3862 `org-element-map' function can be used to find specific elements
3863 or objects within the parse tree.
3865 This function assumes that current major mode is `org-mode'."
3867 (goto-char (point-min))
3868 (org-skip-whitespace)
3869 (org-element--parse-elements
3870 (point-at-bol) (point-max)
3871 ;; Start in `first-section' mode so text before the first
3872 ;; headline belongs to a section.
3873 'first-section nil granularity visible-only
(list 'org-data nil
))))
3875 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3876 "Recursively parse objects in STRING and return structure.
3878 RESTRICTION is a symbol limiting the object types that will be
3881 Optional argument PARENT, when non-nil, is the element or object
3882 containing the secondary string. It is used to set correctly
3883 `:parent' property within the string."
3884 (let ((local-variables (buffer-local-variables)))
3886 (dolist (v local-variables
)
3888 (if (symbolp v
) (makunbound v
)
3889 (org-set-local (car v
) (cdr v
)))))
3891 (restore-buffer-modified-p nil
)
3892 (let ((secondary (org-element--parse-objects
3893 (point-min) (point-max) nil restriction
)))
3895 (dolist (o secondary
) (org-element-put-property o
:parent parent
)))
3898 (defun org-element-map
3899 (data types fun
&optional info first-match no-recursion with-affiliated
)
3900 "Map a function on selected elements or objects.
3902 DATA is a parse tree, an element, an object, a string, or a list
3903 of such constructs. TYPES is a symbol or list of symbols of
3904 elements or objects types (see `org-element-all-elements' and
3905 `org-element-all-objects' for a complete list of types). FUN is
3906 the function called on the matching element or object. It has to
3907 accept one argument: the element or object itself.
3909 When optional argument INFO is non-nil, it should be a plist
3910 holding export options. In that case, parts of the parse tree
3911 not exportable according to that property list will be skipped.
3913 When optional argument FIRST-MATCH is non-nil, stop at the first
3914 match for which FUN doesn't return nil, and return that value.
3916 Optional argument NO-RECURSION is a symbol or a list of symbols
3917 representing elements or objects types. `org-element-map' won't
3918 enter any recursive element or object whose type belongs to that
3919 list. Though, FUN can still be applied on them.
3921 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3922 apply to matching objects within parsed affiliated keywords (see
3923 `org-element-parsed-keywords').
3925 Nil values returned from FUN do not appear in the results.
3931 Assuming TREE is a variable containing an Org buffer parse tree,
3932 the following example will return a flat list of all `src-block'
3933 and `example-block' elements in it:
3935 \(org-element-map tree '(example-block src-block) 'identity)
3937 The following snippet will find the first headline with a level
3938 of 1 and a \"phone\" tag, and will return its beginning position:
3940 \(org-element-map tree 'headline
3942 \(and (= (org-element-property :level hl) 1)
3943 \(member \"phone\" (org-element-property :tags hl))
3944 \(org-element-property :begin hl)))
3947 The next example will return a flat list of all `plain-list' type
3948 elements in TREE that are not a sub-list themselves:
3950 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3952 Eventually, this example will return a flat list of all `bold'
3953 type objects containing a `latex-snippet' type object, even
3954 looking into captions:
3956 \(org-element-map tree 'bold
3958 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3960 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3961 (unless (listp types
) (setq types
(list types
)))
3962 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
3963 ;; Recursion depth is determined by --CATEGORY.
3966 (let ((category 'greater-elements
))
3967 (mapc (lambda (type)
3968 (cond ((or (memq type org-element-all-objects
)
3969 (eq type
'plain-text
))
3970 ;; If one object is found, the function
3971 ;; has to recurse into every object.
3972 (throw 'found
'objects
))
3973 ((not (memq type org-element-greater-elements
))
3974 ;; If one regular element is found, the
3975 ;; function has to recurse, at least,
3976 ;; into every element it encounters.
3977 (and (not (eq category
'elements
))
3978 (setq category
'elements
)))))
3981 ;; Compute properties for affiliated keywords if necessary.
3983 (and with-affiliated
3984 (mapcar (lambda (kwd)
3985 (cons kwd
(intern (concat ":" (downcase kwd
)))))
3986 org-element-affiliated-keywords
)))
3992 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3993 ;; holding contextual information.
3994 (let ((--type (org-element-type --data
)))
3997 ;; Ignored element in an export context.
3998 ((and info
(memq --data
(plist-get info
:ignore-list
))))
3999 ;; List of elements or objects.
4000 ((not --type
) (mapc --walk-tree --data
))
4001 ;; Unconditionally enter parse trees.
4002 ((eq --type
'org-data
)
4003 (mapc --walk-tree
(org-element-contents --data
)))
4005 ;; Check if TYPE is matching among TYPES. If so,
4006 ;; apply FUN to --DATA and accumulate return value
4007 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4008 (when (memq --type types
)
4009 (let ((result (funcall fun --data
)))
4010 (cond ((not result
))
4011 (first-match (throw '--map-first-match result
))
4012 (t (push result --acc
)))))
4013 ;; If --DATA has a secondary string that can contain
4014 ;; objects with their type among TYPES, look into it.
4015 (when (and (eq --category
'objects
) (not (stringp --data
)))
4017 (assq --type org-element-secondary-value-alist
)))
4019 (funcall --walk-tree
4020 (org-element-property (cdr sec-prop
) --data
)))))
4021 ;; If --DATA has any affiliated keywords and
4022 ;; WITH-AFFILIATED is non-nil, look for objects in
4024 (when (and with-affiliated
4025 (eq --category
'objects
)
4026 (memq --type org-element-all-elements
))
4027 (mapc (lambda (kwd-pair)
4028 (let ((kwd (car kwd-pair
))
4029 (value (org-element-property
4030 (cdr kwd-pair
) --data
)))
4031 ;; Pay attention to the type of value.
4032 ;; Preserve order for multiple keywords.
4035 ((and (member kwd org-element-multiple-keywords
)
4036 (member kwd org-element-dual-keywords
))
4037 (mapc (lambda (line)
4038 (funcall --walk-tree
(cdr line
))
4039 (funcall --walk-tree
(car line
)))
4041 ((member kwd org-element-multiple-keywords
)
4042 (mapc (lambda (line) (funcall --walk-tree line
))
4044 ((member kwd org-element-dual-keywords
)
4045 (funcall --walk-tree
(cdr value
))
4046 (funcall --walk-tree
(car value
)))
4047 (t (funcall --walk-tree value
)))))
4048 --affiliated-alist
))
4049 ;; Determine if a recursion into --DATA is possible.
4051 ;; --TYPE is explicitly removed from recursion.
4052 ((memq --type no-recursion
))
4053 ;; --DATA has no contents.
4054 ((not (org-element-contents --data
)))
4055 ;; Looking for greater elements but --DATA is simply
4056 ;; an element or an object.
4057 ((and (eq --category
'greater-elements
)
4058 (not (memq --type org-element-greater-elements
))))
4059 ;; Looking for elements but --DATA is an object.
4060 ((and (eq --category
'elements
)
4061 (memq --type org-element-all-objects
)))
4062 ;; In any other case, map contents.
4063 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4064 (catch '--map-first-match
4065 (funcall --walk-tree data
)
4066 ;; Return value in a proper order.
4068 (put 'org-element-map
'lisp-indent-function
2)
4070 ;; The following functions are internal parts of the parser.
4072 ;; The first one, `org-element--parse-elements' acts at the element's
4075 ;; The second one, `org-element--parse-objects' applies on all objects
4076 ;; of a paragraph or a secondary string.
4078 ;; More precisely, that function looks for every allowed object type
4079 ;; first. Then, it discards failed searches, keeps further matches,
4080 ;; and searches again types matched behind point, for subsequent
4081 ;; calls. Thus, searching for a given type fails only once, and every
4082 ;; object is searched only once at top level (but sometimes more for
4085 (defun org-element--parse-elements
4086 (beg end special structure granularity visible-only acc
)
4087 "Parse elements between BEG and END positions.
4089 SPECIAL prioritize some elements over the others. It can be set
4090 to `first-section', `section' `item' or `table-row'.
4092 When value is `item', STRUCTURE will be used as the current list
4095 GRANULARITY determines the depth of the recursion. See
4096 `org-element-parse-buffer' for more information.
4098 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4101 Elements are accumulated into ACC."
4104 ;; Visible only: skip invisible parts at the beginning of the
4106 (when (and visible-only
(org-invisible-p2))
4107 (goto-char (min (1+ (org-find-visible)) end
)))
4108 ;; When parsing only headlines, skip any text before first one.
4109 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4110 (org-with-limited-levels (outline-next-heading)))
4112 (while (< (point) end
)
4113 ;; Find current element's type and parse it accordingly to
4115 (let* ((element (org-element--current-element
4116 end granularity special structure
))
4117 (type (org-element-type element
))
4118 (cbeg (org-element-property :contents-begin element
)))
4119 (goto-char (org-element-property :end element
))
4120 ;; Visible only: skip invisible parts between siblings.
4121 (when (and visible-only
(org-invisible-p2))
4122 (goto-char (min (1+ (org-find-visible)) end
)))
4123 ;; Fill ELEMENT contents by side-effect.
4125 ;; If element has no contents, don't modify it.
4127 ;; Greater element: parse it between `contents-begin' and
4128 ;; `contents-end'. Make sure GRANULARITY allows the
4129 ;; recursion, or ELEMENT is a headline, in which case going
4130 ;; inside is mandatory, in order to get sub-level headings.
4131 ((and (memq type org-element-greater-elements
)
4132 (or (memq granularity
'(element object nil
))
4133 (and (eq granularity
'greater-element
)
4135 (eq type
'headline
)))
4136 (org-element--parse-elements
4137 cbeg
(org-element-property :contents-end element
)
4138 ;; Possibly switch to a special mode.
4142 (property-drawer 'node-property
)
4144 (and (memq type
'(item plain-list
))
4145 (org-element-property :structure element
))
4146 granularity visible-only element
))
4147 ;; ELEMENT has contents. Parse objects inside, if
4148 ;; GRANULARITY allows it.
4149 ((memq granularity
'(object nil
))
4150 (org-element--parse-objects
4151 cbeg
(org-element-property :contents-end element
) element
4152 (org-element-restriction type
))))
4153 (org-element-adopt-elements acc element
)))
4157 (defconst org-element--object-regexp
4158 (mapconcat #'identity
4159 (let ((link-types (regexp-opt org-link-types
)))
4162 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4163 ;; Bold, code, italic, strike-through, underline and
4166 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4168 (concat "\\<" link-types
":")
4169 ;; Objects starting with "[": regular link, footnote
4170 ;; reference, statistics cookie, timestamp (inactive).
4171 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4172 ;; Objects starting with "@": export snippets.
4174 ;; Objects starting with "{": macro.
4176 ;; Objects starting with "<" : timestamp (active,
4177 ;; diary), target, radio target and angular links.
4178 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4179 ;; Objects starting with "$": latex fragment.
4181 ;; Objects starting with "\": line break, entity,
4183 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4184 ;; Objects starting with raw text: inline Babel
4185 ;; source block, inline Babel call.
4186 "\\(?:call\\|src\\)_"))
4188 "Regexp possibly matching the beginning of an object.
4189 This regexp allows false positives. Dedicated parser (e.g.,
4190 `org-export-bold-parser') will take care of further filtering.
4191 Radio links are not matched by this regexp, as they are treated
4192 specially in `org-element--object-lex'.")
4194 (defun org-element--object-lex (restriction)
4195 "Return next object in current buffer or nil.
4196 RESTRICTION is a list of object types, as symbols, that should be
4197 looked after. This function assumes that the buffer is narrowed
4198 to an appropriate container (e.g., a paragraph)."
4199 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4201 (let ((limit (and org-target-link-regexp
4203 (or (bolp) (backward-char))
4204 (re-search-forward org-target-link-regexp nil t
))
4205 (match-beginning 1)))
4207 (while (and (not found
)
4208 (re-search-forward org-element--object-regexp limit t
))
4209 (goto-char (match-beginning 0))
4210 (let ((result (match-string 0)))
4213 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4214 (and (memq 'inline-babel-call restriction
)
4215 (org-element-inline-babel-call-parser)))
4216 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4217 (and (memq 'inline-src-block restriction
)
4218 (org-element-inline-src-block-parser)))
4221 (?^
(and (memq 'superscript restriction
)
4222 (org-element-superscript-parser)))
4223 (?_
(or (and (memq 'subscript restriction
)
4224 (org-element-subscript-parser))
4225 (and (memq 'underline restriction
)
4226 (org-element-underline-parser))))
4227 (?
* (and (memq 'bold restriction
)
4228 (org-element-bold-parser)))
4229 (?
/ (and (memq 'italic restriction
)
4230 (org-element-italic-parser)))
4231 (?~
(and (memq 'code restriction
)
4232 (org-element-code-parser)))
4233 (?
= (and (memq 'verbatim restriction
)
4234 (org-element-verbatim-parser)))
4235 (?
+ (and (memq 'strike-through restriction
)
4236 (org-element-strike-through-parser)))
4237 (?
@ (and (memq 'export-snippet restriction
)
4238 (org-element-export-snippet-parser)))
4239 (?
{ (and (memq 'macro restriction
)
4240 (org-element-macro-parser)))
4241 (?$
(and (memq 'latex-fragment restriction
)
4242 (org-element-latex-fragment-parser)))
4244 (if (eq (aref result
1) ?
<)
4245 (or (and (memq 'radio-target restriction
)
4246 (org-element-radio-target-parser))
4247 (and (memq 'target restriction
)
4248 (org-element-target-parser)))
4249 (or (and (memq 'timestamp restriction
)
4250 (org-element-timestamp-parser))
4251 (and (memq 'link restriction
)
4252 (org-element-link-parser)))))
4254 (if (eq (aref result
1) ?
\\)
4255 (and (memq 'line-break restriction
)
4256 (org-element-line-break-parser))
4257 (or (and (memq 'entity restriction
)
4258 (org-element-entity-parser))
4259 (and (memq 'latex-fragment restriction
)
4260 (org-element-latex-fragment-parser)))))
4262 (if (eq (aref result
1) ?\
[)
4263 (and (memq 'link restriction
)
4264 (org-element-link-parser))
4265 (or (and (memq 'footnote-reference restriction
)
4266 (org-element-footnote-reference-parser))
4267 (and (memq 'timestamp restriction
)
4268 (org-element-timestamp-parser))
4269 (and (memq 'statistics-cookie restriction
)
4270 (org-element-statistics-cookie-parser)))))
4271 ;; This is probably a plain link.
4272 (otherwise (and (or (memq 'link restriction
)
4273 (memq 'plain-link restriction
))
4274 (org-element-link-parser)))))))
4275 (or (eobp) (forward-char))))
4278 ((and limit
(memq 'link restriction
))
4279 (goto-char limit
) (org-element-link-parser)))))))
4281 (defun org-element--parse-objects (beg end acc restriction
)
4282 "Parse objects between BEG and END and return recursive structure.
4284 Objects are accumulated in ACC.
4286 RESTRICTION is a list of object successors which are allowed in
4287 the current object."
4290 (narrow-to-region beg end
)
4291 (goto-char (point-min))
4293 (while (and (not (eobp))
4294 (setq next-object
(org-element--object-lex restriction
)))
4295 ;; 1. Text before any object. Untabify it.
4296 (let ((obj-beg (org-element-property :begin next-object
)))
4297 (unless (= (point) obj-beg
)
4299 (org-element-adopt-elements
4301 (replace-regexp-in-string
4302 "\t" (make-string tab-width ?
)
4303 (buffer-substring-no-properties (point) obj-beg
))))))
4305 (let ((obj-end (org-element-property :end next-object
))
4306 (cont-beg (org-element-property :contents-begin next-object
)))
4307 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4308 ;; a recursive type.
4310 (memq (car next-object
) org-element-recursive-objects
))
4311 (org-element--parse-objects
4312 cont-beg
(org-element-property :contents-end next-object
)
4313 next-object
(org-element-restriction next-object
)))
4314 (setq acc
(org-element-adopt-elements acc next-object
))
4315 (goto-char obj-end
))))
4316 ;; 3. Text after last object. Untabify it.
4319 (org-element-adopt-elements
4321 (replace-regexp-in-string
4322 "\t" (make-string tab-width ?
)
4323 (buffer-substring-no-properties (point) end
)))))
4329 ;;; Towards A Bijective Process
4331 ;; The parse tree obtained with `org-element-parse-buffer' is really
4332 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4333 ;; interpreted and expanded into a string with canonical Org syntax.
4334 ;; Hence `org-element-interpret-data'.
4336 ;; The function relies internally on
4337 ;; `org-element--interpret-affiliated-keywords'.
4340 (defun org-element-interpret-data (data &optional pseudo-objects
)
4341 "Interpret DATA as Org syntax.
4343 DATA is a parse tree, an element, an object or a secondary string
4346 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4347 new types that should be treated as objects. An unknown type not
4348 belonging to this list is seen as a pseudo-element instead. Both
4349 pseudo-objects and pseudo-elements are transparent entities, i.e.
4350 only their contents are interpreted.
4352 Return Org syntax as a string."
4353 (org-element--interpret-data-1 data nil pseudo-objects
))
4355 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4356 "Interpret DATA as Org syntax.
4358 DATA is a parse tree, an element, an object or a secondary string
4359 to interpret. PARENT is used for recursive calls. It contains
4360 the element or object containing data, or nil. PSEUDO-OBJECTS
4361 are list of symbols defining new element or object types.
4362 Unknown types that don't belong to this list are treated as
4363 pseudo-elements instead.
4365 Return Org syntax as a string."
4366 (let* ((type (org-element-type data
))
4367 ;; Find interpreter for current object or element. If it
4368 ;; doesn't exist (e.g. this is a pseudo object or element),
4369 ;; return contents, if any.
4371 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4372 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4375 ;; Secondary string.
4379 (org-element--interpret-data-1 obj parent pseudo-objects
))
4381 ;; Full Org document.
4382 ((eq type
'org-data
)
4385 (org-element--interpret-data-1 obj parent pseudo-objects
))
4386 (org-element-contents data
) ""))
4387 ;; Plain text: return it.
4388 ((stringp data
) data
)
4389 ;; Element or object without contents.
4390 ((not (org-element-contents data
)) (funcall interpret data nil
))
4391 ;; Element or object with contents.
4393 (funcall interpret data
4394 ;; Recursively interpret contents.
4397 (org-element--interpret-data-1 obj data pseudo-objects
))
4398 (org-element-contents
4399 (if (not (memq type
'(paragraph verse-block
)))
4401 ;; Fix indentation of elements containing
4402 ;; objects. We ignore `table-row' elements
4403 ;; as they are one line long anyway.
4404 (org-element-normalize-contents
4406 ;; When normalizing first paragraph of an
4407 ;; item or a footnote-definition, ignore
4408 ;; first line's indentation.
4409 (and (eq type
'paragraph
)
4410 (equal data
(car (org-element-contents parent
)))
4411 (memq (org-element-type parent
)
4412 '(footnote-definition item
))))))
4414 (if (memq type
'(org-data plain-text nil
)) results
4415 ;; Build white spaces. If no `:post-blank' property is
4416 ;; specified, assume its value is 0.
4417 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4418 (if (or (memq type org-element-all-objects
)
4419 (memq type pseudo-objects
))
4420 (concat results
(make-string post-blank ?\s
))
4422 (org-element--interpret-affiliated-keywords data
)
4423 (org-element-normalize-string results
)
4424 (make-string post-blank ?
\n)))))))
4426 (defun org-element--interpret-affiliated-keywords (element)
4427 "Return ELEMENT's affiliated keywords as Org syntax.
4428 If there is no affiliated keyword, return the empty string."
4429 (let ((keyword-to-org
4433 (when (member key org-element-dual-keywords
)
4434 (setq dual
(cdr value
) value
(car value
)))
4437 (format "[%s]" (org-element-interpret-data dual
)))
4439 (if (member key org-element-parsed-keywords
)
4440 (org-element-interpret-data value
)
4445 (let ((value (org-element-property prop element
))
4446 (keyword (upcase (substring (symbol-name prop
) 1))))
4448 (if (or (member keyword org-element-multiple-keywords
)
4449 ;; All attribute keywords can have multiple lines.
4450 (string-match "^ATTR_" keyword
))
4451 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4454 (funcall keyword-to-org keyword value
)))))
4455 ;; List all ELEMENT's properties matching an attribute line or an
4456 ;; affiliated keyword, but ignore translated keywords since they
4457 ;; cannot belong to the property list.
4458 (loop for prop in
(nth 1 element
) by
'cddr
4459 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4460 (or (string-match "^ATTR_" keyword
)
4462 (member keyword org-element-affiliated-keywords
)
4464 org-element-keyword-translation-alist
)))))
4468 ;; Because interpretation of the parse tree must return the same
4469 ;; number of blank lines between elements and the same number of white
4470 ;; space after objects, some special care must be given to white
4473 ;; The first function, `org-element-normalize-string', ensures any
4474 ;; string different from the empty string will end with a single
4475 ;; newline character.
4477 ;; The second function, `org-element-normalize-contents', removes
4478 ;; global indentation from the contents of the current element.
4480 (defun org-element-normalize-string (s)
4481 "Ensure string S ends with a single newline character.
4483 If S isn't a string return it unchanged. If S is the empty
4484 string, return it. Otherwise, return a new string with a single
4485 newline character at its end."
4487 ((not (stringp s
)) s
)
4489 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4490 (replace-match "\n" nil nil s
)))))
4492 (defun org-element-normalize-contents (element &optional ignore-first
)
4493 "Normalize plain text in ELEMENT's contents.
4495 ELEMENT must only contain plain text and objects.
4497 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4498 indentation to compute maximal common indentation.
4500 Return the normalized element that is element with global
4501 indentation removed from its contents. The function assumes that
4502 indentation is not done with TAB characters."
4503 (let* ((min-ind most-positive-fixnum
)
4504 find-min-ind
; For byte-compiler.
4506 ;; Return minimal common indentation within BLOB. This is
4507 ;; done by walking recursively BLOB and updating MIN-IND
4508 ;; along the way. FIRST-FLAG is non-nil when the first
4509 ;; string hasn't been seen yet. It is required as this
4510 ;; string is the only one whose indentation doesn't happen
4511 ;; after a newline character.
4512 (lambda (blob first-flag
)
4513 (dolist (object (org-element-contents blob
))
4514 (when (and first-flag
(stringp object
))
4515 (setq first-flag nil
)
4516 (string-match "\\` *" object
)
4517 (let ((len (match-end 0)))
4518 ;; An indentation of zero means no string will be
4519 ;; modified. Quit the process.
4520 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4521 (setq min-ind
(min len min-ind
)))))
4524 (dolist (line (cdr (org-split-string object
" *\n")))
4525 (unless (string= line
"")
4526 (setq min-ind
(min (org-get-indentation line
) min-ind
)))))
4527 ((memq (org-element-type object
) org-element-recursive-objects
)
4528 (funcall find-min-ind object first-flag
)))))))
4529 ;; Find minimal indentation in ELEMENT.
4530 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4531 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4532 ;; Build ELEMENT back, replacing each string with the same
4533 ;; string minus common indentation.
4534 (let* (build ; For byte compiler.
4537 (lambda (blob first-flag
)
4538 ;; Return BLOB with all its strings indentation
4539 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4540 ;; is non-nil when the first string hasn't been seen
4545 (when (and first-flag
(stringp object
))
4546 (setq first-flag nil
)
4548 (replace-regexp-in-string
4549 (format "\\` \\{%d\\}" min-ind
)
4553 (replace-regexp-in-string
4554 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4555 ((memq (org-element-type object
)
4556 org-element-recursive-objects
)
4557 (funcall build object first-flag
))
4559 (org-element-contents blob
)))
4561 (funcall build element
(not ignore-first
))))))
4567 ;; Implement a caching mechanism for `org-element-at-point' and
4568 ;; `org-element-context', which see.
4570 ;; A single public function is provided: `org-element-cache-reset'.
4572 ;; Cache is enabled by default, but can be disabled globally with
4573 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4574 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4575 ;; can be tweaked to control caching behaviour.
4577 ;; Internally, parsed elements are stored in an AVL tree,
4578 ;; `org-element--cache'. This tree is updated lazily: whenever
4579 ;; a change happens to the buffer, a synchronization request is
4580 ;; registered in `org-element--cache-sync-requests' (see
4581 ;; `org-element--cache-submit-request'). During idle time, requests
4582 ;; are processed by `org-element--cache-sync'. Synchronization also
4583 ;; happens when an element is required from the cache. In this case,
4584 ;; the process stops as soon as the needed element is up-to-date.
4586 ;; A synchronization request can only apply on a synchronized part of
4587 ;; the cache. Therefore, the cache is updated at least to the
4588 ;; location where the new request applies. Thus, requests are ordered
4589 ;; from left to right and all elements starting before the first
4590 ;; request are correct. This property is used by functions like
4591 ;; `org-element--cache-find' to retrieve elements in the part of the
4592 ;; cache that can be trusted.
4594 ;; A request applies to every element, starting from its original
4595 ;; location (or key, see below). When a request is processed, it
4596 ;; moves forward and may collide the next one. In this case, both
4597 ;; requests are merged into a new one that starts from that element.
4598 ;; As a consequence, the whole synchronization complexity does not
4599 ;; depend on the number of pending requests, but on the number of
4600 ;; elements the very first request will be applied on.
4602 ;; Elements cannot be accessed through their beginning position, which
4603 ;; may or may not be up-to-date. Instead, each element in the tree is
4604 ;; associated to a key, obtained with `org-element--cache-key'. This
4605 ;; mechanism is robust enough to preserve total order among elements
4606 ;; even when the tree is only partially synchronized.
4608 ;; Objects contained in an element are stored in a hash table,
4609 ;; `org-element--cache-objects'.
4612 (defvar org-element-use-cache t
4613 "Non nil when Org parser should cache its results.
4614 This is mostly for debugging purpose.")
4616 (defvar org-element-cache-sync-idle-time
0.6
4617 "Length, in seconds, of idle time before syncing cache.")
4619 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4620 "Maximum duration, as a time value, for a cache synchronization.
4621 If the synchronization is not over after this delay, the process
4622 pauses and resumes after `org-element-cache-sync-break'
4625 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4626 "Duration, as a time value, of the pause between synchronizations.
4627 See `org-element-cache-sync-duration' for more information.")
4632 (defvar org-element--cache nil
4633 "AVL tree used to cache elements.
4634 Each node of the tree contains an element. Comparison is done
4635 with `org-element--cache-compare'. This cache is used in
4636 `org-element-at-point'.")
4638 (defvar org-element--cache-objects nil
4639 "Hash table used as to cache objects.
4640 Key is an element, as returned by `org-element-at-point', and
4641 value is an alist where each association is:
4643 \(PARENT COMPLETEP . OBJECTS)
4645 where PARENT is an element or object, COMPLETEP is a boolean,
4646 non-nil when all direct children of parent are already cached and
4647 OBJECTS is a list of such children, as objects, from farthest to
4650 In the following example, \\alpha, bold object and \\beta are
4651 contained within a paragraph
4655 If the paragraph is completely parsed, OBJECTS-DATA will be
4657 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4658 \(BOLD-OBJECT t ENTITY-OBJECT))
4660 whereas in a partially parsed paragraph, it could be
4662 \((PARAGRAPH nil ENTITY-OBJECT))
4664 This cache is used in `org-element-context'.")
4666 (defvar org-element--cache-sync-requests nil
4667 "List of pending synchronization requests.
4669 A request is a vector with the following pattern:
4671 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4673 Processing a synchronization request consists of three phases:
4675 0. Delete modified elements,
4676 1. Fill missing area in cache,
4677 2. Shift positions and re-parent elements after the changes.
4679 During phase 0, NEXT is the key of the first element to be
4680 removed, BEG and END is buffer position delimiting the
4681 modifications. Elements starting between them (inclusive) are
4682 removed and so are those contained within OUTREACH. PARENT, when
4683 non-nil, is the parent of the first element to be removed.
4685 During phase 1, NEXT is the key of the next known element in
4686 cache and BEG its beginning position. Parse buffer between that
4687 element and the one before it in order to determine the parent of
4688 the next element. Set PARENT to the element containing NEXT.
4690 During phase 2, NEXT is the key of the next element to shift in
4691 the parse tree. All elements starting from this one have their
4692 properties relatives to buffer positions shifted by integer
4693 OFFSET and, if they belong to element PARENT, are adopted by it.
4695 PHASE specifies the phase number, as an integer.")
4697 (defvar org-element--cache-sync-timer nil
4698 "Timer used for cache synchronization.")
4700 (defvar org-element--cache-sync-keys nil
4701 "Hash table used to store keys during synchronization.
4702 See `org-element--cache-key' for more information.")
4704 (defsubst org-element--cache-key
(element)
4705 "Return a unique key for ELEMENT in cache tree.
4707 Keys are used to keep a total order among elements in the cache.
4708 Comparison is done with `org-element--cache-key-less-p'.
4710 When no synchronization is taking place, a key is simply the
4711 beginning position of the element, or that position plus one in
4712 the case of an first item (respectively row) in
4713 a list (respectively a table).
4715 During a synchronization, the key is the one the element had when
4716 the cache was synchronized for the last time. Elements added to
4717 cache during the synchronization get a new key generated with
4718 `org-element--cache-generate-key'.
4720 Such keys are stored in `org-element--cache-sync-keys'. The hash
4721 table is cleared once the synchronization is complete."
4722 (or (gethash element org-element--cache-sync-keys
)
4723 (let* ((begin (org-element-property :begin element
))
4724 ;; Increase beginning position of items (respectively
4725 ;; table rows) by one, so the first item can get
4726 ;; a different key from its parent list (respectively
4728 (key (if (memq (org-element-type element
) '(item table-row
))
4731 (if org-element--cache-sync-requests
4732 (puthash element key org-element--cache-sync-keys
)
4735 (defun org-element--cache-generate-key (lower upper
)
4736 "Generate a key between LOWER and UPPER.
4738 LOWER and UPPER are integers or lists, possibly empty.
4740 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4741 a unique key, as an integer or a list of integers, according to
4742 the following rules:
4744 - LOWER and UPPER are compared level-wise until values differ.
4746 - If, at a given level, LOWER and UPPER differ from more than
4747 2, the new key shares all the levels above with LOWER and
4748 gets a new level. Its value is the mean between LOWER and
4751 \(1 2) + (1 4) --> (1 3)
4753 - If LOWER has no value to compare with, it is assumed that its
4754 value is `most-negative-fixnum'. E.g.,
4762 where m is `most-negative-fixnum'. Likewise, if UPPER is
4763 short of levels, the current value is `most-positive-fixnum'.
4765 - If they differ from only one, the new key inherits from
4766 current LOWER level and fork it at the next level. E.g.,
4774 where M is `most-positive-fixnum'.
4776 - If the key is only one level long, it is returned as an
4779 \(1 2) + (3 2) --> 2
4781 When they are not equals, the function assumes that LOWER is
4782 lesser than UPPER, per `org-element--cache-key-less-p'."
4783 (if (equal lower upper
) lower
4784 (let ((lower (if (integerp lower
) (list lower
) lower
))
4785 (upper (if (integerp upper
) (list upper
) upper
))
4789 (let ((min (or (car lower
) most-negative-fixnum
))
4790 (max (cond (skip-upper most-positive-fixnum
)
4792 (t most-positive-fixnum
))))
4793 (if (< (1+ min
) max
)
4794 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4795 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4796 (when (and (< min max
) (not skip-upper
))
4797 ;; When at a given level, LOWER and UPPER differ from
4798 ;; 1, ignore UPPER altogether. Instead create a key
4799 ;; between LOWER and the greatest key with the same
4800 ;; prefix as LOWER so far.
4801 (setq skip-upper t
))
4803 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
4805 (defsubst org-element--cache-key-less-p
(a b
)
4806 "Non-nil if key A is less than key B.
4807 A and B are either integers or lists of integers, as returned by
4808 `org-element--cache-key'."
4809 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4810 (if (integerp b
) (< (car a
) b
)
4813 (cond ((car-less-than-car a b
) (throw 'exit t
))
4814 ((car-less-than-car b a
) (throw 'exit nil
))
4815 (t (setq a
(cdr a
) b
(cdr b
)))))
4816 ;; If A is empty, either keys are equal (B is also empty) and
4817 ;; we return nil, or A is lesser than B (B is longer) and we
4818 ;; return a non-nil value.
4820 ;; If A is not empty, B is necessarily empty and A is greater
4821 ;; than B (A is longer). Therefore, return nil.
4822 (and (null a
) b
)))))
4824 (defun org-element--cache-compare (a b
)
4825 "Non-nil when element A is located before element B."
4826 (org-element--cache-key-less-p (org-element--cache-key a
)
4827 (org-element--cache-key b
)))
4829 (defsubst org-element--cache-root
()
4830 "Return root value in cache.
4831 This function assumes `org-element--cache' is a valid AVL tree."
4832 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4837 (defsubst org-element--cache-active-p
()
4838 "Non-nil when cache is active in current buffer."
4839 (and org-element-use-cache
4840 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4842 (defun org-element--cache-find (pos &optional side
)
4843 "Find element in cache starting at POS or before.
4845 POS refers to a buffer position.
4847 When optional argument SIDE is non-nil, the function checks for
4848 elements starting at or past POS instead. If SIDE is `both', the
4849 function returns a cons cell where car is the first element
4850 starting at or before POS and cdr the first element starting
4853 The function can only find elements in the synchronized part of
4855 (let ((limit (and org-element--cache-sync-requests
4856 (aref (car org-element--cache-sync-requests
) 0)))
4857 (node (org-element--cache-root))
4860 (let* ((element (avl-tree--node-data node
))
4861 (begin (org-element-property :begin element
)))
4864 (not (org-element--cache-key-less-p
4865 (org-element--cache-key element
) limit
)))
4866 (setq node
(avl-tree--node-left node
)))
4869 node
(avl-tree--node-left node
)))
4872 node
(avl-tree--node-right node
)))
4873 ;; We found an element in cache starting at POS. If `side'
4874 ;; is `both' we also want the next one in order to generate
4875 ;; a key in-between.
4877 ;; If the element is the first row or item in a table or
4878 ;; a plain list, we always return the table or the plain
4881 ;; In any other case, we return the element found.
4883 (setq lower element
)
4884 (setq node
(avl-tree--node-right node
)))
4885 ((and (memq (org-element-type element
) '(item table-row
))
4886 (let ((parent (org-element-property :parent element
)))
4887 (and (= (org-element-property :begin element
)
4888 (org-element-property :contents-begin parent
))
4897 (both (cons lower upper
))
4899 (otherwise upper
))))
4901 (defun org-element--cache-put (element &optional data
)
4902 "Store ELEMENT in current buffer's cache, if allowed.
4903 When optional argument DATA is non-nil, assume is it object data
4904 relative to ELEMENT and store it in the objects cache."
4905 (cond ((not (org-element--cache-active-p)) nil
)
4907 (when org-element--cache-sync-requests
4908 ;; During synchronization, first build an appropriate key
4909 ;; for the new element so `avl-tree-enter' can insert it at
4910 ;; the right spot in the cache.
4911 (let ((keys (org-element--cache-find
4912 (org-element-property :begin element
) 'both
)))
4914 (org-element--cache-generate-key
4915 (and (car keys
) (org-element--cache-key (car keys
)))
4916 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4917 (org-element--cache-sync-requests
4918 (aref (car org-element--cache-sync-requests
) 0))))
4919 org-element--cache-sync-keys
)))
4920 (avl-tree-enter org-element--cache element
))
4921 ;; Headlines are not stored in cache, so objects in titles are
4922 ;; not stored either.
4923 ((eq (org-element-type element
) 'headline
) nil
)
4924 (t (puthash element data org-element--cache-objects
))))
4926 (defsubst org-element--cache-remove
(element)
4927 "Remove ELEMENT from cache.
4928 Assume ELEMENT belongs to cache and that a cache is active."
4929 (avl-tree-delete org-element--cache element
)
4930 (remhash element org-element--cache-objects
))
4933 ;;;; Synchronization
4935 (defsubst org-element--cache-set-timer
(buffer)
4936 "Set idle timer for cache synchronization in BUFFER."
4937 (when org-element--cache-sync-timer
4938 (cancel-timer org-element--cache-sync-timer
))
4939 (setq org-element--cache-sync-timer
4940 (run-with-idle-timer
4941 (let ((idle (current-idle-time)))
4942 (if idle
(time-add idle org-element-cache-sync-break
)
4943 org-element-cache-sync-idle-time
))
4945 #'org-element--cache-sync
4948 (defsubst org-element--cache-interrupt-p
(time-limit)
4949 "Non-nil when synchronization process should be interrupted.
4950 TIME-LIMIT is a time value or nil."
4952 (or (input-pending-p)
4953 (time-less-p time-limit
(current-time)))))
4955 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
4956 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4958 Properties containing buffer positions are `:begin', `:end',
4959 `:contents-begin', `:contents-end' and `:structure'. When
4960 optional argument PROPS is a list of keywords, only shift
4961 properties provided in that list.
4963 Properties are modified by side-effect."
4964 (let ((properties (nth 1 element
)))
4965 ;; Shift `:structure' property for the first plain list only: it
4966 ;; is the only one that really matters and it prevents from
4967 ;; shifting it more than once.
4968 (when (and (or (not props
) (memq :structure props
))
4969 (eq (org-element-type element
) 'plain-list
)
4970 (not (eq (org-element-type (plist-get properties
:parent
))
4972 (dolist (item (plist-get properties
:structure
))
4973 (incf (car item
) offset
)
4974 (incf (nth 6 item
) offset
)))
4975 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
4976 (let ((value (and (or (not props
) (memq key props
))
4977 (plist-get properties key
))))
4978 (and value
(plist-put properties key
(+ offset value
)))))))
4980 (defun org-element--cache-sync (buffer &optional threshold future-change
)
4981 "Synchronize cache with recent modification in BUFFER.
4983 When optional argument THRESHOLD is non-nil, do the
4984 synchronization for all elements starting before or at threshold,
4985 then exit. Otherwise, synchronize cache for as long as
4986 `org-element-cache-sync-duration' or until Emacs leaves idle
4989 FUTURE-CHANGE, when non-nil, is a buffer position where changes
4990 not registered yet in the cache are going to happen. It is used
4991 in `org-element--cache-submit-request', where cache is partially
4992 updated before current modification are actually submitted."
4993 (when (buffer-live-p buffer
)
4994 (with-current-buffer buffer
4995 (let ((inhibit-quit t
) request next
)
4996 (when org-element--cache-sync-timer
4997 (cancel-timer org-element--cache-sync-timer
))
4999 (while org-element--cache-sync-requests
5000 (setq request
(car org-element--cache-sync-requests
)
5001 next
(nth 1 org-element--cache-sync-requests
))
5002 (org-element--cache-process-request
5004 (and next
(aref next
0))
5006 (and (not threshold
)
5007 (time-add (current-time)
5008 org-element-cache-sync-duration
))
5010 ;; Request processed. Merge current and next offsets and
5011 ;; transfer ending position.
5013 (incf (aref next
3) (aref request
3))
5014 (aset next
2 (aref request
2)))
5015 (setq org-element--cache-sync-requests
5016 (cdr org-element--cache-sync-requests
))))
5017 ;; If more requests are awaiting, set idle timer accordingly.
5018 ;; Otherwise, reset keys.
5019 (if org-element--cache-sync-requests
5020 (org-element--cache-set-timer buffer
)
5021 (clrhash org-element--cache-sync-keys
))))))
5023 (defun org-element--cache-process-request
5024 (request next threshold time-limit future-change
)
5025 "Process synchronization REQUEST for all entries before NEXT.
5027 REQUEST is a vector, built by `org-element--cache-submit-request'.
5029 NEXT is a cache key, as returned by `org-element--cache-key'.
5031 When non-nil, THRESHOLD is a buffer position. Synchronization
5032 stops as soon as a shifted element begins after it.
5034 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5035 after this time or when Emacs exits idle state.
5037 When non-nil, FUTURE-CHANGE is a buffer position where changes
5038 not registered yet in the cache are going to happen. See
5039 `org-element--cache-submit-request' for more information.
5041 Throw `interrupt' if the process stops before completing the
5044 (when (= (aref request
6) 0)
5047 ;; Delete all elements starting after BEG, but not after buffer
5048 ;; position END or past element with key NEXT.
5050 ;; At each iteration, we start again at tree root since
5051 ;; a deletion modifies structure of the balanced tree.
5053 (let ((beg (aref request
0))
5054 (end (aref request
2))
5055 (outreach (aref request
4)))
5057 (when (org-element--cache-interrupt-p time-limit
)
5058 (throw 'interrupt nil
))
5059 ;; Find first element in cache with key BEG or after it.
5060 (let ((node (org-element--cache-root)) data data-key
)
5062 (let* ((element (avl-tree--node-data node
))
5063 (key (org-element--cache-key element
)))
5065 ((org-element--cache-key-less-p key beg
)
5066 (setq node
(avl-tree--node-right node
)))
5067 ((org-element--cache-key-less-p beg key
)
5070 node
(avl-tree--node-left node
)))
5071 (t (setq data element
5075 (let ((pos (org-element-property :begin data
)))
5076 (if (if (or (not next
)
5077 (org-element--cache-key-less-p data-key next
))
5080 (while (and up
(not (eq up outreach
)))
5081 (setq up
(org-element-property :parent up
)))
5083 (org-element--cache-remove data
)
5084 (aset request
0 data-key
)
5085 (aset request
1 pos
)
5087 (throw 'end-phase nil
)))
5088 ;; No element starting after modifications left in
5089 ;; cache: further processing is futile.
5090 (throw 'quit t
)))))))
5091 (when (= (aref request
6) 1)
5094 ;; Phase 0 left a hole in the cache. Some elements after it
5095 ;; could have parents within. For example, in the following
5105 ;; if we remove a blank line between "item" and "Paragraph1",
5106 ;; everything down to "Paragraph2" is removed from cache. But
5107 ;; the paragraph now belongs to the list, and its `:parent'
5108 ;; property no longer is accurate.
5110 ;; Therefore we need to parse again elements in the hole, or at
5111 ;; least in its last section, so that we can re-parent
5112 ;; subsequent elements, during phase 2.
5114 ;; Note that we only need to get the parent from the first
5115 ;; element in cache after the hole.
5117 ;; When next key is lesser or equal to the current one, delegate
5118 ;; phase 1 processing to next request in order to preserve key
5119 ;; order among requests.
5120 (let ((key (aref request
0)))
5121 (when (and next
(not (org-element--cache-key-less-p key next
)))
5122 (let ((next-request (nth 1 org-element--cache-sync-requests
)))
5123 (aset next-request
0 key
)
5124 (aset next-request
1 (aref request
1))
5125 (aset next-request
6 1))
5127 ;; Next element will start at its beginning position plus
5128 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5129 ;; contains the real beginning position of the first element to
5130 ;; shift and re-parent.
5131 (let ((limit (+ (aref request
1) (aref request
3))))
5132 (cond ((and threshold
(> limit threshold
)) (throw 'interrupt nil
))
5133 ((and future-change
(>= limit future-change
))
5134 ;; Changes are going to happen around this element and
5135 ;; they will trigger another phase 1 request. Skip the
5139 (let ((parent (org-element--parse-to limit t time-limit
)))
5140 (aset request
5 parent
)
5141 (aset request
6 2))))))
5144 ;; Shift all elements starting from key START, but before NEXT, by
5145 ;; OFFSET, and re-parent them when appropriate.
5147 ;; Elements are modified by side-effect so the tree structure
5150 ;; Once THRESHOLD, if any, is reached, or once there is an input
5151 ;; pending, exit. Before leaving, the current synchronization
5152 ;; request is updated.
5153 (let ((start (aref request
0))
5154 (offset (aref request
3))
5155 (parent (aref request
5))
5156 (node (org-element--cache-root))
5160 ;; No re-parenting nor shifting planned: request is over.
5161 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5163 (let* ((data (avl-tree--node-data node
))
5164 (key (org-element--cache-key data
)))
5165 (if (and leftp
(avl-tree--node-left node
)
5166 (not (org-element--cache-key-less-p key start
)))
5167 (progn (push node stack
)
5168 (setq node
(avl-tree--node-left node
)))
5169 (unless (org-element--cache-key-less-p key start
)
5170 ;; We reached NEXT. Request is complete.
5171 (when (equal key next
) (throw 'quit t
))
5172 ;; Handle interruption request. Update current request.
5173 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5174 (aset request
0 key
)
5175 (aset request
5 parent
)
5176 (throw 'interrupt nil
))
5178 (unless (zerop offset
)
5179 (org-element--cache-shift-positions data offset
)
5180 ;; Shift associated objects data, if any.
5181 (dolist (object-data (gethash data org-element--cache-objects
))
5182 (dolist (object (cddr object-data
))
5183 (org-element--cache-shift-positions object offset
))))
5184 (let ((begin (org-element-property :begin data
)))
5185 ;; Update PARENT and re-parent DATA, only when
5186 ;; necessary. Propagate new structures for lists.
5188 (<= (org-element-property :end parent
) begin
))
5189 (setq parent
(org-element-property :parent parent
)))
5190 (cond ((and (not parent
) (zerop offset
)) (throw 'quit nil
))
5192 (let ((p (org-element-property :parent data
)))
5194 (< (org-element-property :begin p
)
5195 (org-element-property :begin parent
)))))
5196 (org-element-put-property data
:parent parent
)
5197 (let ((s (org-element-property :structure parent
)))
5198 (when (and s
(org-element-property :structure data
))
5199 (org-element-put-property data
:structure s
)))))
5200 ;; Cache is up-to-date past THRESHOLD. Request
5202 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5203 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5204 (avl-tree--node-right node
)
5206 ;; We reached end of tree: synchronization complete.
5209 (defun org-element--parse-to (pos &optional syncp time-limit
)
5210 "Parse elements in current section, down to POS.
5212 Start parsing from the closest between the last known element in
5213 cache or headline above. Return the smallest element containing
5216 When optional argument SYNCP is non-nil, return the parent of the
5217 element containing POS instead. In that case, it is also
5218 possible to provide TIME-LIMIT, which is a time value specifying
5219 when the parsing should stop. The function throws `interrupt' if
5220 the process stopped before finding the expected result."
5222 (org-with-wide-buffer
5224 (let* ((cached (and (org-element--cache-active-p)
5225 (org-element--cache-find pos nil
)))
5226 (begin (org-element-property :begin cached
))
5229 ;; Nothing in cache before point: start parsing from first
5230 ;; element following headline above, or first element in
5233 (when (org-with-limited-levels (outline-previous-heading))
5235 (skip-chars-forward " \r\t\n")
5236 (beginning-of-line))
5237 ;; Cache returned exact match: return it.
5239 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5240 ;; There's a headline between cached value and POS: cached
5241 ;; value is invalid. Start parsing from first element
5242 ;; following the headline.
5243 ((re-search-backward
5244 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5246 (skip-chars-forward " \r\t\n")
5247 (beginning-of-line))
5248 ;; Check if CACHED or any of its ancestors contain point.
5250 ;; If there is such an element, we inspect it in order to know
5251 ;; if we return it or if we need to parse its contents.
5252 ;; Otherwise, we just start parsing from current location,
5253 ;; which is right after the top-most element containing
5256 ;; As a special case, if POS is at the end of the buffer, we
5257 ;; want to return the innermost element ending there.
5259 ;; Also, if we find an ancestor and discover that we need to
5260 ;; parse its contents, make sure we don't start from
5261 ;; `:contents-begin', as we would otherwise go past CACHED
5262 ;; again. Instead, in that situation, we will resume parsing
5263 ;; from NEXT, which is located after CACHED or its higher
5264 ;; ancestor not containing point.
5267 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5268 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5269 (while (let ((end (org-element-property :end up
)))
5272 (setq up
(org-element-property :parent up
)))))
5274 ((eobp) (setq element up
))
5275 (t (setq element up next
(point)))))))
5276 ;; Parse successively each element until we reach POS.
5277 (let ((end (or (org-element-property :end element
)
5279 (org-with-limited-levels (outline-next-heading))
5285 (cond ((= (point) pos
) (throw 'exit parent
))
5286 ((org-element--cache-interrupt-p time-limit
)
5287 (throw 'interrupt nil
))))
5289 (setq element
(org-element--current-element
5290 end
'element special-flag
5291 (org-element-property :structure parent
)))
5292 (org-element-put-property element
:parent parent
)
5293 (org-element--cache-put element
))
5294 (let ((elem-end (org-element-property :end element
))
5295 (type (org-element-type element
)))
5297 ;; Skip any element ending before point. Also skip
5298 ;; element ending at point (unless it is also the end of
5299 ;; buffer) since we're sure that another element begins
5301 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5302 (goto-char elem-end
))
5303 ;; A non-greater element contains point: return it.
5304 ((not (memq type org-element-greater-elements
))
5305 (throw 'exit element
))
5306 ;; Otherwise, we have to decide if ELEMENT really
5307 ;; contains POS. In that case we start parsing from
5308 ;; contents' beginning.
5310 ;; If POS is at contents' beginning but it is also at
5311 ;; the beginning of the first item in a list or a table.
5312 ;; In that case, we need to create an anchor for that
5313 ;; list or table, so return it.
5315 ;; Also, if POS is at the end of the buffer, no element
5316 ;; can start after it, but more than one may end there.
5317 ;; Arbitrarily, we choose to return the innermost of
5319 ((let ((cbeg (org-element-property :contents-begin element
))
5320 (cend (org-element-property :contents-end element
)))
5325 (not (memq type
'(plain-list table
)))))
5327 (and (= cend pos
) (= (point-max) pos
)))))
5328 (goto-char (or next cbeg
))
5330 special-flag
(case type
5332 (property-drawer 'node-property
)
5336 ;; Otherwise, return ELEMENT as it is the smallest
5337 ;; element containing POS.
5338 (t (throw 'exit element
))))
5339 (setq element nil
)))))))
5342 ;;;; Staging Buffer Changes
5344 (defconst org-element--cache-sensitive-re
5346 org-outline-regexp-bol
"\\|"
5349 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5350 ;; LaTeX environments.
5351 "\\\\\\(?:begin{[A-Za-z0-9*]+}\\|end{[A-Za-z0-9*]+}[ \t]*$\\)" "\\|"
5353 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5355 "Regexp matching a sensitive line, structure wise.
5356 A sensitive line is a headline, inlinetask, block, drawer, or
5357 latex-environment boundary. When such a line is modified,
5358 structure changes in the document may propagate in the whole
5359 section, possibly making cache invalid.")
5361 (defvar org-element--cache-change-warning nil
5362 "Non-nil when a sensitive line is about to be changed.
5363 It is a symbol among nil, t and `headline'.")
5365 (defun org-element--cache-before-change (beg end
)
5366 "Request extension of area going to be modified if needed.
5367 BEG and END are the beginning and end of the range of changed
5368 text. See `before-change-functions' for more information."
5369 (when (org-element--cache-active-p)
5370 (org-with-wide-buffer
5373 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5374 (setq org-element--cache-change-warning
5376 (if (and (org-with-limited-levels (org-at-heading-p))
5377 (= (line-end-position) bottom
))
5379 (let ((case-fold-search t
))
5381 org-element--cache-sensitive-re bottom t
)))))))))
5383 (defun org-element--cache-after-change (beg end pre
)
5384 "Update buffer modifications for current buffer.
5385 BEG and END are the beginning and end of the range of changed
5386 text, and the length in bytes of the pre-change text replaced by
5387 that range. See `after-change-functions' for more information."
5388 (when (org-element--cache-active-p)
5389 (org-with-wide-buffer
5394 (bottom (save-excursion (goto-char end
) (line-end-position))))
5395 ;; Determine if modified area needs to be extended, according
5396 ;; to both previous and current state. We make a special
5397 ;; case for headline editing: if a headline is modified but
5398 ;; not removed, do not extend.
5399 (when (case org-element--cache-change-warning
5402 (not (and (org-with-limited-levels (org-at-heading-p))
5403 (= (line-end-position) bottom
))))
5405 (let ((case-fold-search t
))
5407 org-element--cache-sensitive-re bottom t
))))
5408 ;; Effectively extend modified area.
5409 (org-with-limited-levels
5410 (setq top
(progn (goto-char top
)
5411 (when (outline-previous-heading) (forward-line))
5413 (setq bottom
(progn (goto-char bottom
)
5414 (if (outline-next-heading) (1- (point))
5416 ;; Store synchronization request.
5417 (let ((offset (- end beg pre
)))
5418 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5419 ;; Activate a timer to process the request during idle time.
5420 (org-element--cache-set-timer (current-buffer))))
5422 (defun org-element--cache-for-removal (beg end offset
)
5423 "Return first element to remove from cache.
5425 BEG and END are buffer positions delimiting buffer modifications.
5426 OFFSET is the size of the changes.
5428 Returned element is usually the first element in cache containing
5429 any position between BEG and END. As an exception, greater
5430 elements around the changes that are robust to contents
5431 modifications are preserved and updated according to the
5433 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5434 (before (car elements
))
5435 (after (cdr elements
)))
5436 (if (not before
) after
5440 (if (and (memq (org-element-type up
)
5441 '(center-block drawer dynamic-block
5442 property-drawer quote-block
5444 (<= (org-element-property :contents-begin up
) beg
)
5445 (> (org-element-property :contents-end up
) end
))
5446 ;; UP is a robust greater element containing changes.
5447 ;; We only need to extend its ending boundaries.
5448 (org-element--cache-shift-positions
5449 up offset
'(:contents-end
:end
))
5451 (when robust-flag
(setq robust-flag nil
)))
5452 (setq up
(org-element-property :parent up
)))
5453 ;; We're at top level element containing ELEMENT: if it's
5454 ;; altered by buffer modifications, it is first element in
5455 ;; cache to be removed. Otherwise, that first element is the
5458 ;; As a special case, do not remove BEFORE if it is a robust
5459 ;; container for current changes.
5460 (if (or (< (org-element-property :end before
) beg
) robust-flag
) after
5463 (defun org-element--cache-submit-request (beg end offset
)
5464 "Submit a new cache synchronization request for current buffer.
5465 BEG and END are buffer positions delimiting the minimal area
5466 where cache data should be removed. OFFSET is the size of the
5467 change, as an integer."
5468 (let ((next (car org-element--cache-sync-requests
))
5469 delete-to delete-from
)
5471 (zerop (aref next
6))
5472 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5473 (<= (setq delete-from
(aref next
1)) end
))
5474 ;; Current changes can be merged with first sync request: we
5475 ;; can save a partial cache synchronization.
5477 (incf (aref next
3) offset
)
5478 ;; If last change happened within area to be removed, extend
5479 ;; boundaries of robust parents, if any. Otherwise, find
5480 ;; first element to remove and update request accordingly.
5481 (if (> beg delete-from
)
5482 (let ((up (aref next
5)))
5484 (org-element--cache-shift-positions
5485 up offset
'(:contents-end
:end
))
5486 (setq up
(org-element-property :parent up
))))
5487 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5489 (aset next
0 (org-element--cache-key first
))
5490 (aset next
1 (org-element-property :begin first
))
5491 (aset next
5 (org-element-property :parent first
))))))
5492 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5493 ;; if any, is no longer a 0-phase request, thus ensuring that
5494 ;; phases are properly ordered. We need to provide OFFSET as
5495 ;; optional parameter since current modifications are not known
5496 ;; yet to the otherwise correct part of the cache (i.e, before
5497 ;; the first request).
5498 (when next
(org-element--cache-sync (current-buffer) end beg
))
5499 (let ((first (org-element--cache-for-removal beg end offset
)))
5501 (push (let ((beg (org-element-property :begin first
))
5502 (key (org-element--cache-key first
)))
5504 ;; When changes happen before the first known
5505 ;; element, re-parent and shift the rest of the
5507 ((> beg end
) (vector key beg nil offset nil nil
1))
5508 ;; Otherwise, we find the first non robust
5509 ;; element containing END. All elements between
5510 ;; FIRST and this one are to be removed.
5512 ;; Among them, some could be located outside the
5513 ;; synchronized part of the cache, in which case
5514 ;; comparing buffer positions to find them is
5515 ;; useless. Instead, we store the element
5516 ;; containing them in the request itself. All
5517 ;; its children will be removed.
5518 ((let ((first-end (org-element-property :end first
)))
5519 (and (> first-end end
)
5520 (vector key beg first-end offset first
5521 (org-element-property :parent first
) 0))))
5523 (let* ((element (org-element--cache-find end
))
5524 (end (org-element-property :end element
))
5526 (while (and (setq up
(org-element-property :parent up
))
5527 (>= (org-element-property :begin up
) beg
))
5528 (setq end
(org-element-property :end up
)
5530 (vector key beg end offset element
5531 (org-element-property :parent first
) 0)))))
5532 org-element--cache-sync-requests
)
5533 ;; No element to remove. No need to re-parent either.
5534 ;; Simply shift additional elements, if any, by OFFSET.
5535 (when org-element--cache-sync-requests
5536 (incf (aref (car org-element--cache-sync-requests
) 3) offset
)))))))
5539 ;;;; Public Functions
5542 (defun org-element-cache-reset (&optional all
)
5543 "Reset cache in current buffer.
5544 When optional argument ALL is non-nil, reset cache in all Org
5547 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5548 (with-current-buffer buffer
5549 (when (org-element--cache-active-p)
5550 (org-set-local 'org-element--cache
5551 (avl-tree-create #'org-element--cache-compare
))
5552 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5553 (org-set-local 'org-element--cache-sync-keys
5554 (make-hash-table :weakness
'key
:test
#'eq
))
5555 (org-set-local 'org-element--cache-change-warning nil
)
5556 (org-set-local 'org-element--cache-sync-requests nil
)
5557 (org-set-local 'org-element--cache-sync-timer nil
)
5558 (add-hook 'before-change-functions
5559 #'org-element--cache-before-change nil t
)
5560 (add-hook 'after-change-functions
5561 #'org-element--cache-after-change nil t
)))))
5564 (defun org-element-cache-refresh (pos)
5565 "Refresh cache at position POS."
5566 (when (org-element--cache-active-p)
5567 (org-element--cache-sync (current-buffer) pos
)
5568 (org-element--cache-submit-request pos pos
0)
5569 (org-element--cache-set-timer (current-buffer))))
5575 ;; The first move is to implement a way to obtain the smallest element
5576 ;; containing point. This is the job of `org-element-at-point'. It
5577 ;; basically jumps back to the beginning of section containing point
5578 ;; and proceed, one element after the other, with
5579 ;; `org-element--current-element' until the container is found. Note:
5580 ;; When using `org-element-at-point', secondary values are never
5581 ;; parsed since the function focuses on elements, not on objects.
5583 ;; At a deeper level, `org-element-context' lists all elements and
5584 ;; objects containing point.
5586 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5587 ;; internally by navigation and manipulation tools.
5591 (defun org-element-at-point ()
5592 "Determine closest element around point.
5594 Return value is a list like (TYPE PROPS) where TYPE is the type
5595 of the element and PROPS a plist of properties associated to the
5598 Possible types are defined in `org-element-all-elements'.
5599 Properties depend on element or object type, but always include
5600 `:begin', `:end', `:parent' and `:post-blank' properties.
5602 As a special case, if point is at the very beginning of the first
5603 item in a list or sub-list, returned element will be that list
5604 instead of the item. Likewise, if point is at the beginning of
5605 the first row of a table, returned element will be the table
5606 instead of the first row.
5608 When point is at the end of the buffer, return the innermost
5609 element ending there."
5610 (org-with-wide-buffer
5611 (let ((origin (point)))
5613 (skip-chars-backward " \r\t\n")
5615 ;; Within blank lines at the beginning of buffer, return nil.
5617 ;; Within blank lines right after a headline, return that
5619 ((org-with-limited-levels (org-at-heading-p))
5621 (org-element-headline-parser (point-max) t
))
5622 ;; Otherwise parse until we find element containing ORIGIN.
5624 (when (org-element--cache-active-p)
5625 (if (not org-element--cache
) (org-element-cache-reset)
5626 (org-element--cache-sync (current-buffer) origin
)))
5627 (org-element--parse-to origin
))))))
5630 (defun org-element-context (&optional element
)
5631 "Return smallest element or object around point.
5633 Return value is a list like (TYPE PROPS) where TYPE is the type
5634 of the element or object and PROPS a plist of properties
5637 Possible types are defined in `org-element-all-elements' and
5638 `org-element-all-objects'. Properties depend on element or
5639 object type, but always include `:begin', `:end', `:parent' and
5642 As a special case, if point is right after an object and not at
5643 the beginning of any other object, return that object.
5645 Optional argument ELEMENT, when non-nil, is the closest element
5646 containing point, as returned by `org-element-at-point'.
5647 Providing it allows for quicker computation."
5648 (catch 'objects-forbidden
5649 (org-with-wide-buffer
5650 (let* ((pos (point))
5651 (element (or element
(org-element-at-point)))
5652 (type (org-element-type element
)))
5653 ;; If point is inside an element containing objects or
5654 ;; a secondary string, narrow buffer to the container and
5655 ;; proceed with parsing. Otherwise, return ELEMENT.
5657 ;; At a parsed affiliated keyword, check if we're inside main
5659 ((let ((post (org-element-property :post-affiliated element
)))
5660 (and post
(< pos post
)))
5662 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5664 ((not (member-ignore-case (match-string 1)
5665 org-element-parsed-keywords
))
5666 (throw 'objects-forbidden element
))
5667 ((< (match-end 0) pos
)
5668 (narrow-to-region (match-end 0) (line-end-position)))
5669 ((and (match-beginning 2)
5670 (>= pos
(match-beginning 2))
5671 (< pos
(match-end 2)))
5672 (narrow-to-region (match-beginning 2) (match-end 2)))
5673 (t (throw 'objects-forbidden element
)))
5674 ;; Also change type to retrieve correct restrictions.
5675 (setq type
'keyword
))
5676 ;; At an item, objects can only be located within tag, if any.
5678 (let ((tag (org-element-property :tag element
)))
5679 (if (not tag
) (throw 'objects-forbidden element
)
5681 (search-forward tag
(line-end-position))
5682 (goto-char (match-beginning 0))
5683 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5684 (narrow-to-region (point) (match-end 0))
5685 (throw 'objects-forbidden element
)))))
5686 ;; At an headline or inlinetask, objects are in title.
5687 ((memq type
'(headline inlinetask
))
5688 (goto-char (org-element-property :begin element
))
5689 (skip-chars-forward "*")
5690 (if (and (> pos
(point)) (< pos
(line-end-position)))
5691 (narrow-to-region (point) (line-end-position))
5692 (throw 'objects-forbidden element
)))
5693 ;; At a paragraph, a table-row or a verse block, objects are
5694 ;; located within their contents.
5695 ((memq type
'(paragraph table-row verse-block
))
5696 (let ((cbeg (org-element-property :contents-begin element
))
5697 (cend (org-element-property :contents-end element
)))
5698 ;; CBEG is nil for table rules.
5699 (if (and cbeg cend
(>= pos cbeg
)
5700 (or (< pos cend
) (and (= pos cend
) (eobp))))
5701 (narrow-to-region cbeg cend
)
5702 (throw 'objects-forbidden element
))))
5703 ;; At a parsed keyword, objects are located within value.
5705 (if (not (member (org-element-property :key element
)
5706 org-element-document-properties
))
5707 (throw 'objects-forbidden element
)
5709 (search-forward ":")
5710 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5711 (narrow-to-region (point) (line-end-position))
5712 (throw 'objects-forbidden element
))))
5713 ;; At a planning line, if point is at a timestamp, return it,
5714 ;; otherwise, return element.
5715 ((eq type
'planning
)
5716 (dolist (p '(:closed
:deadline
:scheduled
))
5717 (let ((timestamp (org-element-property p element
)))
5718 (when (and timestamp
5719 (<= (org-element-property :begin timestamp
) pos
)
5720 (> (org-element-property :end timestamp
) pos
))
5721 (throw 'objects-forbidden timestamp
))))
5722 ;; All other locations cannot contain objects: bail out.
5723 (throw 'objects-forbidden element
))
5724 (t (throw 'objects-forbidden element
)))
5725 (goto-char (point-min))
5726 (let ((restriction (org-element-restriction type
))
5728 (cache (cond ((not (org-element--cache-active-p)) nil
)
5729 (org-element--cache-objects
5730 (gethash element org-element--cache-objects
))
5731 (t (org-element-cache-reset) nil
)))
5732 next object-data last
)
5736 ;; When entering PARENT for the first time, get list
5737 ;; of objects within known so far. Store it in
5740 (let ((data (assq parent cache
)))
5741 (if data
(setq object-data data
)
5742 (push (setq object-data
(list parent nil
)) cache
))))
5743 ;; Find NEXT object for analysis.
5745 ;; If NEXT is non-nil, we already exhausted the
5746 ;; cache so we can parse buffer to find the object
5748 (if next
(setq next
(org-element--object-lex restriction
))
5749 ;; Otherwise, check if cache can help us.
5750 (let ((objects (cddr object-data
))
5751 (completep (nth 1 object-data
)))
5753 ((and (not objects
) completep
) (throw 'exit parent
))
5755 (setq next
(org-element--object-lex restriction
)))
5758 (org-element-property :end
(car objects
))))
5759 (if (>= cache-limit pos
)
5760 ;; Cache contains the information needed.
5761 (dolist (object objects
(throw 'exit parent
))
5762 (when (<= (org-element-property :begin object
)
5764 (if (>= (org-element-property :end object
)
5766 (throw 'found
(setq next object
))
5767 (throw 'exit parent
))))
5768 (goto-char cache-limit
)
5770 (org-element--object-lex restriction
))))))))
5771 ;; If we have a new object to analyze, store it in
5772 ;; cache. Otherwise record that there is nothing
5773 ;; more to parse in this element at this depth.
5775 (progn (org-element-put-property next
:parent parent
)
5776 (push next
(cddr object-data
)))
5777 (setcar (cdr object-data
) t
)))
5778 ;; Process NEXT, if any, in order to know if we need
5779 ;; to skip it, return it or move into it.
5780 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5781 (throw 'exit
(or last parent
))
5782 (let ((end (org-element-property :end next
))
5783 (cbeg (org-element-property :contents-begin next
))
5784 (cend (org-element-property :contents-end next
)))
5786 ;; Skip objects ending before point. Also skip
5787 ;; objects ending at point unless it is also the
5788 ;; end of buffer, since we want to return the
5789 ;; innermost object.
5790 ((and (<= end pos
) (/= (point-max) end
))
5792 ;; For convenience, when object ends at POS,
5793 ;; without any space, store it in LAST, as we
5794 ;; will return it if no object starts here.
5795 (when (and (= end pos
)
5796 (not (memq (char-before) '(?\s ?
\t))))
5798 ;; If POS is within a container object, move
5799 ;; into that object.
5803 ;; At contents' end, if there is no
5804 ;; space before point, also move into
5805 ;; object, for consistency with
5806 ;; convenience feature above.
5808 (or (= (point-max) pos
)
5809 (not (memq (char-before pos
)
5812 (narrow-to-region (point) cend
)
5814 restriction
(org-element-restriction next
)
5817 ;; Otherwise, return NEXT.
5818 (t (throw 'exit next
)))))))
5819 ;; Store results in cache, if applicable.
5820 (org-element--cache-put element cache
)))))))
5822 (defun org-element-nested-p (elem-A elem-B
)
5823 "Non-nil when elements ELEM-A and ELEM-B are nested."
5824 (let ((beg-A (org-element-property :begin elem-A
))
5825 (beg-B (org-element-property :begin elem-B
))
5826 (end-A (org-element-property :end elem-A
))
5827 (end-B (org-element-property :end elem-B
)))
5828 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5829 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5831 (defun org-element-swap-A-B (elem-A elem-B
)
5832 "Swap elements ELEM-A and ELEM-B.
5833 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5835 (goto-char (org-element-property :begin elem-A
))
5836 ;; There are two special cases when an element doesn't start at bol:
5837 ;; the first paragraph in an item or in a footnote definition.
5838 (let ((specialp (not (bolp))))
5839 ;; Only a paragraph without any affiliated keyword can be moved at
5840 ;; ELEM-A position in such a situation. Note that the case of
5841 ;; a footnote definition is impossible: it cannot contain two
5842 ;; paragraphs in a row because it cannot contain a blank line.
5844 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5845 (/= (org-element-property :begin elem-B
)
5846 (org-element-property :contents-begin elem-B
))))
5847 (error "Cannot swap elements"))
5848 ;; In a special situation, ELEM-A will have no indentation. We'll
5849 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5850 (let* ((ind-B (when specialp
5851 (goto-char (org-element-property :begin elem-B
))
5852 (org-get-indentation)))
5853 (beg-A (org-element-property :begin elem-A
))
5854 (end-A (save-excursion
5855 (goto-char (org-element-property :end elem-A
))
5856 (skip-chars-backward " \r\t\n")
5858 (beg-B (org-element-property :begin elem-B
))
5859 (end-B (save-excursion
5860 (goto-char (org-element-property :end elem-B
))
5861 (skip-chars-backward " \r\t\n")
5863 ;; Store overlays responsible for visibility status. We
5864 ;; also need to store their boundaries as they will be
5865 ;; removed from buffer.
5868 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5869 (overlays-in beg-A end-A
))
5870 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5871 (overlays-in beg-B end-B
))))
5873 (body-A (buffer-substring beg-A end-A
))
5874 (body-B (delete-and-extract-region beg-B end-B
)))
5877 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5878 (org-indent-to-column ind-B
))
5880 ;; Restore ex ELEM-A overlays.
5881 (let ((offset (- beg-B beg-A
)))
5884 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5887 (delete-region beg-A end-A
)
5889 ;; Restore ex ELEM-B overlays.
5892 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5894 (goto-char (org-element-property :end elem-B
)))))
5896 (defun org-element-remove-indentation (s &optional n
)
5897 "Remove maximum common indentation in string S and return it.
5898 When optional argument N is a positive integer, remove exactly
5899 that much characters from indentation, if possible, or return
5900 S as-is otherwise. Unlike to `org-remove-indentation', this
5901 function doesn't call `untabify' on S."
5905 (goto-char (point-min))
5906 ;; Find maximum common indentation, if not specified.
5908 (let ((min-ind (point-max)))
5910 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5911 (let ((ind (1- (current-column))))
5912 (if (zerop ind
) (throw 'exit s
)
5913 (setq min-ind
(min min-ind ind
))))))
5916 ;; Remove exactly N indentation, but give up if not possible.
5918 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5919 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5920 ((< ind n
) (throw 'exit s
))
5921 (t (org-indent-line-to (- ind n
))))
5927 (provide 'org-element
)
5930 ;; generated-autoload-file: "org-loaddefs.el"
5933 ;;; org-element.el ends here