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, greater elements and elements accepting
77 ;; affiliated keywords will have a `:post-affiliated' property,
78 ;; referring to the buffer position after all such keywords.
80 ;; At the lowest level, a `:parent' property is also attached to any
81 ;; string, as a text property.
83 ;; Lisp-wise, an element or an object can be represented as a list.
84 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
85 ;; TYPE is a symbol describing the Org element or object.
86 ;; PROPERTIES is the property list attached to it. See docstring of
87 ;; appropriate parsing function to get an exhaustive
89 ;; CONTENTS is a list of elements, objects or raw strings contained
90 ;; in the current element or object, when applicable.
92 ;; An Org buffer is a nested list of such elements and objects, whose
93 ;; type is `org-data' and properties is nil.
95 ;; The first part of this file defines Org syntax, while the second
96 ;; one provide accessors and setters functions.
98 ;; The next part implements a parser and an interpreter for each
99 ;; element and object type in Org syntax.
101 ;; The following part creates a fully recursive buffer parser. It
102 ;; also provides a tool to map a function to elements or objects
103 ;; matching some criteria in the parse tree. Functions of interest
104 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
105 ;; extent, `org-element-parse-secondary-string'.
107 ;; The penultimate part is the cradle of an interpreter for the
108 ;; obtained parse tree: `org-element-interpret-data'.
110 ;; The library ends by furnishing `org-element-at-point' function, and
111 ;; a way to give information about document structure around point
112 ;; with `org-element-context'. A cache mechanism is also provided for
118 (eval-when-compile (require 'cl
))
124 ;;; Definitions And Rules
126 ;; Define elements, greater elements and specify recursive objects,
127 ;; along with the affiliated keywords recognized. Also set up
128 ;; restrictions on recursive objects combinations.
130 ;; These variables really act as a control center for the parsing
133 (defconst org-element-paragraph-separate
135 ;; Headlines, inlinetasks.
136 org-outline-regexp
"\\|"
137 ;; Footnote definitions.
138 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
144 ;; Tables (any type).
145 "\\(?:|\\|\\+-[-+]\\)" "\\|"
146 ;; Blocks (any type), Babel calls and keywords. Note: this
147 ;; is only an indication and need some thorough check.
148 "#\\(?:[+ ]\\|$\\)" "\\|"
149 ;; Drawers (any type) and fixed-width areas. This is also
150 ;; only an indication.
153 "-\\{5,\\}[ \t]*$" "\\|"
154 ;; LaTeX environments.
155 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
156 ;; Planning and Clock lines.
157 (regexp-opt (list org-scheduled-string
163 (let ((term (case org-plain-list-ordered-item-terminator
164 (?\
) ")") (?.
"\\.") (otherwise "[.)]")))
165 (alpha (and org-list-allow-alphabetical
"\\|[A-Za-z]")))
166 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha
"\\)" term
"\\)"
167 "\\(?:[ \t]\\|$\\)"))
169 "Regexp to separate paragraphs in an Org buffer.
170 In the case of lines starting with \"#\" and \":\", this regexp
171 is not sufficient to know if point is at a paragraph ending. See
172 `org-element-paragraph-parser' for more information.")
174 (defconst org-element-all-elements
175 '(babel-call center-block clock comment comment-block diary-sexp drawer
176 dynamic-block example-block 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' and `:post-blank' keywords.
782 The plist also contains any property set in the property drawer,
783 with its name in upper cases and colons added at the
784 beginning (e.g., `:CUSTOM_ID').
786 LIMIT is a buffer position bounding the search.
788 When RAW-SECONDARY-P is non-nil, headline's title will not be
789 parsed as a secondary string, but as a plain string instead.
791 Assume point is at beginning of the headline."
793 (let* ((components (org-heading-components))
794 (level (nth 1 components
))
795 (todo (nth 2 components
))
797 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
798 (tags (let ((raw-tags (nth 5 components
)))
799 (and raw-tags
(org-split-string raw-tags
":"))))
800 (raw-value (or (nth 4 components
) ""))
802 (let ((case-fold-search nil
))
803 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
805 (archivedp (member org-archive-tag tags
))
806 (footnote-section-p (and org-footnote-section
807 (string= org-footnote-section raw-value
)))
809 ;; Find property drawer associated to current headline and
810 ;; extract properties.
812 ;; Upcase property names. It avoids confusion between
813 ;; properties obtained through property drawer and default
814 ;; properties from the parser (e.g. `:end' and :END:)
815 (let ((end (save-excursion
816 (org-with-limited-levels (outline-next-heading))
820 (while (and (null plist
)
821 (re-search-forward org-property-start-re end t
))
822 (let ((drawer (org-element-at-point)))
823 (when (and (eq (org-element-type drawer
) 'property-drawer
)
824 ;; Make sure drawer is not associated
827 (while (and (setq p
(org-element-property
829 (not (eq (org-element-type p
)
832 (let ((end (org-element-property :contents-end drawer
)))
835 (while (< (point) end
)
836 (when (looking-at org-property-re
)
841 (concat ":" (upcase (match-string 2))))
842 (org-match-string-no-properties 3))))
846 ;; Read time properties on the line below the headline.
849 (when (looking-at org-planning-or-clock-line-re
)
850 (let ((end (line-end-position)) plist
)
851 (while (re-search-forward
852 org-keyword-time-not-clock-regexp end t
)
853 (goto-char (match-end 1))
854 (skip-chars-forward " \t")
855 (let ((keyword (match-string 1))
856 (time (org-element-timestamp-parser)))
857 (cond ((equal keyword org-scheduled-string
)
858 (setq plist
(plist-put plist
:scheduled time
)))
859 ((equal keyword org-deadline-string
)
860 (setq plist
(plist-put plist
:deadline time
)))
861 (t (setq plist
(plist-put plist
:closed time
))))))
864 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
865 (pos-after-head (progn (forward-line) (point)))
866 (contents-begin (save-excursion
867 (skip-chars-forward " \r\t\n" end
)
868 (and (/= (point) end
) (line-beginning-position))))
869 (contents-end (and contents-begin
870 (progn (goto-char end
)
871 (skip-chars-backward " \r\t\n")
874 ;; Clean RAW-VALUE from any comment string.
876 (let ((case-fold-search nil
))
878 (replace-regexp-in-string
879 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
882 ;; Clean TAGS from archive tag, if any.
883 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
887 (list :raw-value raw-value
891 (if (not contents-begin
) 0
892 (count-lines pos-after-head contents-begin
))
893 :contents-begin contents-begin
894 :contents-end contents-end
896 :priority
(nth 3 components
)
900 :post-blank
(count-lines
901 (or contents-end pos-after-head
)
903 :footnote-section-p footnote-section-p
905 :commentedp commentedp
)
908 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
910 (org-element-put-property
912 (if raw-secondary-p alt-title
913 (org-element-parse-secondary-string
914 alt-title
(org-element-restriction 'headline
) headline
)))))
915 (org-element-put-property
917 (if raw-secondary-p raw-value
918 (org-element-parse-secondary-string
919 raw-value
(org-element-restriction 'headline
) headline
)))))))
921 (defun org-element-headline-interpreter (headline contents
)
922 "Interpret HEADLINE element as Org syntax.
923 CONTENTS is the contents of the element."
924 (let* ((level (org-element-property :level headline
))
925 (todo (org-element-property :todo-keyword headline
))
926 (priority (org-element-property :priority headline
))
927 (title (org-element-interpret-data
928 (org-element-property :title headline
)))
929 (tags (let ((tag-list (if (org-element-property :archivedp headline
)
930 (cons org-archive-tag
931 (org-element-property :tags headline
))
932 (org-element-property :tags headline
))))
934 (format ":%s:" (mapconcat 'identity tag-list
":")))))
935 (commentedp (org-element-property :commentedp headline
))
936 (pre-blank (or (org-element-property :pre-blank headline
) 0))
937 (heading (concat (make-string (org-reduced-level level
) ?
*)
938 (and todo
(concat " " todo
))
939 (and commentedp
(concat " " org-comment-string
))
941 (format " [#%s]" (char-to-string priority
)))
942 (cond ((and org-footnote-section
943 (org-element-property
944 :footnote-section-p headline
))
945 (concat " " org-footnote-section
))
946 (title (concat " " title
))))))
951 ((zerop org-tags-column
) (format " %s" tags
))
952 ((< org-tags-column
0)
955 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
960 (make-string (max (- org-tags-column
(length heading
)) 1) ?
)
962 (make-string (1+ pre-blank
) 10)
968 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
969 "Parse an inline task.
971 Return a list whose CAR is `inlinetask' and CDR is a plist
972 containing `:title', `:begin', `:end', `:contents-begin' and
973 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
974 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
975 `:closed' and `:post-blank' keywords.
977 The plist also contains any property set in the property drawer,
978 with its name in upper cases and colons added at the
979 beginning (e.g., `:CUSTOM_ID').
981 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
982 title will not be parsed as a secondary string, but as a plain
985 Assume point is at beginning of the inline task."
987 (let* ((begin (point))
988 (components (org-heading-components))
989 (todo (nth 2 components
))
991 (if (member todo org-done-keywords
) 'done
'todo
)))
992 (tags (let ((raw-tags (nth 5 components
)))
993 (and raw-tags
(org-split-string raw-tags
":"))))
994 (raw-value (or (nth 4 components
) ""))
995 (task-end (save-excursion
997 (and (re-search-forward org-outline-regexp-bol limit t
)
998 (org-looking-at-p "END[ \t]*$")
999 (line-beginning-position))))
1001 ;; Read time properties on the line below the inlinetask
1005 (when (progn (forward-line)
1006 (looking-at org-planning-or-clock-line-re
))
1007 (let ((end (line-end-position)) plist
)
1008 (while (re-search-forward
1009 org-keyword-time-not-clock-regexp end t
)
1010 (goto-char (match-end 1))
1011 (skip-chars-forward " \t")
1012 (let ((keyword (match-string 1))
1013 (time (org-element-timestamp-parser)))
1014 (cond ((equal keyword org-scheduled-string
)
1015 (setq plist
(plist-put plist
:scheduled time
)))
1016 ((equal keyword org-deadline-string
)
1017 (setq plist
(plist-put plist
:deadline time
)))
1018 (t (setq plist
(plist-put plist
:closed time
))))))
1020 (contents-begin (progn (forward-line)
1021 (and task-end
(< (point) task-end
) (point))))
1022 (contents-end (and contents-begin task-end
))
1023 (before-blank (if (not task-end
) (point)
1024 (goto-char task-end
)
1027 (end (progn (skip-chars-forward " \r\t\n" limit
)
1028 (if (eobp) (point) (line-beginning-position))))
1030 ;; Find property drawer associated to current inlinetask
1031 ;; and extract properties.
1033 ;; HACK: Calling `org-element-at-point' triggers a parsing
1034 ;; of this inlinetask and, thus, an infloop. To avoid the
1035 ;; problem, we extract contents of the inlinetask and
1036 ;; parse them in a new buffer.
1038 ;; Upcase property names. It avoids confusion between
1039 ;; properties obtained through property drawer and default
1040 ;; properties from the parser (e.g. `:end' and :END:)
1041 (when contents-begin
1042 (let ((contents (buffer-substring contents-begin contents-end
))
1045 (let ((org-inhibit-startup t
)) (org-mode))
1047 (goto-char (point-min))
1048 (while (and (null plist
)
1050 org-property-start-re task-end t
))
1051 (let ((d (org-element-at-point)))
1052 (when (eq (org-element-type d
) 'property-drawer
)
1053 (let ((end (org-element-property :contents-end d
)))
1056 (while (< (point) end
)
1057 (when (looking-at org-property-re
)
1062 (concat ":" (upcase (match-string 2))))
1063 (org-match-string-no-properties 3))))
1064 (forward-line))))))))
1069 (list :raw-value raw-value
1072 :contents-begin contents-begin
1073 :contents-end contents-end
1074 :level
(nth 1 components
)
1075 :priority
(nth 3 components
)
1078 :todo-type todo-type
1079 :post-blank
(count-lines before-blank end
))
1082 (org-element-put-property
1084 (if raw-secondary-p raw-value
1085 (org-element-parse-secondary-string
1087 (org-element-restriction 'inlinetask
)
1090 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1091 "Interpret INLINETASK element as Org syntax.
1092 CONTENTS is the contents of inlinetask."
1093 (let* ((level (org-element-property :level inlinetask
))
1094 (todo (org-element-property :todo-keyword inlinetask
))
1095 (priority (org-element-property :priority inlinetask
))
1096 (title (org-element-interpret-data
1097 (org-element-property :title inlinetask
)))
1098 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1100 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1101 (task (concat (make-string level ?
*)
1102 (and todo
(concat " " todo
))
1104 (format " [#%s]" (char-to-string priority
)))
1105 (and title
(concat " " title
)))))
1110 ((zerop org-tags-column
) (format " %s" tags
))
1111 ((< org-tags-column
0)
1114 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1119 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1121 ;; Prefer degenerate inlinetasks when there are no
1126 (make-string level ?
*) " END")))))
1131 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1134 STRUCT is the structure of the plain list.
1136 Return a list whose CAR is `item' and CDR is a plist containing
1137 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1138 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1141 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1142 any, will not be parsed as a secondary string, but as a plain
1145 Assume point is at the beginning of the item."
1148 (looking-at org-list-full-item-re
)
1149 (let* ((begin (point))
1150 (bullet (org-match-string-no-properties 1))
1151 (checkbox (let ((box (org-match-string-no-properties 3)))
1152 (cond ((equal "[ ]" box
) 'off
)
1153 ((equal "[X]" box
) 'on
)
1154 ((equal "[-]" box
) 'trans
))))
1155 (counter (let ((c (org-match-string-no-properties 2)))
1159 ((string-match "[A-Za-z]" c
)
1160 (- (string-to-char (upcase (match-string 0 c
)))
1162 ((string-match "[0-9]+" c
)
1163 (string-to-number (match-string 0 c
)))))))
1164 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1165 (unless (bolp) (forward-line))
1169 ;; Ignore tags in un-ordered lists: they are just
1170 ;; a part of item's body.
1171 (if (and (match-beginning 4)
1172 (save-match-data (string-match "[.)]" bullet
)))
1175 (skip-chars-forward " \r\t\n" limit
)
1176 ;; If first line isn't empty, contents really start
1177 ;; at the text after item's meta-data.
1178 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1179 (contents-end (progn (goto-char end
)
1180 (skip-chars-backward " \r\t\n")
1185 (list :bullet bullet
1188 ;; CONTENTS-BEGIN and CONTENTS-END may be
1189 ;; mixed up in the case of an empty item
1190 ;; separated from the next by a blank line.
1191 ;; Thus ensure the former is always the
1193 :contents-begin
(min contents-begin contents-end
)
1194 :contents-end
(max contents-begin contents-end
)
1198 :post-blank
(count-lines contents-end end
)))))
1199 (org-element-put-property
1201 (let ((raw-tag (org-list-get-tag begin struct
)))
1203 (if raw-secondary-p raw-tag
1204 (org-element-parse-secondary-string
1205 raw-tag
(org-element-restriction 'item
) item
))))))))
1207 (defun org-element-item-interpreter (item contents
)
1208 "Interpret ITEM element as Org syntax.
1209 CONTENTS is the contents of the element."
1210 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1211 (org-list-bullet-string
1212 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1213 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1215 (checkbox (org-element-property :checkbox item
))
1216 (counter (org-element-property :counter item
))
1217 (tag (let ((tag (org-element-property :tag item
)))
1218 (and tag
(org-element-interpret-data tag
))))
1219 ;; Compute indentation.
1220 (ind (make-string (length bullet
) 32))
1221 (item-starts-with-par-p
1222 (eq (org-element-type (car (org-element-contents item
)))
1227 (and counter
(format "[@%d] " counter
))
1232 (and tag
(format "%s :: " tag
))
1234 (let ((contents (replace-regexp-in-string
1235 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1236 (if item-starts-with-par-p
(org-trim contents
)
1237 (concat "\n" contents
)))))))
1242 (defun org-element--list-struct (limit)
1243 ;; Return structure of list at point. Internal function. See
1244 ;; `org-list-struct' for details.
1245 (let ((case-fold-search t
)
1247 (item-re (org-item-re))
1248 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1254 ;; At limit: end all items.
1257 (let ((end (progn (skip-chars-backward " \r\t\n")
1260 (dolist (item items
(sort (nconc items struct
)
1261 'car-less-than-car
))
1262 (setcar (nthcdr 6 item
) end
)))))
1263 ;; At list end: end all items.
1264 ((looking-at org-list-end-re
)
1265 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1266 'car-less-than-car
))
1267 (setcar (nthcdr 6 item
) (point)))))
1268 ;; At a new item: end previous sibling.
1269 ((looking-at item-re
)
1270 (let ((ind (save-excursion (skip-chars-forward " \t")
1272 (setq top-ind
(min top-ind ind
))
1273 (while (and items
(<= ind
(nth 1 (car items
))))
1274 (let ((item (pop items
)))
1275 (setcar (nthcdr 6 item
) (point))
1276 (push item struct
)))
1277 (push (progn (looking-at org-list-full-item-re
)
1278 (let ((bullet (match-string-no-properties 1)))
1282 (match-string-no-properties 2) ; counter
1283 (match-string-no-properties 3) ; checkbox
1285 (and (save-match-data
1286 (string-match "[-+*]" bullet
))
1287 (match-string-no-properties 4))
1288 ;; Ending position, unknown so far.
1292 ;; Skip empty lines.
1293 ((looking-at "^[ \t]*$") (forward-line))
1294 ;; Skip inline tasks and blank lines along the way.
1295 ((and inlinetask-re
(looking-at inlinetask-re
))
1297 (let ((origin (point)))
1298 (when (re-search-forward inlinetask-re limit t
)
1299 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1300 (goto-char origin
)))))
1301 ;; At some text line. Check if it ends any previous item.
1303 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1304 (when (<= ind top-ind
)
1305 (skip-chars-backward " \r\t\n")
1307 (while (<= ind
(nth 1 (car items
)))
1308 (let ((item (pop items
)))
1309 (setcar (nthcdr 6 item
) (line-beginning-position))
1312 (throw 'exit
(sort struct
'car-less-than-car
))))))
1313 ;; Skip blocks (any type) and drawers contents.
1315 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1317 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1319 ((and (looking-at org-drawer-regexp
)
1320 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1321 (forward-line))))))))
1323 (defun org-element-plain-list-parser (limit affiliated structure
)
1324 "Parse a plain list.
1326 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1327 the buffer position at the beginning of the first affiliated
1328 keyword and CDR is a plist of affiliated keywords along with
1329 their value. STRUCTURE is the structure of the plain list being
1332 Return a list whose CAR is `plain-list' and CDR is a plist
1333 containing `:type', `:begin', `:end', `:contents-begin' and
1334 `:contents-end', `:structure', `:post-blank' and
1335 `:post-affiliated' keywords.
1337 Assume point is at the beginning of the list."
1339 (let* ((struct (or structure
(org-element--list-struct limit
)))
1340 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1341 ((nth 5 (assq (point) struct
)) 'descriptive
)
1343 (contents-begin (point))
1344 (begin (car affiliated
))
1345 (contents-end (let* ((item (assq contents-begin struct
))
1348 (while (and (setq item
(assq pos struct
))
1349 (= (nth 1 item
) ind
))
1350 (setq pos
(nth 6 item
)))
1352 (end (progn (goto-char contents-end
)
1353 (skip-chars-forward " \r\t\n" limit
)
1354 (if (= (point) limit
) limit
(line-beginning-position)))))
1361 :contents-begin contents-begin
1362 :contents-end contents-end
1364 :post-blank
(count-lines contents-end end
)
1365 :post-affiliated contents-begin
)
1366 (cdr affiliated
))))))
1368 (defun org-element-plain-list-interpreter (plain-list contents
)
1369 "Interpret PLAIN-LIST element as Org syntax.
1370 CONTENTS is the contents of the element."
1373 (goto-char (point-min))
1378 ;;;; Property Drawer
1380 (defun org-element-property-drawer-parser (limit affiliated
)
1381 "Parse a property drawer.
1383 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1384 the buffer position at the beginning of the first affiliated
1385 keyword and CDR is a plist of affiliated keywords along with
1388 Return a list whose CAR is `property-drawer' and CDR is a plist
1389 containing `:begin', `:end', `:contents-begin', `:contents-end',
1390 `:post-blank' and `:post-affiliated' keywords.
1392 Assume point is at the beginning of the property drawer."
1394 (let ((case-fold-search t
))
1395 (if (not (save-excursion
1396 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1397 ;; Incomplete drawer: parse it as a paragraph.
1398 (org-element-paragraph-parser limit affiliated
)
1400 (let* ((drawer-end-line (match-beginning 0))
1401 (begin (car affiliated
))
1402 (post-affiliated (point))
1403 (contents-begin (progn (forward-line)
1404 (and (< (point) drawer-end-line
)
1406 (contents-end (and contents-begin drawer-end-line
))
1407 (pos-before-blank (progn (goto-char drawer-end-line
)
1410 (end (progn (skip-chars-forward " \r\t\n" limit
)
1411 (if (eobp) (point) (line-beginning-position)))))
1412 (list 'property-drawer
1416 :contents-begin contents-begin
1417 :contents-end contents-end
1418 :post-blank
(count-lines pos-before-blank end
)
1419 :post-affiliated post-affiliated
)
1420 (cdr affiliated
)))))))))
1422 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1423 "Interpret PROPERTY-DRAWER element as Org syntax.
1424 CONTENTS is the properties within the drawer."
1425 (format ":PROPERTIES:\n%s:END:" contents
))
1430 (defun org-element-quote-block-parser (limit affiliated
)
1431 "Parse a quote block.
1433 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1434 the buffer position at the beginning of the first affiliated
1435 keyword and CDR is a plist of affiliated keywords along with
1438 Return a list whose CAR is `quote-block' and CDR is a plist
1439 containing `:begin', `:end', `:contents-begin', `:contents-end',
1440 `:post-blank' and `:post-affiliated' keywords.
1442 Assume point is at the beginning of the block."
1443 (let ((case-fold-search t
))
1444 (if (not (save-excursion
1445 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1446 ;; Incomplete block: parse it as a paragraph.
1447 (org-element-paragraph-parser limit affiliated
)
1448 (let ((block-end-line (match-beginning 0)))
1450 (let* ((begin (car affiliated
))
1451 (post-affiliated (point))
1452 ;; Empty blocks have no contents.
1453 (contents-begin (progn (forward-line)
1454 (and (< (point) block-end-line
)
1456 (contents-end (and contents-begin block-end-line
))
1457 (pos-before-blank (progn (goto-char block-end-line
)
1460 (end (progn (skip-chars-forward " \r\t\n" limit
)
1461 (if (eobp) (point) (line-beginning-position)))))
1466 :contents-begin contents-begin
1467 :contents-end contents-end
1468 :post-blank
(count-lines pos-before-blank end
)
1469 :post-affiliated post-affiliated
)
1470 (cdr affiliated
)))))))))
1472 (defun org-element-quote-block-interpreter (quote-block contents
)
1473 "Interpret QUOTE-BLOCK element as Org syntax.
1474 CONTENTS is the contents of the element."
1475 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1480 (defun org-element-section-parser (limit)
1483 LIMIT bounds the search.
1485 Return a list whose CAR is `section' and CDR is a plist
1486 containing `:begin', `:end', `:contents-begin', `contents-end'
1487 and `:post-blank' keywords."
1489 ;; Beginning of section is the beginning of the first non-blank
1490 ;; line after previous headline.
1491 (let ((begin (point))
1492 (end (progn (org-with-limited-levels (outline-next-heading))
1494 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1500 :contents-begin begin
1501 :contents-end pos-before-blank
1502 :post-blank
(count-lines pos-before-blank end
))))))
1504 (defun org-element-section-interpreter (section contents
)
1505 "Interpret SECTION element as Org syntax.
1506 CONTENTS is the contents of the element."
1512 (defun org-element-special-block-parser (limit affiliated
)
1513 "Parse a special block.
1515 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1516 the buffer position at the beginning of the first affiliated
1517 keyword and CDR is a plist of affiliated keywords along with
1520 Return a list whose CAR is `special-block' and CDR is a plist
1521 containing `:type', `:raw-value', `:begin', `:end',
1522 `:contents-begin', `:contents-end', `:post-blank' and
1523 `:post-affiliated' keywords.
1525 Assume point is at the beginning of the block."
1526 (let* ((case-fold-search t
)
1527 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1528 (upcase (match-string-no-properties 1)))))
1529 (if (not (save-excursion
1531 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1533 ;; Incomplete block: parse it as a paragraph.
1534 (org-element-paragraph-parser limit affiliated
)
1535 (let ((block-end-line (match-beginning 0)))
1537 (let* ((begin (car affiliated
))
1538 (post-affiliated (point))
1539 ;; Empty blocks have no contents.
1540 (contents-begin (progn (forward-line)
1541 (and (< (point) block-end-line
)
1543 (contents-end (and contents-begin block-end-line
))
1544 (pos-before-blank (progn (goto-char block-end-line
)
1547 (end (progn (skip-chars-forward " \r\t\n" limit
)
1548 (if (eobp) (point) (line-beginning-position)))))
1549 (list 'special-block
1554 (buffer-substring-no-properties
1555 contents-begin contents-end
))
1558 :contents-begin contents-begin
1559 :contents-end contents-end
1560 :post-blank
(count-lines pos-before-blank end
)
1561 :post-affiliated post-affiliated
)
1562 (cdr affiliated
)))))))))
1564 (defun org-element-special-block-interpreter (special-block contents
)
1565 "Interpret SPECIAL-BLOCK element as Org syntax.
1566 CONTENTS is the contents of the element."
1567 (let ((block-type (org-element-property :type special-block
)))
1568 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1574 ;; For each element, a parser and an interpreter are also defined.
1575 ;; Both follow the same naming convention used for greater elements.
1577 ;; Also, as for greater elements, adding a new element type is done
1578 ;; through the following steps: implement a parser and an interpreter,
1579 ;; tweak `org-element--current-element' so that it recognizes the new
1580 ;; type and add that new type to `org-element-all-elements'.
1582 ;; As a special case, when the newly defined type is a block type,
1583 ;; `org-element-block-name-alist' has to be modified accordingly.
1588 (defun org-element-babel-call-parser (limit affiliated
)
1589 "Parse a babel call.
1591 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1592 the buffer position at the beginning of the first affiliated
1593 keyword and CDR is a plist of affiliated keywords along with
1596 Return a list whose CAR is `babel-call' and CDR is a plist
1597 containing `:begin', `:end', `:value', `:post-blank' and
1598 `:post-affiliated' as keywords."
1600 (let ((begin (car affiliated
))
1601 (post-affiliated (point))
1602 (value (progn (let ((case-fold-search t
))
1603 (re-search-forward "call:[ \t]*" nil t
))
1604 (buffer-substring-no-properties (point)
1605 (line-end-position))))
1606 (pos-before-blank (progn (forward-line) (point)))
1607 (end (progn (skip-chars-forward " \r\t\n" limit
)
1608 (if (eobp) (point) (line-beginning-position)))))
1614 :post-blank
(count-lines pos-before-blank end
)
1615 :post-affiliated post-affiliated
)
1616 (cdr affiliated
))))))
1618 (defun org-element-babel-call-interpreter (babel-call contents
)
1619 "Interpret BABEL-CALL element as Org syntax.
1621 (concat "#+CALL: " (org-element-property :value babel-call
)))
1626 (defun org-element-clock-parser (limit)
1629 LIMIT bounds the search.
1631 Return a list whose CAR is `clock' and CDR is a plist containing
1632 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1635 (let* ((case-fold-search nil
)
1637 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1638 (skip-chars-forward " \t")
1639 (org-element-timestamp-parser)))
1640 (duration (and (search-forward " => " (line-end-position) t
)
1641 (progn (skip-chars-forward " \t")
1642 (looking-at "\\(\\S-+\\)[ \t]*$"))
1643 (org-match-string-no-properties 1)))
1644 (status (if duration
'closed
'running
))
1645 (post-blank (let ((before-blank (progn (forward-line) (point))))
1646 (skip-chars-forward " \r\t\n" limit
)
1647 (skip-chars-backward " \t")
1648 (unless (bolp) (end-of-line))
1649 (count-lines before-blank
(point))))
1652 (list :status status
1657 :post-blank post-blank
)))))
1659 (defun org-element-clock-interpreter (clock contents
)
1660 "Interpret CLOCK element as Org syntax.
1662 (concat org-clock-string
" "
1663 (org-element-timestamp-interpreter
1664 (org-element-property :value clock
) nil
)
1665 (let ((duration (org-element-property :duration clock
)))
1670 (org-split-string duration
":")))))))
1675 (defun org-element-comment-parser (limit affiliated
)
1678 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1679 the buffer position at the beginning of the first affiliated
1680 keyword and CDR is a plist of affiliated keywords along with
1683 Return a list whose CAR is `comment' and CDR is a plist
1684 containing `:begin', `:end', `:value', `:post-blank',
1685 `:post-affiliated' keywords.
1687 Assume point is at comment beginning."
1689 (let* ((begin (car affiliated
))
1690 (post-affiliated (point))
1691 (value (prog2 (looking-at "[ \t]*# ?")
1692 (buffer-substring-no-properties
1693 (match-end 0) (line-end-position))
1696 ;; Get comments ending.
1698 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1699 ;; Accumulate lines without leading hash and first
1704 (buffer-substring-no-properties
1705 (match-end 0) (line-end-position))))
1708 (end (progn (goto-char com-end
)
1709 (skip-chars-forward " \r\t\n" limit
)
1710 (if (eobp) (point) (line-beginning-position)))))
1716 :post-blank
(count-lines com-end end
)
1717 :post-affiliated post-affiliated
)
1718 (cdr affiliated
))))))
1720 (defun org-element-comment-interpreter (comment contents
)
1721 "Interpret COMMENT element as Org syntax.
1723 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1728 (defun org-element-comment-block-parser (limit affiliated
)
1729 "Parse an export block.
1731 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1732 the buffer position at the beginning of the first affiliated
1733 keyword and CDR is a plist of affiliated keywords along with
1736 Return a list whose CAR is `comment-block' and CDR is a plist
1737 containing `:begin', `:end', `:value', `:post-blank' and
1738 `:post-affiliated' keywords.
1740 Assume point is at comment block beginning."
1741 (let ((case-fold-search t
))
1742 (if (not (save-excursion
1743 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1744 ;; Incomplete block: parse it as a paragraph.
1745 (org-element-paragraph-parser limit affiliated
)
1746 (let ((contents-end (match-beginning 0)))
1748 (let* ((begin (car affiliated
))
1749 (post-affiliated (point))
1750 (contents-begin (progn (forward-line) (point)))
1751 (pos-before-blank (progn (goto-char contents-end
)
1754 (end (progn (skip-chars-forward " \r\t\n" limit
)
1755 (if (eobp) (point) (line-beginning-position))))
1756 (value (buffer-substring-no-properties
1757 contents-begin contents-end
)))
1758 (list 'comment-block
1763 :post-blank
(count-lines pos-before-blank end
)
1764 :post-affiliated post-affiliated
)
1765 (cdr affiliated
)))))))))
1767 (defun org-element-comment-block-interpreter (comment-block contents
)
1768 "Interpret COMMENT-BLOCK element as Org syntax.
1770 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1771 (org-element-normalize-string
1772 (org-remove-indentation
1773 (org-element-property :value comment-block
)))))
1778 (defun org-element-diary-sexp-parser (limit affiliated
)
1779 "Parse a diary sexp.
1781 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1782 the buffer position at the beginning of the first affiliated
1783 keyword and CDR is a plist of affiliated keywords along with
1786 Return a list whose CAR is `diary-sexp' and CDR is a plist
1787 containing `:begin', `:end', `:value', `:post-blank' and
1788 `:post-affiliated' keywords."
1790 (let ((begin (car affiliated
))
1791 (post-affiliated (point))
1792 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1793 (org-match-string-no-properties 1)))
1794 (pos-before-blank (progn (forward-line) (point)))
1795 (end (progn (skip-chars-forward " \r\t\n" limit
)
1796 (if (eobp) (point) (line-beginning-position)))))
1802 :post-blank
(count-lines pos-before-blank end
)
1803 :post-affiliated post-affiliated
)
1804 (cdr affiliated
))))))
1806 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1807 "Interpret DIARY-SEXP as Org syntax.
1809 (org-element-property :value diary-sexp
))
1814 (defun org-element-example-block-parser (limit affiliated
)
1815 "Parse an example block.
1817 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1818 the buffer position at the beginning of the first affiliated
1819 keyword and CDR is a plist of affiliated keywords along with
1822 Return a list whose CAR is `example-block' and CDR is a plist
1823 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1824 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1825 `:value', `:post-blank' and `:post-affiliated' keywords."
1826 (let ((case-fold-search t
))
1827 (if (not (save-excursion
1828 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1829 ;; Incomplete block: parse it as a paragraph.
1830 (org-element-paragraph-parser limit affiliated
)
1831 (let ((contents-end (match-beginning 0)))
1835 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1836 (org-match-string-no-properties 1)))
1837 ;; Switches analysis
1839 (cond ((not switches
) nil
)
1840 ((string-match "-n\\>" switches
) 'new
)
1841 ((string-match "+n\\>" switches
) 'continued
)))
1843 (and switches
(string-match "-i\\>" switches
)))
1844 ;; Should labels be retained in (or stripped from) example
1848 (not (string-match "-r\\>" switches
))
1849 (and number-lines
(string-match "-k\\>" switches
))))
1850 ;; What should code-references use - labels or
1855 (not (string-match "-k\\>" switches
)))))
1858 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1859 (match-string 1 switches
)))
1860 ;; Standard block parsing.
1861 (begin (car affiliated
))
1862 (post-affiliated (point))
1863 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1864 (contents-begin (progn (forward-line) (point)))
1865 (value (org-element-remove-indentation
1866 (org-unescape-code-in-string
1867 (buffer-substring-no-properties
1868 contents-begin contents-end
))
1870 (pos-before-blank (progn (goto-char contents-end
)
1873 (end (progn (skip-chars-forward " \r\t\n" limit
)
1874 (if (eobp) (point) (line-beginning-position)))))
1875 (list 'example-block
1881 :number-lines number-lines
1882 :preserve-indent preserve-indent
1883 :retain-labels retain-labels
1884 :use-labels use-labels
1885 :label-fmt label-fmt
1886 :post-blank
(count-lines pos-before-blank end
)
1887 :post-affiliated post-affiliated
)
1888 (cdr affiliated
)))))))))
1890 (defun org-element-example-block-interpreter (example-block contents
)
1891 "Interpret EXAMPLE-BLOCK element as Org syntax.
1893 (let ((switches (org-element-property :switches example-block
))
1894 (value (org-element-property :value example-block
)))
1895 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1896 (org-element-normalize-string
1897 (org-escape-code-in-string
1898 (if (or org-src-preserve-indentation
1899 (org-element-property :preserve-indent example-block
))
1901 (org-element-remove-indentation value
))))
1907 (defun org-element-fixed-width-parser (limit affiliated
)
1908 "Parse a fixed-width section.
1910 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1911 the buffer position at the beginning of the first affiliated
1912 keyword and CDR is a plist of affiliated keywords along with
1915 Return a list whose CAR is `fixed-width' and CDR is a plist
1916 containing `:begin', `:end', `:value', `:post-blank' and
1917 `:post-affiliated' keywords.
1919 Assume point is at the beginning of the fixed-width area."
1921 (let* ((begin (car affiliated
))
1922 (post-affiliated (point))
1926 (while (and (< (point) limit
)
1927 (looking-at "[ \t]*:\\( \\|$\\)"))
1928 ;; Accumulate text without starting colons.
1931 (buffer-substring-no-properties
1932 (match-end 0) (point-at-eol))
1936 (end (progn (skip-chars-forward " \r\t\n" limit
)
1937 (if (eobp) (point) (line-beginning-position)))))
1943 :post-blank
(count-lines end-area end
)
1944 :post-affiliated post-affiliated
)
1945 (cdr affiliated
))))))
1947 (defun org-element-fixed-width-interpreter (fixed-width contents
)
1948 "Interpret FIXED-WIDTH element as Org syntax.
1950 (let ((value (org-element-property :value fixed-width
)))
1952 (replace-regexp-in-string
1954 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
1957 ;;;; Horizontal Rule
1959 (defun org-element-horizontal-rule-parser (limit affiliated
)
1960 "Parse an horizontal rule.
1962 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1963 the buffer position at the beginning of the first affiliated
1964 keyword and CDR is a plist of affiliated keywords along with
1967 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1968 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1971 (let ((begin (car affiliated
))
1972 (post-affiliated (point))
1973 (post-hr (progn (forward-line) (point)))
1974 (end (progn (skip-chars-forward " \r\t\n" limit
)
1975 (if (eobp) (point) (line-beginning-position)))))
1976 (list 'horizontal-rule
1980 :post-blank
(count-lines post-hr end
)
1981 :post-affiliated post-affiliated
)
1982 (cdr affiliated
))))))
1984 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
1985 "Interpret HORIZONTAL-RULE element as Org syntax.
1992 (defun org-element-keyword-parser (limit affiliated
)
1993 "Parse a keyword at point.
1995 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1996 the buffer position at the beginning of the first affiliated
1997 keyword and CDR is a plist of affiliated keywords along with
2000 Return a list whose CAR is `keyword' and CDR is a plist
2001 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2002 `:post-affiliated' keywords."
2004 ;; An orphaned affiliated keyword is considered as a regular
2005 ;; keyword. In this case AFFILIATED is nil, so we take care of
2006 ;; this corner case.
2007 (let ((begin (or (car affiliated
) (point)))
2008 (post-affiliated (point))
2009 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2010 (upcase (org-match-string-no-properties 1))))
2011 (value (org-trim (buffer-substring-no-properties
2012 (match-end 0) (point-at-eol))))
2013 (pos-before-blank (progn (forward-line) (point)))
2014 (end (progn (skip-chars-forward " \r\t\n" limit
)
2015 (if (eobp) (point) (line-beginning-position)))))
2022 :post-blank
(count-lines pos-before-blank end
)
2023 :post-affiliated post-affiliated
)
2024 (cdr affiliated
))))))
2026 (defun org-element-keyword-interpreter (keyword contents
)
2027 "Interpret KEYWORD element as Org syntax.
2030 (org-element-property :key keyword
)
2031 (org-element-property :value keyword
)))
2034 ;;;; Latex Environment
2036 (defconst org-element--latex-begin-environment
2037 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2038 "Regexp matching the beginning of a LaTeX environment.
2039 The environment is captured by the first group.
2041 See also `org-element--latex-end-environment'.")
2043 (defconst org-element--latex-end-environment
2044 "\\\\end{%s}[ \t]*$"
2045 "Format string matching the ending of a LaTeX environment.
2046 See also `org-element--latex-begin-environment'.")
2048 (defun org-element-latex-environment-parser (limit affiliated
)
2049 "Parse a LaTeX environment.
2051 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2052 the buffer position at the beginning of the first affiliated
2053 keyword and CDR is a plist of affiliated keywords along with
2056 Return a list whose CAR is `latex-environment' and CDR is a plist
2057 containing `:begin', `:end', `:value', `:post-blank' and
2058 `:post-affiliated' keywords.
2060 Assume point is at the beginning of the latex environment."
2062 (let ((case-fold-search t
)
2063 (code-begin (point)))
2064 (looking-at org-element--latex-begin-environment
)
2065 (if (not (re-search-forward (format org-element--latex-end-environment
2066 (regexp-quote (match-string 1)))
2068 ;; Incomplete latex environment: parse it as a paragraph.
2069 (org-element-paragraph-parser limit affiliated
)
2070 (let* ((code-end (progn (forward-line) (point)))
2071 (begin (car affiliated
))
2072 (value (buffer-substring-no-properties code-begin code-end
))
2073 (end (progn (skip-chars-forward " \r\t\n" limit
)
2074 (if (eobp) (point) (line-beginning-position)))))
2075 (list 'latex-environment
2080 :post-blank
(count-lines code-end end
)
2081 :post-affiliated code-begin
)
2082 (cdr affiliated
))))))))
2084 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2085 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2087 (org-element-property :value latex-environment
))
2092 (defun org-element-node-property-parser (limit)
2093 "Parse a node-property at point.
2095 LIMIT bounds the search.
2097 Return a list whose CAR is `node-property' and CDR is a plist
2098 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2101 (looking-at org-property-re
)
2102 (let ((case-fold-search t
)
2104 (key (org-match-string-no-properties 2))
2105 (value (org-match-string-no-properties 3))
2106 (pos-before-blank (progn (forward-line) (point)))
2107 (end (progn (skip-chars-forward " \r\t\n" limit
)
2108 (if (eobp) (point) (point-at-bol)))))
2109 (list 'node-property
2114 :post-blank
(count-lines pos-before-blank end
))))))
2116 (defun org-element-node-property-interpreter (node-property contents
)
2117 "Interpret NODE-PROPERTY element as Org syntax.
2119 (format org-property-format
2120 (format ":%s:" (org-element-property :key node-property
))
2121 (org-element-property :value node-property
)))
2126 (defun org-element-paragraph-parser (limit affiliated
)
2129 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2130 the buffer position at the beginning of the first affiliated
2131 keyword and CDR is a plist of affiliated keywords along with
2134 Return a list whose CAR is `paragraph' and CDR is a plist
2135 containing `:begin', `:end', `:contents-begin' and
2136 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2138 Assume point is at the beginning of the paragraph."
2140 (let* ((begin (car affiliated
))
2141 (contents-begin (point))
2143 (let ((case-fold-search t
))
2145 (if (not (re-search-forward
2146 org-element-paragraph-separate limit
'm
))
2148 ;; A matching `org-element-paragraph-separate' is not
2149 ;; necessarily the end of the paragraph. In
2150 ;; particular, lines starting with # or : as a first
2151 ;; non-space character are ambiguous. We have to
2152 ;; check if they are valid Org syntax (e.g., not an
2153 ;; incomplete keyword).
2157 ;; There's no ambiguity for other symbols or
2158 ;; empty lines: stop here.
2159 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2160 ;; Stop at valid fixed-width areas.
2161 (looking-at "[ \t]*:\\(?: \\|$\\)")
2163 (and (looking-at org-drawer-regexp
)
2166 "^[ \t]*:END:[ \t]*$" limit t
)))
2167 ;; Stop at valid comments.
2168 (looking-at "[ \t]*#\\(?: \\|$\\)")
2169 ;; Stop at valid dynamic blocks.
2170 (and (looking-at org-dblock-start-re
)
2173 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2174 ;; Stop at valid blocks.
2175 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2178 (format "^[ \t]*#\\+END_%s[ \t]*$"
2180 (org-match-string-no-properties 1)))
2182 ;; Stop at valid latex environments.
2183 (and (looking-at org-element--latex-begin-environment
)
2186 (format org-element--latex-end-environment
2188 (org-match-string-no-properties 1)))
2190 ;; Stop at valid keywords.
2191 (looking-at "[ \t]*#\\+\\S-+:")
2192 ;; Skip everything else.
2196 (re-search-forward org-element-paragraph-separate
2198 (beginning-of-line)))
2199 (if (= (point) limit
) limit
2200 (goto-char (line-beginning-position)))))
2201 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2204 (end (progn (skip-chars-forward " \r\t\n" limit
)
2205 (if (eobp) (point) (line-beginning-position)))))
2210 :contents-begin contents-begin
2211 :contents-end contents-end
2212 :post-blank
(count-lines before-blank end
)
2213 :post-affiliated contents-begin
)
2214 (cdr affiliated
))))))
2216 (defun org-element-paragraph-interpreter (paragraph contents
)
2217 "Interpret PARAGRAPH element as Org syntax.
2218 CONTENTS is the contents of the element."
2224 (defun org-element-planning-parser (limit)
2227 LIMIT bounds the search.
2229 Return a list whose CAR is `planning' and CDR is a plist
2230 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2231 and `:post-blank' keywords."
2233 (let* ((case-fold-search nil
)
2235 (post-blank (let ((before-blank (progn (forward-line) (point))))
2236 (skip-chars-forward " \r\t\n" limit
)
2237 (skip-chars-backward " \t")
2238 (unless (bolp) (end-of-line))
2239 (count-lines before-blank
(point))))
2241 closed deadline scheduled
)
2243 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2244 (goto-char (match-end 1))
2245 (skip-chars-forward " \t" end
)
2246 (let ((keyword (match-string 1))
2247 (time (org-element-timestamp-parser)))
2248 (cond ((equal keyword org-closed-string
) (setq closed time
))
2249 ((equal keyword org-deadline-string
) (setq deadline time
))
2250 (t (setq scheduled time
)))))
2252 (list :closed closed
2254 :scheduled scheduled
2257 :post-blank post-blank
)))))
2259 (defun org-element-planning-interpreter (planning contents
)
2260 "Interpret PLANNING element as Org syntax.
2265 (list (let ((deadline (org-element-property :deadline planning
)))
2267 (concat org-deadline-string
" "
2268 (org-element-timestamp-interpreter deadline nil
))))
2269 (let ((scheduled (org-element-property :scheduled planning
)))
2271 (concat org-scheduled-string
" "
2272 (org-element-timestamp-interpreter scheduled nil
))))
2273 (let ((closed (org-element-property :closed planning
)))
2275 (concat org-closed-string
" "
2276 (org-element-timestamp-interpreter closed nil
))))))
2282 (defun org-element-src-block-parser (limit affiliated
)
2285 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2286 the buffer position at the beginning of the first affiliated
2287 keyword and CDR is a plist of affiliated keywords along with
2290 Return a list whose CAR is `src-block' and CDR is a plist
2291 containing `:language', `:switches', `:parameters', `:begin',
2292 `:end', `:number-lines', `:retain-labels', `:use-labels',
2293 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2294 `:post-affiliated' keywords.
2296 Assume point is at the beginning of the block."
2297 (let ((case-fold-search t
))
2298 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2300 ;; Incomplete block: parse it as a paragraph.
2301 (org-element-paragraph-parser limit affiliated
)
2302 (let ((contents-end (match-beginning 0)))
2304 (let* ((begin (car affiliated
))
2305 (post-affiliated (point))
2306 ;; Get language as a string.
2310 (concat "^[ \t]*#\\+BEGIN_SRC"
2311 "\\(?: +\\(\\S-+\\)\\)?"
2312 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2314 (org-match-string-no-properties 1)))
2316 (switches (org-match-string-no-properties 2))
2318 (parameters (org-match-string-no-properties 3))
2319 ;; Switches analysis
2321 (cond ((not switches
) nil
)
2322 ((string-match "-n\\>" switches
) 'new
)
2323 ((string-match "+n\\>" switches
) 'continued
)))
2324 (preserve-indent (and switches
2325 (string-match "-i\\>" switches
)))
2328 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2329 (match-string 1 switches
)))
2330 ;; Should labels be retained in (or stripped from)
2334 (not (string-match "-r\\>" switches
))
2335 (and number-lines
(string-match "-k\\>" switches
))))
2336 ;; What should code-references use - labels or
2341 (not (string-match "-k\\>" switches
)))))
2343 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2345 (value (org-element-remove-indentation
2346 (org-unescape-code-in-string
2347 (buffer-substring-no-properties
2348 (progn (forward-line) (point)) contents-end
))
2350 (pos-before-blank (progn (goto-char contents-end
)
2353 ;; Get position after ending blank lines.
2354 (end (progn (skip-chars-forward " \r\t\n" limit
)
2355 (if (eobp) (point) (line-beginning-position)))))
2358 (list :language language
2359 :switches
(and (org-string-nw-p switches
)
2360 (org-trim switches
))
2361 :parameters
(and (org-string-nw-p parameters
)
2362 (org-trim parameters
))
2365 :number-lines number-lines
2366 :preserve-indent preserve-indent
2367 :retain-labels retain-labels
2368 :use-labels use-labels
2369 :label-fmt label-fmt
2371 :post-blank
(count-lines pos-before-blank end
)
2372 :post-affiliated post-affiliated
)
2373 (cdr affiliated
)))))))))
2375 (defun org-element-src-block-interpreter (src-block contents
)
2376 "Interpret SRC-BLOCK element as Org syntax.
2378 (let ((lang (org-element-property :language src-block
))
2379 (switches (org-element-property :switches src-block
))
2380 (params (org-element-property :parameters src-block
))
2382 (let ((val (org-element-property :value src-block
)))
2384 ((or org-src-preserve-indentation
2385 (org-element-property :preserve-indent src-block
))
2387 ((zerop org-edit-src-content-indentation
) val
)
2389 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2390 (replace-regexp-in-string
2391 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2392 (concat (format "#+BEGIN_SRC%s\n"
2393 (concat (and lang
(concat " " lang
))
2394 (and switches
(concat " " switches
))
2395 (and params
(concat " " params
))))
2396 (org-element-normalize-string (org-escape-code-in-string value
))
2402 (defun org-element-table-parser (limit affiliated
)
2403 "Parse a table at point.
2405 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2406 the buffer position at the beginning of the first affiliated
2407 keyword and CDR is a plist of affiliated keywords along with
2410 Return a list whose CAR is `table' and CDR is a plist containing
2411 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2412 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2415 Assume point is at the beginning of the table."
2417 (let* ((case-fold-search t
)
2418 (table-begin (point))
2419 (type (if (org-at-table.el-p
) 'table.el
'org
))
2420 (begin (car affiliated
))
2422 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2423 (goto-char (match-beginning 0))
2426 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2427 (push (org-match-string-no-properties 1) acc
)
2430 (pos-before-blank (point))
2431 (end (progn (skip-chars-forward " \r\t\n" limit
)
2432 (if (eobp) (point) (line-beginning-position)))))
2439 ;; Only `org' tables have contents. `table.el' tables
2440 ;; use a `:value' property to store raw table as
2442 :contents-begin
(and (eq type
'org
) table-begin
)
2443 :contents-end
(and (eq type
'org
) table-end
)
2444 :value
(and (eq type
'table.el
)
2445 (buffer-substring-no-properties
2446 table-begin table-end
))
2447 :post-blank
(count-lines pos-before-blank end
)
2448 :post-affiliated table-begin
)
2449 (cdr affiliated
))))))
2451 (defun org-element-table-interpreter (table contents
)
2452 "Interpret TABLE element as Org syntax.
2454 (if (eq (org-element-property :type table
) 'table.el
)
2455 (org-remove-indentation (org-element-property :value table
))
2456 (concat (with-temp-buffer (insert contents
)
2459 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2460 (reverse (org-element-property :tblfm table
))
2466 (defun org-element-table-row-parser (limit)
2467 "Parse table row at point.
2469 LIMIT bounds the search.
2471 Return a list whose CAR is `table-row' and CDR is a plist
2472 containing `:begin', `:end', `:contents-begin', `:contents-end',
2473 `:type' and `:post-blank' keywords."
2475 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2477 ;; A table rule has no contents. In that case, ensure
2478 ;; CONTENTS-BEGIN matches CONTENTS-END.
2479 (contents-begin (and (eq type
'standard
)
2480 (search-forward "|")
2482 (contents-end (and (eq type
'standard
)
2485 (skip-chars-backward " \t")
2487 (end (progn (forward-line) (point))))
2492 :contents-begin contents-begin
2493 :contents-end contents-end
2496 (defun org-element-table-row-interpreter (table-row contents
)
2497 "Interpret TABLE-ROW element as Org syntax.
2498 CONTENTS is the contents of the table row."
2499 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2500 (concat "| " contents
)))
2505 (defun org-element-verse-block-parser (limit affiliated
)
2506 "Parse a verse block.
2508 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2509 the buffer position at the beginning of the first affiliated
2510 keyword and CDR is a plist of affiliated keywords along with
2513 Return a list whose CAR is `verse-block' and CDR is a plist
2514 containing `:begin', `:end', `:contents-begin', `:contents-end',
2515 `:post-blank' and `:post-affiliated' keywords.
2517 Assume point is at beginning of the block."
2518 (let ((case-fold-search t
))
2519 (if (not (save-excursion
2520 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2521 ;; Incomplete block: parse it as a paragraph.
2522 (org-element-paragraph-parser limit affiliated
)
2523 (let ((contents-end (match-beginning 0)))
2525 (let* ((begin (car affiliated
))
2526 (post-affiliated (point))
2527 (contents-begin (progn (forward-line) (point)))
2528 (pos-before-blank (progn (goto-char contents-end
)
2531 (end (progn (skip-chars-forward " \r\t\n" limit
)
2532 (if (eobp) (point) (line-beginning-position)))))
2537 :contents-begin contents-begin
2538 :contents-end contents-end
2539 :post-blank
(count-lines pos-before-blank end
)
2540 :post-affiliated post-affiliated
)
2541 (cdr affiliated
)))))))))
2543 (defun org-element-verse-block-interpreter (verse-block contents
)
2544 "Interpret VERSE-BLOCK element as Org syntax.
2545 CONTENTS is verse block contents."
2546 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2552 ;; Unlike to elements, raw text can be found between objects. Hence,
2553 ;; `org-element--object-lex' is provided to find the next object in
2556 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2557 ;; object types they can contain will be specified in
2558 ;; `org-element-object-restrictions'.
2560 ;; Creating a new type of object requires to alter
2561 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2562 ;; new type in `org-element-all-objects', and possibly add
2563 ;; restrictions in `org-element-object-restrictions'.
2567 (defun org-element-bold-parser ()
2568 "Parse bold object at point, if any.
2570 When at a bold object, return a list whose car is `bold' and cdr
2571 is a plist with `:begin', `:end', `:contents-begin' and
2572 `:contents-end' and `:post-blank' keywords. Otherwise, return
2575 Assume point is at the first star marker."
2577 (unless (bolp) (backward-char 1))
2578 (when (looking-at org-emph-re
)
2579 (let ((begin (match-beginning 2))
2580 (contents-begin (match-beginning 4))
2581 (contents-end (match-end 4))
2582 (post-blank (progn (goto-char (match-end 2))
2583 (skip-chars-forward " \t")))
2588 :contents-begin contents-begin
2589 :contents-end contents-end
2590 :post-blank post-blank
))))))
2592 (defun org-element-bold-interpreter (bold contents
)
2593 "Interpret BOLD object as Org syntax.
2594 CONTENTS is the contents of the object."
2595 (format "*%s*" contents
))
2600 (defun org-element-code-parser ()
2601 "Parse code object at point, if any.
2603 When at a code object, return a list whose car is `code' and cdr
2604 is a plist with `:value', `:begin', `:end' and `:post-blank'
2605 keywords. Otherwise, return nil.
2607 Assume point is at the first tilde marker."
2609 (unless (bolp) (backward-char 1))
2610 (when (looking-at org-emph-re
)
2611 (let ((begin (match-beginning 2))
2612 (value (org-match-string-no-properties 4))
2613 (post-blank (progn (goto-char (match-end 2))
2614 (skip-chars-forward " \t")))
2620 :post-blank post-blank
))))))
2622 (defun org-element-code-interpreter (code contents
)
2623 "Interpret CODE object as Org syntax.
2625 (format "~%s~" (org-element-property :value code
)))
2630 (defun org-element-entity-parser ()
2631 "Parse entity at point, if any.
2633 When at an entity, return a list whose car is `entity' and cdr
2634 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2635 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2636 `:post-blank' as keywords. Otherwise, return nil.
2638 Assume point is at the beginning of the entity."
2640 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2642 (let* ((value (or (org-entity-get (match-string 1))
2643 (throw 'no-object nil
)))
2644 (begin (match-beginning 0))
2645 (bracketsp (string= (match-string 2) "{}"))
2646 (post-blank (progn (goto-char (match-end 1))
2647 (when bracketsp
(forward-char 2))
2648 (skip-chars-forward " \t")))
2651 (list :name
(car value
)
2652 :latex
(nth 1 value
)
2653 :latex-math-p
(nth 2 value
)
2655 :ascii
(nth 4 value
)
2656 :latin1
(nth 5 value
)
2657 :utf-8
(nth 6 value
)
2660 :use-brackets-p bracketsp
2661 :post-blank post-blank
)))))))
2663 (defun org-element-entity-interpreter (entity contents
)
2664 "Interpret ENTITY object as Org syntax.
2667 (org-element-property :name entity
)
2668 (when (org-element-property :use-brackets-p entity
) "{}")))
2673 (defun org-element-export-snippet-parser ()
2674 "Parse export snippet at point.
2676 When at an export snippet, return a list whose car is
2677 `export-snippet' and cdr a plist with `:begin', `:end',
2678 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2681 Assume point is at the beginning of the snippet."
2684 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2686 (save-match-data (goto-char (match-end 0))
2687 (re-search-forward "@@" nil t
)
2688 (match-beginning 0))))
2689 (let* ((begin (match-beginning 0))
2690 (back-end (org-match-string-no-properties 1))
2691 (value (buffer-substring-no-properties
2692 (match-end 0) contents-end
))
2693 (post-blank (skip-chars-forward " \t"))
2695 (list 'export-snippet
2696 (list :back-end back-end
2700 :post-blank post-blank
)))))))
2702 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2703 "Interpret EXPORT-SNIPPET object as Org syntax.
2706 (org-element-property :back-end export-snippet
)
2707 (org-element-property :value export-snippet
)))
2710 ;;;; Footnote Reference
2712 (defun org-element-footnote-reference-parser ()
2713 "Parse footnote reference at point, if any.
2715 When at a footnote reference, return a list whose car is
2716 `footnote-reference' and cdr a plist with `:label', `:type',
2717 `:begin', `:end', `:content-begin', `:contents-end' and
2718 `:post-blank' as keywords. Otherwise, return nil."
2720 (when (looking-at org-footnote-re
)
2722 (let* ((begin (point))
2724 (or (org-match-string-no-properties 2)
2725 (org-match-string-no-properties 3)
2726 (and (match-string 1)
2727 (concat "fn:" (org-match-string-no-properties 1)))))
2728 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2729 (inner-begin (match-end 0))
2733 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2734 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2735 (unless (zerop count
) (throw 'no-object nil
))
2737 (post-blank (progn (goto-char (1+ inner-end
))
2738 (skip-chars-forward " \t")))
2740 (list 'footnote-reference
2745 :contents-begin
(and (eq type
'inline
) inner-begin
)
2746 :contents-end
(and (eq type
'inline
) inner-end
)
2747 :post-blank post-blank
)))))))
2749 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2750 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2751 CONTENTS is its definition, when inline, or nil."
2753 (concat (or (org-element-property :label footnote-reference
) "fn:")
2754 (and contents
(concat ":" contents
)))))
2757 ;;;; Inline Babel Call
2759 (defun org-element-inline-babel-call-parser ()
2760 "Parse inline babel call at point, if any.
2762 When at an inline babel call, return a list whose car is
2763 `inline-babel-call' and cdr a plist with `:begin', `:end',
2764 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2766 Assume point is at the beginning of the babel call."
2768 (unless (bolp) (backward-char))
2769 (when (let ((case-fold-search t
))
2770 (looking-at org-babel-inline-lob-one-liner-regexp
))
2771 (let ((begin (match-end 1))
2772 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2773 (post-blank (progn (goto-char (match-end 0))
2774 (skip-chars-forward " \t")))
2776 (list 'inline-babel-call
2780 :post-blank post-blank
))))))
2782 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2783 "Interpret INLINE-BABEL-CALL object as Org syntax.
2785 (org-element-property :value inline-babel-call
))
2788 ;;;; Inline Src Block
2790 (defun org-element-inline-src-block-parser ()
2791 "Parse inline source block at point, if any.
2793 When at an inline source block, return a list whose car is
2794 `inline-src-block' and cdr a plist with `:begin', `:end',
2795 `:language', `:value', `:parameters' and `:post-blank' as
2796 keywords. Otherwise, return nil.
2798 Assume point is at the beginning of the inline src block."
2800 (unless (bolp) (backward-char))
2801 (when (looking-at org-babel-inline-src-block-regexp
)
2802 (let ((begin (match-beginning 1))
2803 (language (org-match-string-no-properties 2))
2804 (parameters (org-match-string-no-properties 4))
2805 (value (org-match-string-no-properties 5))
2806 (post-blank (progn (goto-char (match-end 0))
2807 (skip-chars-forward " \t")))
2809 (list 'inline-src-block
2810 (list :language language
2812 :parameters parameters
2815 :post-blank post-blank
))))))
2817 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2818 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2820 (let ((language (org-element-property :language inline-src-block
))
2821 (arguments (org-element-property :parameters inline-src-block
))
2822 (body (org-element-property :value inline-src-block
)))
2823 (format "src_%s%s{%s}"
2825 (if arguments
(format "[%s]" arguments
) "")
2830 (defun org-element-italic-parser ()
2831 "Parse italic object at point, if any.
2833 When at an italic object, return a list whose car is `italic' and
2834 cdr is a plist with `:begin', `:end', `:contents-begin' and
2835 `:contents-end' and `:post-blank' keywords. Otherwise, return
2838 Assume point is at the first slash marker."
2840 (unless (bolp) (backward-char 1))
2841 (when (looking-at org-emph-re
)
2842 (let ((begin (match-beginning 2))
2843 (contents-begin (match-beginning 4))
2844 (contents-end (match-end 4))
2845 (post-blank (progn (goto-char (match-end 2))
2846 (skip-chars-forward " \t")))
2851 :contents-begin contents-begin
2852 :contents-end contents-end
2853 :post-blank post-blank
))))))
2855 (defun org-element-italic-interpreter (italic contents
)
2856 "Interpret ITALIC object as Org syntax.
2857 CONTENTS is the contents of the object."
2858 (format "/%s/" contents
))
2863 (defun org-element-latex-fragment-parser ()
2864 "Parse LaTeX fragment at point, if any.
2866 When at a LaTeX fragment, return a list whose car is
2867 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2868 and `:post-blank' as keywords. Otherwise, return nil.
2870 Assume point is at the beginning of the LaTeX fragment."
2873 (let* ((begin (point))
2875 (if (eq (char-after) ?$
)
2876 (if (eq (char-after (1+ (point))) ?$
)
2877 (search-forward "$$" nil t
2)
2878 (and (not (eq (char-before) ?$
))
2879 (search-forward "$" nil t
2)
2880 (not (memq (char-before (match-beginning 0))
2881 '(?\s ?
\t ?
\n ?
, ?.
)))
2882 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2884 (case (char-after (1+ (point)))
2885 (?\
( (search-forward "\\)" nil t
))
2886 (?\
[ (search-forward "\\]" nil t
))
2889 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2891 (post-blank (if (not after-fragment
) (throw 'no-object nil
)
2892 (goto-char after-fragment
)
2893 (skip-chars-forward " \t")))
2895 (list 'latex-fragment
2896 (list :value
(buffer-substring-no-properties begin after-fragment
)
2899 :post-blank post-blank
))))))
2901 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2902 "Interpret LATEX-FRAGMENT object as Org syntax.
2904 (org-element-property :value latex-fragment
))
2908 (defun org-element-line-break-parser ()
2909 "Parse line break at point, if any.
2911 When at a line break, return a list whose car is `line-break',
2912 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2913 Otherwise, return nil.
2915 Assume point is at the beginning of the line break."
2916 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2917 (not (eq (char-before) ?
\\)))
2919 (list :begin
(point)
2920 :end
(progn (forward-line) (point))
2923 (defun org-element-line-break-interpreter (line-break contents
)
2924 "Interpret LINE-BREAK object as Org syntax.
2931 (defun org-element-link-parser ()
2932 "Parse link at point, if any.
2934 When at a link, return a list whose car is `link' and cdr a plist
2935 with `:type', `:path', `:raw-link', `:application',
2936 `:search-option', `:begin', `:end', `:contents-begin',
2937 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2940 Assume point is at the beginning of the link."
2942 (let ((begin (point))
2943 end contents-begin contents-end link-end post-blank path type
2944 raw-link link search-option application
)
2946 ;; Type 1: Text targeted from a radio target.
2947 ((and org-target-link-regexp
2948 (save-excursion (or (bolp) (backward-char))
2949 (looking-at org-target-link-regexp
)))
2951 link-end
(match-end 1)
2952 path
(org-match-string-no-properties 1)
2953 contents-begin
(match-beginning 1)
2954 contents-end
(match-end 1)))
2955 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2956 ((looking-at org-bracket-link-regexp
)
2957 (setq contents-begin
(match-beginning 3)
2958 contents-end
(match-end 3)
2959 link-end
(match-end 0)
2960 ;; RAW-LINK is the original link. Expand any
2961 ;; abbreviation in it.
2962 raw-link
(org-translate-link
2963 (org-link-expand-abbrev
2964 (org-match-string-no-properties 1))))
2965 ;; Determine TYPE of link and set PATH accordingly.
2968 ((or (file-name-absolute-p raw-link
)
2969 (string-match "\\`\\.\\.?/" raw-link
))
2970 (setq type
"file" path raw-link
))
2971 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2972 ((string-match org-link-types-re raw-link
)
2973 (setq type
(match-string 1 raw-link
)
2974 ;; According to RFC 3986, extra whitespace should be
2975 ;; ignored when a URI is extracted.
2976 path
(replace-regexp-in-string
2977 "[ \t]*\n[ \t]*" "" (substring raw-link
(match-end 0)))))
2978 ;; Id type: PATH is the id.
2979 ((string-match "\\`id:\\([-a-f0-9]+\\)" raw-link
)
2980 (setq type
"id" path
(match-string 1 raw-link
)))
2981 ;; Code-ref type: PATH is the name of the reference.
2982 ((string-match "\\`(\\(.*\\))\\'" raw-link
)
2983 (setq type
"coderef" path
(match-string 1 raw-link
)))
2984 ;; Custom-id type: PATH is the name of the custom id.
2985 ((= (aref raw-link
0) ?
#)
2986 (setq type
"custom-id" path
(substring raw-link
1)))
2987 ;; Fuzzy type: Internal link either matches a target, an
2988 ;; headline name or nothing. PATH is the target or
2990 (t (setq type
"fuzzy" path raw-link
))))
2991 ;; Type 3: Plain link, e.g., http://orgmode.org
2992 ((looking-at org-plain-link-re
)
2993 (setq raw-link
(org-match-string-no-properties 0)
2994 type
(org-match-string-no-properties 1)
2995 link-end
(match-end 0)
2996 path
(org-match-string-no-properties 2)))
2997 ;; Type 4: Angular link, e.g., <http://orgmode.org>
2998 ((looking-at org-angle-link-re
)
2999 (setq raw-link
(buffer-substring-no-properties
3000 (match-beginning 1) (match-end 2))
3001 type
(org-match-string-no-properties 1)
3002 link-end
(match-end 0)
3003 path
(org-match-string-no-properties 2)))
3004 (t (throw 'no-object nil
)))
3005 ;; In any case, deduce end point after trailing white space from
3006 ;; LINK-END variable.
3008 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3010 ;; Special "file" type link processing.
3011 (when (member type org-element-link-type-is-file
)
3012 ;; Extract opening application and search option.
3013 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3014 (setq application
(match-string 1 type
)))
3015 ((not (string-match "^file" type
))
3016 (setq application type
)))
3017 (when (string-match "::\\(.*\\)\\'" path
)
3018 (setq search-option
(match-string 1 path
)
3019 path
(replace-match "" nil nil path
)))
3021 (when (and (file-name-absolute-p path
)
3022 (not (org-string-match-p "\\`[/~]/" path
)))
3023 (setq path
(concat "//" path
)))
3024 ;; Make sure TYPE always reports "file".
3029 :raw-link
(or raw-link path
)
3030 :application application
3031 :search-option search-option
3034 :contents-begin contents-begin
3035 :contents-end contents-end
3036 :post-blank post-blank
))))))
3038 (defun org-element-link-interpreter (link contents
)
3039 "Interpret LINK object as Org syntax.
3040 CONTENTS is the contents of the object, or nil."
3041 (let ((type (org-element-property :type link
))
3042 (raw-link (org-element-property :raw-link link
)))
3043 (if (string= type
"radio") raw-link
3046 (if contents
(format "[%s]" contents
) "")))))
3051 (defun org-element-macro-parser ()
3052 "Parse macro at point, if any.
3054 When at a macro, return a list whose car is `macro' and cdr
3055 a plist with `:key', `:args', `:begin', `:end', `:value' and
3056 `:post-blank' as keywords. Otherwise, return nil.
3058 Assume point is at the macro."
3060 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3061 (let ((begin (point))
3062 (key (downcase (org-match-string-no-properties 1)))
3063 (value (org-match-string-no-properties 0))
3064 (post-blank (progn (goto-char (match-end 0))
3065 (skip-chars-forward " \t")))
3067 (args (let ((args (org-match-string-no-properties 3)))
3069 ;; Do not use `org-split-string' since empty
3070 ;; strings are meaningful here.
3072 (replace-regexp-in-string
3073 "\\(\\\\*\\)\\(,\\)"
3075 (let ((len (length (match-string 1 str
))))
3076 (concat (make-string (/ len
2) ?
\\)
3077 (if (zerop (mod len
2)) "\000" ","))))
3086 :post-blank post-blank
))))))
3088 (defun org-element-macro-interpreter (macro contents
)
3089 "Interpret MACRO object as Org syntax.
3091 (org-element-property :value macro
))
3096 (defun org-element-radio-target-parser ()
3097 "Parse radio target at point, if any.
3099 When at a radio target, return a list whose car is `radio-target'
3100 and cdr a plist with `:begin', `:end', `:contents-begin',
3101 `:contents-end', `:value' and `:post-blank' as keywords.
3102 Otherwise, return nil.
3104 Assume point is at the radio target."
3106 (when (looking-at org-radio-target-regexp
)
3107 (let ((begin (point))
3108 (contents-begin (match-beginning 1))
3109 (contents-end (match-end 1))
3110 (value (org-match-string-no-properties 1))
3111 (post-blank (progn (goto-char (match-end 0))
3112 (skip-chars-forward " \t")))
3117 :contents-begin contents-begin
3118 :contents-end contents-end
3119 :post-blank post-blank
3122 (defun org-element-radio-target-interpreter (target contents
)
3123 "Interpret TARGET object as Org syntax.
3124 CONTENTS is the contents of the object."
3125 (concat "<<<" contents
">>>"))
3128 ;;;; Statistics Cookie
3130 (defun org-element-statistics-cookie-parser ()
3131 "Parse statistics cookie at point, if any.
3133 When at a statistics cookie, return a list whose car is
3134 `statistics-cookie', and cdr a plist with `:begin', `:end',
3135 `:value' and `:post-blank' keywords. Otherwise, return nil.
3137 Assume point is at the beginning of the statistics-cookie."
3139 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3140 (let* ((begin (point))
3141 (value (buffer-substring-no-properties
3142 (match-beginning 0) (match-end 0)))
3143 (post-blank (progn (goto-char (match-end 0))
3144 (skip-chars-forward " \t")))
3146 (list 'statistics-cookie
3150 :post-blank post-blank
))))))
3152 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3153 "Interpret STATISTICS-COOKIE object as Org syntax.
3155 (org-element-property :value statistics-cookie
))
3160 (defun org-element-strike-through-parser ()
3161 "Parse strike-through object at point, if any.
3163 When at a strike-through object, return a list whose car is
3164 `strike-through' and cdr is a plist with `:begin', `:end',
3165 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3166 Otherwise, return nil.
3168 Assume point is at the first plus sign marker."
3170 (unless (bolp) (backward-char 1))
3171 (when (looking-at org-emph-re
)
3172 (let ((begin (match-beginning 2))
3173 (contents-begin (match-beginning 4))
3174 (contents-end (match-end 4))
3175 (post-blank (progn (goto-char (match-end 2))
3176 (skip-chars-forward " \t")))
3178 (list 'strike-through
3181 :contents-begin contents-begin
3182 :contents-end contents-end
3183 :post-blank post-blank
))))))
3185 (defun org-element-strike-through-interpreter (strike-through contents
)
3186 "Interpret STRIKE-THROUGH object as Org syntax.
3187 CONTENTS is the contents of the object."
3188 (format "+%s+" contents
))
3193 (defun org-element-subscript-parser ()
3194 "Parse subscript at point, if any.
3196 When at a subscript object, return a list whose car is
3197 `subscript' and cdr a plist with `:begin', `:end',
3198 `:contents-begin', `:contents-end', `:use-brackets-p' and
3199 `:post-blank' as keywords. Otherwise, return nil.
3201 Assume point is at the underscore."
3203 (unless (bolp) (backward-char))
3204 (when (looking-at org-match-substring-regexp
)
3205 (let ((bracketsp (match-beginning 4))
3206 (begin (match-beginning 2))
3207 (contents-begin (or (match-beginning 4)
3208 (match-beginning 3)))
3209 (contents-end (or (match-end 4) (match-end 3)))
3210 (post-blank (progn (goto-char (match-end 0))
3211 (skip-chars-forward " \t")))
3216 :use-brackets-p bracketsp
3217 :contents-begin contents-begin
3218 :contents-end contents-end
3219 :post-blank post-blank
))))))
3221 (defun org-element-subscript-interpreter (subscript contents
)
3222 "Interpret SUBSCRIPT object as Org syntax.
3223 CONTENTS is the contents of the object."
3225 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3231 (defun org-element-superscript-parser ()
3232 "Parse superscript at point, if any.
3234 When at a superscript object, return a list whose car is
3235 `superscript' and cdr a plist with `:begin', `:end',
3236 `:contents-begin', `:contents-end', `:use-brackets-p' and
3237 `:post-blank' as keywords. Otherwise, return nil.
3239 Assume point is at the caret."
3241 (unless (bolp) (backward-char))
3242 (when (looking-at org-match-substring-regexp
)
3243 (let ((bracketsp (match-beginning 4))
3244 (begin (match-beginning 2))
3245 (contents-begin (or (match-beginning 4)
3246 (match-beginning 3)))
3247 (contents-end (or (match-end 4) (match-end 3)))
3248 (post-blank (progn (goto-char (match-end 0))
3249 (skip-chars-forward " \t")))
3254 :use-brackets-p bracketsp
3255 :contents-begin contents-begin
3256 :contents-end contents-end
3257 :post-blank post-blank
))))))
3259 (defun org-element-superscript-interpreter (superscript contents
)
3260 "Interpret SUPERSCRIPT object as Org syntax.
3261 CONTENTS is the contents of the object."
3263 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3269 (defun org-element-table-cell-parser ()
3270 "Parse table cell at point.
3271 Return a list whose car is `table-cell' and cdr is a plist
3272 containing `:begin', `:end', `:contents-begin', `:contents-end'
3273 and `:post-blank' keywords."
3274 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3275 (let* ((begin (match-beginning 0))
3277 (contents-begin (match-beginning 1))
3278 (contents-end (match-end 1)))
3282 :contents-begin contents-begin
3283 :contents-end contents-end
3286 (defun org-element-table-cell-interpreter (table-cell contents
)
3287 "Interpret TABLE-CELL element as Org syntax.
3288 CONTENTS is the contents of the cell, or nil."
3289 (concat " " contents
" |"))
3294 (defun org-element-target-parser ()
3295 "Parse target at point, if any.
3297 When at a target, return a list whose car is `target' and cdr
3298 a plist with `:begin', `:end', `:value' and `:post-blank' as
3299 keywords. Otherwise, return nil.
3301 Assume point is at the target."
3303 (when (looking-at org-target-regexp
)
3304 (let ((begin (point))
3305 (value (org-match-string-no-properties 1))
3306 (post-blank (progn (goto-char (match-end 0))
3307 (skip-chars-forward " \t")))
3313 :post-blank post-blank
))))))
3315 (defun org-element-target-interpreter (target contents
)
3316 "Interpret TARGET object as Org syntax.
3318 (format "<<%s>>" (org-element-property :value target
)))
3323 (defconst org-element--timestamp-regexp
3324 (concat org-ts-regexp-both
3326 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3328 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3329 "Regexp matching any timestamp type object.")
3331 (defun org-element-timestamp-parser ()
3332 "Parse time stamp at point, if any.
3334 When at a time stamp, return a list whose car is `timestamp', and
3335 cdr a plist with `:type', `:raw-value', `:year-start',
3336 `:month-start', `:day-start', `:hour-start', `:minute-start',
3337 `:year-end', `:month-end', `:day-end', `:hour-end',
3338 `:minute-end', `:repeater-type', `:repeater-value',
3339 `:repeater-unit', `:warning-type', `:warning-value',
3340 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3341 Otherwise, return nil.
3343 Assume point is at the beginning of the timestamp."
3344 (when (org-looking-at-p org-element--timestamp-regexp
)
3346 (let* ((begin (point))
3347 (activep (eq (char-after) ?
<))
3350 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3351 (match-string-no-properties 0)))
3352 (date-start (match-string-no-properties 1))
3353 (date-end (match-string 3))
3354 (diaryp (match-beginning 2))
3355 (post-blank (progn (goto-char (match-end 0))
3356 (skip-chars-forward " \t")))
3361 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3363 (cons (string-to-number (match-string 2 date-start
))
3364 (string-to-number (match-string 3 date-start
)))))
3365 (type (cond (diaryp 'diary
)
3366 ((and activep
(or date-end time-range
)) 'active-range
)
3368 ((or date-end time-range
) 'inactive-range
)
3372 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3376 (let ((type (match-string 1 raw-value
)))
3377 (cond ((equal "++" type
) 'catch-up
)
3378 ((equal ".+" type
) 'restart
)
3380 :repeater-value
(string-to-number (match-string 2 raw-value
))
3382 (case (string-to-char (match-string 3 raw-value
))
3383 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3386 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3388 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3389 :warning-value
(string-to-number (match-string 2 raw-value
))
3391 (case (string-to-char (match-string 3 raw-value
))
3392 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3393 year-start month-start day-start hour-start minute-start year-end
3394 month-end day-end hour-end minute-end
)
3395 ;; Parse date-start.
3397 (let ((date (org-parse-time-string date-start t
)))
3398 (setq year-start
(nth 5 date
)
3399 month-start
(nth 4 date
)
3400 day-start
(nth 3 date
)
3401 hour-start
(nth 2 date
)
3402 minute-start
(nth 1 date
))))
3403 ;; Compute date-end. It can be provided directly in time-stamp,
3404 ;; or extracted from time range. Otherwise, it defaults to the
3405 ;; same values as date-start.
3407 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3408 (setq year-end
(or (nth 5 date
) year-start
)
3409 month-end
(or (nth 4 date
) month-start
)
3410 day-end
(or (nth 3 date
) day-start
)
3411 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3412 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3414 (nconc (list :type type
3415 :raw-value raw-value
3416 :year-start year-start
3417 :month-start month-start
3418 :day-start day-start
3419 :hour-start hour-start
3420 :minute-start minute-start
3422 :month-end month-end
3425 :minute-end minute-end
3428 :post-blank post-blank
)
3432 (defun org-element-timestamp-interpreter (timestamp contents
)
3433 "Interpret TIMESTAMP object as Org syntax.
3435 (let* ((repeat-string
3437 (case (org-element-property :repeater-type timestamp
)
3438 (cumulate "+") (catch-up "++") (restart ".+"))
3439 (let ((val (org-element-property :repeater-value timestamp
)))
3440 (and val
(number-to-string val
)))
3441 (case (org-element-property :repeater-unit timestamp
)
3442 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3445 (case (org-element-property :warning-type timestamp
)
3448 (let ((val (org-element-property :warning-value timestamp
)))
3449 (and val
(number-to-string val
)))
3450 (case (org-element-property :warning-unit timestamp
)
3451 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3453 ;; Build an Org timestamp string from TIME. ACTIVEP is
3454 ;; non-nil when time stamp is active. If WITH-TIME-P is
3455 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3456 ;; specify a time range in the timestamp. REPEAT-STRING is
3457 ;; the repeater string, if any.
3458 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3459 (let ((ts (format-time-string
3460 (funcall (if with-time-p
'cdr
'car
)
3461 org-time-stamp-formats
)
3463 (when (and hour-end minute-end
)
3464 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3467 (format "\\&-%02d:%02d" hour-end minute-end
)
3469 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3470 (dolist (s (list repeat-string warning-string
))
3471 (when (org-string-nw-p s
)
3472 (setq ts
(concat (substring ts
0 -
1)
3475 (substring ts -
1)))))
3478 (type (org-element-property :type timestamp
)))
3481 (let* ((minute-start (org-element-property :minute-start timestamp
))
3482 (minute-end (org-element-property :minute-end timestamp
))
3483 (hour-start (org-element-property :hour-start timestamp
))
3484 (hour-end (org-element-property :hour-end timestamp
))
3485 (time-range-p (and hour-start hour-end minute-start minute-end
3486 (or (/= hour-start hour-end
)
3487 (/= minute-start minute-end
)))))
3493 (org-element-property :day-start timestamp
)
3494 (org-element-property :month-start timestamp
)
3495 (org-element-property :year-start timestamp
))
3497 (and hour-start minute-start
)
3498 (and time-range-p hour-end
)
3499 (and time-range-p minute-end
))))
3500 ((active-range inactive-range
)
3501 (let ((minute-start (org-element-property :minute-start timestamp
))
3502 (minute-end (org-element-property :minute-end timestamp
))
3503 (hour-start (org-element-property :hour-start timestamp
))
3504 (hour-end (org-element-property :hour-end timestamp
)))
3507 build-ts-string
(encode-time
3511 (org-element-property :day-start timestamp
)
3512 (org-element-property :month-start timestamp
)
3513 (org-element-property :year-start timestamp
))
3514 (eq type
'active-range
)
3515 (and hour-start minute-start
))
3517 (funcall build-ts-string
3521 (org-element-property :day-end timestamp
)
3522 (org-element-property :month-end timestamp
)
3523 (org-element-property :year-end timestamp
))
3524 (eq type
'active-range
)
3525 (and hour-end minute-end
))))))))
3530 (defun org-element-underline-parser ()
3531 "Parse underline object at point, if any.
3533 When at an underline object, return a list whose car is
3534 `underline' and cdr is a plist with `:begin', `:end',
3535 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3536 Otherwise, return nil.
3538 Assume point is at the first underscore marker."
3540 (unless (bolp) (backward-char 1))
3541 (when (looking-at org-emph-re
)
3542 (let ((begin (match-beginning 2))
3543 (contents-begin (match-beginning 4))
3544 (contents-end (match-end 4))
3545 (post-blank (progn (goto-char (match-end 2))
3546 (skip-chars-forward " \t")))
3551 :contents-begin contents-begin
3552 :contents-end contents-end
3553 :post-blank post-blank
))))))
3555 (defun org-element-underline-interpreter (underline contents
)
3556 "Interpret UNDERLINE object as Org syntax.
3557 CONTENTS is the contents of the object."
3558 (format "_%s_" contents
))
3563 (defun org-element-verbatim-parser ()
3564 "Parse verbatim object at point, if any.
3566 When at a verbatim object, return a list whose car is `verbatim'
3567 and cdr is a plist with `:value', `:begin', `:end' and
3568 `:post-blank' keywords. Otherwise, return nil.
3570 Assume point is at the first equal sign marker."
3572 (unless (bolp) (backward-char 1))
3573 (when (looking-at org-emph-re
)
3574 (let ((begin (match-beginning 2))
3575 (value (org-match-string-no-properties 4))
3576 (post-blank (progn (goto-char (match-end 2))
3577 (skip-chars-forward " \t")))
3583 :post-blank post-blank
))))))
3585 (defun org-element-verbatim-interpreter (verbatim contents
)
3586 "Interpret VERBATIM object as Org syntax.
3588 (format "=%s=" (org-element-property :value verbatim
)))
3592 ;;; Parsing Element Starting At Point
3594 ;; `org-element--current-element' is the core function of this section.
3595 ;; It returns the Lisp representation of the element starting at
3598 ;; `org-element--current-element' makes use of special modes. They
3599 ;; are activated for fixed element chaining (e.g., `plain-list' >
3600 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3601 ;; `section'). Special modes are: `first-section', `item',
3602 ;; `node-property', `section' and `table-row'.
3604 (defun org-element--current-element
3605 (limit &optional granularity special structure
)
3606 "Parse the element starting at point.
3608 Return value is a list like (TYPE PROPS) where TYPE is the type
3609 of the element and PROPS a plist of properties associated to the
3612 Possible types are defined in `org-element-all-elements'.
3614 LIMIT bounds the search.
3616 Optional argument GRANULARITY determines the depth of the
3617 recursion. Allowed values are `headline', `greater-element',
3618 `element', `object' or nil. When it is broader than `object' (or
3619 nil), secondary values will not be parsed, since they only
3622 Optional argument SPECIAL, when non-nil, can be either
3623 `first-section', `item', `node-property', `section', and
3626 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3629 This function assumes point is always at the beginning of the
3630 element it has to parse."
3632 (let ((case-fold-search t
)
3633 ;; Determine if parsing depth allows for secondary strings
3634 ;; parsing. It only applies to elements referenced in
3635 ;; `org-element-secondary-value-alist'.
3636 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3640 (org-element-item-parser limit structure raw-secondary-p
))
3642 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3644 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3646 ((org-with-limited-levels (org-at-heading-p))
3647 (org-element-headline-parser limit raw-secondary-p
))
3648 ;; Sections (must be checked after headline).
3649 ((eq special
'section
) (org-element-section-parser limit
))
3650 ((eq special
'first-section
)
3651 (org-element-section-parser
3652 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3654 ;; When not at bol, point is at the beginning of an item or
3655 ;; a footnote definition: next item is always a paragraph.
3656 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3657 ;; Planning and Clock.
3658 ((looking-at org-planning-or-clock-line-re
)
3659 (if (equal (match-string 1) org-clock-string
)
3660 (org-element-clock-parser limit
)
3661 (org-element-planning-parser limit
)))
3664 (org-element-inlinetask-parser limit raw-secondary-p
))
3665 ;; From there, elements can have affiliated keywords.
3666 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3668 ;; Jumping over affiliated keywords put point off-limits.
3669 ;; Parse them as regular keywords.
3670 ((and (cdr affiliated
) (>= (point) limit
))
3671 (goto-char (car affiliated
))
3672 (org-element-keyword-parser limit nil
))
3673 ;; LaTeX Environment.
3674 ((looking-at org-element--latex-begin-environment
)
3675 (org-element-latex-environment-parser limit affiliated
))
3676 ;; Drawer and Property Drawer.
3677 ((looking-at org-drawer-regexp
)
3678 (if (equal (match-string 1) "PROPERTIES")
3679 (org-element-property-drawer-parser limit affiliated
)
3680 (org-element-drawer-parser limit affiliated
)))
3682 ((looking-at "[ \t]*:\\( \\|$\\)")
3683 (org-element-fixed-width-parser limit affiliated
))
3684 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3686 ((looking-at "[ \t]*#")
3687 (goto-char (match-end 0))
3688 (cond ((looking-at "\\(?: \\|$\\)")
3690 (org-element-comment-parser limit affiliated
))
3691 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3693 (let ((parser (assoc (upcase (match-string 1))
3694 org-element-block-name-alist
)))
3695 (if parser
(funcall (cdr parser
) limit affiliated
)
3696 (org-element-special-block-parser limit affiliated
))))
3697 ((looking-at "\\+CALL:")
3699 (org-element-babel-call-parser limit affiliated
))
3700 ((looking-at "\\+BEGIN:? ")
3702 (org-element-dynamic-block-parser limit affiliated
))
3703 ((looking-at "\\+\\S-+:")
3705 (org-element-keyword-parser limit affiliated
))
3708 (org-element-paragraph-parser limit affiliated
))))
3709 ;; Footnote Definition.
3710 ((looking-at org-footnote-definition-re
)
3711 (org-element-footnote-definition-parser limit affiliated
))
3713 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3714 (org-element-horizontal-rule-parser limit affiliated
))
3717 (org-element-diary-sexp-parser limit affiliated
))
3719 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3721 ((looking-at (org-item-re))
3722 (org-element-plain-list-parser
3724 (or structure
(org-element--list-struct limit
))))
3725 ;; Default element: Paragraph.
3726 (t (org-element-paragraph-parser limit affiliated
)))))))))
3729 ;; Most elements can have affiliated keywords. When looking for an
3730 ;; element beginning, we want to move before them, as they belong to
3731 ;; that element, and, in the meantime, collect information they give
3732 ;; into appropriate properties. Hence the following function.
3734 (defun org-element--collect-affiliated-keywords (limit)
3735 "Collect affiliated keywords from point down to LIMIT.
3737 Return a list whose CAR is the position at the first of them and
3738 CDR a plist of keywords and values and move point to the
3739 beginning of the first line after them.
3741 As a special case, if element doesn't start at the beginning of
3742 the line (e.g., a paragraph starting an item), CAR is current
3743 position of point and CDR is nil."
3744 (if (not (bolp)) (list (point))
3745 (let ((case-fold-search t
)
3747 ;; RESTRICT is the list of objects allowed in parsed
3749 (restrict (org-element-restriction 'keyword
))
3751 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3752 (let* ((raw-kwd (upcase (match-string 1)))
3753 ;; Apply translation to RAW-KWD. From there, KWD is
3754 ;; the official keyword.
3755 (kwd (or (cdr (assoc raw-kwd
3756 org-element-keyword-translation-alist
))
3758 ;; Find main value for any keyword.
3762 (buffer-substring-no-properties
3763 (match-end 0) (point-at-eol)))))
3764 ;; PARSEDP is non-nil when keyword should have its
3766 (parsedp (member kwd org-element-parsed-keywords
))
3767 ;; If KWD is a dual keyword, find its secondary
3768 ;; value. Maybe parse it.
3769 (dualp (member kwd org-element-dual-keywords
))
3772 (let ((sec (org-match-string-no-properties 2)))
3773 (if (or (not sec
) (not parsedp
)) sec
3774 (org-element-parse-secondary-string sec restrict
)))))
3775 ;; Attribute a property name to KWD.
3776 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3777 ;; Now set final shape for VALUE.
3779 (setq value
(org-element-parse-secondary-string value restrict
)))
3781 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3782 (when (or (member kwd org-element-multiple-keywords
)
3783 ;; Attributes can always appear on multiple lines.
3784 (string-match "^ATTR_" kwd
))
3785 (setq value
(cons value
(plist-get output kwd-sym
))))
3786 ;; Eventually store the new value in OUTPUT.
3787 (setq output
(plist-put output kwd-sym value
))
3788 ;; Move to next keyword.
3790 ;; If affiliated keywords are orphaned: move back to first one.
3791 ;; They will be parsed as a paragraph.
3792 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3794 (cons origin output
))))
3800 ;; The two major functions here are `org-element-parse-buffer', which
3801 ;; parses Org syntax inside the current buffer, taking into account
3802 ;; region, narrowing, or even visibility if specified, and
3803 ;; `org-element-parse-secondary-string', which parses objects within
3806 ;; The (almost) almighty `org-element-map' allows to apply a function
3807 ;; on elements or objects matching some type, and accumulate the
3808 ;; resulting values. In an export situation, it also skips unneeded
3809 ;; parts of the parse tree.
3811 (defun org-element-parse-buffer (&optional granularity visible-only
)
3812 "Recursively parse the buffer and return structure.
3813 If narrowing is in effect, only parse the visible part of the
3816 Optional argument GRANULARITY determines the depth of the
3817 recursion. It can be set to the following symbols:
3819 `headline' Only parse headlines.
3820 `greater-element' Don't recurse into greater elements excepted
3821 headlines and sections. Thus, elements
3822 parsed are the top-level ones.
3823 `element' Parse everything but objects and plain text.
3824 `object' Parse the complete buffer (default).
3826 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3829 An element or an objects is represented as a list with the
3830 pattern (TYPE PROPERTIES CONTENTS), where :
3832 TYPE is a symbol describing the element or object. See
3833 `org-element-all-elements' and `org-element-all-objects' for an
3834 exhaustive list of such symbols. One can retrieve it with
3835 `org-element-type' function.
3837 PROPERTIES is the list of attributes attached to the element or
3838 object, as a plist. Although most of them are specific to the
3839 element or object type, all types share `:begin', `:end',
3840 `:post-blank' and `:parent' properties, which respectively
3841 refer to buffer position where the element or object starts,
3842 ends, the number of white spaces or blank lines after it, and
3843 the element or object containing it. Properties values can be
3844 obtained by using `org-element-property' function.
3846 CONTENTS is a list of elements, objects or raw strings
3847 contained in the current element or object, when applicable.
3848 One can access them with `org-element-contents' function.
3850 The Org buffer has `org-data' as type and nil as properties.
3851 `org-element-map' function can be used to find specific elements
3852 or objects within the parse tree.
3854 This function assumes that current major mode is `org-mode'."
3856 (goto-char (point-min))
3857 (org-skip-whitespace)
3858 (org-element--parse-elements
3859 (point-at-bol) (point-max)
3860 ;; Start in `first-section' mode so text before the first
3861 ;; headline belongs to a section.
3862 'first-section nil granularity visible-only
(list 'org-data nil
))))
3864 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3865 "Recursively parse objects in STRING and return structure.
3867 RESTRICTION is a symbol limiting the object types that will be
3870 Optional argument PARENT, when non-nil, is the element or object
3871 containing the secondary string. It is used to set correctly
3872 `:parent' property within the string."
3873 (let ((local-variables (buffer-local-variables)))
3875 (dolist (v local-variables
)
3877 (if (symbolp v
) (makunbound v
)
3878 (org-set-local (car v
) (cdr v
)))))
3880 (restore-buffer-modified-p nil
)
3881 (let ((secondary (org-element--parse-objects
3882 (point-min) (point-max) nil restriction
)))
3884 (dolist (o secondary
) (org-element-put-property o
:parent parent
)))
3887 (defun org-element-map
3888 (data types fun
&optional info first-match no-recursion with-affiliated
)
3889 "Map a function on selected elements or objects.
3891 DATA is a parse tree, an element, an object, a string, or a list
3892 of such constructs. TYPES is a symbol or list of symbols of
3893 elements or objects types (see `org-element-all-elements' and
3894 `org-element-all-objects' for a complete list of types). FUN is
3895 the function called on the matching element or object. It has to
3896 accept one argument: the element or object itself.
3898 When optional argument INFO is non-nil, it should be a plist
3899 holding export options. In that case, parts of the parse tree
3900 not exportable according to that property list will be skipped.
3902 When optional argument FIRST-MATCH is non-nil, stop at the first
3903 match for which FUN doesn't return nil, and return that value.
3905 Optional argument NO-RECURSION is a symbol or a list of symbols
3906 representing elements or objects types. `org-element-map' won't
3907 enter any recursive element or object whose type belongs to that
3908 list. Though, FUN can still be applied on them.
3910 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3911 apply to matching objects within parsed affiliated keywords (see
3912 `org-element-parsed-keywords').
3914 Nil values returned from FUN do not appear in the results.
3920 Assuming TREE is a variable containing an Org buffer parse tree,
3921 the following example will return a flat list of all `src-block'
3922 and `example-block' elements in it:
3924 \(org-element-map tree '(example-block src-block) 'identity)
3926 The following snippet will find the first headline with a level
3927 of 1 and a \"phone\" tag, and will return its beginning position:
3929 \(org-element-map tree 'headline
3931 \(and (= (org-element-property :level hl) 1)
3932 \(member \"phone\" (org-element-property :tags hl))
3933 \(org-element-property :begin hl)))
3936 The next example will return a flat list of all `plain-list' type
3937 elements in TREE that are not a sub-list themselves:
3939 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3941 Eventually, this example will return a flat list of all `bold'
3942 type objects containing a `latex-snippet' type object, even
3943 looking into captions:
3945 \(org-element-map tree 'bold
3947 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3949 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3950 (unless (listp types
) (setq types
(list types
)))
3951 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
3952 ;; Recursion depth is determined by --CATEGORY.
3955 (let ((category 'greater-elements
))
3956 (mapc (lambda (type)
3957 (cond ((or (memq type org-element-all-objects
)
3958 (eq type
'plain-text
))
3959 ;; If one object is found, the function
3960 ;; has to recurse into every object.
3961 (throw 'found
'objects
))
3962 ((not (memq type org-element-greater-elements
))
3963 ;; If one regular element is found, the
3964 ;; function has to recurse, at least,
3965 ;; into every element it encounters.
3966 (and (not (eq category
'elements
))
3967 (setq category
'elements
)))))
3970 ;; Compute properties for affiliated keywords if necessary.
3972 (and with-affiliated
3973 (mapcar (lambda (kwd)
3974 (cons kwd
(intern (concat ":" (downcase kwd
)))))
3975 org-element-affiliated-keywords
)))
3981 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3982 ;; holding contextual information.
3983 (let ((--type (org-element-type --data
)))
3986 ;; Ignored element in an export context.
3987 ((and info
(memq --data
(plist-get info
:ignore-list
))))
3988 ;; List of elements or objects.
3989 ((not --type
) (mapc --walk-tree --data
))
3990 ;; Unconditionally enter parse trees.
3991 ((eq --type
'org-data
)
3992 (mapc --walk-tree
(org-element-contents --data
)))
3994 ;; Check if TYPE is matching among TYPES. If so,
3995 ;; apply FUN to --DATA and accumulate return value
3996 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3997 (when (memq --type types
)
3998 (let ((result (funcall fun --data
)))
3999 (cond ((not result
))
4000 (first-match (throw '--map-first-match result
))
4001 (t (push result --acc
)))))
4002 ;; If --DATA has a secondary string that can contain
4003 ;; objects with their type among TYPES, look into it.
4004 (when (and (eq --category
'objects
) (not (stringp --data
)))
4006 (assq --type org-element-secondary-value-alist
)))
4008 (funcall --walk-tree
4009 (org-element-property (cdr sec-prop
) --data
)))))
4010 ;; If --DATA has any affiliated keywords and
4011 ;; WITH-AFFILIATED is non-nil, look for objects in
4013 (when (and with-affiliated
4014 (eq --category
'objects
)
4015 (memq --type org-element-all-elements
))
4016 (mapc (lambda (kwd-pair)
4017 (let ((kwd (car kwd-pair
))
4018 (value (org-element-property
4019 (cdr kwd-pair
) --data
)))
4020 ;; Pay attention to the type of value.
4021 ;; Preserve order for multiple keywords.
4024 ((and (member kwd org-element-multiple-keywords
)
4025 (member kwd org-element-dual-keywords
))
4026 (mapc (lambda (line)
4027 (funcall --walk-tree
(cdr line
))
4028 (funcall --walk-tree
(car line
)))
4030 ((member kwd org-element-multiple-keywords
)
4031 (mapc (lambda (line) (funcall --walk-tree line
))
4033 ((member kwd org-element-dual-keywords
)
4034 (funcall --walk-tree
(cdr value
))
4035 (funcall --walk-tree
(car value
)))
4036 (t (funcall --walk-tree value
)))))
4037 --affiliated-alist
))
4038 ;; Determine if a recursion into --DATA is possible.
4040 ;; --TYPE is explicitly removed from recursion.
4041 ((memq --type no-recursion
))
4042 ;; --DATA has no contents.
4043 ((not (org-element-contents --data
)))
4044 ;; Looking for greater elements but --DATA is simply
4045 ;; an element or an object.
4046 ((and (eq --category
'greater-elements
)
4047 (not (memq --type org-element-greater-elements
))))
4048 ;; Looking for elements but --DATA is an object.
4049 ((and (eq --category
'elements
)
4050 (memq --type org-element-all-objects
)))
4051 ;; In any other case, map contents.
4052 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4053 (catch '--map-first-match
4054 (funcall --walk-tree data
)
4055 ;; Return value in a proper order.
4057 (put 'org-element-map
'lisp-indent-function
2)
4059 ;; The following functions are internal parts of the parser.
4061 ;; The first one, `org-element--parse-elements' acts at the element's
4064 ;; The second one, `org-element--parse-objects' applies on all objects
4065 ;; of a paragraph or a secondary string.
4067 ;; More precisely, that function looks for every allowed object type
4068 ;; first. Then, it discards failed searches, keeps further matches,
4069 ;; and searches again types matched behind point, for subsequent
4070 ;; calls. Thus, searching for a given type fails only once, and every
4071 ;; object is searched only once at top level (but sometimes more for
4074 (defun org-element--parse-elements
4075 (beg end special structure granularity visible-only acc
)
4076 "Parse elements between BEG and END positions.
4078 SPECIAL prioritize some elements over the others. It can be set
4079 to `first-section', `section' `item' or `table-row'.
4081 When value is `item', STRUCTURE will be used as the current list
4084 GRANULARITY determines the depth of the recursion. See
4085 `org-element-parse-buffer' for more information.
4087 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4090 Elements are accumulated into ACC."
4093 ;; Visible only: skip invisible parts at the beginning of the
4095 (when (and visible-only
(org-invisible-p2))
4096 (goto-char (min (1+ (org-find-visible)) end
)))
4097 ;; When parsing only headlines, skip any text before first one.
4098 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4099 (org-with-limited-levels (outline-next-heading)))
4101 (while (< (point) end
)
4102 ;; Find current element's type and parse it accordingly to
4104 (let* ((element (org-element--current-element
4105 end granularity special structure
))
4106 (type (org-element-type element
))
4107 (cbeg (org-element-property :contents-begin element
)))
4108 (goto-char (org-element-property :end element
))
4109 ;; Visible only: skip invisible parts between siblings.
4110 (when (and visible-only
(org-invisible-p2))
4111 (goto-char (min (1+ (org-find-visible)) end
)))
4112 ;; Fill ELEMENT contents by side-effect.
4114 ;; If element has no contents, don't modify it.
4116 ;; Greater element: parse it between `contents-begin' and
4117 ;; `contents-end'. Make sure GRANULARITY allows the
4118 ;; recursion, or ELEMENT is a headline, in which case going
4119 ;; inside is mandatory, in order to get sub-level headings.
4120 ((and (memq type org-element-greater-elements
)
4121 (or (memq granularity
'(element object nil
))
4122 (and (eq granularity
'greater-element
)
4124 (eq type
'headline
)))
4125 (org-element--parse-elements
4126 cbeg
(org-element-property :contents-end element
)
4127 ;; Possibly switch to a special mode.
4131 (property-drawer 'node-property
)
4133 (and (memq type
'(item plain-list
))
4134 (org-element-property :structure element
))
4135 granularity visible-only element
))
4136 ;; ELEMENT has contents. Parse objects inside, if
4137 ;; GRANULARITY allows it.
4138 ((memq granularity
'(object nil
))
4139 (org-element--parse-objects
4140 cbeg
(org-element-property :contents-end element
) element
4141 (org-element-restriction type
))))
4142 (org-element-adopt-elements acc element
)))
4146 (defconst org-element--object-regexp
4147 (mapconcat #'identity
4148 (let ((link-types (regexp-opt org-link-types
)))
4151 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4152 ;; Bold, code, italic, strike-through, underline and
4155 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4157 (concat "\\<" link-types
":")
4158 ;; Objects starting with "[": regular link, footnote
4159 ;; reference, statistics cookie, timestamp (inactive).
4160 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4161 ;; Objects starting with "@": export snippets.
4163 ;; Objects starting with "{": macro.
4165 ;; Objects starting with "<" : timestamp (active,
4166 ;; diary), target, radio target and angular links.
4167 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4168 ;; Objects starting with "$": latex fragment.
4170 ;; Objects starting with "\": line break, entity,
4172 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4173 ;; Objects starting with raw text: inline Babel
4174 ;; source block, inline Babel call.
4175 "\\(?:call\\|src\\)_"))
4177 "Regexp possibly matching the beginning of an object.
4178 This regexp allows false positives. Dedicated parser (e.g.,
4179 `org-export-bold-parser') will take care of further filtering.
4180 Radio links are not matched by this regexp, as they are treated
4181 specially in `org-element--object-lex'.")
4183 (defun org-element--object-lex (restriction)
4184 "Return next object in current buffer or nil.
4185 RESTRICTION is a list of object types, as symbols, that should be
4186 looked after. This function assumes that the buffer is narrowed
4187 to an appropriate container (e.g., a paragraph)."
4188 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4190 (let ((limit (and org-target-link-regexp
4192 (or (bolp) (backward-char))
4193 (re-search-forward org-target-link-regexp nil t
))
4194 (match-beginning 1)))
4196 (while (and (not found
)
4197 (re-search-forward org-element--object-regexp limit t
))
4198 (goto-char (match-beginning 0))
4199 (let ((result (match-string 0)))
4202 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4203 (and (memq 'inline-babel-call restriction
)
4204 (org-element-inline-babel-call-parser)))
4205 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4206 (and (memq 'inline-src-block restriction
)
4207 (org-element-inline-src-block-parser)))
4210 (?^
(and (memq 'superscript restriction
)
4211 (org-element-superscript-parser)))
4212 (?_
(or (and (memq 'subscript restriction
)
4213 (org-element-subscript-parser))
4214 (and (memq 'underline restriction
)
4215 (org-element-underline-parser))))
4216 (?
* (and (memq 'bold restriction
)
4217 (org-element-bold-parser)))
4218 (?
/ (and (memq 'italic restriction
)
4219 (org-element-italic-parser)))
4220 (?~
(and (memq 'code restriction
)
4221 (org-element-code-parser)))
4222 (?
= (and (memq 'verbatim restriction
)
4223 (org-element-verbatim-parser)))
4224 (?
+ (and (memq 'strike-through restriction
)
4225 (org-element-strike-through-parser)))
4226 (?
@ (and (memq 'export-snippet restriction
)
4227 (org-element-export-snippet-parser)))
4228 (?
{ (and (memq 'macro restriction
)
4229 (org-element-macro-parser)))
4230 (?$
(and (memq 'latex-fragment restriction
)
4231 (org-element-latex-fragment-parser)))
4233 (if (eq (aref result
1) ?
<)
4234 (or (and (memq 'radio-target restriction
)
4235 (org-element-radio-target-parser))
4236 (and (memq 'target restriction
)
4237 (org-element-target-parser)))
4238 (or (and (memq 'timestamp restriction
)
4239 (org-element-timestamp-parser))
4240 (and (memq 'link restriction
)
4241 (org-element-link-parser)))))
4243 (if (eq (aref result
1) ?
\\)
4244 (and (memq 'line-break restriction
)
4245 (org-element-line-break-parser))
4246 (or (and (memq 'entity restriction
)
4247 (org-element-entity-parser))
4248 (and (memq 'latex-fragment restriction
)
4249 (org-element-latex-fragment-parser)))))
4251 (if (eq (aref result
1) ?\
[)
4252 (and (memq 'link restriction
)
4253 (org-element-link-parser))
4254 (or (and (memq 'footnote-reference restriction
)
4255 (org-element-footnote-reference-parser))
4256 (and (memq 'timestamp restriction
)
4257 (org-element-timestamp-parser))
4258 (and (memq 'statistics-cookie restriction
)
4259 (org-element-statistics-cookie-parser)))))
4260 ;; This is probably a plain link.
4261 (otherwise (and (or (memq 'link restriction
)
4262 (memq 'plain-link restriction
))
4263 (org-element-link-parser)))))))
4264 (or (eobp) (forward-char))))
4267 ((and limit
(memq 'link restriction
))
4268 (goto-char limit
) (org-element-link-parser)))))))
4270 (defun org-element--parse-objects (beg end acc restriction
)
4271 "Parse objects between BEG and END and return recursive structure.
4273 Objects are accumulated in ACC.
4275 RESTRICTION is a list of object successors which are allowed in
4276 the current object."
4279 (narrow-to-region beg end
)
4280 (goto-char (point-min))
4282 (while (and (not (eobp))
4283 (setq next-object
(org-element--object-lex restriction
)))
4284 ;; 1. Text before any object. Untabify it.
4285 (let ((obj-beg (org-element-property :begin next-object
)))
4286 (unless (= (point) obj-beg
)
4288 (org-element-adopt-elements
4290 (replace-regexp-in-string
4291 "\t" (make-string tab-width ?
)
4292 (buffer-substring-no-properties (point) obj-beg
))))))
4294 (let ((obj-end (org-element-property :end next-object
))
4295 (cont-beg (org-element-property :contents-begin next-object
)))
4296 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4297 ;; a recursive type.
4299 (memq (car next-object
) org-element-recursive-objects
))
4300 (org-element--parse-objects
4301 cont-beg
(org-element-property :contents-end next-object
)
4302 next-object
(org-element-restriction next-object
)))
4303 (setq acc
(org-element-adopt-elements acc next-object
))
4304 (goto-char obj-end
))))
4305 ;; 3. Text after last object. Untabify it.
4308 (org-element-adopt-elements
4310 (replace-regexp-in-string
4311 "\t" (make-string tab-width ?
)
4312 (buffer-substring-no-properties (point) end
)))))
4318 ;;; Towards A Bijective Process
4320 ;; The parse tree obtained with `org-element-parse-buffer' is really
4321 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4322 ;; interpreted and expanded into a string with canonical Org syntax.
4323 ;; Hence `org-element-interpret-data'.
4325 ;; The function relies internally on
4326 ;; `org-element--interpret-affiliated-keywords'.
4329 (defun org-element-interpret-data (data &optional pseudo-objects
)
4330 "Interpret DATA as Org syntax.
4332 DATA is a parse tree, an element, an object or a secondary string
4335 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4336 new types that should be treated as objects. An unknown type not
4337 belonging to this list is seen as a pseudo-element instead. Both
4338 pseudo-objects and pseudo-elements are transparent entities, i.e.
4339 only their contents are interpreted.
4341 Return Org syntax as a string."
4342 (org-element--interpret-data-1 data nil pseudo-objects
))
4344 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4345 "Interpret DATA as Org syntax.
4347 DATA is a parse tree, an element, an object or a secondary string
4348 to interpret. PARENT is used for recursive calls. It contains
4349 the element or object containing data, or nil. PSEUDO-OBJECTS
4350 are list of symbols defining new element or object types.
4351 Unknown types that don't belong to this list are treated as
4352 pseudo-elements instead.
4354 Return Org syntax as a string."
4355 (let* ((type (org-element-type data
))
4356 ;; Find interpreter for current object or element. If it
4357 ;; doesn't exist (e.g. this is a pseudo object or element),
4358 ;; return contents, if any.
4360 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4361 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4364 ;; Secondary string.
4368 (org-element--interpret-data-1 obj parent pseudo-objects
))
4370 ;; Full Org document.
4371 ((eq type
'org-data
)
4374 (org-element--interpret-data-1 obj parent pseudo-objects
))
4375 (org-element-contents data
) ""))
4376 ;; Plain text: return it.
4377 ((stringp data
) data
)
4378 ;; Element or object without contents.
4379 ((not (org-element-contents data
)) (funcall interpret data nil
))
4380 ;; Element or object with contents.
4382 (funcall interpret data
4383 ;; Recursively interpret contents.
4386 (org-element--interpret-data-1 obj data pseudo-objects
))
4387 (org-element-contents
4388 (if (not (memq type
'(paragraph verse-block
)))
4390 ;; Fix indentation of elements containing
4391 ;; objects. We ignore `table-row' elements
4392 ;; as they are one line long anyway.
4393 (org-element-normalize-contents
4395 ;; When normalizing first paragraph of an
4396 ;; item or a footnote-definition, ignore
4397 ;; first line's indentation.
4398 (and (eq type
'paragraph
)
4399 (equal data
(car (org-element-contents parent
)))
4400 (memq (org-element-type parent
)
4401 '(footnote-definition item
))))))
4403 (if (memq type
'(org-data plain-text nil
)) results
4404 ;; Build white spaces. If no `:post-blank' property is
4405 ;; specified, assume its value is 0.
4406 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4407 (if (or (memq type org-element-all-objects
)
4408 (memq type pseudo-objects
))
4409 (concat results
(make-string post-blank ?\s
))
4411 (org-element--interpret-affiliated-keywords data
)
4412 (org-element-normalize-string results
)
4413 (make-string post-blank ?
\n)))))))
4415 (defun org-element--interpret-affiliated-keywords (element)
4416 "Return ELEMENT's affiliated keywords as Org syntax.
4417 If there is no affiliated keyword, return the empty string."
4418 (let ((keyword-to-org
4422 (when (member key org-element-dual-keywords
)
4423 (setq dual
(cdr value
) value
(car value
)))
4426 (format "[%s]" (org-element-interpret-data dual
)))
4428 (if (member key org-element-parsed-keywords
)
4429 (org-element-interpret-data value
)
4434 (let ((value (org-element-property prop element
))
4435 (keyword (upcase (substring (symbol-name prop
) 1))))
4437 (if (or (member keyword org-element-multiple-keywords
)
4438 ;; All attribute keywords can have multiple lines.
4439 (string-match "^ATTR_" keyword
))
4440 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4443 (funcall keyword-to-org keyword value
)))))
4444 ;; List all ELEMENT's properties matching an attribute line or an
4445 ;; affiliated keyword, but ignore translated keywords since they
4446 ;; cannot belong to the property list.
4447 (loop for prop in
(nth 1 element
) by
'cddr
4448 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4449 (or (string-match "^ATTR_" keyword
)
4451 (member keyword org-element-affiliated-keywords
)
4453 org-element-keyword-translation-alist
)))))
4457 ;; Because interpretation of the parse tree must return the same
4458 ;; number of blank lines between elements and the same number of white
4459 ;; space after objects, some special care must be given to white
4462 ;; The first function, `org-element-normalize-string', ensures any
4463 ;; string different from the empty string will end with a single
4464 ;; newline character.
4466 ;; The second function, `org-element-normalize-contents', removes
4467 ;; global indentation from the contents of the current element.
4469 (defun org-element-normalize-string (s)
4470 "Ensure string S ends with a single newline character.
4472 If S isn't a string return it unchanged. If S is the empty
4473 string, return it. Otherwise, return a new string with a single
4474 newline character at its end."
4476 ((not (stringp s
)) s
)
4478 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4479 (replace-match "\n" nil nil s
)))))
4481 (defun org-element-normalize-contents (element &optional ignore-first
)
4482 "Normalize plain text in ELEMENT's contents.
4484 ELEMENT must only contain plain text and objects.
4486 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4487 indentation to compute maximal common indentation.
4489 Return the normalized element that is element with global
4490 indentation removed from its contents. The function assumes that
4491 indentation is not done with TAB characters."
4492 (let* ((min-ind most-positive-fixnum
)
4493 find-min-ind
; For byte-compiler.
4496 ;; Return minimal common indentation within BLOB. This is
4497 ;; done by walking recursively BLOB and updating MIN-IND
4498 ;; along the way. FIRST-FLAG is non-nil when the first
4499 ;; string hasn't been seen yet. It is required as this
4500 ;; string is the only one whose indentation doesn't happen
4501 ;; after a newline character.
4502 (lambda (blob first-flag
)
4503 (dolist (object (org-element-contents blob
))
4504 (when (and first-flag
(stringp object
))
4505 (setq first-flag nil
)
4506 (string-match "\\`\\( *\\)" object
)
4507 (let ((len (length (match-string 1 object
))))
4508 ;; An indentation of zero means no string will be
4509 ;; modified. Quit the process.
4510 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4511 (setq min-ind
(min len min-ind
)))))
4514 (dolist (line (delq "" (cdr (org-split-string object
" *\n"))))
4515 (setq min-ind
(min (org-get-indentation line
) min-ind
))))
4516 ((memq (org-element-type object
) org-element-recursive-objects
)
4517 (funcall find-min-ind object first-flag
))))))))
4518 ;; Find minimal indentation in ELEMENT.
4519 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4520 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4521 ;; Build ELEMENT back, replacing each string with the same
4522 ;; string minus common indentation.
4523 (let* (build ; For byte compiler.
4526 (lambda (blob first-flag
)
4527 ;; Return BLOB with all its strings indentation
4528 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4529 ;; is non-nil when the first string hasn't been seen
4534 (when (and first-flag
(stringp object
))
4535 (setq first-flag nil
)
4537 (replace-regexp-in-string
4538 (format "\\` \\{%d\\}" min-ind
)
4542 (replace-regexp-in-string
4543 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4544 ((memq (org-element-type object
)
4545 org-element-recursive-objects
)
4546 (funcall build object first-flag
))
4548 (org-element-contents blob
)))
4550 (funcall build element
(not ignore-first
))))))
4556 ;; Implement a caching mechanism for `org-element-at-point' and
4557 ;; `org-element-context', which see.
4559 ;; A single public function is provided: `org-element-cache-reset'.
4561 ;; Cache is enabled by default, but can be disabled globally with
4562 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4563 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4564 ;; can be tweaked to control caching behaviour.
4566 ;; Internally, parsed elements are stored in an AVL tree,
4567 ;; `org-element--cache'. This tree is updated lazily: whenever
4568 ;; a change happens to the buffer, a synchronization request is
4569 ;; registered in `org-element--cache-sync-requests' (see
4570 ;; `org-element--cache-submit-request'). During idle time, requests
4571 ;; are processed by `org-element--cache-sync'. Synchronization also
4572 ;; happens when an element is required from the cache. In this case,
4573 ;; the process stops as soon as the needed element is up-to-date.
4575 ;; A synchronization request can only apply on a synchronized part of
4576 ;; the cache. Therefore, the cache is updated at least to the
4577 ;; location where the new request applies. Thus, requests are ordered
4578 ;; from left to right and all elements starting before the first
4579 ;; request are correct. This property is used by functions like
4580 ;; `org-element--cache-find' to retrieve elements in the part of the
4581 ;; cache that can be trusted.
4583 ;; A request applies to every element, starting from its original
4584 ;; location (or key, see below). When a request is processed, it
4585 ;; moves forward and may collide the next one. In this case, both
4586 ;; requests are merged into a new one that starts from that element.
4587 ;; As a consequence, the whole synchronization complexity does not
4588 ;; depend on the number of pending requests, but on the number of
4589 ;; elements the very first request will be applied on.
4591 ;; Elements cannot be accessed through their beginning position, which
4592 ;; may or may not be up-to-date. Instead, each element in the tree is
4593 ;; associated to a key, obtained with `org-element--cache-key'. This
4594 ;; mechanism is robust enough to preserve total order among elements
4595 ;; even when the tree is only partially synchronized.
4597 ;; Objects contained in an element are stored in a hash table,
4598 ;; `org-element--cache-objects'.
4601 (defvar org-element-use-cache t
4602 "Non nil when Org parser should cache its results.
4603 This is mostly for debugging purpose.")
4605 (defvar org-element-cache-sync-idle-time
0.6
4606 "Length, in seconds, of idle time before syncing cache.")
4608 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4609 "Maximum duration, as a time value, for a cache synchronization.
4610 If the synchronization is not over after this delay, the process
4611 pauses and resumes after `org-element-cache-sync-break'
4614 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4615 "Duration, as a time value, of the pause between synchronizations.
4616 See `org-element-cache-sync-duration' for more information.")
4621 (defvar org-element--cache nil
4622 "AVL tree used to cache elements.
4623 Each node of the tree contains an element. Comparison is done
4624 with `org-element--cache-compare'. This cache is used in
4625 `org-element-at-point'.")
4627 (defvar org-element--cache-objects nil
4628 "Hash table used as to cache objects.
4629 Key is an element, as returned by `org-element-at-point', and
4630 value is an alist where each association is:
4632 \(PARENT COMPLETEP . OBJECTS)
4634 where PARENT is an element or object, COMPLETEP is a boolean,
4635 non-nil when all direct children of parent are already cached and
4636 OBJECTS is a list of such children, as objects, from farthest to
4639 In the following example, \\alpha, bold object and \\beta are
4640 contained within a paragraph
4644 If the paragraph is completely parsed, OBJECTS-DATA will be
4646 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4647 \(BOLD-OBJECT t ENTITY-OBJECT))
4649 whereas in a partially parsed paragraph, it could be
4651 \((PARAGRAPH nil ENTITY-OBJECT))
4653 This cache is used in `org-element-context'.")
4655 (defvar org-element--cache-sync-requests nil
4656 "List of pending synchronization requests.
4658 A request is a vector with the following pattern:
4660 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4662 Processing a synchronization request consists of three phases:
4664 0. Delete modified elements,
4665 1. Fill missing area in cache,
4666 2. Shift positions and re-parent elements after the changes.
4668 During phase 0, NEXT is the key of the first element to be
4669 removed, BEG and END is buffer position delimiting the
4670 modifications. Elements starting between them (inclusive) are
4671 removed and so are those contained within OUTREACH. PARENT, when
4672 non-nil, is the parent of the first element to be removed.
4674 During phase 1, NEXT is the key of the next known element in
4675 cache and BEG its beginning position. Parse buffer between that
4676 element and the one before it in order to determine the parent of
4677 the next element. Set PARENT to the element containing NEXT.
4679 During phase 2, NEXT is the key of the next element to shift in
4680 the parse tree. All elements starting from this one have their
4681 properties relatives to buffer positions shifted by integer
4682 OFFSET and, if they belong to element PARENT, are adopted by it.
4684 PHASE specifies the phase number, as an integer.")
4686 (defvar org-element--cache-sync-timer nil
4687 "Timer used for cache synchronization.")
4689 (defvar org-element--cache-sync-keys nil
4690 "Hash table used to store keys during synchronization.
4691 See `org-element--cache-key' for more information.")
4693 (defsubst org-element--cache-key
(element)
4694 "Return a unique key for ELEMENT in cache tree.
4696 Keys are used to keep a total order among elements in the cache.
4697 Comparison is done with `org-element--cache-key-less-p'.
4699 When no synchronization is taking place, a key is simply the
4700 beginning position of the element, or that position plus one in
4701 the case of an first item (respectively row) in
4702 a list (respectively a table).
4704 During a synchronization, the key is the one the element had when
4705 the cache was synchronized for the last time. Elements added to
4706 cache during the synchronization get a new key generated with
4707 `org-element--cache-generate-key'.
4709 Such keys are stored in `org-element--cache-sync-keys'. The hash
4710 table is cleared once the synchronization is complete."
4711 (or (gethash element org-element--cache-sync-keys
)
4712 (let* ((begin (org-element-property :begin element
))
4713 ;; Increase beginning position of items (respectively
4714 ;; table rows) by one, so the first item can get
4715 ;; a different key from its parent list (respectively
4717 (key (if (memq (org-element-type element
) '(item table-row
))
4720 (if org-element--cache-sync-requests
4721 (puthash element key org-element--cache-sync-keys
)
4724 (defun org-element--cache-generate-key (lower upper
)
4725 "Generate a key between LOWER and UPPER.
4727 LOWER and UPPER are integers or lists, possibly empty.
4729 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4730 a unique key, as an integer or a list of integers, according to
4731 the following rules:
4733 - LOWER and UPPER are compared level-wise until values differ.
4735 - If, at a given level, LOWER and UPPER differ from more than
4736 2, the new key shares all the levels above with LOWER and
4737 gets a new level. Its value is the mean between LOWER and
4740 \(1 2) + (1 4) --> (1 3)
4742 - If LOWER has no value to compare with, it is assumed that its
4743 value is `most-negative-fixnum'. E.g.,
4751 where m is `most-negative-fixnum'. Likewise, if UPPER is
4752 short of levels, the current value is `most-positive-fixnum'.
4754 - If they differ from only one, the new key inherits from
4755 current LOWER level and fork it at the next level. E.g.,
4763 where M is `most-positive-fixnum'.
4765 - If the key is only one level long, it is returned as an
4768 \(1 2) + (3 2) --> 2
4770 When they are not equals, the function assumes that LOWER is
4771 lesser than UPPER, per `org-element--cache-key-less-p'."
4772 (if (equal lower upper
) lower
4773 (let ((lower (if (integerp lower
) (list lower
) lower
))
4774 (upper (if (integerp upper
) (list upper
) upper
))
4778 (let ((min (or (car lower
) most-negative-fixnum
))
4779 (max (cond (skip-upper most-positive-fixnum
)
4781 (t most-positive-fixnum
))))
4782 (if (< (1+ min
) max
)
4783 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4784 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4785 (when (and (< min max
) (not skip-upper
))
4786 ;; When at a given level, LOWER and UPPER differ from
4787 ;; 1, ignore UPPER altogether. Instead create a key
4788 ;; between LOWER and the greatest key with the same
4789 ;; prefix as LOWER so far.
4790 (setq skip-upper t
))
4792 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
4794 (defsubst org-element--cache-key-less-p
(a b
)
4795 "Non-nil if key A is less than key B.
4796 A and B are either integers or lists of integers, as returned by
4797 `org-element--cache-key'."
4798 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4799 (if (integerp b
) (< (car a
) b
)
4802 (cond ((car-less-than-car a b
) (throw 'exit t
))
4803 ((car-less-than-car b a
) (throw 'exit nil
))
4804 (t (setq a
(cdr a
) b
(cdr b
)))))
4805 ;; If A is empty, either keys are equal (B is also empty) and
4806 ;; we return nil, or A is lesser than B (B is longer) and we
4807 ;; return a non-nil value.
4809 ;; If A is not empty, B is necessarily empty and A is greater
4810 ;; than B (A is longer). Therefore, return nil.
4811 (and (null a
) b
)))))
4813 (defun org-element--cache-compare (a b
)
4814 "Non-nil when element A is located before element B."
4815 (org-element--cache-key-less-p (org-element--cache-key a
)
4816 (org-element--cache-key b
)))
4818 (defsubst org-element--cache-root
()
4819 "Return root value in cache.
4820 This function assumes `org-element--cache' is a valid AVL tree."
4821 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4826 (defsubst org-element--cache-active-p
()
4827 "Non-nil when cache is active in current buffer."
4828 (and org-element-use-cache
4829 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4831 (defun org-element--cache-find (pos &optional side
)
4832 "Find element in cache starting at POS or before.
4834 POS refers to a buffer position.
4836 When optional argument SIDE is non-nil, the function checks for
4837 elements starting at or past POS instead. If SIDE is `both', the
4838 function returns a cons cell where car is the first element
4839 starting at or before POS and cdr the first element starting
4842 The function can only find elements in the synchronized part of
4844 (let ((limit (and org-element--cache-sync-requests
4845 (aref (car org-element--cache-sync-requests
) 0)))
4846 (node (org-element--cache-root))
4849 (let* ((element (avl-tree--node-data node
))
4850 (begin (org-element-property :begin element
)))
4853 (not (org-element--cache-key-less-p
4854 (org-element--cache-key element
) limit
)))
4855 (setq node
(avl-tree--node-left node
)))
4858 node
(avl-tree--node-left node
)))
4861 node
(avl-tree--node-right node
)))
4862 ;; We found an element in cache starting at POS. If `side'
4863 ;; is `both' we also want the next one in order to generate
4864 ;; a key in-between.
4866 ;; If the element is the first row or item in a table or
4867 ;; a plain list, we always return the table or the plain
4870 ;; In any other case, we return the element found.
4872 (setq lower element
)
4873 (setq node
(avl-tree--node-right node
)))
4874 ((and (memq (org-element-type element
) '(item table-row
))
4875 (let ((parent (org-element-property :parent element
)))
4876 (and (= (org-element-property :begin element
)
4877 (org-element-property :contents-begin parent
))
4886 (both (cons lower upper
))
4888 (otherwise upper
))))
4890 (defun org-element--cache-put (element &optional data
)
4891 "Store ELEMENT in current buffer's cache, if allowed.
4892 When optional argument DATA is non-nil, assume is it object data
4893 relative to ELEMENT and store it in the objects cache."
4894 (cond ((not (org-element--cache-active-p)) nil
)
4896 (when org-element--cache-sync-requests
4897 ;; During synchronization, first build an appropriate key
4898 ;; for the new element so `avl-tree-enter' can insert it at
4899 ;; the right spot in the cache.
4900 (let ((keys (org-element--cache-find
4901 (org-element-property :begin element
) 'both
)))
4903 (org-element--cache-generate-key
4904 (and (car keys
) (org-element--cache-key (car keys
)))
4905 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4906 (org-element--cache-sync-requests
4907 (aref (car org-element--cache-sync-requests
) 0))))
4908 org-element--cache-sync-keys
)))
4909 (avl-tree-enter org-element--cache element
))
4910 ;; Headlines are not stored in cache, so objects in titles are
4911 ;; not stored either.
4912 ((eq (org-element-type element
) 'headline
) nil
)
4913 (t (puthash element data org-element--cache-objects
))))
4915 (defsubst org-element--cache-remove
(element)
4916 "Remove ELEMENT from cache.
4917 Assume ELEMENT belongs to cache and that a cache is active."
4918 (avl-tree-delete org-element--cache element
)
4919 (remhash element org-element--cache-objects
))
4922 ;;;; Synchronization
4924 (defsubst org-element--cache-set-timer
(buffer)
4925 "Set idle timer for cache synchronization in BUFFER."
4926 (when org-element--cache-sync-timer
4927 (cancel-timer org-element--cache-sync-timer
))
4928 (setq org-element--cache-sync-timer
4929 (run-with-idle-timer
4930 (let ((idle (current-idle-time)))
4931 (if idle
(time-add idle org-element-cache-sync-break
)
4932 org-element-cache-sync-idle-time
))
4934 #'org-element--cache-sync
4937 (defsubst org-element--cache-interrupt-p
(time-limit)
4938 "Non-nil when synchronization process should be interrupted.
4939 TIME-LIMIT is a time value or nil."
4941 (or (input-pending-p)
4942 (time-less-p time-limit
(current-time)))))
4944 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
4945 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4947 Properties containing buffer positions are `:begin', `:end',
4948 `:contents-begin', `:contents-end' and `:structure'. When
4949 optional argument PROPS is a list of keywords, only shift
4950 properties provided in that list.
4952 Properties are modified by side-effect."
4953 (let ((properties (nth 1 element
)))
4954 ;; Shift `:structure' property for the first plain list only: it
4955 ;; is the only one that really matters and it prevents from
4956 ;; shifting it more than once.
4957 (when (and (or (not props
) (memq :structure props
))
4958 (eq (org-element-type element
) 'plain-list
)
4959 (not (eq (org-element-type (plist-get properties
:parent
))
4961 (dolist (item (plist-get properties
:structure
))
4962 (incf (car item
) offset
)
4963 (incf (nth 6 item
) offset
)))
4964 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
4965 (let ((value (and (or (not props
) (memq key props
))
4966 (plist-get properties key
))))
4967 (and value
(plist-put properties key
(+ offset value
)))))))
4969 (defun org-element--cache-sync (buffer &optional threshold future-change
)
4970 "Synchronize cache with recent modification in BUFFER.
4972 When optional argument THRESHOLD is non-nil, do the
4973 synchronization for all elements starting before or at threshold,
4974 then exit. Otherwise, synchronize cache for as long as
4975 `org-element-cache-sync-duration' or until Emacs leaves idle
4978 FUTURE-CHANGE, when non-nil, is a buffer position where changes
4979 not registered yet in the cache are going to happen. It is used
4980 in `org-element--cache-submit-request', where cache is partially
4981 updated before current modification are actually submitted."
4982 (when (buffer-live-p buffer
)
4983 (with-current-buffer buffer
4984 (let ((inhibit-quit t
) request next
)
4985 (when org-element--cache-sync-timer
4986 (cancel-timer org-element--cache-sync-timer
))
4988 (while org-element--cache-sync-requests
4989 (setq request
(car org-element--cache-sync-requests
)
4990 next
(nth 1 org-element--cache-sync-requests
))
4991 (org-element--cache-process-request
4993 (and next
(aref next
0))
4995 (and (not threshold
)
4996 (time-add (current-time)
4997 org-element-cache-sync-duration
))
4999 ;; Request processed. Merge current and next offsets and
5000 ;; transfer ending position.
5002 (incf (aref next
3) (aref request
3))
5003 (aset next
2 (aref request
2)))
5004 (setq org-element--cache-sync-requests
5005 (cdr org-element--cache-sync-requests
))))
5006 ;; If more requests are awaiting, set idle timer accordingly.
5007 ;; Otherwise, reset keys.
5008 (if org-element--cache-sync-requests
5009 (org-element--cache-set-timer buffer
)
5010 (clrhash org-element--cache-sync-keys
))))))
5012 (defun org-element--cache-process-request
5013 (request next threshold time-limit future-change
)
5014 "Process synchronization REQUEST for all entries before NEXT.
5016 REQUEST is a vector, built by `org-element--cache-submit-request'.
5018 NEXT is a cache key, as returned by `org-element--cache-key'.
5020 When non-nil, THRESHOLD is a buffer position. Synchronization
5021 stops as soon as a shifted element begins after it.
5023 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5024 after this time or when Emacs exits idle state.
5026 When non-nil, FUTURE-CHANGE is a buffer position where changes
5027 not registered yet in the cache are going to happen. See
5028 `org-element--cache-submit-request' for more information.
5030 Throw `interrupt' if the process stops before completing the
5033 (when (= (aref request
6) 0)
5036 ;; Delete all elements starting after BEG, but not after buffer
5037 ;; position END or past element with key NEXT.
5039 ;; At each iteration, we start again at tree root since
5040 ;; a deletion modifies structure of the balanced tree.
5042 (let ((beg (aref request
0))
5043 (end (aref request
2))
5044 (outreach (aref request
4)))
5046 (when (org-element--cache-interrupt-p time-limit
)
5047 (throw 'interrupt nil
))
5048 ;; Find first element in cache with key BEG or after it.
5049 (let ((node (org-element--cache-root)) data data-key
)
5051 (let* ((element (avl-tree--node-data node
))
5052 (key (org-element--cache-key element
)))
5054 ((org-element--cache-key-less-p key beg
)
5055 (setq node
(avl-tree--node-right node
)))
5056 ((org-element--cache-key-less-p beg key
)
5059 node
(avl-tree--node-left node
)))
5060 (t (setq data element
5064 (let ((pos (org-element-property :begin data
)))
5065 (if (if (or (not next
)
5066 (org-element--cache-key-less-p data-key next
))
5069 (while (and up
(not (eq up outreach
)))
5070 (setq up
(org-element-property :parent up
)))
5072 (org-element--cache-remove data
)
5073 (aset request
0 data-key
)
5074 (aset request
1 pos
)
5076 (throw 'end-phase nil
)))
5077 ;; No element starting after modifications left in
5078 ;; cache: further processing is futile.
5079 (throw 'quit t
)))))))
5080 (when (= (aref request
6) 1)
5083 ;; Phase 0 left a hole in the cache. Some elements after it
5084 ;; could have parents within. For example, in the following
5094 ;; if we remove a blank line between "item" and "Paragraph1",
5095 ;; everything down to "Paragraph2" is removed from cache. But
5096 ;; the paragraph now belongs to the list, and its `:parent'
5097 ;; property no longer is accurate.
5099 ;; Therefore we need to parse again elements in the hole, or at
5100 ;; least in its last section, so that we can re-parent
5101 ;; subsequent elements, during phase 2.
5103 ;; Note that we only need to get the parent from the first
5104 ;; element in cache after the hole.
5106 ;; When next key is lesser or equal to the current one, delegate
5107 ;; phase 1 processing to next request in order to preserve key
5108 ;; order among requests.
5109 (let ((key (aref request
0)))
5110 (when (and next
(not (org-element--cache-key-less-p key next
)))
5111 (let ((next-request (nth 1 org-element--cache-sync-requests
)))
5112 (aset next-request
0 key
)
5113 (aset next-request
1 (aref request
1))
5114 (aset next-request
6 1))
5116 ;; Next element will start at its beginning position plus
5117 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5118 ;; contains the real beginning position of the first element to
5119 ;; shift and re-parent.
5120 (let ((limit (+ (aref request
1) (aref request
3))))
5121 (cond ((and threshold
(> limit threshold
)) (throw 'interrupt nil
))
5122 ((and future-change
(>= limit future-change
))
5123 ;; Changes are going to happen around this element and
5124 ;; they will trigger another phase 1 request. Skip the
5128 (let ((parent (org-element--parse-to limit t time-limit
)))
5129 (aset request
5 parent
)
5130 (aset request
6 2))))))
5133 ;; Shift all elements starting from key START, but before NEXT, by
5134 ;; OFFSET, and re-parent them when appropriate.
5136 ;; Elements are modified by side-effect so the tree structure
5139 ;; Once THRESHOLD, if any, is reached, or once there is an input
5140 ;; pending, exit. Before leaving, the current synchronization
5141 ;; request is updated.
5142 (let ((start (aref request
0))
5143 (offset (aref request
3))
5144 (parent (aref request
5))
5145 (node (org-element--cache-root))
5149 ;; No re-parenting nor shifting planned: request is over.
5150 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5152 (let* ((data (avl-tree--node-data node
))
5153 (key (org-element--cache-key data
)))
5154 (if (and leftp
(avl-tree--node-left node
)
5155 (not (org-element--cache-key-less-p key start
)))
5156 (progn (push node stack
)
5157 (setq node
(avl-tree--node-left node
)))
5158 (unless (org-element--cache-key-less-p key start
)
5159 ;; We reached NEXT. Request is complete.
5160 (when (equal key next
) (throw 'quit t
))
5161 ;; Handle interruption request. Update current request.
5162 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5163 (aset request
0 key
)
5164 (aset request
5 parent
)
5165 (throw 'interrupt nil
))
5167 (unless (zerop offset
)
5168 (org-element--cache-shift-positions data offset
)
5169 ;; Shift associated objects data, if any.
5170 (dolist (object-data (gethash data org-element--cache-objects
))
5171 (dolist (object (cddr object-data
))
5172 (org-element--cache-shift-positions object offset
))))
5173 (let ((begin (org-element-property :begin data
)))
5174 ;; Update PARENT and re-parent DATA, only when
5175 ;; necessary. Propagate new structures for lists.
5177 (<= (org-element-property :end parent
) begin
))
5178 (setq parent
(org-element-property :parent parent
)))
5179 (cond ((and (not parent
) (zerop offset
)) (throw 'quit nil
))
5181 (let ((p (org-element-property :parent data
)))
5183 (< (org-element-property :begin p
)
5184 (org-element-property :begin parent
)))))
5185 (org-element-put-property data
:parent parent
)
5186 (let ((s (org-element-property :structure parent
)))
5187 (when (and s
(org-element-property :structure data
))
5188 (org-element-put-property data
:structure s
)))))
5189 ;; Cache is up-to-date past THRESHOLD. Request
5191 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5192 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5193 (avl-tree--node-right node
)
5195 ;; We reached end of tree: synchronization complete.
5198 (defun org-element--parse-to (pos &optional syncp time-limit
)
5199 "Parse elements in current section, down to POS.
5201 Start parsing from the closest between the last known element in
5202 cache or headline above. Return the smallest element containing
5205 When optional argument SYNCP is non-nil, return the parent of the
5206 element containing POS instead. In that case, it is also
5207 possible to provide TIME-LIMIT, which is a time value specifying
5208 when the parsing should stop. The function throws `interrupt' if
5209 the process stopped before finding the expected result."
5211 (org-with-wide-buffer
5213 (let* ((cached (and (org-element--cache-active-p)
5214 (org-element--cache-find pos nil
)))
5215 (begin (org-element-property :begin cached
))
5218 ;; Nothing in cache before point: start parsing from first
5219 ;; element following headline above, or first element in
5222 (when (org-with-limited-levels (outline-previous-heading))
5224 (skip-chars-forward " \r\t\n")
5225 (beginning-of-line))
5226 ;; Cache returned exact match: return it.
5228 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5229 ;; There's a headline between cached value and POS: cached
5230 ;; value is invalid. Start parsing from first element
5231 ;; following the headline.
5232 ((re-search-backward
5233 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5235 (skip-chars-forward " \r\t\n")
5236 (beginning-of-line))
5237 ;; Check if CACHED or any of its ancestors contain point.
5239 ;; If there is such an element, we inspect it in order to know
5240 ;; if we return it or if we need to parse its contents.
5241 ;; Otherwise, we just start parsing from current location,
5242 ;; which is right after the top-most element containing
5245 ;; As a special case, if POS is at the end of the buffer, we
5246 ;; want to return the innermost element ending there.
5248 ;; Also, if we find an ancestor and discover that we need to
5249 ;; parse its contents, make sure we don't start from
5250 ;; `:contents-begin', as we would otherwise go past CACHED
5251 ;; again. Instead, in that situation, we will resume parsing
5252 ;; from NEXT, which is located after CACHED or its higher
5253 ;; ancestor not containing point.
5256 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5257 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5258 (while (let ((end (org-element-property :end up
)))
5261 (setq up
(org-element-property :parent up
)))))
5263 ((eobp) (setq element up
))
5264 (t (setq element up next
(point)))))))
5265 ;; Parse successively each element until we reach POS.
5266 (let ((end (or (org-element-property :end element
)
5268 (org-with-limited-levels (outline-next-heading))
5274 (cond ((= (point) pos
) (throw 'exit parent
))
5275 ((org-element--cache-interrupt-p time-limit
)
5276 (throw 'interrupt nil
))))
5278 (setq element
(org-element--current-element
5279 end
'element special-flag
5280 (org-element-property :structure parent
)))
5281 (org-element-put-property element
:parent parent
)
5282 (org-element--cache-put element
))
5283 (let ((elem-end (org-element-property :end element
))
5284 (type (org-element-type element
)))
5286 ;; Skip any element ending before point. Also skip
5287 ;; element ending at point (unless it is also the end of
5288 ;; buffer) since we're sure that another element begins
5290 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5291 (goto-char elem-end
))
5292 ;; A non-greater element contains point: return it.
5293 ((not (memq type org-element-greater-elements
))
5294 (throw 'exit element
))
5295 ;; Otherwise, we have to decide if ELEMENT really
5296 ;; contains POS. In that case we start parsing from
5297 ;; contents' beginning.
5299 ;; If POS is at contents' beginning but it is also at
5300 ;; the beginning of the first item in a list or a table.
5301 ;; In that case, we need to create an anchor for that
5302 ;; list or table, so return it.
5304 ;; Also, if POS is at the end of the buffer, no element
5305 ;; can start after it, but more than one may end there.
5306 ;; Arbitrarily, we choose to return the innermost of
5308 ((let ((cbeg (org-element-property :contents-begin element
))
5309 (cend (org-element-property :contents-end element
)))
5314 (not (memq type
'(plain-list table
)))))
5316 (and (= cend pos
) (= (point-max) pos
)))))
5317 (goto-char (or next cbeg
))
5319 special-flag
(case type
5321 (property-drawer 'node-property
)
5325 ;; Otherwise, return ELEMENT as it is the smallest
5326 ;; element containing POS.
5327 (t (throw 'exit element
))))
5328 (setq element nil
)))))))
5331 ;;;; Staging Buffer Changes
5333 (defconst org-element--cache-sensitive-re
5335 org-outline-regexp-bol
"\\|"
5338 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5339 ;; LaTeX environments.
5340 "\\\\\\(?:begin{[A-Za-z0-9*]+}\\|end{[A-Za-z0-9*]+}[ \t]*$\\)" "\\|"
5342 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5344 "Regexp matching a sensitive line, structure wise.
5345 A sensitive line is a headline, inlinetask, block, drawer, or
5346 latex-environment boundary. When such a line is modified,
5347 structure changes in the document may propagate in the whole
5348 section, possibly making cache invalid.")
5350 (defvar org-element--cache-change-warning nil
5351 "Non-nil when a sensitive line is about to be changed.
5352 It is a symbol among nil, t and `headline'.")
5354 (defun org-element--cache-before-change (beg end
)
5355 "Request extension of area going to be modified if needed.
5356 BEG and END are the beginning and end of the range of changed
5357 text. See `before-change-functions' for more information."
5358 (when (org-element--cache-active-p)
5359 (org-with-wide-buffer
5362 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5363 (setq org-element--cache-change-warning
5365 (if (and (org-with-limited-levels (org-at-heading-p))
5366 (= (line-end-position) bottom
))
5368 (let ((case-fold-search t
))
5370 org-element--cache-sensitive-re bottom t
)))))))))
5372 (defun org-element--cache-after-change (beg end pre
)
5373 "Update buffer modifications for current buffer.
5374 BEG and END are the beginning and end of the range of changed
5375 text, and the length in bytes of the pre-change text replaced by
5376 that range. See `after-change-functions' for more information."
5377 (when (org-element--cache-active-p)
5378 (org-with-wide-buffer
5383 (bottom (save-excursion (goto-char end
) (line-end-position))))
5384 ;; Determine if modified area needs to be extended, according
5385 ;; to both previous and current state. We make a special
5386 ;; case for headline editing: if a headline is modified but
5387 ;; not removed, do not extend.
5388 (when (case org-element--cache-change-warning
5391 (not (and (org-with-limited-levels (org-at-heading-p))
5392 (= (line-end-position) bottom
))))
5394 (let ((case-fold-search t
))
5396 org-element--cache-sensitive-re bottom t
))))
5397 ;; Effectively extend modified area.
5398 (org-with-limited-levels
5399 (setq top
(progn (goto-char top
)
5400 (when (outline-previous-heading) (forward-line))
5402 (setq bottom
(progn (goto-char bottom
)
5403 (if (outline-next-heading) (1- (point))
5405 ;; Store synchronization request.
5406 (let ((offset (- end beg pre
)))
5407 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5408 ;; Activate a timer to process the request during idle time.
5409 (org-element--cache-set-timer (current-buffer))))
5411 (defun org-element--cache-for-removal (beg end offset
)
5412 "Return first element to remove from cache.
5414 BEG and END are buffer positions delimiting buffer modifications.
5415 OFFSET is the size of the changes.
5417 Returned element is usually the first element in cache containing
5418 any position between BEG and END. As an exception, greater
5419 elements around the changes that are robust to contents
5420 modifications are preserved and updated according to the
5422 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5423 (before (car elements
))
5424 (after (cdr elements
)))
5425 (if (not before
) after
5429 (if (and (memq (org-element-type up
)
5430 '(center-block drawer dynamic-block
5431 property-drawer quote-block
5433 (<= (org-element-property :contents-begin up
) beg
)
5434 (> (org-element-property :contents-end up
) end
))
5435 ;; UP is a robust greater element containing changes.
5436 ;; We only need to extend its ending boundaries.
5437 (org-element--cache-shift-positions
5438 up offset
'(:contents-end
:end
))
5440 (when robust-flag
(setq robust-flag nil
)))
5441 (setq up
(org-element-property :parent up
)))
5442 ;; We're at top level element containing ELEMENT: if it's
5443 ;; altered by buffer modifications, it is first element in
5444 ;; cache to be removed. Otherwise, that first element is the
5447 ;; As a special case, do not remove BEFORE if it is a robust
5448 ;; container for current changes.
5449 (if (or (< (org-element-property :end before
) beg
) robust-flag
) after
5452 (defun org-element--cache-submit-request (beg end offset
)
5453 "Submit a new cache synchronization request for current buffer.
5454 BEG and END are buffer positions delimiting the minimal area
5455 where cache data should be removed. OFFSET is the size of the
5456 change, as an integer."
5457 (let ((next (car org-element--cache-sync-requests
))
5458 delete-to delete-from
)
5460 (zerop (aref next
6))
5461 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5462 (<= (setq delete-from
(aref next
1)) end
))
5463 ;; Current changes can be merged with first sync request: we
5464 ;; can save a partial cache synchronization.
5466 (incf (aref next
3) offset
)
5467 ;; If last change happened within area to be removed, extend
5468 ;; boundaries of robust parents, if any. Otherwise, find
5469 ;; first element to remove and update request accordingly.
5470 (if (> beg delete-from
)
5471 (let ((up (aref next
5)))
5473 (org-element--cache-shift-positions
5474 up offset
'(:contents-end
:end
))
5475 (setq up
(org-element-property :parent up
))))
5476 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5478 (aset next
0 (org-element--cache-key first
))
5479 (aset next
1 (org-element-property :begin first
))
5480 (aset next
5 (org-element-property :parent first
))))))
5481 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5482 ;; if any, is no longer a 0-phase request, thus ensuring that
5483 ;; phases are properly ordered. We need to provide OFFSET as
5484 ;; optional parameter since current modifications are not known
5485 ;; yet to the otherwise correct part of the cache (i.e, before
5486 ;; the first request).
5487 (when next
(org-element--cache-sync (current-buffer) end beg
))
5488 (let ((first (org-element--cache-for-removal beg end offset
)))
5490 (push (let ((beg (org-element-property :begin first
))
5491 (key (org-element--cache-key first
)))
5493 ;; When changes happen before the first known
5494 ;; element, re-parent and shift the rest of the
5496 ((> beg end
) (vector key beg nil offset nil nil
1))
5497 ;; Otherwise, we find the first non robust
5498 ;; element containing END. All elements between
5499 ;; FIRST and this one are to be removed.
5501 ;; Among them, some could be located outside the
5502 ;; synchronized part of the cache, in which case
5503 ;; comparing buffer positions to find them is
5504 ;; useless. Instead, we store the element
5505 ;; containing them in the request itself. All
5506 ;; its children will be removed.
5507 ((let ((first-end (org-element-property :end first
)))
5508 (and (> first-end end
)
5509 (vector key beg first-end offset first
5510 (org-element-property :parent first
) 0))))
5512 (let* ((element (org-element--cache-find end
))
5513 (end (org-element-property :end element
))
5515 (while (and (setq up
(org-element-property :parent up
))
5516 (>= (org-element-property :begin up
) beg
))
5517 (setq end
(org-element-property :end up
)
5519 (vector key beg end offset element
5520 (org-element-property :parent first
) 0)))))
5521 org-element--cache-sync-requests
)
5522 ;; No element to remove. No need to re-parent either.
5523 ;; Simply shift additional elements, if any, by OFFSET.
5524 (when org-element--cache-sync-requests
5525 (incf (aref (car org-element--cache-sync-requests
) 3) offset
)))))))
5528 ;;;; Public Functions
5531 (defun org-element-cache-reset (&optional all
)
5532 "Reset cache in current buffer.
5533 When optional argument ALL is non-nil, reset cache in all Org
5536 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5537 (with-current-buffer buffer
5538 (when (org-element--cache-active-p)
5539 (org-set-local 'org-element--cache
5540 (avl-tree-create #'org-element--cache-compare
))
5541 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5542 (org-set-local 'org-element--cache-sync-keys
5543 (make-hash-table :weakness
'key
:test
#'eq
))
5544 (org-set-local 'org-element--cache-change-warning nil
)
5545 (org-set-local 'org-element--cache-sync-requests nil
)
5546 (org-set-local 'org-element--cache-sync-timer nil
)
5547 (add-hook 'before-change-functions
5548 #'org-element--cache-before-change nil t
)
5549 (add-hook 'after-change-functions
5550 #'org-element--cache-after-change nil t
)))))
5553 (defun org-element-cache-refresh (pos)
5554 "Refresh cache at position POS."
5555 (when (org-element--cache-active-p)
5556 (org-element--cache-sync (current-buffer) pos
)
5557 (org-element--cache-submit-request pos pos
0)
5558 (org-element--cache-set-timer (current-buffer))))
5564 ;; The first move is to implement a way to obtain the smallest element
5565 ;; containing point. This is the job of `org-element-at-point'. It
5566 ;; basically jumps back to the beginning of section containing point
5567 ;; and proceed, one element after the other, with
5568 ;; `org-element--current-element' until the container is found. Note:
5569 ;; When using `org-element-at-point', secondary values are never
5570 ;; parsed since the function focuses on elements, not on objects.
5572 ;; At a deeper level, `org-element-context' lists all elements and
5573 ;; objects containing point.
5575 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5576 ;; internally by navigation and manipulation tools.
5580 (defun org-element-at-point ()
5581 "Determine closest element around point.
5583 Return value is a list like (TYPE PROPS) where TYPE is the type
5584 of the element and PROPS a plist of properties associated to the
5587 Possible types are defined in `org-element-all-elements'.
5588 Properties depend on element or object type, but always include
5589 `:begin', `:end', `:parent' and `:post-blank' properties.
5591 As a special case, if point is at the very beginning of the first
5592 item in a list or sub-list, returned element will be that list
5593 instead of the item. Likewise, if point is at the beginning of
5594 the first row of a table, returned element will be the table
5595 instead of the first row.
5597 When point is at the end of the buffer, return the innermost
5598 element ending there."
5599 (org-with-wide-buffer
5600 (let ((origin (point)))
5602 (skip-chars-backward " \r\t\n")
5604 ;; Within blank lines at the beginning of buffer, return nil.
5606 ;; Within blank lines right after a headline, return that
5608 ((org-with-limited-levels (org-at-heading-p))
5610 (org-element-headline-parser (point-max) t
))
5611 ;; Otherwise parse until we find element containing ORIGIN.
5613 (when (org-element--cache-active-p)
5614 (if (not org-element--cache
) (org-element-cache-reset)
5615 (org-element--cache-sync (current-buffer) origin
)))
5616 (org-element--parse-to origin
))))))
5619 (defun org-element-context (&optional element
)
5620 "Return smallest element or object around point.
5622 Return value is a list like (TYPE PROPS) where TYPE is the type
5623 of the element or object and PROPS a plist of properties
5626 Possible types are defined in `org-element-all-elements' and
5627 `org-element-all-objects'. Properties depend on element or
5628 object type, but always include `:begin', `:end', `:parent' and
5631 As a special case, if point is right after an object and not at
5632 the beginning of any other object, return that object.
5634 Optional argument ELEMENT, when non-nil, is the closest element
5635 containing point, as returned by `org-element-at-point'.
5636 Providing it allows for quicker computation."
5637 (catch 'objects-forbidden
5638 (org-with-wide-buffer
5639 (let* ((pos (point))
5640 (element (or element
(org-element-at-point)))
5641 (type (org-element-type element
)))
5642 ;; If point is inside an element containing objects or
5643 ;; a secondary string, narrow buffer to the container and
5644 ;; proceed with parsing. Otherwise, return ELEMENT.
5646 ;; At a parsed affiliated keyword, check if we're inside main
5648 ((let ((post (org-element-property :post-affiliated element
)))
5649 (and post
(< pos post
)))
5651 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5653 ((not (member-ignore-case (match-string 1)
5654 org-element-parsed-keywords
))
5655 (throw 'objects-forbidden element
))
5656 ((< (match-end 0) pos
)
5657 (narrow-to-region (match-end 0) (line-end-position)))
5658 ((and (match-beginning 2)
5659 (>= pos
(match-beginning 2))
5660 (< pos
(match-end 2)))
5661 (narrow-to-region (match-beginning 2) (match-end 2)))
5662 (t (throw 'objects-forbidden element
)))
5663 ;; Also change type to retrieve correct restrictions.
5664 (setq type
'keyword
))
5665 ;; At an item, objects can only be located within tag, if any.
5667 (let ((tag (org-element-property :tag element
)))
5668 (if (not tag
) (throw 'objects-forbidden element
)
5670 (search-forward tag
(line-end-position))
5671 (goto-char (match-beginning 0))
5672 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5673 (narrow-to-region (point) (match-end 0))
5674 (throw 'objects-forbidden element
)))))
5675 ;; At an headline or inlinetask, objects are in title.
5676 ((memq type
'(headline inlinetask
))
5677 (goto-char (org-element-property :begin element
))
5678 (skip-chars-forward "*")
5679 (if (and (> pos
(point)) (< pos
(line-end-position)))
5680 (narrow-to-region (point) (line-end-position))
5681 (throw 'objects-forbidden element
)))
5682 ;; At a paragraph, a table-row or a verse block, objects are
5683 ;; located within their contents.
5684 ((memq type
'(paragraph table-row verse-block
))
5685 (let ((cbeg (org-element-property :contents-begin element
))
5686 (cend (org-element-property :contents-end element
)))
5687 ;; CBEG is nil for table rules.
5688 (if (and cbeg cend
(>= pos cbeg
)
5689 (or (< pos cend
) (and (= pos cend
) (eobp))))
5690 (narrow-to-region cbeg cend
)
5691 (throw 'objects-forbidden element
))))
5692 ;; At a parsed keyword, objects are located within value.
5694 (if (not (member (org-element-property :key element
)
5695 org-element-document-properties
))
5696 (throw 'objects-forbidden element
)
5698 (search-forward ":")
5699 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5700 (narrow-to-region (point) (line-end-position))
5701 (throw 'objects-forbidden element
))))
5702 ;; At a planning line, if point is at a timestamp, return it,
5703 ;; otherwise, return element.
5704 ((eq type
'planning
)
5705 (dolist (p '(:closed
:deadline
:scheduled
))
5706 (let ((timestamp (org-element-property p element
)))
5707 (when (and timestamp
5708 (<= (org-element-property :begin timestamp
) pos
)
5709 (> (org-element-property :end timestamp
) pos
))
5710 (throw 'objects-forbidden timestamp
))))
5711 ;; All other locations cannot contain objects: bail out.
5712 (throw 'objects-forbidden element
))
5713 (t (throw 'objects-forbidden element
)))
5714 (goto-char (point-min))
5715 (let ((restriction (org-element-restriction type
))
5717 (cache (cond ((not (org-element--cache-active-p)) nil
)
5718 (org-element--cache-objects
5719 (gethash element org-element--cache-objects
))
5720 (t (org-element-cache-reset) nil
)))
5721 next object-data last
)
5725 ;; When entering PARENT for the first time, get list
5726 ;; of objects within known so far. Store it in
5729 (let ((data (assq parent cache
)))
5730 (if data
(setq object-data data
)
5731 (push (setq object-data
(list parent nil
)) cache
))))
5732 ;; Find NEXT object for analysis.
5734 ;; If NEXT is non-nil, we already exhausted the
5735 ;; cache so we can parse buffer to find the object
5737 (if next
(setq next
(org-element--object-lex restriction
))
5738 ;; Otherwise, check if cache can help us.
5739 (let ((objects (cddr object-data
))
5740 (completep (nth 1 object-data
)))
5742 ((and (not objects
) completep
) (throw 'exit parent
))
5744 (setq next
(org-element--object-lex restriction
)))
5747 (org-element-property :end
(car objects
))))
5748 (if (>= cache-limit pos
)
5749 ;; Cache contains the information needed.
5750 (dolist (object objects
(throw 'exit parent
))
5751 (when (<= (org-element-property :begin object
)
5753 (if (>= (org-element-property :end object
)
5755 (throw 'found
(setq next object
))
5756 (throw 'exit parent
))))
5757 (goto-char cache-limit
)
5759 (org-element--object-lex restriction
))))))))
5760 ;; If we have a new object to analyze, store it in
5761 ;; cache. Otherwise record that there is nothing
5762 ;; more to parse in this element at this depth.
5764 (progn (org-element-put-property next
:parent parent
)
5765 (push next
(cddr object-data
)))
5766 (setcar (cdr object-data
) t
)))
5767 ;; Process NEXT, if any, in order to know if we need
5768 ;; to skip it, return it or move into it.
5769 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5770 (throw 'exit
(or last parent
))
5771 (let ((end (org-element-property :end next
))
5772 (cbeg (org-element-property :contents-begin next
))
5773 (cend (org-element-property :contents-end next
)))
5775 ;; Skip objects ending before point. Also skip
5776 ;; objects ending at point unless it is also the
5777 ;; end of buffer, since we want to return the
5778 ;; innermost object.
5779 ((and (<= end pos
) (/= (point-max) end
))
5781 ;; For convenience, when object ends at POS,
5782 ;; without any space, store it in LAST, as we
5783 ;; will return it if no object starts here.
5784 (when (and (= end pos
)
5785 (not (memq (char-before) '(?\s ?
\t))))
5787 ;; If POS is within a container object, move
5788 ;; into that object.
5792 ;; At contents' end, if there is no
5793 ;; space before point, also move into
5794 ;; object, for consistency with
5795 ;; convenience feature above.
5797 (or (= (point-max) pos
)
5798 (not (memq (char-before pos
)
5801 (narrow-to-region (point) cend
)
5803 restriction
(org-element-restriction next
)
5806 ;; Otherwise, return NEXT.
5807 (t (throw 'exit next
)))))))
5808 ;; Store results in cache, if applicable.
5809 (org-element--cache-put element cache
)))))))
5811 (defun org-element-nested-p (elem-A elem-B
)
5812 "Non-nil when elements ELEM-A and ELEM-B are nested."
5813 (let ((beg-A (org-element-property :begin elem-A
))
5814 (beg-B (org-element-property :begin elem-B
))
5815 (end-A (org-element-property :end elem-A
))
5816 (end-B (org-element-property :end elem-B
)))
5817 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5818 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5820 (defun org-element-swap-A-B (elem-A elem-B
)
5821 "Swap elements ELEM-A and ELEM-B.
5822 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5824 (goto-char (org-element-property :begin elem-A
))
5825 ;; There are two special cases when an element doesn't start at bol:
5826 ;; the first paragraph in an item or in a footnote definition.
5827 (let ((specialp (not (bolp))))
5828 ;; Only a paragraph without any affiliated keyword can be moved at
5829 ;; ELEM-A position in such a situation. Note that the case of
5830 ;; a footnote definition is impossible: it cannot contain two
5831 ;; paragraphs in a row because it cannot contain a blank line.
5833 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5834 (/= (org-element-property :begin elem-B
)
5835 (org-element-property :contents-begin elem-B
))))
5836 (error "Cannot swap elements"))
5837 ;; In a special situation, ELEM-A will have no indentation. We'll
5838 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5839 (let* ((ind-B (when specialp
5840 (goto-char (org-element-property :begin elem-B
))
5841 (org-get-indentation)))
5842 (beg-A (org-element-property :begin elem-A
))
5843 (end-A (save-excursion
5844 (goto-char (org-element-property :end elem-A
))
5845 (skip-chars-backward " \r\t\n")
5847 (beg-B (org-element-property :begin elem-B
))
5848 (end-B (save-excursion
5849 (goto-char (org-element-property :end elem-B
))
5850 (skip-chars-backward " \r\t\n")
5852 ;; Store overlays responsible for visibility status. We
5853 ;; also need to store their boundaries as they will be
5854 ;; removed from buffer.
5857 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5858 (overlays-in beg-A end-A
))
5859 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5860 (overlays-in beg-B end-B
))))
5862 (body-A (buffer-substring beg-A end-A
))
5863 (body-B (delete-and-extract-region beg-B end-B
)))
5866 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5867 (org-indent-to-column ind-B
))
5869 ;; Restore ex ELEM-A overlays.
5870 (let ((offset (- beg-B beg-A
)))
5873 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5876 (delete-region beg-A end-A
)
5878 ;; Restore ex ELEM-B overlays.
5881 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5883 (goto-char (org-element-property :end elem-B
)))))
5885 (defun org-element-remove-indentation (s &optional n
)
5886 "Remove maximum common indentation in string S and return it.
5887 When optional argument N is a positive integer, remove exactly
5888 that much characters from indentation, if possible, or return
5889 S as-is otherwise. Unlike to `org-remove-indentation', this
5890 function doesn't call `untabify' on S."
5894 (goto-char (point-min))
5895 ;; Find maximum common indentation, if not specified.
5897 (let ((min-ind (point-max)))
5899 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5900 (let ((ind (1- (current-column))))
5901 (if (zerop ind
) (throw 'exit s
)
5902 (setq min-ind
(min min-ind ind
))))))
5905 ;; Remove exactly N indentation, but give up if not possible.
5907 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5908 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5909 ((< ind n
) (throw 'exit s
))
5910 (t (org-indent-line-to (- ind n
))))
5916 (provide 'org-element
)
5919 ;; generated-autoload-file: "org-loaddefs.el"
5922 ;;; org-element.el ends here