1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; Elements are related to the structure of the document. Indeed, all
29 ;; elements are a cover for the document: each position within belongs
30 ;; to at least one element.
32 ;; An element always starts and ends at the beginning of a line. With
33 ;; a few exceptions (`clock', `headline', `inlinetask', `item',
34 ;; `planning', `node-property', `section' and `table-row' types), it
35 ;; can also accept a fixed set of keywords as attributes. Those are
36 ;; called "affiliated keywords" to distinguish them from other
37 ;; keywords, which are full-fledged elements. Almost all affiliated
38 ;; keywords are referenced in `org-element-affiliated-keywords'; the
39 ;; others are export attributes and start with "ATTR_" prefix.
41 ;; Element containing other elements (and only elements) are called
42 ;; greater elements. Concerned types are: `center-block', `drawer',
43 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
44 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
45 ;; and `special-block'.
47 ;; Other element types are: `babel-call', `clock', `comment',
48 ;; `comment-block', `diary-sexp', `example-block', `export-block',
49 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
50 ;; `node-property', `paragraph', `planning', `src-block', `table',
51 ;; `table-row' and `verse-block'. Among them, `paragraph' and
52 ;; `verse-block' types can contain Org objects and plain text.
54 ;; Objects are related to document's contents. Some of them are
55 ;; recursive. Associated types are of the following: `bold', `code',
56 ;; `entity', `export-snippet', `footnote-reference',
57 ;; `inline-babel-call', `inline-src-block', `italic',
58 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
59 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
60 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
62 ;; Some elements also have special properties whose value can hold
63 ;; objects themselves (e.g. an item tag or a headline name). Such
64 ;; values are called "secondary strings". Any object belongs to
65 ;; either an element or a secondary string.
67 ;; Notwithstanding affiliated keywords, each greater element, element
68 ;; and object has a fixed set of properties attached to it. Among
69 ;; them, four are shared by all types: `:begin' and `:end', which
70 ;; refer to the beginning and ending buffer positions of the
71 ;; considered element or object, `:post-blank', which holds the number
72 ;; of blank lines, or white spaces, at its end and `:parent' which
73 ;; refers to the element or object containing it. Greater elements,
74 ;; elements and objects containing objects will also have
75 ;; `:contents-begin' and `:contents-end' properties to delimit
76 ;; contents. Eventually, greater elements and elements accepting
77 ;; affiliated keywords will have a `:post-affiliated' property,
78 ;; referring to the buffer position after all such keywords.
80 ;; At the lowest level, a `:parent' property is also attached to any
81 ;; string, as a text property.
83 ;; Lisp-wise, an element or an object can be represented as a list.
84 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
85 ;; TYPE is a symbol describing the Org element or object.
86 ;; PROPERTIES is the property list attached to it. See docstring of
87 ;; appropriate parsing function to get an exhaustive
89 ;; CONTENTS is a list of elements, objects or raw strings contained
90 ;; in the current element or object, when applicable.
92 ;; An Org buffer is a nested list of such elements and objects, whose
93 ;; type is `org-data' and properties is nil.
95 ;; The first part of this file defines Org syntax, while the second
96 ;; one provide accessors and setters functions.
98 ;; The next part implements a parser and an interpreter for each
99 ;; element and object type in Org syntax.
101 ;; The following part creates a fully recursive buffer parser. It
102 ;; also provides a tool to map a function to elements or objects
103 ;; matching some criteria in the parse tree. Functions of interest
104 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
105 ;; extent, `org-element-parse-secondary-string'.
107 ;; The penultimate part is the cradle of an interpreter for the
108 ;; obtained parse tree: `org-element-interpret-data'.
110 ;; The library ends by furnishing `org-element-at-point' function, and
111 ;; a way to give information about document structure around point
112 ;; with `org-element-context'. A cache mechanism is also provided for
118 (eval-when-compile (require 'cl
))
124 ;;; Definitions And Rules
126 ;; Define elements, greater elements and specify recursive objects,
127 ;; along with the affiliated keywords recognized. Also set up
128 ;; restrictions on recursive objects combinations.
130 ;; These variables really act as a control center for the parsing
133 (defconst org-element-paragraph-separate
135 ;; Headlines, inlinetasks.
136 org-outline-regexp
"\\|"
137 ;; Footnote definitions.
138 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
144 ;; Tables (any type).
145 "\\(?:|\\|\\+-[-+]\\)" "\\|"
146 ;; Blocks (any type), Babel calls and keywords. Note: this
147 ;; is only an indication and need some thorough check.
148 "#\\(?:[+ ]\\|$\\)" "\\|"
149 ;; Drawers (any type) and fixed-width areas. This is also
150 ;; only an indication.
153 "-\\{5,\\}[ \t]*$" "\\|"
154 ;; LaTeX environments.
155 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
156 ;; Planning and Clock lines.
157 (regexp-opt (list org-scheduled-string
163 (let ((term (case org-plain-list-ordered-item-terminator
164 (?\
) ")") (?.
"\\.") (otherwise "[.)]")))
165 (alpha (and org-list-allow-alphabetical
"\\|[A-Za-z]")))
166 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha
"\\)" term
"\\)"
167 "\\(?:[ \t]\\|$\\)"))
169 "Regexp to separate paragraphs in an Org buffer.
170 In the case of lines starting with \"#\" and \":\", this regexp
171 is not sufficient to know if point is at a paragraph ending. See
172 `org-element-paragraph-parser' for more information.")
174 (defconst org-element-all-elements
175 '(babel-call center-block clock comment comment-block diary-sexp drawer
176 dynamic-block example-block export-block fixed-width
177 footnote-definition headline horizontal-rule inlinetask item
178 keyword latex-environment node-property paragraph plain-list
179 planning property-drawer quote-block section
180 special-block src-block table table-row verse-block
)
181 "Complete list of element types.")
183 (defconst org-element-greater-elements
184 '(center-block drawer dynamic-block footnote-definition headline inlinetask
185 item plain-list property-drawer quote-block section
187 "List of recursive element types aka Greater Elements.")
189 (defconst org-element-all-objects
190 '(bold code entity export-snippet footnote-reference inline-babel-call
191 inline-src-block italic line-break latex-fragment link macro
192 radio-target statistics-cookie strike-through subscript superscript
193 table-cell target timestamp underline verbatim
)
194 "Complete list of object types.")
196 (defconst org-element-recursive-objects
197 '(bold italic link subscript radio-target strike-through superscript
198 table-cell underline
)
199 "List of recursive object types.")
201 (defvar org-element-block-name-alist
202 '(("CENTER" . org-element-center-block-parser
)
203 ("COMMENT" . org-element-comment-block-parser
)
204 ("EXAMPLE" . org-element-example-block-parser
)
205 ("QUOTE" . org-element-quote-block-parser
)
206 ("SRC" . org-element-src-block-parser
)
207 ("VERSE" . org-element-verse-block-parser
))
208 "Alist between block names and the associated parsing function.
209 Names must be uppercase. Any block whose name has no association
210 is parsed with `org-element-special-block-parser'.")
212 (defconst org-element-link-type-is-file
213 '("file" "file+emacs" "file+sys" "docview")
214 "List of link types equivalent to \"file\".
215 Only these types can accept search options and an explicit
216 application to open them.")
218 (defconst org-element-affiliated-keywords
219 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
220 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
221 "List of affiliated keywords as strings.
222 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
223 are affiliated keywords and need not to be in this list.")
225 (defconst org-element-keyword-translation-alist
226 '(("DATA" .
"NAME") ("LABEL" .
"NAME") ("RESNAME" .
"NAME")
227 ("SOURCE" .
"NAME") ("SRCNAME" .
"NAME") ("TBLNAME" .
"NAME")
228 ("RESULT" .
"RESULTS") ("HEADERS" .
"HEADER"))
229 "Alist of usual translations for keywords.
230 The key is the old name and the value the new one. The property
231 holding their value will be named after the translated name.")
233 (defconst org-element-multiple-keywords
'("CAPTION" "HEADER")
234 "List of affiliated keywords that can occur more than once in an element.
236 Their value will be consed into a list of strings, which will be
237 returned as the value of the property.
239 This list is checked after translations have been applied. See
240 `org-element-keyword-translation-alist'.
242 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
243 allow multiple occurrences and need not to be in this list.")
245 (defconst org-element-parsed-keywords
'("CAPTION")
246 "List of affiliated keywords whose value can be parsed.
248 Their value will be stored as a secondary string: a list of
251 This list is checked after translations have been applied. See
252 `org-element-keyword-translation-alist'.")
254 (defconst org-element-dual-keywords
'("CAPTION" "RESULTS")
255 "List of affiliated keywords which can have a secondary value.
257 In Org syntax, they can be written with optional square brackets
258 before the colons. For example, RESULTS keyword can be
259 associated to a hash value with the following:
261 #+RESULTS[hash-string]: some-source
263 This list is checked after translations have been applied. See
264 `org-element-keyword-translation-alist'.")
266 (defconst org-element-document-properties
'("AUTHOR" "DATE" "TITLE")
267 "List of properties associated to the whole document.
268 Any keyword in this list will have its value parsed and stored as
269 a secondary string.")
271 (defconst org-element--affiliated-re
272 (format "[ \t]*#\\+\\(?:%s\\):\\(?: \\|$\\)"
274 ;; Dual affiliated keywords.
275 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
276 (regexp-opt org-element-dual-keywords
))
278 ;; Regular affiliated keywords.
279 (format "\\(?1:%s\\)"
283 (member keyword org-element-dual-keywords
))
284 org-element-affiliated-keywords
)))
286 ;; Export attributes.
287 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
288 "Regexp matching any affiliated keyword.
290 Keyword name is put in match group 1. Moreover, if keyword
291 belongs to `org-element-dual-keywords', put the dual value in
294 Don't modify it, set `org-element-affiliated-keywords' instead.")
296 (defconst org-element-object-restrictions
297 (let* ((standard-set (remq 'table-cell org-element-all-objects
))
298 (standard-set-no-line-break (remq 'line-break standard-set
)))
299 `((bold ,@standard-set
)
300 (footnote-reference ,@standard-set
)
301 (headline ,@standard-set-no-line-break
)
302 (inlinetask ,@standard-set-no-line-break
)
303 (italic ,@standard-set
)
304 (item ,@standard-set-no-line-break
)
305 (keyword ,@standard-set
)
306 ;; Ignore all links excepted plain links in a link description.
307 ;; Also ignore radio-targets and line breaks.
308 (link bold code entity export-snippet inline-babel-call inline-src-block
309 italic latex-fragment macro plain-link statistics-cookie
310 strike-through subscript superscript underline verbatim
)
311 (paragraph ,@standard-set
)
312 ;; Remove any variable object from radio target as it would
313 ;; prevent it from being properly recognized.
314 (radio-target bold code entity italic latex-fragment strike-through
315 subscript superscript underline superscript
)
316 (strike-through ,@standard-set
)
317 (subscript ,@standard-set
)
318 (superscript ,@standard-set
)
319 ;; Ignore inline babel call and inline src block as formulas are
320 ;; possible. Also ignore line breaks and statistics cookies.
321 (table-cell bold code entity export-snippet footnote-reference italic
322 latex-fragment link macro radio-target strike-through
323 subscript superscript target timestamp underline verbatim
)
324 (table-row table-cell
)
325 (underline ,@standard-set
)
326 (verse-block ,@standard-set
)))
327 "Alist of objects restrictions.
329 key is an element or object type containing objects and value is
330 a list of types that can be contained within an element or object
333 For example, in a `radio-target' object, one can only find
334 entities, latex-fragments, subscript, superscript and text
337 This alist also applies to secondary string. For example, an
338 `headline' type element doesn't directly contain objects, but
339 still has an entry since one of its properties (`:title') does.")
341 (defconst org-element-secondary-value-alist
342 '((headline .
:title
)
343 (inlinetask .
:title
)
345 (footnote-reference .
:inline-definition
))
346 "Alist between element types and location of secondary value.")
348 (defconst org-element-object-variables
'(org-link-abbrev-alist-local)
349 "List of buffer-local variables used when parsing objects.
350 These variables are copied to the temporary buffer created by
351 `org-export-secondary-string'.")
355 ;;; Accessors and Setters
357 ;; Provide four accessors: `org-element-type', `org-element-property'
358 ;; `org-element-contents' and `org-element-restriction'.
360 ;; Setter functions allow to modify elements by side effect. There is
361 ;; `org-element-put-property', `org-element-set-contents'. These
362 ;; low-level functions are useful to build a parse tree.
364 ;; `org-element-adopt-element', `org-element-set-element',
365 ;; `org-element-extract-element' and `org-element-insert-before' are
366 ;; high-level functions useful to modify a parse tree.
368 ;; `org-element-secondary-p' is a predicate used to know if a given
369 ;; object belongs to a secondary string.
371 (defsubst org-element-type
(element)
372 "Return type of ELEMENT.
374 The function returns the type of the element or object provided.
375 It can also return the following special value:
376 `plain-text' for a string
377 `org-data' for a complete document
378 nil in any other case."
380 ((not (consp element
)) (and (stringp element
) 'plain-text
))
381 ((symbolp (car element
)) (car element
))))
383 (defsubst org-element-property
(property element
)
384 "Extract the value from the PROPERTY of an ELEMENT."
385 (if (stringp element
) (get-text-property 0 property element
)
386 (plist-get (nth 1 element
) property
)))
388 (defsubst org-element-contents
(element)
389 "Extract contents from an ELEMENT."
390 (cond ((not (consp element
)) nil
)
391 ((symbolp (car element
)) (nthcdr 2 element
))
394 (defsubst org-element-restriction
(element)
395 "Return restriction associated to ELEMENT.
396 ELEMENT can be an element, an object or a symbol representing an
397 element or object type."
398 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
399 org-element-object-restrictions
)))
401 (defsubst org-element-put-property
(element property value
)
402 "In ELEMENT set PROPERTY to VALUE.
403 Return modified element."
404 (if (stringp element
) (org-add-props element nil property value
)
405 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
408 (defsubst org-element-set-contents
(element &rest contents
)
409 "Set ELEMENT contents to CONTENTS.
410 Return modified element."
411 (cond ((not element
) (list contents
))
412 ((not (symbolp (car element
))) contents
)
413 ((cdr element
) (setcdr (cdr element
) contents
))
414 (t (nconc element contents
))))
416 (defun org-element-secondary-p (object)
417 "Non-nil when OBJECT belongs to a secondary string.
418 Return value is the property name, as a keyword, or nil."
419 (let* ((parent (org-element-property :parent object
))
420 (property (cdr (assq (org-element-type parent
)
421 org-element-secondary-value-alist
))))
423 (memq object
(org-element-property property parent
))
426 (defsubst org-element-adopt-elements
(parent &rest children
)
427 "Append elements to the contents of another element.
429 PARENT is an element or object. CHILDREN can be elements,
430 objects, or a strings.
432 The function takes care of setting `:parent' property for CHILD.
433 Return parent element."
434 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
435 ;; string: parent is the list itself.
436 (mapc (lambda (child)
437 (org-element-put-property child
:parent
(or parent children
)))
439 ;; Add CHILDREN at the end of PARENT contents.
441 (apply 'org-element-set-contents
443 (nconc (org-element-contents parent
) children
)))
444 ;; Return modified PARENT element.
445 (or parent children
))
447 (defun org-element-extract-element (element)
448 "Extract ELEMENT from parse tree.
449 Remove element from the parse tree by side-effect, and return it
450 with its `:parent' property stripped out."
451 (let ((parent (org-element-property :parent element
))
452 (secondary (org-element-secondary-p element
)))
454 (org-element-put-property
456 (delq element
(org-element-property secondary parent
)))
457 (apply #'org-element-set-contents
459 (delq element
(org-element-contents parent
))))
460 ;; Return ELEMENT with its :parent removed.
461 (org-element-put-property element
:parent nil
)))
463 (defun org-element-insert-before (element location
)
464 "Insert ELEMENT before LOCATION in parse tree.
465 LOCATION is an element, object or string within the parse tree.
466 Parse tree is modified by side effect."
467 (let* ((parent (org-element-property :parent location
))
468 (property (org-element-secondary-p location
))
469 (siblings (if property
(org-element-property property parent
)
470 (org-element-contents parent
)))
471 ;; Special case: LOCATION is the first element of an
472 ;; independent secondary string (e.g. :title property). Add
474 (specialp (and (not property
)
476 (eq (car parent
) location
))))
477 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
479 ((or (null siblings
) (eq (car siblings
) location
))
480 (push element siblings
))
481 ((null location
) (nconc siblings
(list element
)))
482 (t (let ((previous (cadr (memq location
(reverse siblings
)))))
484 (error "No location found to insert element")
485 (let ((next (memq previous siblings
)))
486 (setcdr next
(cons element
(cdr next
))))))))
487 ;; Store SIBLINGS at appropriate place in parse tree.
489 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
490 (property (org-element-put-property parent property siblings
))
491 (t (apply #'org-element-set-contents parent siblings
)))
492 ;; Set appropriate :parent property.
493 (org-element-put-property element
:parent parent
)))
495 (defun org-element-set-element (old new
)
496 "Replace element or object OLD with element or object NEW.
497 The function takes care of setting `:parent' property for NEW."
498 ;; Ensure OLD and NEW have the same parent.
499 (org-element-put-property new
:parent
(org-element-property :parent old
))
500 (if (or (memq (org-element-type old
) '(plain-text nil
))
501 (memq (org-element-type new
) '(plain-text nil
)))
502 ;; We cannot replace OLD with NEW since one of them is not an
503 ;; object or element. We take the long path.
504 (progn (org-element-insert-before new old
)
505 (org-element-extract-element old
))
506 ;; Since OLD is going to be changed into NEW by side-effect, first
507 ;; make sure that every element or object within NEW has OLD as
509 (dolist (blob (org-element-contents new
))
510 (org-element-put-property blob
:parent old
))
511 ;; Transfer contents.
512 (apply #'org-element-set-contents old
(org-element-contents new
))
513 ;; Overwrite OLD's properties with NEW's.
514 (setcar (cdr old
) (nth 1 new
))
516 (setcar old
(car new
))))
522 ;; For each greater element type, we define a parser and an
525 ;; A parser returns the element or object as the list described above.
526 ;; Most of them accepts no argument. Though, exceptions exist. Hence
527 ;; every element containing a secondary string (see
528 ;; `org-element-secondary-value-alist') will accept an optional
529 ;; argument to toggle parsing of that secondary string. Moreover,
530 ;; `item' parser requires current list's structure as its first
533 ;; An interpreter accepts two arguments: the list representation of
534 ;; the element or object, and its contents. The latter may be nil,
535 ;; depending on the element or object considered. It returns the
536 ;; appropriate Org syntax, as a string.
538 ;; Parsing functions must follow the naming convention:
539 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
540 ;; defined in `org-element-greater-elements'.
542 ;; Similarly, interpreting functions must follow the naming
543 ;; convention: org-element-TYPE-interpreter.
545 ;; With the exception of `headline' and `item' types, greater elements
546 ;; cannot contain other greater elements of their own type.
548 ;; Beside implementing a parser and an interpreter, adding a new
549 ;; greater element requires to tweak `org-element--current-element'.
550 ;; Moreover, the newly defined type must be added to both
551 ;; `org-element-all-elements' and `org-element-greater-elements'.
556 (defun org-element-center-block-parser (limit affiliated
)
557 "Parse a center block.
559 LIMIT bounds the search. AFFILIATED is a list of which CAR is
560 the buffer position at the beginning of the first affiliated
561 keyword and CDR is a plist of affiliated keywords along with
564 Return a list whose CAR is `center-block' and CDR is a plist
565 containing `:begin', `:end', `:contents-begin', `:contents-end',
566 `:post-blank' and `:post-affiliated' keywords.
568 Assume point is at the beginning of the block."
569 (let ((case-fold-search t
))
570 (if (not (save-excursion
571 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
572 ;; Incomplete block: parse it as a paragraph.
573 (org-element-paragraph-parser limit affiliated
)
574 (let ((block-end-line (match-beginning 0)))
575 (let* ((begin (car affiliated
))
576 (post-affiliated (point))
577 ;; Empty blocks have no contents.
578 (contents-begin (progn (forward-line)
579 (and (< (point) block-end-line
)
581 (contents-end (and contents-begin block-end-line
))
582 (pos-before-blank (progn (goto-char block-end-line
)
586 (skip-chars-forward " \r\t\n" limit
)
587 (if (eobp) (point) (line-beginning-position)))))
592 :contents-begin contents-begin
593 :contents-end contents-end
594 :post-blank
(count-lines pos-before-blank end
)
595 :post-affiliated post-affiliated
)
596 (cdr affiliated
))))))))
598 (defun org-element-center-block-interpreter (center-block contents
)
599 "Interpret CENTER-BLOCK element as Org syntax.
600 CONTENTS is the contents of the element."
601 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
606 (defun org-element-drawer-parser (limit affiliated
)
609 LIMIT bounds the search. AFFILIATED is a list of which CAR is
610 the buffer position at the beginning of the first affiliated
611 keyword and CDR is a plist of affiliated keywords along with
614 Return a list whose CAR is `drawer' and CDR is a plist containing
615 `:drawer-name', `:begin', `:end', `:contents-begin',
616 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
618 Assume point is at beginning of drawer."
619 (let ((case-fold-search t
))
620 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
621 ;; Incomplete drawer: parse it as a paragraph.
622 (org-element-paragraph-parser limit affiliated
)
624 (let* ((drawer-end-line (match-beginning 0))
625 (name (progn (looking-at org-drawer-regexp
)
626 (org-match-string-no-properties 1)))
627 (begin (car affiliated
))
628 (post-affiliated (point))
629 ;; Empty drawers have no contents.
630 (contents-begin (progn (forward-line)
631 (and (< (point) drawer-end-line
)
633 (contents-end (and contents-begin drawer-end-line
))
634 (pos-before-blank (progn (goto-char drawer-end-line
)
637 (end (progn (skip-chars-forward " \r\t\n" limit
)
638 (if (eobp) (point) (line-beginning-position)))))
644 :contents-begin contents-begin
645 :contents-end contents-end
646 :post-blank
(count-lines pos-before-blank end
)
647 :post-affiliated post-affiliated
)
648 (cdr affiliated
))))))))
650 (defun org-element-drawer-interpreter (drawer contents
)
651 "Interpret DRAWER element as Org syntax.
652 CONTENTS is the contents of the element."
653 (format ":%s:\n%s:END:"
654 (org-element-property :drawer-name drawer
)
660 (defun org-element-dynamic-block-parser (limit affiliated
)
661 "Parse a dynamic block.
663 LIMIT bounds the search. AFFILIATED is a list of which CAR is
664 the buffer position at the beginning of the first affiliated
665 keyword and CDR is a plist of affiliated keywords along with
668 Return a list whose CAR is `dynamic-block' and CDR is a plist
669 containing `:block-name', `:begin', `:end', `:contents-begin',
670 `:contents-end', `:arguments', `:post-blank' and
671 `:post-affiliated' keywords.
673 Assume point is at beginning of dynamic block."
674 (let ((case-fold-search t
))
675 (if (not (save-excursion
676 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
677 ;; Incomplete block: parse it as a paragraph.
678 (org-element-paragraph-parser limit affiliated
)
679 (let ((block-end-line (match-beginning 0)))
681 (let* ((name (progn (looking-at org-dblock-start-re
)
682 (org-match-string-no-properties 1)))
683 (arguments (org-match-string-no-properties 3))
684 (begin (car affiliated
))
685 (post-affiliated (point))
686 ;; Empty blocks have no contents.
687 (contents-begin (progn (forward-line)
688 (and (< (point) block-end-line
)
690 (contents-end (and contents-begin block-end-line
))
691 (pos-before-blank (progn (goto-char block-end-line
)
694 (end (progn (skip-chars-forward " \r\t\n" limit
)
695 (if (eobp) (point) (line-beginning-position)))))
702 :contents-begin contents-begin
703 :contents-end contents-end
704 :post-blank
(count-lines pos-before-blank end
)
705 :post-affiliated post-affiliated
)
706 (cdr affiliated
)))))))))
708 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
709 "Interpret DYNAMIC-BLOCK element as Org syntax.
710 CONTENTS is the contents of the element."
711 (format "#+BEGIN: %s%s\n%s#+END:"
712 (org-element-property :block-name dynamic-block
)
713 (let ((args (org-element-property :arguments dynamic-block
)))
714 (and args
(concat " " args
)))
718 ;;;; Footnote Definition
720 (defun org-element-footnote-definition-parser (limit affiliated
)
721 "Parse a footnote definition.
723 LIMIT bounds the search. AFFILIATED is a list of which CAR is
724 the buffer position at the beginning of the first affiliated
725 keyword and CDR is a plist of affiliated keywords along with
728 Return a list whose CAR is `footnote-definition' and CDR is
729 a plist containing `:label', `:begin' `:end', `:contents-begin',
730 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
732 Assume point is at the beginning of the footnote definition."
734 (let* ((label (progn (looking-at org-footnote-definition-re
)
735 (org-match-string-no-properties 1)))
736 (begin (car affiliated
))
737 (post-affiliated (point))
738 (ending (save-excursion
742 (concat org-outline-regexp-bol
"\\|"
743 org-footnote-definition-re
"\\|"
744 "^\\([ \t]*\n\\)\\{2,\\}") limit
'move
))
747 (contents-begin (progn
749 (skip-chars-forward " \r\t\n" ending
)
750 (cond ((= (point) ending
) nil
)
751 ((= (line-beginning-position) begin
) (point))
752 (t (line-beginning-position)))))
753 (contents-end (and contents-begin ending
))
754 (end (progn (goto-char ending
)
755 (skip-chars-forward " \r\t\n" limit
)
756 (if (eobp) (point) (line-beginning-position)))))
757 (list 'footnote-definition
762 :contents-begin contents-begin
763 :contents-end contents-end
764 :post-blank
(count-lines ending end
)
765 :post-affiliated post-affiliated
)
766 (cdr affiliated
))))))
768 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
769 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
770 CONTENTS is the contents of the footnote-definition."
771 (concat (format "[%s]" (org-element-property :label footnote-definition
))
778 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
781 Return a list whose CAR is `headline' and CDR is a plist
782 containing `:raw-value', `:title', `:alt-title', `:begin',
783 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
784 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
785 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
786 and `:footnote-section-p' keywords.
788 The plist also contains any property set in the property drawer,
789 with its name in upper cases and colons added at the
790 beginning (e.g., `:CUSTOM_ID').
792 LIMIT is a buffer position bounding the search.
794 When RAW-SECONDARY-P is non-nil, headline's title will not be
795 parsed as a secondary string, but as a plain string instead.
797 Assume point is at beginning of the headline."
799 (let* ((components (org-heading-components))
800 (level (nth 1 components
))
801 (todo (nth 2 components
))
803 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
804 (tags (let ((raw-tags (nth 5 components
)))
805 (and raw-tags
(org-split-string raw-tags
":"))))
806 (raw-value (or (nth 4 components
) ""))
808 (let ((case-fold-search nil
))
809 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
811 (archivedp (member org-archive-tag tags
))
812 (footnote-section-p (and org-footnote-section
813 (string= org-footnote-section raw-value
)))
814 ;; Upcase property names. It avoids confusion between
815 ;; properties obtained through property drawer and default
816 ;; properties from the parser (e.g. `:end' and :END:)
823 (intern (concat ":" (upcase (car p
))))
825 (org-entry-properties nil
'standard
))
828 ;; Read time properties on the line below the headline.
830 (when (progn (forward-line)
831 (looking-at org-planning-or-clock-line-re
))
832 (let ((end (line-end-position)) plist
)
833 (while (re-search-forward
834 org-keyword-time-not-clock-regexp end t
)
835 (goto-char (match-end 1))
836 (skip-chars-forward " \t")
837 (let ((keyword (match-string 1))
838 (time (org-element-timestamp-parser)))
839 (cond ((equal keyword org-scheduled-string
)
840 (setq plist
(plist-put plist
:scheduled time
)))
841 ((equal keyword org-deadline-string
)
842 (setq plist
(plist-put plist
:deadline time
)))
843 (t (setq plist
(plist-put plist
:closed time
))))))
846 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
847 (pos-after-head (progn (forward-line) (point)))
848 (contents-begin (save-excursion
849 (skip-chars-forward " \r\t\n" end
)
850 (and (/= (point) end
) (line-beginning-position))))
851 (contents-end (and contents-begin
852 (progn (goto-char end
)
853 (skip-chars-backward " \r\t\n")
856 ;; Clean RAW-VALUE from any comment string.
858 (let ((case-fold-search nil
))
860 (replace-regexp-in-string
861 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
864 ;; Clean TAGS from archive tag, if any.
865 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
869 (list :raw-value raw-value
873 (if (not contents-begin
) 0
874 (count-lines pos-after-head contents-begin
))
875 :contents-begin contents-begin
876 :contents-end contents-end
878 :priority
(nth 3 components
)
882 :post-blank
(count-lines
883 (or contents-end pos-after-head
)
885 :footnote-section-p footnote-section-p
887 :commentedp commentedp
)
890 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
892 (org-element-put-property
894 (if raw-secondary-p alt-title
895 (org-element-parse-secondary-string
896 alt-title
(org-element-restriction 'headline
) headline
)))))
897 (org-element-put-property
899 (if raw-secondary-p raw-value
900 (org-element-parse-secondary-string
901 raw-value
(org-element-restriction 'headline
) headline
)))))))
903 (defun org-element-headline-interpreter (headline contents
)
904 "Interpret HEADLINE element as Org syntax.
905 CONTENTS is the contents of the element."
906 (let* ((level (org-element-property :level headline
))
907 (todo (org-element-property :todo-keyword headline
))
908 (priority (org-element-property :priority headline
))
909 (title (org-element-interpret-data
910 (org-element-property :title headline
)))
911 (tags (let ((tag-list (if (org-element-property :archivedp headline
)
912 (cons org-archive-tag
913 (org-element-property :tags headline
))
914 (org-element-property :tags headline
))))
916 (format ":%s:" (mapconcat 'identity tag-list
":")))))
917 (commentedp (org-element-property :commentedp headline
))
918 (pre-blank (or (org-element-property :pre-blank headline
) 0))
919 (heading (concat (make-string (org-reduced-level level
) ?
*)
920 (and todo
(concat " " todo
))
921 (and commentedp
(concat " " org-comment-string
))
923 (format " [#%s]" (char-to-string priority
)))
924 (cond ((and org-footnote-section
925 (org-element-property
926 :footnote-section-p headline
))
927 (concat " " org-footnote-section
))
928 (title (concat " " title
))))))
933 ((zerop org-tags-column
) (format " %s" tags
))
934 ((< org-tags-column
0)
937 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
942 (make-string (max (- org-tags-column
(length heading
)) 1) ?
)
944 (make-string (1+ pre-blank
) 10)
950 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
951 "Parse an inline task.
953 Return a list whose CAR is `inlinetask' and CDR is a plist
954 containing `:title', `:begin', `:end', `:contents-begin' and
955 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
956 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
957 `:closed' and `:post-blank' keywords.
959 The plist also contains any property set in the property drawer,
960 with its name in upper cases and colons added at the
961 beginning (e.g., `:CUSTOM_ID').
963 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
964 title will not be parsed as a secondary string, but as a plain
967 Assume point is at beginning of the inline task."
969 (let* ((begin (point))
970 (components (org-heading-components))
971 (todo (nth 2 components
))
973 (if (member todo org-done-keywords
) 'done
'todo
)))
974 (tags (let ((raw-tags (nth 5 components
)))
975 (and raw-tags
(org-split-string raw-tags
":"))))
976 (raw-value (or (nth 4 components
) ""))
977 ;; Upcase property names. It avoids confusion between
978 ;; properties obtained through property drawer and default
979 ;; properties from the parser (e.g. `:end' and :END:)
986 (intern (concat ":" (upcase (car p
))))
988 (org-entry-properties nil
'standard
))
991 ;; Read time properties on the line below the inlinetask
994 (when (progn (forward-line)
995 (looking-at org-planning-or-clock-line-re
))
996 (let ((end (line-end-position)) plist
)
997 (while (re-search-forward
998 org-keyword-time-not-clock-regexp end t
)
999 (goto-char (match-end 1))
1000 (skip-chars-forward " \t")
1001 (let ((keyword (match-string 1))
1002 (time (org-element-timestamp-parser)))
1003 (cond ((equal keyword org-scheduled-string
)
1004 (setq plist
(plist-put plist
:scheduled time
)))
1005 ((equal keyword org-deadline-string
)
1006 (setq plist
(plist-put plist
:deadline time
)))
1007 (t (setq plist
(plist-put plist
:closed time
))))))
1009 (task-end (save-excursion
1011 (and (re-search-forward org-outline-regexp-bol limit t
)
1012 (org-looking-at-p "END[ \t]*$")
1013 (line-beginning-position))))
1014 (contents-begin (progn (forward-line)
1015 (and task-end
(< (point) task-end
) (point))))
1016 (contents-end (and contents-begin task-end
))
1017 (before-blank (if (not task-end
) (point)
1018 (goto-char task-end
)
1021 (end (progn (skip-chars-forward " \r\t\n" limit
)
1022 (if (eobp) (point) (line-beginning-position))))
1026 (list :raw-value raw-value
1029 :contents-begin contents-begin
1030 :contents-end contents-end
1031 :level
(nth 1 components
)
1032 :priority
(nth 3 components
)
1035 :todo-type todo-type
1036 :post-blank
(count-lines before-blank end
))
1039 (org-element-put-property
1041 (if raw-secondary-p raw-value
1042 (org-element-parse-secondary-string
1044 (org-element-restriction 'inlinetask
)
1047 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1048 "Interpret INLINETASK element as Org syntax.
1049 CONTENTS is the contents of inlinetask."
1050 (let* ((level (org-element-property :level inlinetask
))
1051 (todo (org-element-property :todo-keyword inlinetask
))
1052 (priority (org-element-property :priority inlinetask
))
1053 (title (org-element-interpret-data
1054 (org-element-property :title inlinetask
)))
1055 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1057 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1058 (task (concat (make-string level ?
*)
1059 (and todo
(concat " " todo
))
1061 (format " [#%s]" (char-to-string priority
)))
1062 (and title
(concat " " title
)))))
1067 ((zerop org-tags-column
) (format " %s" tags
))
1068 ((< org-tags-column
0)
1071 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1076 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1078 ;; Prefer degenerate inlinetasks when there are no
1083 (make-string level ?
*) " END")))))
1088 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1091 STRUCT is the structure of the plain list.
1093 Return a list whose CAR is `item' and CDR is a plist containing
1094 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1095 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1098 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1099 any, will not be parsed as a secondary string, but as a plain
1102 Assume point is at the beginning of the item."
1105 (looking-at org-list-full-item-re
)
1106 (let* ((begin (point))
1107 (bullet (org-match-string-no-properties 1))
1108 (checkbox (let ((box (org-match-string-no-properties 3)))
1109 (cond ((equal "[ ]" box
) 'off
)
1110 ((equal "[X]" box
) 'on
)
1111 ((equal "[-]" box
) 'trans
))))
1112 (counter (let ((c (org-match-string-no-properties 2)))
1116 ((string-match "[A-Za-z]" c
)
1117 (- (string-to-char (upcase (match-string 0 c
)))
1119 ((string-match "[0-9]+" c
)
1120 (string-to-number (match-string 0 c
)))))))
1121 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1122 (unless (bolp) (forward-line))
1126 ;; Ignore tags in un-ordered lists: they are just
1127 ;; a part of item's body.
1128 (if (and (match-beginning 4)
1129 (save-match-data (string-match "[.)]" bullet
)))
1132 (skip-chars-forward " \r\t\n" limit
)
1133 ;; If first line isn't empty, contents really start
1134 ;; at the text after item's meta-data.
1135 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1136 (contents-end (progn (goto-char end
)
1137 (skip-chars-backward " \r\t\n")
1142 (list :bullet bullet
1145 ;; CONTENTS-BEGIN and CONTENTS-END may be
1146 ;; mixed up in the case of an empty item
1147 ;; separated from the next by a blank line.
1148 ;; Thus ensure the former is always the
1150 :contents-begin
(min contents-begin contents-end
)
1151 :contents-end
(max contents-begin contents-end
)
1155 :post-blank
(count-lines contents-end end
)))))
1156 (org-element-put-property
1158 (let ((raw-tag (org-list-get-tag begin struct
)))
1160 (if raw-secondary-p raw-tag
1161 (org-element-parse-secondary-string
1162 raw-tag
(org-element-restriction 'item
) item
))))))))
1164 (defun org-element-item-interpreter (item contents
)
1165 "Interpret ITEM element as Org syntax.
1166 CONTENTS is the contents of the element."
1167 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1168 (org-list-bullet-string
1169 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1170 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1172 (checkbox (org-element-property :checkbox item
))
1173 (counter (org-element-property :counter item
))
1174 (tag (let ((tag (org-element-property :tag item
)))
1175 (and tag
(org-element-interpret-data tag
))))
1176 ;; Compute indentation.
1177 (ind (make-string (length bullet
) 32))
1178 (item-starts-with-par-p
1179 (eq (org-element-type (car (org-element-contents item
)))
1184 (and counter
(format "[@%d] " counter
))
1189 (and tag
(format "%s :: " tag
))
1191 (let ((contents (replace-regexp-in-string
1192 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1193 (if item-starts-with-par-p
(org-trim contents
)
1194 (concat "\n" contents
)))))))
1199 (defun org-element--list-struct (limit)
1200 ;; Return structure of list at point. Internal function. See
1201 ;; `org-list-struct' for details.
1202 (let ((case-fold-search t
)
1204 (item-re (org-item-re))
1205 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1211 ;; At limit: end all items.
1214 (let ((end (progn (skip-chars-backward " \r\t\n")
1217 (dolist (item items
(sort (nconc items struct
)
1218 'car-less-than-car
))
1219 (setcar (nthcdr 6 item
) end
)))))
1220 ;; At list end: end all items.
1221 ((looking-at org-list-end-re
)
1222 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1223 'car-less-than-car
))
1224 (setcar (nthcdr 6 item
) (point)))))
1225 ;; At a new item: end previous sibling.
1226 ((looking-at item-re
)
1227 (let ((ind (save-excursion (skip-chars-forward " \t")
1229 (setq top-ind
(min top-ind ind
))
1230 (while (and items
(<= ind
(nth 1 (car items
))))
1231 (let ((item (pop items
)))
1232 (setcar (nthcdr 6 item
) (point))
1233 (push item struct
)))
1234 (push (progn (looking-at org-list-full-item-re
)
1235 (let ((bullet (match-string-no-properties 1)))
1239 (match-string-no-properties 2) ; counter
1240 (match-string-no-properties 3) ; checkbox
1242 (and (save-match-data
1243 (string-match "[-+*]" bullet
))
1244 (match-string-no-properties 4))
1245 ;; Ending position, unknown so far.
1249 ;; Skip empty lines.
1250 ((looking-at "^[ \t]*$") (forward-line))
1251 ;; Skip inline tasks and blank lines along the way.
1252 ((and inlinetask-re
(looking-at inlinetask-re
))
1254 (let ((origin (point)))
1255 (when (re-search-forward inlinetask-re limit t
)
1256 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1257 (goto-char origin
)))))
1258 ;; At some text line. Check if it ends any previous item.
1260 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1261 (when (<= ind top-ind
)
1262 (skip-chars-backward " \r\t\n")
1264 (while (<= ind
(nth 1 (car items
)))
1265 (let ((item (pop items
)))
1266 (setcar (nthcdr 6 item
) (line-beginning-position))
1269 (throw 'exit
(sort struct
'car-less-than-car
))))))
1270 ;; Skip blocks (any type) and drawers contents.
1272 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1274 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1276 ((and (looking-at org-drawer-regexp
)
1277 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1278 (forward-line))))))))
1280 (defun org-element-plain-list-parser (limit affiliated structure
)
1281 "Parse a plain list.
1283 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1284 the buffer position at the beginning of the first affiliated
1285 keyword and CDR is a plist of affiliated keywords along with
1286 their value. STRUCTURE is the structure of the plain list being
1289 Return a list whose CAR is `plain-list' and CDR is a plist
1290 containing `:type', `:begin', `:end', `:contents-begin' and
1291 `:contents-end', `:structure', `:post-blank' and
1292 `:post-affiliated' keywords.
1294 Assume point is at the beginning of the list."
1296 (let* ((struct (or structure
(org-element--list-struct limit
)))
1297 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1298 ((nth 5 (assq (point) struct
)) 'descriptive
)
1300 (contents-begin (point))
1301 (begin (car affiliated
))
1302 (contents-end (let* ((item (assq contents-begin struct
))
1305 (while (and (setq item
(assq pos struct
))
1306 (= (nth 1 item
) ind
))
1307 (setq pos
(nth 6 item
)))
1309 (end (progn (goto-char contents-end
)
1310 (skip-chars-forward " \r\t\n" limit
)
1311 (if (= (point) limit
) limit
(line-beginning-position)))))
1318 :contents-begin contents-begin
1319 :contents-end contents-end
1321 :post-blank
(count-lines contents-end end
)
1322 :post-affiliated contents-begin
)
1323 (cdr affiliated
))))))
1325 (defun org-element-plain-list-interpreter (plain-list contents
)
1326 "Interpret PLAIN-LIST element as Org syntax.
1327 CONTENTS is the contents of the element."
1330 (goto-char (point-min))
1335 ;;;; Property Drawer
1337 (defun org-element-property-drawer-parser (limit affiliated
)
1338 "Parse a property drawer.
1340 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1341 the buffer position at the beginning of the first affiliated
1342 keyword and CDR is a plist of affiliated keywords along with
1345 Return a list whose CAR is `property-drawer' and CDR is a plist
1346 containing `:begin', `:end', `:contents-begin', `:contents-end',
1347 `:post-blank' and `:post-affiliated' keywords.
1349 Assume point is at the beginning of the property drawer."
1351 (let ((case-fold-search t
))
1352 (if (not (save-excursion
1353 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1354 ;; Incomplete drawer: parse it as a paragraph.
1355 (org-element-paragraph-parser limit affiliated
)
1357 (let* ((drawer-end-line (match-beginning 0))
1358 (begin (car affiliated
))
1359 (post-affiliated (point))
1360 (contents-begin (progn (forward-line)
1361 (and (< (point) drawer-end-line
)
1363 (contents-end (and contents-begin drawer-end-line
))
1364 (pos-before-blank (progn (goto-char drawer-end-line
)
1367 (end (progn (skip-chars-forward " \r\t\n" limit
)
1368 (if (eobp) (point) (line-beginning-position)))))
1369 (list 'property-drawer
1373 :contents-begin contents-begin
1374 :contents-end contents-end
1375 :post-blank
(count-lines pos-before-blank end
)
1376 :post-affiliated post-affiliated
)
1377 (cdr affiliated
)))))))))
1379 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1380 "Interpret PROPERTY-DRAWER element as Org syntax.
1381 CONTENTS is the properties within the drawer."
1382 (format ":PROPERTIES:\n%s:END:" contents
))
1387 (defun org-element-quote-block-parser (limit affiliated
)
1388 "Parse a quote block.
1390 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1391 the buffer position at the beginning of the first affiliated
1392 keyword and CDR is a plist of affiliated keywords along with
1395 Return a list whose CAR is `quote-block' and CDR is a plist
1396 containing `:begin', `:end', `:contents-begin', `:contents-end',
1397 `:post-blank' and `:post-affiliated' keywords.
1399 Assume point is at the beginning of the block."
1400 (let ((case-fold-search t
))
1401 (if (not (save-excursion
1402 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1403 ;; Incomplete block: parse it as a paragraph.
1404 (org-element-paragraph-parser limit affiliated
)
1405 (let ((block-end-line (match-beginning 0)))
1407 (let* ((begin (car affiliated
))
1408 (post-affiliated (point))
1409 ;; Empty blocks have no contents.
1410 (contents-begin (progn (forward-line)
1411 (and (< (point) block-end-line
)
1413 (contents-end (and contents-begin block-end-line
))
1414 (pos-before-blank (progn (goto-char block-end-line
)
1417 (end (progn (skip-chars-forward " \r\t\n" limit
)
1418 (if (eobp) (point) (line-beginning-position)))))
1423 :contents-begin contents-begin
1424 :contents-end contents-end
1425 :post-blank
(count-lines pos-before-blank end
)
1426 :post-affiliated post-affiliated
)
1427 (cdr affiliated
)))))))))
1429 (defun org-element-quote-block-interpreter (quote-block contents
)
1430 "Interpret QUOTE-BLOCK element as Org syntax.
1431 CONTENTS is the contents of the element."
1432 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1437 (defun org-element-section-parser (limit)
1440 LIMIT bounds the search.
1442 Return a list whose CAR is `section' and CDR is a plist
1443 containing `:begin', `:end', `:contents-begin', `contents-end'
1444 and `:post-blank' keywords."
1446 ;; Beginning of section is the beginning of the first non-blank
1447 ;; line after previous headline.
1448 (let ((begin (point))
1449 (end (progn (org-with-limited-levels (outline-next-heading))
1451 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1457 :contents-begin begin
1458 :contents-end pos-before-blank
1459 :post-blank
(count-lines pos-before-blank end
))))))
1461 (defun org-element-section-interpreter (section contents
)
1462 "Interpret SECTION element as Org syntax.
1463 CONTENTS is the contents of the element."
1469 (defun org-element-special-block-parser (limit affiliated
)
1470 "Parse a special block.
1472 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1473 the buffer position at the beginning of the first affiliated
1474 keyword and CDR is a plist of affiliated keywords along with
1477 Return a list whose CAR is `special-block' and CDR is a plist
1478 containing `:type', `:begin', `:end', `:contents-begin',
1479 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1481 Assume point is at the beginning of the block."
1482 (let* ((case-fold-search t
)
1483 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1484 (upcase (match-string-no-properties 1)))))
1485 (if (not (save-excursion
1487 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1489 ;; Incomplete block: parse it as a paragraph.
1490 (org-element-paragraph-parser limit affiliated
)
1491 (let ((block-end-line (match-beginning 0)))
1493 (let* ((begin (car affiliated
))
1494 (post-affiliated (point))
1495 ;; Empty blocks have no contents.
1496 (contents-begin (progn (forward-line)
1497 (and (< (point) block-end-line
)
1499 (contents-end (and contents-begin block-end-line
))
1500 (pos-before-blank (progn (goto-char block-end-line
)
1503 (end (progn (skip-chars-forward " \r\t\n" limit
)
1504 (if (eobp) (point) (line-beginning-position)))))
1505 (list 'special-block
1510 :contents-begin contents-begin
1511 :contents-end contents-end
1512 :post-blank
(count-lines pos-before-blank end
)
1513 :post-affiliated post-affiliated
)
1514 (cdr affiliated
)))))))))
1516 (defun org-element-special-block-interpreter (special-block contents
)
1517 "Interpret SPECIAL-BLOCK element as Org syntax.
1518 CONTENTS is the contents of the element."
1519 (let ((block-type (org-element-property :type special-block
)))
1520 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1526 ;; For each element, a parser and an interpreter are also defined.
1527 ;; Both follow the same naming convention used for greater elements.
1529 ;; Also, as for greater elements, adding a new element type is done
1530 ;; through the following steps: implement a parser and an interpreter,
1531 ;; tweak `org-element--current-element' so that it recognizes the new
1532 ;; type and add that new type to `org-element-all-elements'.
1534 ;; As a special case, when the newly defined type is a block type,
1535 ;; `org-element-block-name-alist' has to be modified accordingly.
1540 (defun org-element-babel-call-parser (limit affiliated
)
1541 "Parse a babel call.
1543 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1544 the buffer position at the beginning of the first affiliated
1545 keyword and CDR is a plist of affiliated keywords along with
1548 Return a list whose CAR is `babel-call' and CDR is a plist
1549 containing `:begin', `:end', `:value', `:post-blank' and
1550 `:post-affiliated' as keywords."
1552 (let ((begin (car affiliated
))
1553 (post-affiliated (point))
1554 (value (progn (let ((case-fold-search t
))
1555 (re-search-forward "call:[ \t]*" nil t
))
1556 (buffer-substring-no-properties (point)
1557 (line-end-position))))
1558 (pos-before-blank (progn (forward-line) (point)))
1559 (end (progn (skip-chars-forward " \r\t\n" limit
)
1560 (if (eobp) (point) (line-beginning-position)))))
1566 :post-blank
(count-lines pos-before-blank end
)
1567 :post-affiliated post-affiliated
)
1568 (cdr affiliated
))))))
1570 (defun org-element-babel-call-interpreter (babel-call contents
)
1571 "Interpret BABEL-CALL element as Org syntax.
1573 (concat "#+CALL: " (org-element-property :value babel-call
)))
1578 (defun org-element-clock-parser (limit)
1581 LIMIT bounds the search.
1583 Return a list whose CAR is `clock' and CDR is a plist containing
1584 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1587 (let* ((case-fold-search nil
)
1589 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1590 (skip-chars-forward " \t")
1591 (org-element-timestamp-parser)))
1592 (duration (and (search-forward " => " (line-end-position) t
)
1593 (progn (skip-chars-forward " \t")
1594 (looking-at "\\(\\S-+\\)[ \t]*$"))
1595 (org-match-string-no-properties 1)))
1596 (status (if duration
'closed
'running
))
1597 (post-blank (let ((before-blank (progn (forward-line) (point))))
1598 (skip-chars-forward " \r\t\n" limit
)
1599 (skip-chars-backward " \t")
1600 (unless (bolp) (end-of-line))
1601 (count-lines before-blank
(point))))
1604 (list :status status
1609 :post-blank post-blank
)))))
1611 (defun org-element-clock-interpreter (clock contents
)
1612 "Interpret CLOCK element as Org syntax.
1614 (concat org-clock-string
" "
1615 (org-element-timestamp-interpreter
1616 (org-element-property :value clock
) nil
)
1617 (let ((duration (org-element-property :duration clock
)))
1622 (org-split-string duration
":")))))))
1627 (defun org-element-comment-parser (limit affiliated
)
1630 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1631 the buffer position at the beginning of the first affiliated
1632 keyword and CDR is a plist of affiliated keywords along with
1635 Return a list whose CAR is `comment' and CDR is a plist
1636 containing `:begin', `:end', `:value', `:post-blank',
1637 `:post-affiliated' keywords.
1639 Assume point is at comment beginning."
1641 (let* ((begin (car affiliated
))
1642 (post-affiliated (point))
1643 (value (prog2 (looking-at "[ \t]*# ?")
1644 (buffer-substring-no-properties
1645 (match-end 0) (line-end-position))
1648 ;; Get comments ending.
1650 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1651 ;; Accumulate lines without leading hash and first
1656 (buffer-substring-no-properties
1657 (match-end 0) (line-end-position))))
1660 (end (progn (goto-char com-end
)
1661 (skip-chars-forward " \r\t\n" limit
)
1662 (if (eobp) (point) (line-beginning-position)))))
1668 :post-blank
(count-lines com-end end
)
1669 :post-affiliated post-affiliated
)
1670 (cdr affiliated
))))))
1672 (defun org-element-comment-interpreter (comment contents
)
1673 "Interpret COMMENT element as Org syntax.
1675 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1680 (defun org-element-comment-block-parser (limit affiliated
)
1681 "Parse an export block.
1683 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1684 the buffer position at the beginning of the first affiliated
1685 keyword and CDR is a plist of affiliated keywords along with
1688 Return a list whose CAR is `comment-block' and CDR is a plist
1689 containing `:begin', `:end', `:value', `:post-blank' and
1690 `:post-affiliated' keywords.
1692 Assume point is at comment block beginning."
1693 (let ((case-fold-search t
))
1694 (if (not (save-excursion
1695 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1696 ;; Incomplete block: parse it as a paragraph.
1697 (org-element-paragraph-parser limit affiliated
)
1698 (let ((contents-end (match-beginning 0)))
1700 (let* ((begin (car affiliated
))
1701 (post-affiliated (point))
1702 (contents-begin (progn (forward-line) (point)))
1703 (pos-before-blank (progn (goto-char contents-end
)
1706 (end (progn (skip-chars-forward " \r\t\n" limit
)
1707 (if (eobp) (point) (line-beginning-position))))
1708 (value (buffer-substring-no-properties
1709 contents-begin contents-end
)))
1710 (list 'comment-block
1715 :post-blank
(count-lines pos-before-blank end
)
1716 :post-affiliated post-affiliated
)
1717 (cdr affiliated
)))))))))
1719 (defun org-element-comment-block-interpreter (comment-block contents
)
1720 "Interpret COMMENT-BLOCK element as Org syntax.
1722 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1723 (org-remove-indentation (org-element-property :value comment-block
))))
1728 (defun org-element-diary-sexp-parser (limit affiliated
)
1729 "Parse a diary sexp.
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 `diary-sexp' and CDR is a plist
1737 containing `:begin', `:end', `:value', `:post-blank' and
1738 `:post-affiliated' keywords."
1740 (let ((begin (car affiliated
))
1741 (post-affiliated (point))
1742 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1743 (org-match-string-no-properties 1)))
1744 (pos-before-blank (progn (forward-line) (point)))
1745 (end (progn (skip-chars-forward " \r\t\n" limit
)
1746 (if (eobp) (point) (line-beginning-position)))))
1752 :post-blank
(count-lines pos-before-blank end
)
1753 :post-affiliated post-affiliated
)
1754 (cdr affiliated
))))))
1756 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1757 "Interpret DIARY-SEXP as Org syntax.
1759 (org-element-property :value diary-sexp
))
1764 (defun org-element-example-block-parser (limit affiliated
)
1765 "Parse an example block.
1767 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1768 the buffer position at the beginning of the first affiliated
1769 keyword and CDR is a plist of affiliated keywords along with
1772 Return a list whose CAR is `example-block' and CDR is a plist
1773 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1774 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1775 `:value', `:post-blank' and `:post-affiliated' keywords."
1776 (let ((case-fold-search t
))
1777 (if (not (save-excursion
1778 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1779 ;; Incomplete block: parse it as a paragraph.
1780 (org-element-paragraph-parser limit affiliated
)
1781 (let ((contents-end (match-beginning 0)))
1785 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1786 (org-match-string-no-properties 1)))
1787 ;; Switches analysis
1789 (cond ((not switches
) nil
)
1790 ((string-match "-n\\>" switches
) 'new
)
1791 ((string-match "+n\\>" switches
) 'continued
)))
1793 (and switches
(string-match "-i\\>" switches
)))
1794 ;; Should labels be retained in (or stripped from) example
1798 (not (string-match "-r\\>" switches
))
1799 (and number-lines
(string-match "-k\\>" switches
))))
1800 ;; What should code-references use - labels or
1805 (not (string-match "-k\\>" switches
)))))
1808 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1809 (match-string 1 switches
)))
1810 ;; Standard block parsing.
1811 (begin (car affiliated
))
1812 (post-affiliated (point))
1813 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1814 (contents-begin (progn (forward-line) (point)))
1815 (value (org-element-remove-indentation
1816 (org-unescape-code-in-string
1817 (buffer-substring-no-properties
1818 contents-begin contents-end
))
1820 (pos-before-blank (progn (goto-char contents-end
)
1823 (end (progn (skip-chars-forward " \r\t\n" limit
)
1824 (if (eobp) (point) (line-beginning-position)))))
1825 (list 'example-block
1831 :number-lines number-lines
1832 :preserve-indent preserve-indent
1833 :retain-labels retain-labels
1834 :use-labels use-labels
1835 :label-fmt label-fmt
1836 :post-blank
(count-lines pos-before-blank end
)
1837 :post-affiliated post-affiliated
)
1838 (cdr affiliated
)))))))))
1840 (defun org-element-example-block-interpreter (example-block contents
)
1841 "Interpret EXAMPLE-BLOCK element as Org syntax.
1843 (let ((switches (org-element-property :switches example-block
))
1844 (value (org-element-property :value example-block
)))
1845 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1846 (org-escape-code-in-string
1847 (if (or org-src-preserve-indentation
1848 (org-element-property :preserve-indent example-block
))
1850 (org-element-remove-indentation value
)))
1856 (defun org-element-export-block-parser (limit affiliated
)
1857 "Parse an export block.
1859 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1860 the buffer position at the beginning of the first affiliated
1861 keyword and CDR is a plist of affiliated keywords along with
1864 Return a list whose CAR is `export-block' and CDR is a plist
1865 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1866 `:post-affiliated' keywords.
1868 Assume point is at export-block beginning."
1869 (let* ((case-fold-search t
)
1870 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1871 (upcase (org-match-string-no-properties 1)))))
1872 (if (not (save-excursion
1874 (format "^[ \t]*#\\+END_%s[ \t]*$" type
) limit t
)))
1875 ;; Incomplete block: parse it as a paragraph.
1876 (org-element-paragraph-parser limit affiliated
)
1877 (let ((contents-end (match-beginning 0)))
1879 (let* ((begin (car affiliated
))
1880 (post-affiliated (point))
1881 (contents-begin (progn (forward-line) (point)))
1882 (pos-before-blank (progn (goto-char contents-end
)
1885 (end (progn (skip-chars-forward " \r\t\n" limit
)
1886 (if (eobp) (point) (line-beginning-position))))
1887 (value (buffer-substring-no-properties contents-begin
1895 :post-blank
(count-lines pos-before-blank end
)
1896 :post-affiliated post-affiliated
)
1897 (cdr affiliated
)))))))))
1899 (defun org-element-export-block-interpreter (export-block contents
)
1900 "Interpret EXPORT-BLOCK element as Org syntax.
1902 (let ((type (org-element-property :type export-block
)))
1903 (concat (format "#+BEGIN_%s\n" type
)
1904 (org-element-property :value export-block
)
1905 (format "#+END_%s" type
))))
1910 (defun org-element-fixed-width-parser (limit affiliated
)
1911 "Parse a fixed-width section.
1913 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1914 the buffer position at the beginning of the first affiliated
1915 keyword and CDR is a plist of affiliated keywords along with
1918 Return a list whose CAR is `fixed-width' and CDR is a plist
1919 containing `:begin', `:end', `:value', `:post-blank' and
1920 `:post-affiliated' keywords.
1922 Assume point is at the beginning of the fixed-width area."
1924 (let* ((begin (car affiliated
))
1925 (post-affiliated (point))
1929 (while (and (< (point) limit
)
1930 (looking-at "[ \t]*:\\( \\|$\\)"))
1931 ;; Accumulate text without starting colons.
1934 (buffer-substring-no-properties
1935 (match-end 0) (point-at-eol))
1939 (end (progn (skip-chars-forward " \r\t\n" limit
)
1940 (if (eobp) (point) (line-beginning-position)))))
1946 :post-blank
(count-lines end-area end
)
1947 :post-affiliated post-affiliated
)
1948 (cdr affiliated
))))))
1950 (defun org-element-fixed-width-interpreter (fixed-width contents
)
1951 "Interpret FIXED-WIDTH element as Org syntax.
1953 (let ((value (org-element-property :value fixed-width
)))
1955 (replace-regexp-in-string
1957 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
1960 ;;;; Horizontal Rule
1962 (defun org-element-horizontal-rule-parser (limit affiliated
)
1963 "Parse an horizontal rule.
1965 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1966 the buffer position at the beginning of the first affiliated
1967 keyword and CDR is a plist of affiliated keywords along with
1970 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1971 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1974 (let ((begin (car affiliated
))
1975 (post-affiliated (point))
1976 (post-hr (progn (forward-line) (point)))
1977 (end (progn (skip-chars-forward " \r\t\n" limit
)
1978 (if (eobp) (point) (line-beginning-position)))))
1979 (list 'horizontal-rule
1983 :post-blank
(count-lines post-hr end
)
1984 :post-affiliated post-affiliated
)
1985 (cdr affiliated
))))))
1987 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
1988 "Interpret HORIZONTAL-RULE element as Org syntax.
1995 (defun org-element-keyword-parser (limit affiliated
)
1996 "Parse a keyword at point.
1998 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1999 the buffer position at the beginning of the first affiliated
2000 keyword and CDR is a plist of affiliated keywords along with
2003 Return a list whose CAR is `keyword' and CDR is a plist
2004 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2005 `:post-affiliated' keywords."
2007 ;; An orphaned affiliated keyword is considered as a regular
2008 ;; keyword. In this case AFFILIATED is nil, so we take care of
2009 ;; this corner case.
2010 (let ((begin (or (car affiliated
) (point)))
2011 (post-affiliated (point))
2012 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2013 (upcase (org-match-string-no-properties 1))))
2014 (value (org-trim (buffer-substring-no-properties
2015 (match-end 0) (point-at-eol))))
2016 (pos-before-blank (progn (forward-line) (point)))
2017 (end (progn (skip-chars-forward " \r\t\n" limit
)
2018 (if (eobp) (point) (line-beginning-position)))))
2025 :post-blank
(count-lines pos-before-blank end
)
2026 :post-affiliated post-affiliated
)
2027 (cdr affiliated
))))))
2029 (defun org-element-keyword-interpreter (keyword contents
)
2030 "Interpret KEYWORD element as Org syntax.
2033 (org-element-property :key keyword
)
2034 (org-element-property :value keyword
)))
2037 ;;;; Latex Environment
2039 (defun org-element-latex-environment-parser (limit affiliated
)
2040 "Parse a LaTeX environment.
2042 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2043 the buffer position at the beginning of the first affiliated
2044 keyword and CDR is a plist of affiliated keywords along with
2047 Return a list whose CAR is `latex-environment' and CDR is a plist
2048 containing `:begin', `:end', `:value', `:post-blank' and
2049 `:post-affiliated' keywords.
2051 Assume point is at the beginning of the latex environment."
2053 (let ((case-fold-search t
)
2054 (code-begin (point)))
2055 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2056 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2057 (regexp-quote (match-string 1)))
2059 ;; Incomplete latex environment: parse it as a paragraph.
2060 (org-element-paragraph-parser limit affiliated
)
2061 (let* ((code-end (progn (forward-line) (point)))
2062 (begin (car affiliated
))
2063 (value (buffer-substring-no-properties code-begin code-end
))
2064 (end (progn (skip-chars-forward " \r\t\n" limit
)
2065 (if (eobp) (point) (line-beginning-position)))))
2066 (list 'latex-environment
2071 :post-blank
(count-lines code-end end
)
2072 :post-affiliated code-begin
)
2073 (cdr affiliated
))))))))
2075 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2076 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2078 (org-element-property :value latex-environment
))
2083 (defun org-element-node-property-parser (limit)
2084 "Parse a node-property at point.
2086 LIMIT bounds the search.
2088 Return a list whose CAR is `node-property' and CDR is a plist
2089 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2092 (looking-at org-property-re
)
2093 (let ((case-fold-search t
)
2095 (key (org-match-string-no-properties 2))
2096 (value (org-match-string-no-properties 3))
2097 (pos-before-blank (progn (forward-line) (point)))
2098 (end (progn (skip-chars-forward " \r\t\n" limit
)
2099 (if (eobp) (point) (point-at-bol)))))
2100 (list 'node-property
2105 :post-blank
(count-lines pos-before-blank end
))))))
2107 (defun org-element-node-property-interpreter (node-property contents
)
2108 "Interpret NODE-PROPERTY element as Org syntax.
2110 (format org-property-format
2111 (format ":%s:" (org-element-property :key node-property
))
2112 (org-element-property :value node-property
)))
2117 (defun org-element-paragraph-parser (limit affiliated
)
2120 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2121 the buffer position at the beginning of the first affiliated
2122 keyword and CDR is a plist of affiliated keywords along with
2125 Return a list whose CAR is `paragraph' and CDR is a plist
2126 containing `:begin', `:end', `:contents-begin' and
2127 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2129 Assume point is at the beginning of the paragraph."
2131 (let* ((begin (car affiliated
))
2132 (contents-begin (point))
2134 (let ((case-fold-search t
))
2136 (if (not (re-search-forward
2137 org-element-paragraph-separate limit
'm
))
2139 ;; A matching `org-element-paragraph-separate' is not
2140 ;; necessarily the end of the paragraph. In
2141 ;; particular, lines starting with # or : as a first
2142 ;; non-space character are ambiguous. We have to
2143 ;; check if they are valid Org syntax (e.g., not an
2144 ;; incomplete keyword).
2148 ;; There's no ambiguity for other symbols or
2149 ;; empty lines: stop here.
2150 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2151 ;; Stop at valid fixed-width areas.
2152 (looking-at "[ \t]*:\\(?: \\|$\\)")
2154 (and (looking-at org-drawer-regexp
)
2157 "^[ \t]*:END:[ \t]*$" limit t
)))
2158 ;; Stop at valid comments.
2159 (looking-at "[ \t]*#\\(?: \\|$\\)")
2160 ;; Stop at valid dynamic blocks.
2161 (and (looking-at org-dblock-start-re
)
2164 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2165 ;; Stop at valid blocks.
2166 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2169 (format "^[ \t]*#\\+END_%s[ \t]*$"
2171 (org-match-string-no-properties 1)))
2173 ;; Stop at valid latex environments.
2175 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2178 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2180 (org-match-string-no-properties 1)))
2182 ;; Stop at valid keywords.
2183 (looking-at "[ \t]*#\\+\\S-+:")
2184 ;; Skip everything else.
2188 (re-search-forward org-element-paragraph-separate
2190 (beginning-of-line)))
2191 (if (= (point) limit
) limit
2192 (goto-char (line-beginning-position)))))
2193 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2196 (end (progn (skip-chars-forward " \r\t\n" limit
)
2197 (if (eobp) (point) (line-beginning-position)))))
2202 :contents-begin contents-begin
2203 :contents-end contents-end
2204 :post-blank
(count-lines before-blank end
)
2205 :post-affiliated contents-begin
)
2206 (cdr affiliated
))))))
2208 (defun org-element-paragraph-interpreter (paragraph contents
)
2209 "Interpret PARAGRAPH element as Org syntax.
2210 CONTENTS is the contents of the element."
2216 (defun org-element-planning-parser (limit)
2219 LIMIT bounds the search.
2221 Return a list whose CAR is `planning' and CDR is a plist
2222 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2223 and `:post-blank' keywords."
2225 (let* ((case-fold-search nil
)
2227 (post-blank (let ((before-blank (progn (forward-line) (point))))
2228 (skip-chars-forward " \r\t\n" limit
)
2229 (skip-chars-backward " \t")
2230 (unless (bolp) (end-of-line))
2231 (count-lines before-blank
(point))))
2233 closed deadline scheduled
)
2235 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2236 (goto-char (match-end 1))
2237 (skip-chars-forward " \t" end
)
2238 (let ((keyword (match-string 1))
2239 (time (org-element-timestamp-parser)))
2240 (cond ((equal keyword org-closed-string
) (setq closed time
))
2241 ((equal keyword org-deadline-string
) (setq deadline time
))
2242 (t (setq scheduled time
)))))
2244 (list :closed closed
2246 :scheduled scheduled
2249 :post-blank post-blank
)))))
2251 (defun org-element-planning-interpreter (planning contents
)
2252 "Interpret PLANNING element as Org syntax.
2257 (list (let ((deadline (org-element-property :deadline planning
)))
2259 (concat org-deadline-string
" "
2260 (org-element-timestamp-interpreter deadline nil
))))
2261 (let ((scheduled (org-element-property :scheduled planning
)))
2263 (concat org-scheduled-string
" "
2264 (org-element-timestamp-interpreter scheduled nil
))))
2265 (let ((closed (org-element-property :closed planning
)))
2267 (concat org-closed-string
" "
2268 (org-element-timestamp-interpreter closed nil
))))))
2274 (defun org-element-src-block-parser (limit affiliated
)
2277 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2278 the buffer position at the beginning of the first affiliated
2279 keyword and CDR is a plist of affiliated keywords along with
2282 Return a list whose CAR is `src-block' and CDR is a plist
2283 containing `:language', `:switches', `:parameters', `:begin',
2284 `:end', `:number-lines', `:retain-labels', `:use-labels',
2285 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2286 `:post-affiliated' keywords.
2288 Assume point is at the beginning of the block."
2289 (let ((case-fold-search t
))
2290 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2292 ;; Incomplete block: parse it as a paragraph.
2293 (org-element-paragraph-parser limit affiliated
)
2294 (let ((contents-end (match-beginning 0)))
2296 (let* ((begin (car affiliated
))
2297 (post-affiliated (point))
2298 ;; Get language as a string.
2302 (concat "^[ \t]*#\\+BEGIN_SRC"
2303 "\\(?: +\\(\\S-+\\)\\)?"
2304 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2306 (org-match-string-no-properties 1)))
2308 (switches (org-match-string-no-properties 2))
2310 (parameters (org-match-string-no-properties 3))
2311 ;; Switches analysis
2313 (cond ((not switches
) nil
)
2314 ((string-match "-n\\>" switches
) 'new
)
2315 ((string-match "+n\\>" switches
) 'continued
)))
2316 (preserve-indent (and switches
2317 (string-match "-i\\>" switches
)))
2320 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2321 (match-string 1 switches
)))
2322 ;; Should labels be retained in (or stripped from)
2326 (not (string-match "-r\\>" switches
))
2327 (and number-lines
(string-match "-k\\>" switches
))))
2328 ;; What should code-references use - labels or
2333 (not (string-match "-k\\>" switches
)))))
2335 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2337 (value (org-element-remove-indentation
2338 (org-unescape-code-in-string
2339 (buffer-substring-no-properties
2340 (progn (forward-line) (point)) contents-end
))
2342 (pos-before-blank (progn (goto-char contents-end
)
2345 ;; Get position after ending blank lines.
2346 (end (progn (skip-chars-forward " \r\t\n" limit
)
2347 (if (eobp) (point) (line-beginning-position)))))
2350 (list :language language
2351 :switches
(and (org-string-nw-p switches
)
2352 (org-trim switches
))
2353 :parameters
(and (org-string-nw-p parameters
)
2354 (org-trim parameters
))
2357 :number-lines number-lines
2358 :preserve-indent preserve-indent
2359 :retain-labels retain-labels
2360 :use-labels use-labels
2361 :label-fmt label-fmt
2363 :post-blank
(count-lines pos-before-blank end
)
2364 :post-affiliated post-affiliated
)
2365 (cdr affiliated
)))))))))
2367 (defun org-element-src-block-interpreter (src-block contents
)
2368 "Interpret SRC-BLOCK element as Org syntax.
2370 (let ((lang (org-element-property :language src-block
))
2371 (switches (org-element-property :switches src-block
))
2372 (params (org-element-property :parameters src-block
))
2374 (let ((val (org-element-property :value src-block
)))
2376 ((or org-src-preserve-indentation
2377 (org-element-property :preserve-indent src-block
))
2379 ((zerop org-edit-src-content-indentation
) val
)
2381 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2382 (replace-regexp-in-string
2383 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2384 (concat (format "#+BEGIN_SRC%s\n"
2385 (concat (and lang
(concat " " lang
))
2386 (and switches
(concat " " switches
))
2387 (and params
(concat " " params
))))
2388 (org-escape-code-in-string value
)
2394 (defun org-element-table-parser (limit affiliated
)
2395 "Parse a table at point.
2397 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2398 the buffer position at the beginning of the first affiliated
2399 keyword and CDR is a plist of affiliated keywords along with
2402 Return a list whose CAR is `table' and CDR is a plist containing
2403 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2404 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2407 Assume point is at the beginning of the table."
2409 (let* ((case-fold-search t
)
2410 (table-begin (point))
2411 (type (if (org-at-table.el-p
) 'table.el
'org
))
2412 (begin (car affiliated
))
2414 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2415 (goto-char (match-beginning 0))
2418 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2419 (push (org-match-string-no-properties 1) acc
)
2422 (pos-before-blank (point))
2423 (end (progn (skip-chars-forward " \r\t\n" limit
)
2424 (if (eobp) (point) (line-beginning-position)))))
2431 ;; Only `org' tables have contents. `table.el' tables
2432 ;; use a `:value' property to store raw table as
2434 :contents-begin
(and (eq type
'org
) table-begin
)
2435 :contents-end
(and (eq type
'org
) table-end
)
2436 :value
(and (eq type
'table.el
)
2437 (buffer-substring-no-properties
2438 table-begin table-end
))
2439 :post-blank
(count-lines pos-before-blank end
)
2440 :post-affiliated table-begin
)
2441 (cdr affiliated
))))))
2443 (defun org-element-table-interpreter (table contents
)
2444 "Interpret TABLE element as Org syntax.
2446 (if (eq (org-element-property :type table
) 'table.el
)
2447 (org-remove-indentation (org-element-property :value table
))
2448 (concat (with-temp-buffer (insert contents
)
2451 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2452 (reverse (org-element-property :tblfm table
))
2458 (defun org-element-table-row-parser (limit)
2459 "Parse table row at point.
2461 LIMIT bounds the search.
2463 Return a list whose CAR is `table-row' and CDR is a plist
2464 containing `:begin', `:end', `:contents-begin', `:contents-end',
2465 `:type' and `:post-blank' keywords."
2467 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2469 ;; A table rule has no contents. In that case, ensure
2470 ;; CONTENTS-BEGIN matches CONTENTS-END.
2471 (contents-begin (and (eq type
'standard
)
2472 (search-forward "|")
2474 (contents-end (and (eq type
'standard
)
2477 (skip-chars-backward " \t")
2479 (end (progn (forward-line) (point))))
2484 :contents-begin contents-begin
2485 :contents-end contents-end
2488 (defun org-element-table-row-interpreter (table-row contents
)
2489 "Interpret TABLE-ROW element as Org syntax.
2490 CONTENTS is the contents of the table row."
2491 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2492 (concat "| " contents
)))
2497 (defun org-element-verse-block-parser (limit affiliated
)
2498 "Parse a verse block.
2500 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2501 the buffer position at the beginning of the first affiliated
2502 keyword and CDR is a plist of affiliated keywords along with
2505 Return a list whose CAR is `verse-block' and CDR is a plist
2506 containing `:begin', `:end', `:contents-begin', `:contents-end',
2507 `:post-blank' and `:post-affiliated' keywords.
2509 Assume point is at beginning of the block."
2510 (let ((case-fold-search t
))
2511 (if (not (save-excursion
2512 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2513 ;; Incomplete block: parse it as a paragraph.
2514 (org-element-paragraph-parser limit affiliated
)
2515 (let ((contents-end (match-beginning 0)))
2517 (let* ((begin (car affiliated
))
2518 (post-affiliated (point))
2519 (contents-begin (progn (forward-line) (point)))
2520 (pos-before-blank (progn (goto-char contents-end
)
2523 (end (progn (skip-chars-forward " \r\t\n" limit
)
2524 (if (eobp) (point) (line-beginning-position)))))
2529 :contents-begin contents-begin
2530 :contents-end contents-end
2531 :post-blank
(count-lines pos-before-blank end
)
2532 :post-affiliated post-affiliated
)
2533 (cdr affiliated
)))))))))
2535 (defun org-element-verse-block-interpreter (verse-block contents
)
2536 "Interpret VERSE-BLOCK element as Org syntax.
2537 CONTENTS is verse block contents."
2538 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2544 ;; Unlike to elements, raw text can be found between objects. Hence,
2545 ;; `org-element--object-lex' is provided to find the next object in
2548 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2549 ;; object types they can contain will be specified in
2550 ;; `org-element-object-restrictions'.
2552 ;; Creating a new type of object requires to alter
2553 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2554 ;; new type in `org-element-all-objects', and possibly add
2555 ;; restrictions in `org-element-object-restrictions'.
2559 (defun org-element-bold-parser ()
2560 "Parse bold object at point, if any.
2562 When at a bold object, return a list whose car is `bold' and cdr
2563 is a plist with `:begin', `:end', `:contents-begin' and
2564 `:contents-end' and `:post-blank' keywords. Otherwise, return
2567 Assume point is at the first star marker."
2569 (unless (bolp) (backward-char 1))
2570 (when (looking-at org-emph-re
)
2571 (let ((begin (match-beginning 2))
2572 (contents-begin (match-beginning 4))
2573 (contents-end (match-end 4))
2574 (post-blank (progn (goto-char (match-end 2))
2575 (skip-chars-forward " \t")))
2580 :contents-begin contents-begin
2581 :contents-end contents-end
2582 :post-blank post-blank
))))))
2584 (defun org-element-bold-interpreter (bold contents
)
2585 "Interpret BOLD object as Org syntax.
2586 CONTENTS is the contents of the object."
2587 (format "*%s*" contents
))
2592 (defun org-element-code-parser ()
2593 "Parse code object at point, if any.
2595 When at a code object, return a list whose car is `code' and cdr
2596 is a plist with `:value', `:begin', `:end' and `:post-blank'
2597 keywords. Otherwise, return nil.
2599 Assume point is at the first tilde marker."
2601 (unless (bolp) (backward-char 1))
2602 (when (looking-at org-emph-re
)
2603 (let ((begin (match-beginning 2))
2604 (value (org-match-string-no-properties 4))
2605 (post-blank (progn (goto-char (match-end 2))
2606 (skip-chars-forward " \t")))
2612 :post-blank post-blank
))))))
2614 (defun org-element-code-interpreter (code contents
)
2615 "Interpret CODE object as Org syntax.
2617 (format "~%s~" (org-element-property :value code
)))
2622 (defun org-element-entity-parser ()
2623 "Parse entity at point, if any.
2625 When at an entity, return a list whose car is `entity' and cdr
2626 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2627 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2628 `:post-blank' as keywords. Otherwise, return nil.
2630 Assume point is at the beginning of the entity."
2632 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2634 (let* ((value (or (org-entity-get (match-string 1))
2635 (throw 'no-object nil
)))
2636 (begin (match-beginning 0))
2637 (bracketsp (string= (match-string 2) "{}"))
2638 (post-blank (progn (goto-char (match-end 1))
2639 (when bracketsp
(forward-char 2))
2640 (skip-chars-forward " \t")))
2643 (list :name
(car value
)
2644 :latex
(nth 1 value
)
2645 :latex-math-p
(nth 2 value
)
2647 :ascii
(nth 4 value
)
2648 :latin1
(nth 5 value
)
2649 :utf-8
(nth 6 value
)
2652 :use-brackets-p bracketsp
2653 :post-blank post-blank
)))))))
2655 (defun org-element-entity-interpreter (entity contents
)
2656 "Interpret ENTITY object as Org syntax.
2659 (org-element-property :name entity
)
2660 (when (org-element-property :use-brackets-p entity
) "{}")))
2665 (defun org-element-export-snippet-parser ()
2666 "Parse export snippet at point.
2668 When at an export snippet, return a list whose car is
2669 `export-snippet' and cdr a plist with `:begin', `:end',
2670 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2673 Assume point is at the beginning of the snippet."
2676 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2678 (save-match-data (goto-char (match-end 0))
2679 (re-search-forward "@@" nil t
)
2680 (match-beginning 0))))
2681 (let* ((begin (match-beginning 0))
2682 (back-end (org-match-string-no-properties 1))
2683 (value (buffer-substring-no-properties
2684 (match-end 0) contents-end
))
2685 (post-blank (skip-chars-forward " \t"))
2687 (list 'export-snippet
2688 (list :back-end back-end
2692 :post-blank post-blank
)))))))
2694 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2695 "Interpret EXPORT-SNIPPET object as Org syntax.
2698 (org-element-property :back-end export-snippet
)
2699 (org-element-property :value export-snippet
)))
2702 ;;;; Footnote Reference
2704 (defun org-element-footnote-reference-parser ()
2705 "Parse footnote reference at point, if any.
2707 When at a footnote reference, return a list whose car is
2708 `footnote-reference' and cdr a plist with `:label', `:type',
2709 `:inline-definition', `:begin', `:end' and `:post-blank' as
2710 keywords. Otherwise, return nil."
2712 (when (looking-at org-footnote-re
)
2714 (let* ((begin (point))
2715 (label (or (org-match-string-no-properties 2)
2716 (org-match-string-no-properties 3)
2717 (and (match-string 1)
2718 (concat "fn:" (org-match-string-no-properties 1)))))
2719 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2720 (inner-begin (match-end 0))
2724 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2725 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2726 (unless (zerop count
) (throw 'no-object nil
))
2728 (post-blank (progn (goto-char (1+ inner-end
))
2729 (skip-chars-forward " \t")))
2732 (list 'footnote-reference
2737 :post-blank post-blank
))))
2738 (org-element-put-property
2739 footnote-reference
:inline-definition
2740 (and (eq type
'inline
)
2741 (org-element-parse-secondary-string
2742 (buffer-substring inner-begin inner-end
)
2743 (org-element-restriction 'footnote-reference
)
2744 footnote-reference
))))))))
2746 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2747 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2749 (let ((label (or (org-element-property :label footnote-reference
) "fn:"))
2752 (org-element-property :inline-definition footnote-reference
)))
2753 (if (not inline-def
) ""
2754 (concat ":" (org-element-interpret-data inline-def
))))))
2755 (format "[%s]" (concat label def
))))
2758 ;;;; Inline Babel Call
2760 (defun org-element-inline-babel-call-parser ()
2761 "Parse inline babel call at point, if any.
2763 When at an inline babel call, return a list whose car is
2764 `inline-babel-call' and cdr a plist with `:begin', `:end',
2765 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2767 Assume point is at the beginning of the babel call."
2769 (unless (bolp) (backward-char))
2770 (when (let ((case-fold-search t
))
2771 (looking-at org-babel-inline-lob-one-liner-regexp
))
2772 (let ((begin (match-end 1))
2773 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2774 (post-blank (progn (goto-char (match-end 0))
2775 (skip-chars-forward " \t")))
2777 (list 'inline-babel-call
2781 :post-blank post-blank
))))))
2783 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2784 "Interpret INLINE-BABEL-CALL object as Org syntax.
2786 (org-element-property :value inline-babel-call
))
2789 ;;;; Inline Src Block
2791 (defun org-element-inline-src-block-parser ()
2792 "Parse inline source block at point, if any.
2794 When at an inline source block, return a list whose car is
2795 `inline-src-block' and cdr a plist with `:begin', `:end',
2796 `:language', `:value', `:parameters' and `:post-blank' as
2797 keywords. Otherwise, return nil.
2799 Assume point is at the beginning of the inline src block."
2801 (unless (bolp) (backward-char))
2802 (when (looking-at org-babel-inline-src-block-regexp
)
2803 (let ((begin (match-beginning 1))
2804 (language (org-match-string-no-properties 2))
2805 (parameters (org-match-string-no-properties 4))
2806 (value (org-match-string-no-properties 5))
2807 (post-blank (progn (goto-char (match-end 0))
2808 (skip-chars-forward " \t")))
2810 (list 'inline-src-block
2811 (list :language language
2813 :parameters parameters
2816 :post-blank post-blank
))))))
2818 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2819 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2821 (let ((language (org-element-property :language inline-src-block
))
2822 (arguments (org-element-property :parameters inline-src-block
))
2823 (body (org-element-property :value inline-src-block
)))
2824 (format "src_%s%s{%s}"
2826 (if arguments
(format "[%s]" arguments
) "")
2831 (defun org-element-italic-parser ()
2832 "Parse italic object at point, if any.
2834 When at an italic object, return a list whose car is `italic' and
2835 cdr is a plist with `:begin', `:end', `:contents-begin' and
2836 `:contents-end' and `:post-blank' keywords. Otherwise, return
2839 Assume point is at the first slash marker."
2841 (unless (bolp) (backward-char 1))
2842 (when (looking-at org-emph-re
)
2843 (let ((begin (match-beginning 2))
2844 (contents-begin (match-beginning 4))
2845 (contents-end (match-end 4))
2846 (post-blank (progn (goto-char (match-end 2))
2847 (skip-chars-forward " \t")))
2852 :contents-begin contents-begin
2853 :contents-end contents-end
2854 :post-blank post-blank
))))))
2856 (defun org-element-italic-interpreter (italic contents
)
2857 "Interpret ITALIC object as Org syntax.
2858 CONTENTS is the contents of the object."
2859 (format "/%s/" contents
))
2864 (defun org-element-latex-fragment-parser ()
2865 "Parse LaTeX fragment at point, if any.
2867 When at a LaTeX fragment, return a list whose car is
2868 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2869 and `:post-blank' as keywords. Otherwise, return nil.
2871 Assume point is at the beginning of the LaTeX fragment."
2874 (let* ((begin (point))
2877 (dolist (e (cdr org-latex-regexps
))
2878 (let ((latex-regexp (nth 1 e
)))
2879 (when (or (looking-at latex-regexp
)
2883 (looking-at latex-regexp
))))
2884 (throw 'exit
(nth 2 e
))))))
2886 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2888 ;; No fragment found.
2889 (throw 'no-object nil
)))
2890 (value (org-match-string-no-properties substring-match
))
2891 (post-blank (progn (goto-char (match-end substring-match
))
2892 (skip-chars-forward " \t")))
2894 (list 'latex-fragment
2898 :post-blank post-blank
))))))
2900 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2901 "Interpret LATEX-FRAGMENT object as Org syntax.
2903 (org-element-property :value latex-fragment
))
2907 (defun org-element-line-break-parser ()
2908 "Parse line break at point, if any.
2910 When at a line break, return a list whose car is `line-break',
2911 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2912 Otherwise, return nil.
2914 Assume point is at the beginning of the line break."
2915 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2916 (not (eq (char-before) ?
\\)))
2918 (list :begin
(point)
2919 :end
(progn (forward-line) (point))
2922 (defun org-element-line-break-interpreter (line-break contents
)
2923 "Interpret LINE-BREAK object as Org syntax.
2930 (defun org-element-link-parser ()
2931 "Parse link at point, if any.
2933 When at a link, return a list whose car is `link' and cdr a plist
2934 with `:type', `:path', `:raw-link', `:application',
2935 `:search-option', `:begin', `:end', `:contents-begin',
2936 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2939 Assume point is at the beginning of the link."
2941 (let ((begin (point))
2942 end contents-begin contents-end link-end post-blank path type
2943 raw-link link search-option application
)
2945 ;; Type 1: Text targeted from a radio target.
2946 ((and org-target-link-regexp
2947 (save-excursion (or (bolp) (backward-char))
2948 (looking-at org-target-link-regexp
)))
2950 link-end
(match-end 1)
2951 path
(org-match-string-no-properties 1)
2952 contents-begin
(match-beginning 1)
2953 contents-end
(match-end 1)))
2954 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2955 ((looking-at org-bracket-link-regexp
)
2956 (setq contents-begin
(match-beginning 3)
2957 contents-end
(match-end 3)
2958 link-end
(match-end 0)
2959 ;; RAW-LINK is the original link. Expand any
2960 ;; abbreviation in it.
2961 raw-link
(org-translate-link
2962 (org-link-expand-abbrev
2963 (org-match-string-no-properties 1))))
2964 ;; Determine TYPE of link and set PATH accordingly.
2967 ((or (file-name-absolute-p raw-link
)
2968 (string-match "^\\.\\.?/" raw-link
))
2969 (setq type
"file" path raw-link
))
2970 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2971 ((string-match org-link-re-with-space3 raw-link
)
2972 (setq type
(match-string 1 raw-link
) path
(match-string 2 raw-link
)))
2973 ;; Id type: PATH is the id.
2974 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link
)
2975 (setq type
"id" path
(match-string 1 raw-link
)))
2976 ;; Code-ref type: PATH is the name of the reference.
2977 ((string-match "^(\\(.*\\))$" raw-link
)
2978 (setq type
"coderef" path
(match-string 1 raw-link
)))
2979 ;; Custom-id type: PATH is the name of the custom id.
2980 ((= (aref raw-link
0) ?
#)
2981 (setq type
"custom-id" path
(substring raw-link
1)))
2982 ;; Fuzzy type: Internal link either matches a target, an
2983 ;; headline name or nothing. PATH is the target or
2985 (t (setq type
"fuzzy" path raw-link
))))
2986 ;; Type 3: Plain link, e.g., http://orgmode.org
2987 ((looking-at org-plain-link-re
)
2988 (setq raw-link
(org-match-string-no-properties 0)
2989 type
(org-match-string-no-properties 1)
2990 link-end
(match-end 0)
2991 path
(org-match-string-no-properties 2)))
2992 ;; Type 4: Angular link, e.g., <http://orgmode.org>
2993 ((looking-at org-angle-link-re
)
2994 (setq raw-link
(buffer-substring-no-properties
2995 (match-beginning 1) (match-end 2))
2996 type
(org-match-string-no-properties 1)
2997 link-end
(match-end 0)
2998 path
(org-match-string-no-properties 2)))
2999 (t (throw 'no-object nil
)))
3000 ;; In any case, deduce end point after trailing white space from
3001 ;; LINK-END variable.
3003 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3005 ;; Special "file" type link processing.
3006 (when (member type org-element-link-type-is-file
)
3007 ;; Extract opening application and search option.
3008 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3009 (setq application
(match-string 1 type
)))
3010 ((not (string-match "^file" type
))
3011 (setq application type
)))
3012 (when (string-match "::\\(.*\\)\\'" path
)
3013 (setq search-option
(match-string 1 path
)
3014 path
(replace-match "" nil nil path
)))
3016 (when (and (not (org-string-match-p "\\`//" path
))
3017 (file-name-absolute-p path
))
3018 (setq path
(concat "//" (expand-file-name path
))))
3019 ;; Make sure TYPE always reports "file".
3024 :raw-link
(or raw-link path
)
3025 :application application
3026 :search-option search-option
3029 :contents-begin contents-begin
3030 :contents-end contents-end
3031 :post-blank post-blank
))))))
3033 (defun org-element-link-interpreter (link contents
)
3034 "Interpret LINK object as Org syntax.
3035 CONTENTS is the contents of the object, or nil."
3036 (let ((type (org-element-property :type link
))
3037 (raw-link (org-element-property :raw-link link
)))
3038 (if (string= type
"radio") raw-link
3041 (if contents
(format "[%s]" contents
) "")))))
3046 (defun org-element-macro-parser ()
3047 "Parse macro at point, if any.
3049 When at a macro, return a list whose car is `macro' and cdr
3050 a plist with `:key', `:args', `:begin', `:end', `:value' and
3051 `:post-blank' as keywords. Otherwise, return nil.
3053 Assume point is at the macro."
3055 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3056 (let ((begin (point))
3057 (key (downcase (org-match-string-no-properties 1)))
3058 (value (org-match-string-no-properties 0))
3059 (post-blank (progn (goto-char (match-end 0))
3060 (skip-chars-forward " \t")))
3062 (args (let ((args (org-match-string-no-properties 3)))
3064 ;; Do not use `org-split-string' since empty
3065 ;; strings are meaningful here.
3067 (replace-regexp-in-string
3068 "\\(\\\\*\\)\\(,\\)"
3070 (let ((len (length (match-string 1 str
))))
3071 (concat (make-string (/ len
2) ?
\\)
3072 (if (zerop (mod len
2)) "\000" ","))))
3081 :post-blank post-blank
))))))
3083 (defun org-element-macro-interpreter (macro contents
)
3084 "Interpret MACRO object as Org syntax.
3086 (org-element-property :value macro
))
3091 (defun org-element-radio-target-parser ()
3092 "Parse radio target at point, if any.
3094 When at a radio target, return a list whose car is `radio-target'
3095 and cdr a plist with `:begin', `:end', `:contents-begin',
3096 `:contents-end', `:value' and `:post-blank' as keywords.
3097 Otherwise, return nil.
3099 Assume point is at the radio target."
3101 (when (looking-at org-radio-target-regexp
)
3102 (let ((begin (point))
3103 (contents-begin (match-beginning 1))
3104 (contents-end (match-end 1))
3105 (value (org-match-string-no-properties 1))
3106 (post-blank (progn (goto-char (match-end 0))
3107 (skip-chars-forward " \t")))
3112 :contents-begin contents-begin
3113 :contents-end contents-end
3114 :post-blank post-blank
3117 (defun org-element-radio-target-interpreter (target contents
)
3118 "Interpret TARGET object as Org syntax.
3119 CONTENTS is the contents of the object."
3120 (concat "<<<" contents
">>>"))
3123 ;;;; Statistics Cookie
3125 (defun org-element-statistics-cookie-parser ()
3126 "Parse statistics cookie at point, if any.
3128 When at a statistics cookie, return a list whose car is
3129 `statistics-cookie', and cdr a plist with `:begin', `:end',
3130 `:value' and `:post-blank' keywords. Otherwise, return nil.
3132 Assume point is at the beginning of the statistics-cookie."
3134 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3135 (let* ((begin (point))
3136 (value (buffer-substring-no-properties
3137 (match-beginning 0) (match-end 0)))
3138 (post-blank (progn (goto-char (match-end 0))
3139 (skip-chars-forward " \t")))
3141 (list 'statistics-cookie
3145 :post-blank post-blank
))))))
3147 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3148 "Interpret STATISTICS-COOKIE object as Org syntax.
3150 (org-element-property :value statistics-cookie
))
3155 (defun org-element-strike-through-parser ()
3156 "Parse strike-through object at point, if any.
3158 When at a strike-through object, return a list whose car is
3159 `strike-through' and cdr is a plist with `:begin', `:end',
3160 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3161 Otherwise, return nil.
3163 Assume point is at the first plus sign marker."
3165 (unless (bolp) (backward-char 1))
3166 (when (looking-at org-emph-re
)
3167 (let ((begin (match-beginning 2))
3168 (contents-begin (match-beginning 4))
3169 (contents-end (match-end 4))
3170 (post-blank (progn (goto-char (match-end 2))
3171 (skip-chars-forward " \t")))
3173 (list 'strike-through
3176 :contents-begin contents-begin
3177 :contents-end contents-end
3178 :post-blank post-blank
))))))
3180 (defun org-element-strike-through-interpreter (strike-through contents
)
3181 "Interpret STRIKE-THROUGH object as Org syntax.
3182 CONTENTS is the contents of the object."
3183 (format "+%s+" contents
))
3188 (defun org-element-subscript-parser ()
3189 "Parse subscript at point, if any.
3191 When at a subscript object, return a list whose car is
3192 `subscript' and cdr a plist with `:begin', `:end',
3193 `:contents-begin', `:contents-end', `:use-brackets-p' and
3194 `:post-blank' as keywords. Otherwise, return nil.
3196 Assume point is at the underscore."
3198 (unless (bolp) (backward-char))
3199 (when (looking-at org-match-substring-regexp
)
3200 (let ((bracketsp (match-beginning 4))
3201 (begin (match-beginning 2))
3202 (contents-begin (or (match-beginning 4)
3203 (match-beginning 3)))
3204 (contents-end (or (match-end 4) (match-end 3)))
3205 (post-blank (progn (goto-char (match-end 0))
3206 (skip-chars-forward " \t")))
3211 :use-brackets-p bracketsp
3212 :contents-begin contents-begin
3213 :contents-end contents-end
3214 :post-blank post-blank
))))))
3216 (defun org-element-subscript-interpreter (subscript contents
)
3217 "Interpret SUBSCRIPT object as Org syntax.
3218 CONTENTS is the contents of the object."
3220 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3226 (defun org-element-superscript-parser ()
3227 "Parse superscript at point, if any.
3229 When at a superscript object, return a list whose car is
3230 `superscript' and cdr a plist with `:begin', `:end',
3231 `:contents-begin', `:contents-end', `:use-brackets-p' and
3232 `:post-blank' as keywords. Otherwise, return nil.
3234 Assume point is at the caret."
3236 (unless (bolp) (backward-char))
3237 (when (looking-at org-match-substring-regexp
)
3238 (let ((bracketsp (match-beginning 4))
3239 (begin (match-beginning 2))
3240 (contents-begin (or (match-beginning 4)
3241 (match-beginning 3)))
3242 (contents-end (or (match-end 4) (match-end 3)))
3243 (post-blank (progn (goto-char (match-end 0))
3244 (skip-chars-forward " \t")))
3249 :use-brackets-p bracketsp
3250 :contents-begin contents-begin
3251 :contents-end contents-end
3252 :post-blank post-blank
))))))
3254 (defun org-element-superscript-interpreter (superscript contents
)
3255 "Interpret SUPERSCRIPT object as Org syntax.
3256 CONTENTS is the contents of the object."
3258 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3264 (defun org-element-table-cell-parser ()
3265 "Parse table cell at point.
3266 Return a list whose car is `table-cell' and cdr is a plist
3267 containing `:begin', `:end', `:contents-begin', `:contents-end'
3268 and `:post-blank' keywords."
3269 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3270 (let* ((begin (match-beginning 0))
3272 (contents-begin (match-beginning 1))
3273 (contents-end (match-end 1)))
3277 :contents-begin contents-begin
3278 :contents-end contents-end
3281 (defun org-element-table-cell-interpreter (table-cell contents
)
3282 "Interpret TABLE-CELL element as Org syntax.
3283 CONTENTS is the contents of the cell, or nil."
3284 (concat " " contents
" |"))
3289 (defun org-element-target-parser ()
3290 "Parse target at point, if any.
3292 When at a target, return a list whose car is `target' and cdr
3293 a plist with `:begin', `:end', `:value' and `:post-blank' as
3294 keywords. Otherwise, return nil.
3296 Assume point is at the target."
3298 (when (looking-at org-target-regexp
)
3299 (let ((begin (point))
3300 (value (org-match-string-no-properties 1))
3301 (post-blank (progn (goto-char (match-end 0))
3302 (skip-chars-forward " \t")))
3308 :post-blank post-blank
))))))
3310 (defun org-element-target-interpreter (target contents
)
3311 "Interpret TARGET object as Org syntax.
3313 (format "<<%s>>" (org-element-property :value target
)))
3318 (defconst org-element--timestamp-regexp
3319 (concat org-ts-regexp-both
3321 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3323 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3324 "Regexp matching any timestamp type object.")
3326 (defun org-element-timestamp-parser ()
3327 "Parse time stamp at point, if any.
3329 When at a time stamp, return a list whose car is `timestamp', and
3330 cdr a plist with `:type', `:raw-value', `:year-start',
3331 `:month-start', `:day-start', `:hour-start', `:minute-start',
3332 `:year-end', `:month-end', `:day-end', `:hour-end',
3333 `:minute-end', `:repeater-type', `:repeater-value',
3334 `:repeater-unit', `:warning-type', `:warning-value',
3335 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3336 Otherwise, return nil.
3338 Assume point is at the beginning of the timestamp."
3339 (when (org-looking-at-p org-element--timestamp-regexp
)
3341 (let* ((begin (point))
3342 (activep (eq (char-after) ?
<))
3345 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3346 (match-string-no-properties 0)))
3347 (date-start (match-string-no-properties 1))
3348 (date-end (match-string 3))
3349 (diaryp (match-beginning 2))
3350 (post-blank (progn (goto-char (match-end 0))
3351 (skip-chars-forward " \t")))
3356 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3358 (cons (string-to-number (match-string 2 date-start
))
3359 (string-to-number (match-string 3 date-start
)))))
3360 (type (cond (diaryp 'diary
)
3361 ((and activep
(or date-end time-range
)) 'active-range
)
3363 ((or date-end time-range
) 'inactive-range
)
3367 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3371 (let ((type (match-string 1 raw-value
)))
3372 (cond ((equal "++" type
) 'catch-up
)
3373 ((equal ".+" type
) 'restart
)
3375 :repeater-value
(string-to-number (match-string 2 raw-value
))
3377 (case (string-to-char (match-string 3 raw-value
))
3378 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3381 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3383 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3384 :warning-value
(string-to-number (match-string 2 raw-value
))
3386 (case (string-to-char (match-string 3 raw-value
))
3387 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3388 year-start month-start day-start hour-start minute-start year-end
3389 month-end day-end hour-end minute-end
)
3390 ;; Parse date-start.
3392 (let ((date (org-parse-time-string date-start t
)))
3393 (setq year-start
(nth 5 date
)
3394 month-start
(nth 4 date
)
3395 day-start
(nth 3 date
)
3396 hour-start
(nth 2 date
)
3397 minute-start
(nth 1 date
))))
3398 ;; Compute date-end. It can be provided directly in time-stamp,
3399 ;; or extracted from time range. Otherwise, it defaults to the
3400 ;; same values as date-start.
3402 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3403 (setq year-end
(or (nth 5 date
) year-start
)
3404 month-end
(or (nth 4 date
) month-start
)
3405 day-end
(or (nth 3 date
) day-start
)
3406 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3407 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3409 (nconc (list :type type
3410 :raw-value raw-value
3411 :year-start year-start
3412 :month-start month-start
3413 :day-start day-start
3414 :hour-start hour-start
3415 :minute-start minute-start
3417 :month-end month-end
3420 :minute-end minute-end
3423 :post-blank post-blank
)
3427 (defun org-element-timestamp-interpreter (timestamp contents
)
3428 "Interpret TIMESTAMP object as Org syntax.
3430 (let* ((repeat-string
3432 (case (org-element-property :repeater-type timestamp
)
3433 (cumulate "+") (catch-up "++") (restart ".+"))
3434 (let ((val (org-element-property :repeater-value timestamp
)))
3435 (and val
(number-to-string val
)))
3436 (case (org-element-property :repeater-unit timestamp
)
3437 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3440 (case (org-element-property :warning-type timestamp
)
3443 (let ((val (org-element-property :warning-value timestamp
)))
3444 (and val
(number-to-string val
)))
3445 (case (org-element-property :warning-unit timestamp
)
3446 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3448 ;; Build an Org timestamp string from TIME. ACTIVEP is
3449 ;; non-nil when time stamp is active. If WITH-TIME-P is
3450 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3451 ;; specify a time range in the timestamp. REPEAT-STRING is
3452 ;; the repeater string, if any.
3453 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3454 (let ((ts (format-time-string
3455 (funcall (if with-time-p
'cdr
'car
)
3456 org-time-stamp-formats
)
3458 (when (and hour-end minute-end
)
3459 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3462 (format "\\&-%02d:%02d" hour-end minute-end
)
3464 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3465 (dolist (s (list repeat-string warning-string
))
3466 (when (org-string-nw-p s
)
3467 (setq ts
(concat (substring ts
0 -
1)
3470 (substring ts -
1)))))
3473 (type (org-element-property :type timestamp
)))
3476 (let* ((minute-start (org-element-property :minute-start timestamp
))
3477 (minute-end (org-element-property :minute-end timestamp
))
3478 (hour-start (org-element-property :hour-start timestamp
))
3479 (hour-end (org-element-property :hour-end timestamp
))
3480 (time-range-p (and hour-start hour-end minute-start minute-end
3481 (or (/= hour-start hour-end
)
3482 (/= minute-start minute-end
)))))
3488 (org-element-property :day-start timestamp
)
3489 (org-element-property :month-start timestamp
)
3490 (org-element-property :year-start timestamp
))
3492 (and hour-start minute-start
)
3493 (and time-range-p hour-end
)
3494 (and time-range-p minute-end
))))
3495 ((active-range inactive-range
)
3496 (let ((minute-start (org-element-property :minute-start timestamp
))
3497 (minute-end (org-element-property :minute-end timestamp
))
3498 (hour-start (org-element-property :hour-start timestamp
))
3499 (hour-end (org-element-property :hour-end timestamp
)))
3502 build-ts-string
(encode-time
3506 (org-element-property :day-start timestamp
)
3507 (org-element-property :month-start timestamp
)
3508 (org-element-property :year-start timestamp
))
3509 (eq type
'active-range
)
3510 (and hour-start minute-start
))
3512 (funcall build-ts-string
3516 (org-element-property :day-end timestamp
)
3517 (org-element-property :month-end timestamp
)
3518 (org-element-property :year-end timestamp
))
3519 (eq type
'active-range
)
3520 (and hour-end minute-end
))))))))
3525 (defun org-element-underline-parser ()
3526 "Parse underline object at point, if any.
3528 When at an underline object, return a list whose car is
3529 `underline' and cdr is a plist with `:begin', `:end',
3530 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3531 Otherwise, return nil.
3533 Assume point is at the first underscore marker."
3535 (unless (bolp) (backward-char 1))
3536 (when (looking-at org-emph-re
)
3537 (let ((begin (match-beginning 2))
3538 (contents-begin (match-beginning 4))
3539 (contents-end (match-end 4))
3540 (post-blank (progn (goto-char (match-end 2))
3541 (skip-chars-forward " \t")))
3546 :contents-begin contents-begin
3547 :contents-end contents-end
3548 :post-blank post-blank
))))))
3550 (defun org-element-underline-interpreter (underline contents
)
3551 "Interpret UNDERLINE object as Org syntax.
3552 CONTENTS is the contents of the object."
3553 (format "_%s_" contents
))
3558 (defun org-element-verbatim-parser ()
3559 "Parse verbatim object at point, if any.
3561 When at a verbatim object, return a list whose car is `verbatim'
3562 and cdr is a plist with `:value', `:begin', `:end' and
3563 `:post-blank' keywords. Otherwise, return nil.
3565 Assume point is at the first equal sign marker."
3567 (unless (bolp) (backward-char 1))
3568 (when (looking-at org-emph-re
)
3569 (let ((begin (match-beginning 2))
3570 (value (org-match-string-no-properties 4))
3571 (post-blank (progn (goto-char (match-end 2))
3572 (skip-chars-forward " \t")))
3578 :post-blank post-blank
))))))
3580 (defun org-element-verbatim-interpreter (verbatim contents
)
3581 "Interpret VERBATIM object as Org syntax.
3583 (format "=%s=" (org-element-property :value verbatim
)))
3587 ;;; Parsing Element Starting At Point
3589 ;; `org-element--current-element' is the core function of this section.
3590 ;; It returns the Lisp representation of the element starting at
3593 ;; `org-element--current-element' makes use of special modes. They
3594 ;; are activated for fixed element chaining (e.g., `plain-list' >
3595 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3596 ;; `section'). Special modes are: `first-section', `item',
3597 ;; `node-property', `section' and `table-row'.
3599 (defun org-element--current-element
3600 (limit &optional granularity special structure
)
3601 "Parse the element starting at point.
3603 Return value is a list like (TYPE PROPS) where TYPE is the type
3604 of the element and PROPS a plist of properties associated to the
3607 Possible types are defined in `org-element-all-elements'.
3609 LIMIT bounds the search.
3611 Optional argument GRANULARITY determines the depth of the
3612 recursion. Allowed values are `headline', `greater-element',
3613 `element', `object' or nil. When it is broader than `object' (or
3614 nil), secondary values will not be parsed, since they only
3617 Optional argument SPECIAL, when non-nil, can be either
3618 `first-section', `item', `node-property', `section', and
3621 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3624 This function assumes point is always at the beginning of the
3625 element it has to parse."
3627 (let ((case-fold-search t
)
3628 ;; Determine if parsing depth allows for secondary strings
3629 ;; parsing. It only applies to elements referenced in
3630 ;; `org-element-secondary-value-alist'.
3631 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3635 (org-element-item-parser limit structure raw-secondary-p
))
3637 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3639 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3641 ((org-with-limited-levels (org-at-heading-p))
3642 (org-element-headline-parser limit raw-secondary-p
))
3643 ;; Sections (must be checked after headline).
3644 ((eq special
'section
) (org-element-section-parser limit
))
3645 ((eq special
'first-section
)
3646 (org-element-section-parser
3647 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3649 ;; When not at bol, point is at the beginning of an item or
3650 ;; a footnote definition: next item is always a paragraph.
3651 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3652 ;; Planning and Clock.
3653 ((looking-at org-planning-or-clock-line-re
)
3654 (if (equal (match-string 1) org-clock-string
)
3655 (org-element-clock-parser limit
)
3656 (org-element-planning-parser limit
)))
3659 (org-element-inlinetask-parser limit raw-secondary-p
))
3660 ;; From there, elements can have affiliated keywords.
3661 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3663 ;; Jumping over affiliated keywords put point off-limits.
3664 ;; Parse them as regular keywords.
3665 ((and (cdr affiliated
) (>= (point) limit
))
3666 (goto-char (car affiliated
))
3667 (org-element-keyword-parser limit nil
))
3668 ;; LaTeX Environment.
3670 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3671 (org-element-latex-environment-parser limit affiliated
))
3672 ;; Drawer and Property Drawer.
3673 ((looking-at org-drawer-regexp
)
3674 (if (equal (match-string 1) "PROPERTIES")
3675 (org-element-property-drawer-parser limit affiliated
)
3676 (org-element-drawer-parser limit affiliated
)))
3678 ((looking-at "[ \t]*:\\( \\|$\\)")
3679 (org-element-fixed-width-parser limit affiliated
))
3680 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3682 ((looking-at "[ \t]*#")
3683 (goto-char (match-end 0))
3684 (cond ((looking-at "\\(?: \\|$\\)")
3686 (org-element-comment-parser limit affiliated
))
3687 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3689 (let ((parser (assoc (upcase (match-string 1))
3690 org-element-block-name-alist
)))
3691 (if parser
(funcall (cdr parser
) limit affiliated
)
3692 (org-element-special-block-parser limit affiliated
))))
3693 ((looking-at "\\+CALL:")
3695 (org-element-babel-call-parser limit affiliated
))
3696 ((looking-at "\\+BEGIN:? ")
3698 (org-element-dynamic-block-parser limit affiliated
))
3699 ((looking-at "\\+\\S-+:")
3701 (org-element-keyword-parser limit affiliated
))
3704 (org-element-paragraph-parser limit affiliated
))))
3705 ;; Footnote Definition.
3706 ((looking-at org-footnote-definition-re
)
3707 (org-element-footnote-definition-parser limit affiliated
))
3709 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3710 (org-element-horizontal-rule-parser limit affiliated
))
3713 (org-element-diary-sexp-parser limit affiliated
))
3715 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3717 ((looking-at (org-item-re))
3718 (org-element-plain-list-parser
3720 (or structure
(org-element--list-struct limit
))))
3721 ;; Default element: Paragraph.
3722 (t (org-element-paragraph-parser limit affiliated
)))))))))
3725 ;; Most elements can have affiliated keywords. When looking for an
3726 ;; element beginning, we want to move before them, as they belong to
3727 ;; that element, and, in the meantime, collect information they give
3728 ;; into appropriate properties. Hence the following function.
3730 (defun org-element--collect-affiliated-keywords (limit)
3731 "Collect affiliated keywords from point down to LIMIT.
3733 Return a list whose CAR is the position at the first of them and
3734 CDR a plist of keywords and values and move point to the
3735 beginning of the first line after them.
3737 As a special case, if element doesn't start at the beginning of
3738 the line (e.g., a paragraph starting an item), CAR is current
3739 position of point and CDR is nil."
3740 (if (not (bolp)) (list (point))
3741 (let ((case-fold-search t
)
3743 ;; RESTRICT is the list of objects allowed in parsed
3745 (restrict (org-element-restriction 'keyword
))
3747 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3748 (let* ((raw-kwd (upcase (match-string 1)))
3749 ;; Apply translation to RAW-KWD. From there, KWD is
3750 ;; the official keyword.
3751 (kwd (or (cdr (assoc raw-kwd
3752 org-element-keyword-translation-alist
))
3754 ;; Find main value for any keyword.
3758 (buffer-substring-no-properties
3759 (match-end 0) (point-at-eol)))))
3760 ;; PARSEDP is non-nil when keyword should have its
3762 (parsedp (member kwd org-element-parsed-keywords
))
3763 ;; If KWD is a dual keyword, find its secondary
3764 ;; value. Maybe parse it.
3765 (dualp (member kwd org-element-dual-keywords
))
3768 (let ((sec (org-match-string-no-properties 2)))
3769 (if (or (not sec
) (not parsedp
)) sec
3770 (org-element-parse-secondary-string sec restrict
)))))
3771 ;; Attribute a property name to KWD.
3772 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3773 ;; Now set final shape for VALUE.
3775 (setq value
(org-element-parse-secondary-string value restrict
)))
3777 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3778 (when (or (member kwd org-element-multiple-keywords
)
3779 ;; Attributes can always appear on multiple lines.
3780 (string-match "^ATTR_" kwd
))
3781 (setq value
(cons value
(plist-get output kwd-sym
))))
3782 ;; Eventually store the new value in OUTPUT.
3783 (setq output
(plist-put output kwd-sym value
))
3784 ;; Move to next keyword.
3786 ;; If affiliated keywords are orphaned: move back to first one.
3787 ;; They will be parsed as a paragraph.
3788 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3790 (cons origin output
))))
3796 ;; The two major functions here are `org-element-parse-buffer', which
3797 ;; parses Org syntax inside the current buffer, taking into account
3798 ;; region, narrowing, or even visibility if specified, and
3799 ;; `org-element-parse-secondary-string', which parses objects within
3802 ;; The (almost) almighty `org-element-map' allows to apply a function
3803 ;; on elements or objects matching some type, and accumulate the
3804 ;; resulting values. In an export situation, it also skips unneeded
3805 ;; parts of the parse tree.
3807 (defun org-element-parse-buffer (&optional granularity visible-only
)
3808 "Recursively parse the buffer and return structure.
3809 If narrowing is in effect, only parse the visible part of the
3812 Optional argument GRANULARITY determines the depth of the
3813 recursion. It can be set to the following symbols:
3815 `headline' Only parse headlines.
3816 `greater-element' Don't recurse into greater elements excepted
3817 headlines and sections. Thus, elements
3818 parsed are the top-level ones.
3819 `element' Parse everything but objects and plain text.
3820 `object' Parse the complete buffer (default).
3822 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3825 An element or an objects is represented as a list with the
3826 pattern (TYPE PROPERTIES CONTENTS), where :
3828 TYPE is a symbol describing the element or object. See
3829 `org-element-all-elements' and `org-element-all-objects' for an
3830 exhaustive list of such symbols. One can retrieve it with
3831 `org-element-type' function.
3833 PROPERTIES is the list of attributes attached to the element or
3834 object, as a plist. Although most of them are specific to the
3835 element or object type, all types share `:begin', `:end',
3836 `:post-blank' and `:parent' properties, which respectively
3837 refer to buffer position where the element or object starts,
3838 ends, the number of white spaces or blank lines after it, and
3839 the element or object containing it. Properties values can be
3840 obtained by using `org-element-property' function.
3842 CONTENTS is a list of elements, objects or raw strings
3843 contained in the current element or object, when applicable.
3844 One can access them with `org-element-contents' function.
3846 The Org buffer has `org-data' as type and nil as properties.
3847 `org-element-map' function can be used to find specific elements
3848 or objects within the parse tree.
3850 This function assumes that current major mode is `org-mode'."
3852 (goto-char (point-min))
3853 (org-skip-whitespace)
3854 (org-element--parse-elements
3855 (point-at-bol) (point-max)
3856 ;; Start in `first-section' mode so text before the first
3857 ;; headline belongs to a section.
3858 'first-section nil granularity visible-only
(list 'org-data nil
))))
3860 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3861 "Recursively parse objects in STRING and return structure.
3863 RESTRICTION is a symbol limiting the object types that will be
3866 Optional argument PARENT, when non-nil, is the element or object
3867 containing the secondary string. It is used to set correctly
3868 `:parent' property within the string."
3869 ;; Copy buffer-local variables listed in
3870 ;; `org-element-object-variables' into temporary buffer. This is
3871 ;; required since object parsing is dependent on these variables.
3872 (let ((pairs (delq nil
(mapcar (lambda (var)
3874 (cons var
(symbol-value var
))))
3875 org-element-object-variables
))))
3877 (mapc (lambda (pair) (org-set-local (car pair
) (cdr pair
))) pairs
)
3879 (let ((secondary (org-element--parse-objects
3880 (point-min) (point-max) nil restriction
)))
3882 (mapc (lambda (obj) (org-element-put-property obj
:parent parent
))
3886 (defun org-element-map
3887 (data types fun
&optional info first-match no-recursion with-affiliated
)
3888 "Map a function on selected elements or objects.
3890 DATA is a parse tree, an element, an object, a string, or a list
3891 of such constructs. TYPES is a symbol or list of symbols of
3892 elements or objects types (see `org-element-all-elements' and
3893 `org-element-all-objects' for a complete list of types). FUN is
3894 the function called on the matching element or object. It has to
3895 accept one argument: the element or object itself.
3897 When optional argument INFO is non-nil, it should be a plist
3898 holding export options. In that case, parts of the parse tree
3899 not exportable according to that property list will be skipped.
3901 When optional argument FIRST-MATCH is non-nil, stop at the first
3902 match for which FUN doesn't return nil, and return that value.
3904 Optional argument NO-RECURSION is a symbol or a list of symbols
3905 representing elements or objects types. `org-element-map' won't
3906 enter any recursive element or object whose type belongs to that
3907 list. Though, FUN can still be applied on them.
3909 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3910 apply to matching objects within parsed affiliated keywords (see
3911 `org-element-parsed-keywords').
3913 Nil values returned from FUN do not appear in the results.
3919 Assuming TREE is a variable containing an Org buffer parse tree,
3920 the following example will return a flat list of all `src-block'
3921 and `example-block' elements in it:
3923 \(org-element-map tree '(example-block src-block) 'identity)
3925 The following snippet will find the first headline with a level
3926 of 1 and a \"phone\" tag, and will return its beginning position:
3928 \(org-element-map tree 'headline
3930 \(and (= (org-element-property :level hl) 1)
3931 \(member \"phone\" (org-element-property :tags hl))
3932 \(org-element-property :begin hl)))
3935 The next example will return a flat list of all `plain-list' type
3936 elements in TREE that are not a sub-list themselves:
3938 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3940 Eventually, this example will return a flat list of all `bold'
3941 type objects containing a `latex-snippet' type object, even
3942 looking into captions:
3944 \(org-element-map tree 'bold
3946 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3948 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3949 (unless (listp types
) (setq types
(list types
)))
3950 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
3951 ;; Recursion depth is determined by --CATEGORY.
3954 (let ((category 'greater-elements
))
3955 (mapc (lambda (type)
3956 (cond ((or (memq type org-element-all-objects
)
3957 (eq type
'plain-text
))
3958 ;; If one object is found, the function
3959 ;; has to recurse into every object.
3960 (throw 'found
'objects
))
3961 ((not (memq type org-element-greater-elements
))
3962 ;; If one regular element is found, the
3963 ;; function has to recurse, at least,
3964 ;; into every element it encounters.
3965 (and (not (eq category
'elements
))
3966 (setq category
'elements
)))))
3969 ;; Compute properties for affiliated keywords if necessary.
3971 (and with-affiliated
3972 (mapcar (lambda (kwd)
3973 (cons kwd
(intern (concat ":" (downcase kwd
)))))
3974 org-element-affiliated-keywords
)))
3980 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3981 ;; holding contextual information.
3982 (let ((--type (org-element-type --data
)))
3985 ;; Ignored element in an export context.
3986 ((and info
(memq --data
(plist-get info
:ignore-list
))))
3987 ;; List of elements or objects.
3988 ((not --type
) (mapc --walk-tree --data
))
3989 ;; Unconditionally enter parse trees.
3990 ((eq --type
'org-data
)
3991 (mapc --walk-tree
(org-element-contents --data
)))
3993 ;; Check if TYPE is matching among TYPES. If so,
3994 ;; apply FUN to --DATA and accumulate return value
3995 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3996 (when (memq --type types
)
3997 (let ((result (funcall fun --data
)))
3998 (cond ((not result
))
3999 (first-match (throw '--map-first-match result
))
4000 (t (push result --acc
)))))
4001 ;; If --DATA has a secondary string that can contain
4002 ;; objects with their type among TYPES, look into it.
4003 (when (and (eq --category
'objects
) (not (stringp --data
)))
4005 (assq --type org-element-secondary-value-alist
)))
4007 (funcall --walk-tree
4008 (org-element-property (cdr sec-prop
) --data
)))))
4009 ;; If --DATA has any affiliated keywords and
4010 ;; WITH-AFFILIATED is non-nil, look for objects in
4012 (when (and with-affiliated
4013 (eq --category
'objects
)
4014 (memq --type org-element-all-elements
))
4015 (mapc (lambda (kwd-pair)
4016 (let ((kwd (car kwd-pair
))
4017 (value (org-element-property
4018 (cdr kwd-pair
) --data
)))
4019 ;; Pay attention to the type of value.
4020 ;; Preserve order for multiple keywords.
4023 ((and (member kwd org-element-multiple-keywords
)
4024 (member kwd org-element-dual-keywords
))
4025 (mapc (lambda (line)
4026 (funcall --walk-tree
(cdr line
))
4027 (funcall --walk-tree
(car line
)))
4029 ((member kwd org-element-multiple-keywords
)
4030 (mapc (lambda (line) (funcall --walk-tree line
))
4032 ((member kwd org-element-dual-keywords
)
4033 (funcall --walk-tree
(cdr value
))
4034 (funcall --walk-tree
(car value
)))
4035 (t (funcall --walk-tree value
)))))
4036 --affiliated-alist
))
4037 ;; Determine if a recursion into --DATA is possible.
4039 ;; --TYPE is explicitly removed from recursion.
4040 ((memq --type no-recursion
))
4041 ;; --DATA has no contents.
4042 ((not (org-element-contents --data
)))
4043 ;; Looking for greater elements but --DATA is simply
4044 ;; an element or an object.
4045 ((and (eq --category
'greater-elements
)
4046 (not (memq --type org-element-greater-elements
))))
4047 ;; Looking for elements but --DATA is an object.
4048 ((and (eq --category
'elements
)
4049 (memq --type org-element-all-objects
)))
4050 ;; In any other case, map contents.
4051 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4052 (catch '--map-first-match
4053 (funcall --walk-tree data
)
4054 ;; Return value in a proper order.
4056 (put 'org-element-map
'lisp-indent-function
2)
4058 ;; The following functions are internal parts of the parser.
4060 ;; The first one, `org-element--parse-elements' acts at the element's
4063 ;; The second one, `org-element--parse-objects' applies on all objects
4064 ;; of a paragraph or a secondary string.
4066 ;; More precisely, that function looks for every allowed object type
4067 ;; first. Then, it discards failed searches, keeps further matches,
4068 ;; and searches again types matched behind point, for subsequent
4069 ;; calls. Thus, searching for a given type fails only once, and every
4070 ;; object is searched only once at top level (but sometimes more for
4073 (defun org-element--parse-elements
4074 (beg end special structure granularity visible-only acc
)
4075 "Parse elements between BEG and END positions.
4077 SPECIAL prioritize some elements over the others. It can be set
4078 to `first-section', `section' `item' or `table-row'.
4080 When value is `item', STRUCTURE will be used as the current list
4083 GRANULARITY determines the depth of the recursion. See
4084 `org-element-parse-buffer' for more information.
4086 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4089 Elements are accumulated into ACC."
4092 ;; Visible only: skip invisible parts at the beginning of the
4094 (when (and visible-only
(org-invisible-p2))
4095 (goto-char (min (1+ (org-find-visible)) end
)))
4096 ;; When parsing only headlines, skip any text before first one.
4097 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4098 (org-with-limited-levels (outline-next-heading)))
4100 (while (< (point) end
)
4101 ;; Find current element's type and parse it accordingly to
4103 (let* ((element (org-element--current-element
4104 end granularity special structure
))
4105 (type (org-element-type element
))
4106 (cbeg (org-element-property :contents-begin element
)))
4107 (goto-char (org-element-property :end element
))
4108 ;; Visible only: skip invisible parts between siblings.
4109 (when (and visible-only
(org-invisible-p2))
4110 (goto-char (min (1+ (org-find-visible)) end
)))
4111 ;; Fill ELEMENT contents by side-effect.
4113 ;; If element has no contents, don't modify it.
4115 ;; Greater element: parse it between `contents-begin' and
4116 ;; `contents-end'. Make sure GRANULARITY allows the
4117 ;; recursion, or ELEMENT is a headline, in which case going
4118 ;; inside is mandatory, in order to get sub-level headings.
4119 ((and (memq type org-element-greater-elements
)
4120 (or (memq granularity
'(element object nil
))
4121 (and (eq granularity
'greater-element
)
4123 (eq type
'headline
)))
4124 (org-element--parse-elements
4125 cbeg
(org-element-property :contents-end element
)
4126 ;; Possibly switch to a special mode.
4130 (property-drawer 'node-property
)
4132 (and (memq type
'(item plain-list
))
4133 (org-element-property :structure element
))
4134 granularity visible-only element
))
4135 ;; ELEMENT has contents. Parse objects inside, if
4136 ;; GRANULARITY allows it.
4137 ((memq granularity
'(object nil
))
4138 (org-element--parse-objects
4139 cbeg
(org-element-property :contents-end element
) element
4140 (org-element-restriction type
))))
4141 (org-element-adopt-elements acc element
)))
4145 (defconst org-element--object-regexp
4146 (mapconcat #'identity
4147 (let ((link-types (regexp-opt org-link-types
)))
4150 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4151 ;; Bold, code, italic, strike-through, underline and
4154 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4156 (concat "\\<" link-types
":")
4157 ;; Objects starting with "[": regular link, footnote
4158 ;; reference, statistics cookie, timestamp (inactive).
4159 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4160 ;; Objects starting with "@": export snippets.
4162 ;; Objects starting with "{": macro.
4164 ;; Objects starting with "<" : timestamp (active,
4165 ;; diary), target, radio target and angular links.
4166 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4167 ;; Objects starting with "$": latex fragment.
4169 ;; Objects starting with "\": line break, entity,
4171 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4172 ;; Objects starting with raw text: inline Babel
4173 ;; source block, inline Babel call.
4174 "\\(?:call\\|src\\)_"))
4176 "Regexp possibly matching the beginning of an object.
4177 This regexp allows false positives. Dedicated parser (e.g.,
4178 `org-export-bold-parser') will take care of further filtering.
4179 Radio links are not matched by this regexp, as they are treated
4180 specially in `org-element--object-lex'.")
4182 (defun org-element--object-lex (restriction)
4183 "Return next object in current buffer or nil.
4184 RESTRICTION is a list of object types, as symbols, that should be
4185 looked after. This function assumes that the buffer is narrowed
4186 to an appropriate container (e.g., a paragraph)."
4187 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4189 (let ((limit (and org-target-link-regexp
4191 (or (bolp) (backward-char))
4192 (re-search-forward org-target-link-regexp nil t
))
4193 (match-beginning 1)))
4195 (while (and (not found
)
4196 (re-search-forward org-element--object-regexp limit t
))
4197 (goto-char (match-beginning 0))
4198 (let ((result (match-string 0)))
4201 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4202 (and (memq 'inline-babel-call restriction
)
4203 (org-element-inline-babel-call-parser)))
4204 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4205 (and (memq 'inline-src-block restriction
)
4206 (org-element-inline-src-block-parser)))
4209 (?^
(and (memq 'superscript restriction
)
4210 (org-element-superscript-parser)))
4211 (?_
(or (and (memq 'subscript restriction
)
4212 (org-element-subscript-parser))
4213 (and (memq 'underline restriction
)
4214 (org-element-underline-parser))))
4215 (?
* (and (memq 'bold restriction
)
4216 (org-element-bold-parser)))
4217 (?
/ (and (memq 'italic restriction
)
4218 (org-element-italic-parser)))
4219 (?~
(and (memq 'code restriction
)
4220 (org-element-code-parser)))
4221 (?
= (and (memq 'verbatim restriction
)
4222 (org-element-verbatim-parser)))
4223 (?
+ (and (memq 'strike-through restriction
)
4224 (org-element-strike-through-parser)))
4225 (?
@ (and (memq 'export-snippet restriction
)
4226 (org-element-export-snippet-parser)))
4227 (?
{ (and (memq 'macro restriction
)
4228 (org-element-macro-parser)))
4229 (?$
(and (memq 'latex-fragment restriction
)
4230 (org-element-latex-fragment-parser)))
4232 (if (eq (aref result
1) ?
<)
4233 (or (and (memq 'radio-target restriction
)
4234 (org-element-radio-target-parser))
4235 (and (memq 'target restriction
)
4236 (org-element-target-parser)))
4237 (or (and (memq 'timestamp restriction
)
4238 (org-element-timestamp-parser))
4239 (and (memq 'link restriction
)
4240 (org-element-link-parser)))))
4241 (?
\\ (or (and (memq 'line-break restriction
)
4242 (org-element-line-break-parser))
4243 (and (memq 'entity restriction
)
4244 (org-element-entity-parser))
4245 (and (memq 'latex-fragment restriction
)
4246 (org-element-latex-fragment-parser))))
4248 (if (eq (aref result
1) ?\
[)
4249 (and (memq 'link restriction
)
4250 (org-element-link-parser))
4251 (or (and (memq 'footnote-reference restriction
)
4252 (org-element-footnote-reference-parser))
4253 (and (memq 'timestamp restriction
)
4254 (org-element-timestamp-parser))
4255 (and (memq 'statistics-cookie restriction
)
4256 (org-element-statistics-cookie-parser)))))
4257 ;; This is probably a plain link.
4258 (otherwise (and (or (memq 'link restriction
)
4259 (memq 'plain-link restriction
))
4260 (org-element-link-parser)))))))
4261 (or (eobp) (forward-char))))
4264 ((and limit
(memq 'link restriction
))
4265 (goto-char limit
) (org-element-link-parser)))))))
4267 (defun org-element--parse-objects (beg end acc restriction
)
4268 "Parse objects between BEG and END and return recursive structure.
4270 Objects are accumulated in ACC.
4272 RESTRICTION is a list of object successors which are allowed in
4273 the current object."
4276 (narrow-to-region beg end
)
4277 (goto-char (point-min))
4279 (while (and (not (eobp))
4280 (setq next-object
(org-element--object-lex restriction
)))
4281 ;; 1. Text before any object. Untabify it.
4282 (let ((obj-beg (org-element-property :begin next-object
)))
4283 (unless (= (point) obj-beg
)
4285 (org-element-adopt-elements
4287 (replace-regexp-in-string
4288 "\t" (make-string tab-width ?
)
4289 (buffer-substring-no-properties (point) obj-beg
))))))
4291 (let ((obj-end (org-element-property :end next-object
))
4292 (cont-beg (org-element-property :contents-begin next-object
)))
4293 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4294 ;; a recursive type.
4296 (memq (car next-object
) org-element-recursive-objects
))
4297 (org-element--parse-objects
4298 cont-beg
(org-element-property :contents-end next-object
)
4299 next-object
(org-element-restriction next-object
)))
4300 (setq acc
(org-element-adopt-elements acc next-object
))
4301 (goto-char obj-end
))))
4302 ;; 3. Text after last object. Untabify it.
4305 (org-element-adopt-elements
4307 (replace-regexp-in-string
4308 "\t" (make-string tab-width ?
)
4309 (buffer-substring-no-properties (point) end
)))))
4315 ;;; Towards A Bijective Process
4317 ;; The parse tree obtained with `org-element-parse-buffer' is really
4318 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4319 ;; interpreted and expanded into a string with canonical Org syntax.
4320 ;; Hence `org-element-interpret-data'.
4322 ;; The function relies internally on
4323 ;; `org-element--interpret-affiliated-keywords'.
4326 (defun org-element-interpret-data (data &optional pseudo-objects
)
4327 "Interpret DATA as Org syntax.
4329 DATA is a parse tree, an element, an object or a secondary string
4332 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4333 new types that should be treated as objects. An unknown type not
4334 belonging to this list is seen as a pseudo-element instead. Both
4335 pseudo-objects and pseudo-elements are transparent entities, i.e.
4336 only their contents are interpreted.
4338 Return Org syntax as a string."
4339 (org-element--interpret-data-1 data nil pseudo-objects
))
4341 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4342 "Interpret DATA as Org syntax.
4344 DATA is a parse tree, an element, an object or a secondary string
4345 to interpret. PARENT is used for recursive calls. It contains
4346 the element or object containing data, or nil. PSEUDO-OBJECTS
4347 are list of symbols defining new element or object types.
4348 Unknown types that don't belong to this list are treated as
4349 pseudo-elements instead.
4351 Return Org syntax as a string."
4352 (let* ((type (org-element-type data
))
4353 ;; Find interpreter for current object or element. If it
4354 ;; doesn't exist (e.g. this is a pseudo object or element),
4355 ;; return contents, if any.
4357 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4358 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4361 ;; Secondary string.
4365 (org-element--interpret-data-1 obj parent pseudo-objects
))
4367 ;; Full Org document.
4368 ((eq type
'org-data
)
4371 (org-element--interpret-data-1 obj parent pseudo-objects
))
4372 (org-element-contents data
) ""))
4373 ;; Plain text: return it.
4374 ((stringp data
) data
)
4375 ;; Element or object without contents.
4376 ((not (org-element-contents data
)) (funcall interpret data nil
))
4377 ;; Element or object with contents.
4379 (funcall interpret data
4380 ;; Recursively interpret contents.
4383 (org-element--interpret-data-1 obj data pseudo-objects
))
4384 (org-element-contents
4385 (if (not (memq type
'(paragraph verse-block
)))
4387 ;; Fix indentation of elements containing
4388 ;; objects. We ignore `table-row' elements
4389 ;; as they are one line long anyway.
4390 (org-element-normalize-contents
4392 ;; When normalizing first paragraph of an
4393 ;; item or a footnote-definition, ignore
4394 ;; first line's indentation.
4395 (and (eq type
'paragraph
)
4396 (equal data
(car (org-element-contents parent
)))
4397 (memq (org-element-type parent
)
4398 '(footnote-definition item
))))))
4400 (if (memq type
'(org-data plain-text nil
)) results
4401 ;; Build white spaces. If no `:post-blank' property is
4402 ;; specified, assume its value is 0.
4403 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4404 (if (or (memq type org-element-all-objects
)
4405 (memq type pseudo-objects
))
4406 (concat results
(make-string post-blank ?\s
))
4408 (org-element--interpret-affiliated-keywords data
)
4409 (org-element-normalize-string results
)
4410 (make-string post-blank ?
\n)))))))
4412 (defun org-element--interpret-affiliated-keywords (element)
4413 "Return ELEMENT's affiliated keywords as Org syntax.
4414 If there is no affiliated keyword, return the empty string."
4415 (let ((keyword-to-org
4419 (when (member key org-element-dual-keywords
)
4420 (setq dual
(cdr value
) value
(car value
)))
4423 (format "[%s]" (org-element-interpret-data dual
)))
4425 (if (member key org-element-parsed-keywords
)
4426 (org-element-interpret-data value
)
4431 (let ((value (org-element-property prop element
))
4432 (keyword (upcase (substring (symbol-name prop
) 1))))
4434 (if (or (member keyword org-element-multiple-keywords
)
4435 ;; All attribute keywords can have multiple lines.
4436 (string-match "^ATTR_" keyword
))
4437 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4440 (funcall keyword-to-org keyword value
)))))
4441 ;; List all ELEMENT's properties matching an attribute line or an
4442 ;; affiliated keyword, but ignore translated keywords since they
4443 ;; cannot belong to the property list.
4444 (loop for prop in
(nth 1 element
) by
'cddr
4445 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4446 (or (string-match "^ATTR_" keyword
)
4448 (member keyword org-element-affiliated-keywords
)
4450 org-element-keyword-translation-alist
)))))
4454 ;; Because interpretation of the parse tree must return the same
4455 ;; number of blank lines between elements and the same number of white
4456 ;; space after objects, some special care must be given to white
4459 ;; The first function, `org-element-normalize-string', ensures any
4460 ;; string different from the empty string will end with a single
4461 ;; newline character.
4463 ;; The second function, `org-element-normalize-contents', removes
4464 ;; global indentation from the contents of the current element.
4466 (defun org-element-normalize-string (s)
4467 "Ensure string S ends with a single newline character.
4469 If S isn't a string return it unchanged. If S is the empty
4470 string, return it. Otherwise, return a new string with a single
4471 newline character at its end."
4473 ((not (stringp s
)) s
)
4475 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4476 (replace-match "\n" nil nil s
)))))
4478 (defun org-element-normalize-contents (element &optional ignore-first
)
4479 "Normalize plain text in ELEMENT's contents.
4481 ELEMENT must only contain plain text and objects.
4483 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4484 indentation to compute maximal common indentation.
4486 Return the normalized element that is element with global
4487 indentation removed from its contents. The function assumes that
4488 indentation is not done with TAB characters."
4489 (let* ((min-ind most-positive-fixnum
)
4490 find-min-ind
; For byte-compiler.
4493 ;; Return minimal common indentation within BLOB. This is
4494 ;; done by walking recursively BLOB and updating MIN-IND
4495 ;; along the way. FIRST-FLAG is non-nil when the first
4496 ;; string hasn't been seen yet. It is required as this
4497 ;; string is the only one whose indentation doesn't happen
4498 ;; after a newline character.
4499 (lambda (blob first-flag
)
4500 (dolist (object (org-element-contents blob
))
4501 (when (and first-flag
(stringp object
))
4502 (setq first-flag nil
)
4503 (string-match "\\`\\( *\\)" object
)
4504 (let ((len (length (match-string 1 object
))))
4505 ;; An indentation of zero means no string will be
4506 ;; modified. Quit the process.
4507 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4508 (setq min-ind
(min len min-ind
)))))
4511 (dolist (line (delq "" (cdr (org-split-string object
" *\n"))))
4512 (setq min-ind
(min (org-get-indentation line
) min-ind
))))
4513 ((memq (org-element-type object
) org-element-recursive-objects
)
4514 (funcall find-min-ind object first-flag
))))))))
4515 ;; Find minimal indentation in ELEMENT.
4516 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4517 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4518 ;; Build ELEMENT back, replacing each string with the same
4519 ;; string minus common indentation.
4520 (let* (build ; For byte compiler.
4523 (lambda (blob first-flag
)
4524 ;; Return BLOB with all its strings indentation
4525 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4526 ;; is non-nil when the first string hasn't been seen
4531 (when (and first-flag
(stringp object
))
4532 (setq first-flag nil
)
4534 (replace-regexp-in-string
4535 (format "\\` \\{%d\\}" min-ind
)
4539 (replace-regexp-in-string
4540 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4541 ((memq (org-element-type object
)
4542 org-element-recursive-objects
)
4543 (funcall build object first-flag
))
4545 (org-element-contents blob
)))
4547 (funcall build element
(not ignore-first
))))))
4553 ;; Implement a caching mechanism for `org-element-at-point' and
4554 ;; `org-element-context', which see.
4556 ;; A single public function is provided: `org-element-cache-reset'.
4558 ;; Cache is enabled by default, but can be disabled globally with
4559 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4560 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4561 ;; can be tweaked to control caching behaviour.
4563 ;; Internally, parsed elements are stored in an AVL tree,
4564 ;; `org-element--cache'. This tree is updated lazily: whenever
4565 ;; a change happens to the buffer, a synchronization request is
4566 ;; registered in `org-element--cache-sync-requests' (see
4567 ;; `org-element--cache-submit-request'). During idle time, requests
4568 ;; are processed by `org-element--cache-sync'. Synchronization also
4569 ;; happens when an element is required from the cache. In this case,
4570 ;; the process stops as soon as the needed element is up-to-date.
4572 ;; A synchronization request can only apply on a synchronized part of
4573 ;; the cache. Therefore, the cache is updated at least to the
4574 ;; location where the new request applies. Thus, requests are ordered
4575 ;; from left to right and all elements starting before the first
4576 ;; request are correct. This property is used by functions like
4577 ;; `org-element--cache-find' to retrieve elements in the part of the
4578 ;; cache that can be trusted.
4580 ;; A request applies to every element, starting from its original
4581 ;; location (or key, see below). When a request is processed, it
4582 ;; moves forward and may collide the next one. In this case, both
4583 ;; requests are merged into a new one that starts from that element.
4584 ;; As a consequence, the whole synchronization complexity does not
4585 ;; depend on the number of pending requests, but on the number of
4586 ;; elements the very first request will be applied on.
4588 ;; Elements cannot be accessed through their beginning position, which
4589 ;; may or may not be up-to-date. Instead, each element in the tree is
4590 ;; associated to a key, obtained with `org-element--cache-key'. This
4591 ;; mechanism is robust enough to preserve total order among elements
4592 ;; even when the tree is only partially synchronized.
4594 ;; Objects contained in an element are stored in a hash table,
4595 ;; `org-element--cache-objects'.
4598 (defvar org-element-use-cache t
4599 "Non nil when Org parser should cache its results.
4600 This is mostly for debugging purpose.")
4602 (defvar org-element-cache-sync-idle-time
0.4
4603 "Length, in seconds, of idle time before syncing cache.")
4605 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4606 "Maximum duration, as a time value, for a cache synchronization.
4607 If the synchronization is not over after this delay, the process
4608 pauses and resumes after `org-element-cache-sync-break'
4611 (defvar org-element-cache-sync-break
(seconds-to-time 0.2)
4612 "Duration, as a time value, of the pause between synchronizations.
4613 See `org-element-cache-sync-duration' for more information.")
4618 (defvar org-element--cache nil
4619 "AVL tree used to cache elements.
4620 Each node of the tree contains an element. Comparison is done
4621 with `org-element--cache-compare'. This cache is used in
4622 `org-element-at-point'.")
4624 (defvar org-element--cache-objects nil
4625 "Hash table used as to cache objects.
4626 Key is an element, as returned by `org-element-at-point', and
4627 value is an alist where each association is:
4629 \(PARENT COMPLETEP . OBJECTS)
4631 where PARENT is an element or object, COMPLETEP is a boolean,
4632 non-nil when all direct children of parent are already cached and
4633 OBJECTS is a list of such children, as objects, from farthest to
4636 In the following example, \\alpha, bold object and \\beta are
4637 contained within a paragraph
4641 If the paragraph is completely parsed, OBJECTS-DATA will be
4643 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4644 \(BOLD-OBJECT t ENTITY-OBJECT))
4646 whereas in a partially parsed paragraph, it could be
4648 \((PARAGRAPH nil ENTITY-OBJECT))
4650 This cache is used in `org-element-context'.")
4652 (defvar org-element--cache-sync-requests nil
4653 "List of pending synchronization requests.
4655 A request is a vector with the following pattern:
4657 \[NEXT END OFFSET PARENT PHASE]
4659 Processing a synchronization request consists in three phases:
4661 0. Delete modified elements,
4662 1. Fill missing area in cache,
4663 2. Shift positions and re-parent elements after the changes.
4665 During phase 0, NEXT is the key of the first element to be
4666 removed and END is buffer position delimiting the modifications.
4667 Every element starting between these are removed. PARENT is an
4668 element to be removed. Every element contained in it will also
4671 During phase 1, NEXT is the key of the next known element in
4672 cache. Parse buffer between that element and the one before it
4673 in order to determine the parent of the next element. Set PARENT
4674 to the element containing NEXT.
4676 During phase 2, NEXT is the key of the next element to shift in
4677 the parse tree. All elements starting from this one have their
4678 properties relatives to buffer positions shifted by integer
4679 OFFSET and, if they belong to element PARENT, are adopted by it.
4681 PHASE specifies the phase number, as an integer.")
4683 (defvar org-element--cache-sync-timer nil
4684 "Timer used for cache synchronization.")
4686 (defvar org-element--cache-sync-keys nil
4687 "Hash table used to store keys during synchronization.
4688 See `org-element--cache-key' for more information.")
4690 (defsubst org-element--cache-key
(element)
4691 "Return a unique key for ELEMENT in cache tree.
4693 Keys are used to keep a total order among elements in the cache.
4694 Comparison is done with `org-element--cache-key-less-p'.
4696 When no synchronization is taking place, a key is simply the
4697 beginning position of the element, or that position plus one in
4698 the case of an first item (respectively row) in
4699 a list (respectively a table).
4701 During a synchronization, the key is the one the element had when
4702 the cache was synchronized for the last time. Elements added to
4703 cache during the synchronization get a new key generated with
4704 `org-element--cache-generate-key'.
4706 Such keys are stored in `org-element--cache-sync-keys'. The hash
4707 table is cleared once the synchronization is complete."
4708 (or (gethash element org-element--cache-sync-keys
)
4709 (let* ((begin (org-element-property :begin element
))
4710 ;; Increase beginning position of items (respectively
4711 ;; table rows) by one, so the first item can get
4712 ;; a different key from its parent list (respectively
4714 (key (if (memq (org-element-type element
) '(item table-row
))
4717 (if org-element--cache-sync-requests
4718 (puthash element key org-element--cache-sync-keys
)
4721 (defconst org-element--cache-default-key
(ash most-positive-fixnum -
1)
4722 "Default value for a new key level.
4723 See `org-element--cache-generate-key' for more information.")
4725 (defun org-element--cache-generate-key (lower upper
)
4726 "Generate a key between LOWER and UPPER.
4728 LOWER and UPPER are integers or lists, possibly empty.
4730 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4731 a unique key, as an integer or a list of integers, according to
4732 the following rules:
4734 - LOWER and UPPER are compared level-wise until values differ.
4736 - If, at a given level, LOWER and UPPER differ from more than
4737 2, the new key shares all the levels above with LOWER and
4738 gets a new level. Its value is the mean between LOWER and
4741 \(1 2) + (1 4) --> (1 3)
4743 - If LOWER has no value to compare with, it is assumed that its
4746 \(1 1) + (1 1 2) --> (1 1 1)
4748 Likewise, if UPPER is short of levels, the current value is
4749 `most-positive-fixnum'.
4751 - If they differ from only one, the new key inherits from
4752 current LOWER lever and has a new level at the value
4753 `org-element--cache-default-key'.
4755 \(1 2) + (1 3) --> (1 2 org-element--cache-default-key)
4757 - If the key is only one level long, it is returned as an
4760 \(1 2) + (3 2) --> 2"
4761 (if (equal lower upper
) lower
4762 (let ((lower (if (integerp lower
) (list lower
) lower
))
4763 (upper (if (integerp upper
) (list upper
) upper
))
4766 (while (and lower upper
)
4767 (let ((lower-level (car lower
))
4768 (upper-level (car upper
)))
4770 ((= lower-level upper-level
)
4771 (push lower-level key
)
4772 (setq lower
(cdr lower
) upper
(cdr upper
)))
4773 ((= (- upper-level lower-level
) 1)
4774 (push lower-level key
)
4775 (setq lower
(cdr lower
))
4776 (while (and lower
(= (car lower
) most-positive-fixnum
))
4777 (push most-positive-fixnum key
)
4778 (setq lower
(cdr lower
)))
4780 (let ((n (car lower
)))
4781 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4782 org-element--cache-default-key
))
4783 org-element--cache-default-key
)
4787 (push (let ((n (car lower
)))
4788 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4789 (ash (car upper
) -
1)))
4794 (while (and upper
(zerop (car upper
)))
4796 (setq upper
(cdr upper
)))
4797 ;; (n) is equivalent to (n 0 0 0 0 ...) so we want to avoid
4798 ;; ending on a sequence of 0.
4799 (if (= (car upper
) 1)
4801 (push org-element--cache-default-key key
))
4802 (push (if upper
(ash (car upper
) -
1) org-element--cache-default-key
)
4805 (while (and lower
(= (car lower
) most-positive-fixnum
))
4806 (push most-positive-fixnum key
)
4807 (setq lower
(cdr lower
)))
4809 (let ((n (car lower
)))
4810 (+ (ash (if (zerop (mod n
2)) n
(1+ n
)) -
1)
4811 org-element--cache-default-key
))
4812 org-element--cache-default-key
)
4814 ;; Ensure we don't return a list with a single element.
4815 (if (cdr key
) (nreverse key
) (car key
)))))
4817 (defsubst org-element--cache-key-less-p
(a b
)
4818 "Non-nil if key A is less than key B.
4819 A and B are either integers or lists of integers, as returned by
4820 `org-element--cache-key'."
4821 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4822 (if (integerp b
) (< (car a
) b
)
4825 (cond ((car-less-than-car a b
) (throw 'exit t
))
4826 ((car-less-than-car b a
) (throw 'exit nil
))
4827 (t (setq a
(cdr a
) b
(cdr b
)))))
4828 ;; If A is empty, either keys are equal (B is also empty) or
4829 ;; B is less than A (B is longer). Therefore return nil.
4831 ;; If A is not empty, B is necessarily empty and A is less
4832 ;; than B (A is longer). Therefore, return a non-nil value.
4835 (defun org-element--cache-compare (a b
)
4836 "Non-nil when element A is located before element B."
4837 (org-element--cache-key-less-p (org-element--cache-key a
)
4838 (org-element--cache-key b
)))
4840 (defsubst org-element--cache-root
()
4841 "Return root value in cache.
4842 This function assumes `org-element--cache' is a valid AVL tree."
4843 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4848 (defsubst org-element--cache-active-p
()
4849 "Non-nil when cache is active in current buffer."
4850 (and org-element-use-cache
4851 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4853 (defun org-element--cache-find (pos &optional side
)
4854 "Find element in cache starting at POS or before.
4856 POS refers to a buffer position.
4858 When optional argument SIDE is non-nil, the function checks for
4859 elements starting at or past POS instead. If SIDE is `both', the
4860 function returns a cons cell where car is the first element
4861 starting at or before POS and cdr the first element starting
4864 The function can only find elements in the synchronized part of
4866 (let ((limit (and org-element--cache-sync-requests
4867 (aref (car org-element--cache-sync-requests
) 0)))
4868 (node (org-element--cache-root))
4871 (let* ((element (avl-tree--node-data node
))
4872 (begin (org-element-property :begin element
)))
4875 (not (org-element--cache-key-less-p
4876 (org-element--cache-key element
) limit
)))
4877 (setq node
(avl-tree--node-left node
)))
4880 node
(avl-tree--node-left node
)))
4883 node
(avl-tree--node-right node
)))
4884 ;; We found an element in cache starting at POS. If `side'
4885 ;; is `both' we also want the next one in order to generate
4886 ;; a key in-between.
4888 ;; If the element is the first row or item in a table or
4889 ;; a plain list, we always return the table or the plain
4892 ;; In any other case, we return the element found.
4894 (setq lower element
)
4895 (setq node
(avl-tree--node-right node
)))
4896 ((and (memq (org-element-type element
) '(item table-row
))
4897 (let ((parent (org-element-property :parent element
)))
4898 (and (= (org-element-property :begin element
)
4899 (org-element-property :contents-begin parent
))
4908 (both (cons lower upper
))
4910 (otherwise upper
))))
4912 (defun org-element--cache-put (element &optional data
)
4913 "Store ELEMENT in current buffer's cache, if allowed.
4914 When optional argument DATA is non-nil, assume is it object data
4915 relative to ELEMENT and store it in the objects cache."
4916 (cond ((not (org-element--cache-active-p)) nil
)
4918 (when org-element--cache-sync-requests
4919 ;; During synchronization, first build an appropriate key
4920 ;; for the new element so `avl-tree-enter' can insert it at
4921 ;; the right spot in the cache.
4922 (let ((keys (org-element--cache-find
4923 (org-element-property :begin element
) 'both
)))
4925 (org-element--cache-generate-key
4926 (and (car keys
) (org-element--cache-key (car keys
)))
4927 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4928 (org-element--cache-sync-requests
4929 (aref (car org-element--cache-sync-requests
) 0))))
4930 org-element--cache-sync-keys
)))
4931 (avl-tree-enter org-element--cache element
))
4932 ;; Headlines are not stored in cache, so objects in titles are
4933 ;; not stored either.
4934 ((eq (org-element-type element
) 'headline
) nil
)
4935 (t (puthash element data org-element--cache-objects
))))
4937 (defsubst org-element--cache-remove
(element)
4938 "Remove ELEMENT from cache.
4939 Assume ELEMENT belongs to cache and that a cache is active."
4940 (avl-tree-delete org-element--cache element
)
4941 (remhash element org-element--cache-objects
))
4944 ;;;; Synchronization
4946 (defsubst org-element--cache-set-timer
(buffer)
4947 "Set idle timer for cache synchronization in BUFFER."
4948 (when org-element--cache-sync-timer
4949 (cancel-timer org-element--cache-sync-timer
))
4950 (setq org-element--cache-sync-timer
4951 (run-with-idle-timer
4952 (let ((idle (current-idle-time)))
4953 (if idle
(time-add idle org-element-cache-sync-break
)
4954 org-element-cache-sync-idle-time
))
4956 #'org-element--cache-sync
4959 (defsubst org-element--cache-interrupt-p
(time-limit)
4960 "Non-nil when synchronization process should be interrupted.
4961 TIME-LIMIT is a time value or nil."
4963 (or (input-pending-p)
4964 (time-less-p time-limit
(current-time)))))
4966 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
4967 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4969 Properties containing buffer positions are `:begin', `:end',
4970 `:contents-begin', `:contents-end' and `:structure'. When
4971 optional argument PROPS is a list of keywords, only shift
4972 properties provided in that list.
4974 Properties are modified by side-effect."
4975 (let ((properties (nth 1 element
)))
4976 ;; Shift `:structure' property for the first plain list only: it
4977 ;; is the only one that really matters and it prevents from
4978 ;; shifting it more than once.
4979 (when (and (or (not props
) (memq :structure props
))
4980 (eq (org-element-type element
) 'plain-list
)
4981 (not (eq (org-element-type (plist-get properties
:parent
))
4983 (dolist (item (plist-get properties
:structure
))
4984 (incf (car item
) offset
)
4985 (incf (nth 6 item
) offset
)))
4986 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
4987 (let ((value (and (or (not props
) (memq key props
))
4988 (plist-get properties key
))))
4989 (and value
(plist-put properties key
(+ offset value
)))))))
4991 (defun org-element--cache-sync (buffer &optional threshold
)
4992 "Synchronize cache with recent modification in BUFFER.
4993 When optional argument THRESHOLD is non-nil, do the
4994 synchronization for all elements starting before or at threshold,
4995 then exit. Otherwise, synchronize cache for as long as
4996 `org-element-cache-sync-duration' or until Emacs leaves idle
4998 (when (buffer-live-p buffer
)
4999 (with-current-buffer buffer
5000 (let ((inhibit-quit t
) request next
)
5001 (when org-element--cache-sync-timer
5002 (cancel-timer org-element--cache-sync-timer
))
5004 (while org-element--cache-sync-requests
5005 (setq request
(car org-element--cache-sync-requests
)
5006 next
(nth 1 org-element--cache-sync-requests
))
5007 (or (org-element--cache-process-request
5009 (and next
(aref next
0))
5011 (and (not threshold
)
5012 (time-add (current-time)
5013 org-element-cache-sync-duration
)))
5014 (throw 'interrupt t
))
5015 ;; Request processed. Merge current and next offsets and
5016 ;; transfer phase number and ending position.
5018 (incf (aref next
2) (aref request
2))
5019 (aset next
1 (aref request
1))
5020 (aset next
4 (aref request
4)))
5021 (setq org-element--cache-sync-requests
5022 (cdr org-element--cache-sync-requests
))))
5023 ;; If more requests are awaiting, set idle timer accordingly.
5024 ;; Otherwise, reset keys.
5025 (if org-element--cache-sync-requests
5026 (org-element--cache-set-timer buffer
)
5027 (clrhash org-element--cache-sync-keys
))))))
5029 (defun org-element--cache-process-request (request next threshold time-limit
)
5030 "Process synchronization REQUEST for all entries before NEXT.
5032 REQUEST is a vector, built by `org-element--cache-submit-request'.
5034 NEXT is a cache key, as returned by `org-element--cache-key'.
5036 When non-nil, THRESHOLD is a buffer position. Synchronization
5037 stops as soon as a shifted element begins after it.
5039 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5040 after this time or when Emacs exits idle state.
5042 Return nil if the process stops before completing the request,
5045 (when (= (aref request
4) 0)
5048 ;; Delete all elements starting after BEG, but not after buffer
5049 ;; position END or past element with key NEXT.
5051 ;; As an exception, also delete elements starting after
5052 ;; modifications but included in an element altered by
5053 ;; modifications (orphans).
5055 ;; At each iteration, we start again at tree root since
5056 ;; a deletion modifies structure of the balanced tree.
5058 (let ((beg (aref request
0))
5059 (end (aref request
1))
5060 (deleted-parent (aref request
3)))
5062 (when (org-element--cache-interrupt-p time-limit
)
5063 (aset request
3 deleted-parent
)
5065 ;; Find first element in cache with key BEG or after it.
5066 ;; We don't use `org-element--cache-find' because it
5067 ;; couldn't reach orphaned elements past NEXT. Moreover,
5068 ;; BEG is a key, not a buffer position.
5069 (let ((node (org-element--cache-root)) data data-key
)
5071 (let* ((element (avl-tree--node-data node
))
5072 (key (org-element--cache-key element
)))
5074 ((org-element--cache-key-less-p key beg
)
5075 (setq node
(avl-tree--node-right node
)))
5076 ((org-element--cache-key-less-p beg key
)
5079 node
(avl-tree--node-left node
)))
5080 (t (setq data element
5083 (if (not data
) (throw 'quit t
)
5084 (let ((pos (org-element-property :begin data
)))
5086 ;; Remove orphaned elements.
5087 ((and deleted-parent
5090 (setq up
(org-element-property :parent up
))
5091 (not (eq up deleted-parent
))))
5093 (org-element--cache-remove data
))
5095 (not (org-element--cache-key-less-p data-key
5098 (aset request
0 data-key
)
5099 (aset request
1 pos
)
5101 (throw 'end-phase nil
))
5102 (t (org-element--cache-remove data
)
5103 (when (= (org-element-property :end data
) end
)
5104 (setq deleted-parent data
)))))))))))
5105 (when (= (aref request
4) 1)
5108 ;; Phase 1 left a hole in the parse tree. Some elements after
5109 ;; it could have parents within. For example, in the following
5121 ;; if we remove a blank line between "item" and "Paragraph1",
5122 ;; everything down to "Paragraph2" is removed from cache. But
5123 ;; the paragraph now belongs to the list, and its `:parent'
5124 ;; property no longer is accurate.
5126 ;; Therefore we need to parse again elements in the hole, or at
5127 ;; least in its last section, so that we can re-parent
5128 ;; subsequent elements, during phase 3.
5130 ;; Note that we only need to get the parent from the first
5131 ;; element in cache after the hole.
5133 ;; Also, this part can be delayed if we don't need to retrieve
5134 ;; an element after the hole.
5136 ;; Next element will start at its beginning position plus
5137 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5138 ;; contains the real beginning position of the first element
5139 ;; to shift and re-parent.
5140 (when (equal (aref request
0) next
) (throw 'quit t
))
5141 (let ((limit (+ (aref request
1) (aref request
2))))
5142 (when (and threshold
(< threshold limit
)) (throw 'quit nil
))
5143 (let ((parent (org-element--parse-to limit t time-limit
)))
5144 (if (eq parent
'interrupted
) (throw 'quit nil
)
5145 (aset request
3 parent
)
5147 (throw 'end-phase nil
))))))
5150 ;; Shift all elements starting from key START, but before NEXT, by
5151 ;; OFFSET, and re-parent them when appropriate.
5153 ;; Elements are modified by side-effect so the tree structure
5156 ;; Once THRESHOLD, if any, is reached, or once there is an input
5157 ;; pending, exit. Before leaving, the current synchronization
5158 ;; request is updated.
5159 (let ((start (aref request
0))
5160 (offset (aref request
2))
5161 (parent (aref request
3))
5162 (node (org-element--cache-root))
5166 ;; No re-parenting nor shifting planned: request is over.
5167 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5169 (let* ((data (avl-tree--node-data node
))
5170 (key (org-element--cache-key data
)))
5171 (if (and leftp
(avl-tree--node-left node
)
5172 (not (org-element--cache-key-less-p key start
)))
5173 (progn (push node stack
)
5174 (setq node
(avl-tree--node-left node
)))
5175 (unless (org-element--cache-key-less-p key start
)
5176 ;; We reached NEXT. Request is complete.
5177 (when (equal key next
) (throw 'quit t
))
5178 ;; Handle interruption request. Update current request.
5179 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5180 (aset request
0 key
)
5181 (aset request
3 parent
)
5184 (unless (zerop offset
)
5185 (org-element--cache-shift-positions data offset
)
5186 ;; Shift associated objects data, if any.
5187 (dolist (object-data (gethash data org-element--cache-objects
))
5188 (dolist (object (cddr object-data
))
5189 (org-element--cache-shift-positions object offset
))))
5190 (let ((begin (org-element-property :begin data
)))
5193 (<= (org-element-property :end parent
) begin
))
5194 (setq parent
(org-element-property :parent parent
)))
5195 (cond (parent (org-element-put-property data
:parent parent
))
5196 ((zerop offset
) (throw 'quit t
)))
5197 ;; Cache is up-to-date past THRESHOLD. Request
5199 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5200 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5201 (avl-tree--node-right node
)
5203 ;; We reached end of tree: synchronization complete.
5206 (defun org-element--parse-to (pos &optional syncp time-limit
)
5207 "Parse elements in current section, down to POS.
5209 Start parsing from the closest between the last known element in
5210 cache or headline above. Return the smallest element containing
5213 When optional argument SYNCP is non-nil, return the parent of the
5214 element containing POS instead. In that case, it is also
5215 possible to provide TIME-LIMIT, which is a time value specifying
5216 when the parsing should stop. The function returns `interrupted'
5217 if the process stopped before finding the expected result."
5219 (org-with-wide-buffer
5221 (let* ((cached (and (org-element--cache-active-p)
5222 (org-element--cache-find pos nil
)))
5223 (begin (org-element-property :begin cached
))
5226 ;; Nothing in cache before point: start parsing from first
5227 ;; element following headline above, or first element in
5230 (when (org-with-limited-levels (outline-previous-heading))
5232 (skip-chars-forward " \r\t\n")
5233 (beginning-of-line))
5234 ;; Cache returned exact match: return it.
5236 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5237 ;; There's a headline between cached value and POS: cached
5238 ;; value is invalid. Start parsing from first element
5239 ;; following the headline.
5240 ((re-search-backward
5241 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5243 (skip-chars-forward " \r\t\n")
5244 (beginning-of-line))
5245 ;; Check if CACHED or any of its ancestors contain point.
5247 ;; If there is such an element, we inspect it in order to know
5248 ;; if we return it or if we need to parse its contents.
5249 ;; Otherwise, we just start parsing from current location,
5250 ;; which is right after the top-most element containing
5253 ;; As a special case, if POS is at the end of the buffer, we
5254 ;; want to return the innermost element ending there.
5256 ;; Also, if we find an ancestor and discover that we need to
5257 ;; parse its contents, make sure we don't start from
5258 ;; `:contents-begin', as we would otherwise go past CACHED
5259 ;; again. Instead, in that situation, we will resume parsing
5260 ;; from NEXT, which is located after CACHED or its higher
5261 ;; ancestor not containing point.
5264 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5265 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5266 (while (let ((end (org-element-property :end up
)))
5269 (setq up
(org-element-property :parent up
)))))
5271 ((eobp) (setq element up
))
5272 (t (setq element up next
(point)))))))
5273 ;; Parse successively each element until we reach POS.
5274 (let ((end (or (org-element-property :end element
)
5276 (org-with-limited-levels (outline-next-heading))
5282 (cond ((= (point) pos
) (throw 'exit parent
))
5283 ((org-element--cache-interrupt-p time-limit
)
5284 (throw 'exit
'interrupted
))))
5286 (setq element
(org-element--current-element
5287 end
'element special-flag
5288 (org-element-property :structure parent
)))
5289 (org-element-put-property element
:parent parent
)
5290 (org-element--cache-put element
))
5291 (let ((elem-end (org-element-property :end element
))
5292 (type (org-element-type element
)))
5294 ;; Skip any element ending before point. Also skip
5295 ;; element ending at point (unless it is also the end of
5296 ;; buffer) since we're sure that another element begins
5298 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5299 (goto-char elem-end
))
5300 ;; A non-greater element contains point: return it.
5301 ((not (memq type org-element-greater-elements
))
5302 (throw 'exit element
))
5303 ;; Otherwise, we have to decide if ELEMENT really
5304 ;; contains POS. In that case we start parsing from
5305 ;; contents' beginning.
5307 ;; If POS is at contents' beginning but it is also at
5308 ;; the beginning of the first item in a list or a table.
5309 ;; In that case, we need to create an anchor for that
5310 ;; list or table, so return it.
5312 ;; Also, if POS is at the end of the buffer, no element
5313 ;; can start after it, but more than one may end there.
5314 ;; Arbitrarily, we choose to return the innermost of
5316 ((let ((cbeg (org-element-property :contents-begin element
))
5317 (cend (org-element-property :contents-end element
)))
5322 (not (memq type
'(plain-list table
)))))
5324 (and (= cend pos
) (= (point-max) pos
)))))
5325 (goto-char (or next cbeg
))
5327 special-flag
(case type
5329 (property-drawer 'node-property
)
5333 ;; Otherwise, return ELEMENT as it is the smallest
5334 ;; element containing POS.
5335 (t (throw 'exit element
))))
5336 (setq element nil
)))))))
5339 ;;;; Staging Buffer Changes
5341 (defconst org-element--cache-opening-line
5342 (concat "^[ \t]*\\(?:"
5343 "#\\+BEGIN[:_]" "\\|"
5344 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
5347 "Regexp matching an element opening line.
5348 When such a line is modified, modifications may propagate after
5349 modified area. In that situation, every element between that
5350 area and next section is removed from cache.")
5352 (defconst org-element--cache-closing-line
5353 (concat "^[ \t]*\\(?:"
5354 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
5355 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
5358 "Regexp matching an element closing line.
5359 When such a line is modified, modifications may propagate before
5360 modified area. In that situation, every element between that
5361 area and previous section is removed from cache.")
5363 (defvar org-element--cache-change-warning nil
5364 "Non-nil when a sensitive line is about to be changed.
5365 It is a symbol among nil, t and `headline'.")
5367 (defun org-element--cache-before-change (beg end
)
5368 "Request extension of area going to be modified if needed.
5369 BEG and END are the beginning and end of the range of changed
5370 text. See `before-change-functions' for more information."
5371 (let ((inhibit-quit t
))
5372 ;; Make sure buffer positions in cache are correct until END.
5374 (org-element--cache-sync (current-buffer) end
)
5375 (org-with-wide-buffer
5379 (bottom (save-excursion (goto-char end
) (line-end-position)))
5381 ;; A sensitive line is a headline or a block (or drawer,
5382 ;; or latex-environment) boundary. Inserting one can
5383 ;; modify buffer drastically both above and below that
5384 ;; line, possibly making cache invalid. Therefore, we
5385 ;; need to pay attention to changes happening to them.
5387 "\\(" (org-with-limited-levels org-outline-regexp-bol
) "\\)" "\\|"
5388 org-element--cache-closing-line
"\\|"
5389 org-element--cache-opening-line
)))
5390 (setq org-element--cache-change-warning
5391 (cond ((not (re-search-forward sensitive-re bottom t
)) nil
)
5392 ((and (match-beginning 1)
5393 (progn (goto-char bottom
)
5394 (or (not (re-search-backward sensitive-re
5396 (match-beginning 1))))
5400 (defun org-element--cache-after-change (beg end pre
)
5401 "Update buffer modifications for current buffer.
5402 BEG and END are the beginning and end of the range of changed
5403 text, and the length in bytes of the pre-change text replaced by
5404 that range. See `after-change-functions' for more information."
5405 (let ((inhibit-quit t
))
5406 (when (org-element--cache-active-p)
5407 (org-with-wide-buffer
5411 (bottom (save-excursion (goto-char end
) (line-end-position))))
5412 (org-with-limited-levels
5414 ;; Determine if modified area needs to be extended,
5415 ;; according to both previous and current state. We make
5416 ;; a special case for headline editing: if a headline is
5417 ;; modified but not removed, do not extend.
5418 (when (let ((previous-state org-element--cache-change-warning
)
5420 (concat "\\(" org-outline-regexp-bol
"\\)" "\\|"
5421 org-element--cache-closing-line
"\\|"
5422 org-element--cache-opening-line
))
5423 (case-fold-search t
))
5424 (cond ((eq previous-state t
))
5425 ((not (re-search-forward sensitive-re bottom t
))
5426 (eq previous-state
'headline
))
5427 ((match-beginning 1)
5428 (or (not (eq previous-state
'headline
))
5429 (and (progn (goto-char bottom
)
5431 sensitive-re
(match-end 1) t
))
5432 (not (match-beginning 1)))))
5434 ;; Effectively extend modified area.
5435 (setq top
(progn (goto-char top
)
5436 (when (outline-previous-heading) (forward-line))
5438 (setq bottom
(progn (goto-char bottom
)
5439 (if (outline-next-heading) (1- (point))
5441 ;; Store synchronization request.
5442 (let ((offset (- end beg pre
)))
5443 (org-element--cache-submit-request top
(- bottom offset
) offset
))))
5444 ;; Activate a timer to process the request during idle time.
5445 (org-element--cache-set-timer (current-buffer)))))
5447 (defun org-element--cache-submit-request (beg end offset
)
5448 "Submit a new cache synchronization request for current buffer.
5449 BEG and END are buffer positions delimiting the minimal area
5450 where cache data should be removed. OFFSET is the size of the
5451 change, as an integer."
5452 (let ((first-element
5453 ;; Find the position of the first element in cache to remove.
5455 ;; Partially modified elements will be removed during request
5456 ;; processing. As an exception, greater elements around the
5457 ;; changes that are robust to contents modifications are
5460 ;; We look just before BEG because an element ending at BEG
5461 ;; needs to be removed too.
5462 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5463 (before (car elements
))
5464 (after (cdr elements
)))
5465 (if (not before
) after
5467 (while (setq up
(org-element-property :parent up
))
5468 (if (and (memq (org-element-type up
)
5470 drawer dynamic-block inlinetask
5471 property-drawer quote-block special-block
))
5472 (<= (org-element-property :contents-begin up
) beg
)
5473 (> (org-element-property :contents-end up
) end
))
5474 ;; UP is a greater element that is wrapped around
5475 ;; the changes. We only need to extend its
5476 ;; ending boundaries and those of all its
5479 (org-element--cache-shift-positions
5480 up offset
'(:contents-end
:end
))
5481 (setq up
(org-element-property :parent up
)))
5483 ;; We're at top level element containing ELEMENT: if
5484 ;; it's altered by buffer modifications, it is first
5485 ;; element in cache to be removed. Otherwise, that
5486 ;; first element is the following one.
5487 (if (< (org-element-property :end before
) beg
) after before
))))))
5489 ;; Changes happened before the first known element. Shift the
5490 ;; rest of the cache.
5491 ((and first-element
(> (org-element-property :begin first-element
) end
))
5492 (push (vector (org-element--cache-key first-element
) nil offset nil
2)
5493 org-element--cache-sync-requests
))
5494 ;; There is at least an element to remove. Find position past
5495 ;; every element containing END.
5497 (if (> (org-element-property :end first-element
) end
)
5498 (setq end
(org-element-property :end first-element
))
5499 (let ((element (org-element--cache-find end
)))
5500 (setq end
(org-element-property :end element
))
5502 (while (and (setq up
(org-element-property :parent up
))
5503 (>= (org-element-property :begin up
) beg
))
5504 (setq end
(org-element-property :end up
))))))
5505 (push (vector (org-element--cache-key first-element
) end offset nil
0)
5506 org-element--cache-sync-requests
))
5507 ;; No element to remove. No need to re-parent either. Simply
5508 ;; shift additional elements, if any, by OFFSET.
5509 (org-element--cache-sync-requests
5510 (incf (aref (car org-element--cache-sync-requests
) 2) offset
)))))
5513 ;;;; Public Functions
5516 (defun org-element-cache-reset (&optional all
)
5517 "Reset cache in current buffer.
5518 When optional argument ALL is non-nil, reset cache in all Org
5521 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5522 (with-current-buffer buffer
5523 (when (org-element--cache-active-p)
5524 (org-set-local 'org-element--cache
5525 (avl-tree-create #'org-element--cache-compare
))
5526 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5527 (org-set-local 'org-element--cache-sync-keys
5528 (make-hash-table :weakness
'key
:test
#'eq
))
5529 (org-set-local 'org-element--cache-change-warning nil
)
5530 (org-set-local 'org-element--cache-sync-requests nil
)
5531 (org-set-local 'org-element--cache-sync-timer nil
)
5532 (add-hook 'before-change-functions
5533 #'org-element--cache-before-change nil t
)
5534 (add-hook 'after-change-functions
5535 #'org-element--cache-after-change nil t
)))))
5538 (defun org-element-cache-refresh (pos)
5539 "Refresh cache at position POS."
5540 (when (org-element--cache-active-p)
5541 (org-element--cache-sync (current-buffer) pos
)
5542 (org-element--cache-submit-request pos pos
0)
5543 (org-element--cache-set-timer (current-buffer))))
5549 ;; The first move is to implement a way to obtain the smallest element
5550 ;; containing point. This is the job of `org-element-at-point'. It
5551 ;; basically jumps back to the beginning of section containing point
5552 ;; and proceed, one element after the other, with
5553 ;; `org-element--current-element' until the container is found. Note:
5554 ;; When using `org-element-at-point', secondary values are never
5555 ;; parsed since the function focuses on elements, not on objects.
5557 ;; At a deeper level, `org-element-context' lists all elements and
5558 ;; objects containing point.
5560 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5561 ;; internally by navigation and manipulation tools.
5565 (defun org-element-at-point ()
5566 "Determine closest element around point.
5568 Return value is a list like (TYPE PROPS) where TYPE is the type
5569 of the element and PROPS a plist of properties associated to the
5572 Possible types are defined in `org-element-all-elements'.
5573 Properties depend on element or object type, but always include
5574 `:begin', `:end', `:parent' and `:post-blank' properties.
5576 As a special case, if point is at the very beginning of the first
5577 item in a list or sub-list, returned element will be that list
5578 instead of the item. Likewise, if point is at the beginning of
5579 the first row of a table, returned element will be the table
5580 instead of the first row.
5582 When point is at the end of the buffer, return the innermost
5583 element ending there."
5584 (org-with-wide-buffer
5585 (let ((origin (point)))
5587 (skip-chars-backward " \r\t\n")
5589 ;; Within blank lines at the beginning of buffer, return nil.
5591 ;; Within blank lines right after a headline, return that
5593 ((org-with-limited-levels (org-at-heading-p))
5595 (org-element-headline-parser (point-max) t
))
5596 ;; Otherwise parse until we find element containing ORIGIN.
5598 (when (org-element--cache-active-p)
5599 (if (not org-element--cache
) (org-element-cache-reset)
5600 (org-element--cache-sync (current-buffer) origin
)))
5601 (org-element--parse-to origin
))))))
5604 (defun org-element-context (&optional element
)
5605 "Return smallest element or object around point.
5607 Return value is a list like (TYPE PROPS) where TYPE is the type
5608 of the element or object and PROPS a plist of properties
5611 Possible types are defined in `org-element-all-elements' and
5612 `org-element-all-objects'. Properties depend on element or
5613 object type, but always include `:begin', `:end', `:parent' and
5616 As a special case, if point is right after an object and not at
5617 the beginning of any other object, return that object.
5619 Optional argument ELEMENT, when non-nil, is the closest element
5620 containing point, as returned by `org-element-at-point'.
5621 Providing it allows for quicker computation."
5622 (catch 'objects-forbidden
5623 (org-with-wide-buffer
5624 (let* ((pos (point))
5625 (element (or element
(org-element-at-point)))
5626 (type (org-element-type element
)))
5627 ;; If point is inside an element containing objects or
5628 ;; a secondary string, narrow buffer to the container and
5629 ;; proceed with parsing. Otherwise, return ELEMENT.
5631 ;; At a parsed affiliated keyword, check if we're inside main
5633 ((let ((post (org-element-property :post-affiliated element
)))
5634 (and post
(< pos post
)))
5636 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5638 ((not (member-ignore-case (match-string 1)
5639 org-element-parsed-keywords
))
5640 (throw 'objects-forbidden element
))
5641 ((< (match-end 0) pos
)
5642 (narrow-to-region (match-end 0) (line-end-position)))
5643 ((and (match-beginning 2)
5644 (>= pos
(match-beginning 2))
5645 (< pos
(match-end 2)))
5646 (narrow-to-region (match-beginning 2) (match-end 2)))
5647 (t (throw 'objects-forbidden element
)))
5648 ;; Also change type to retrieve correct restrictions.
5649 (setq type
'keyword
))
5650 ;; At an item, objects can only be located within tag, if any.
5652 (let ((tag (org-element-property :tag element
)))
5653 (if (not tag
) (throw 'objects-forbidden element
)
5655 (search-forward tag
(line-end-position))
5656 (goto-char (match-beginning 0))
5657 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5658 (narrow-to-region (point) (match-end 0))
5659 (throw 'objects-forbidden element
)))))
5660 ;; At an headline or inlinetask, objects are in title.
5661 ((memq type
'(headline inlinetask
))
5662 (goto-char (org-element-property :begin element
))
5663 (skip-chars-forward "*")
5664 (if (and (> pos
(point)) (< pos
(line-end-position)))
5665 (narrow-to-region (point) (line-end-position))
5666 (throw 'objects-forbidden element
)))
5667 ;; At a paragraph, a table-row or a verse block, objects are
5668 ;; located within their contents.
5669 ((memq type
'(paragraph table-row verse-block
))
5670 (let ((cbeg (org-element-property :contents-begin element
))
5671 (cend (org-element-property :contents-end element
)))
5672 ;; CBEG is nil for table rules.
5673 (if (and cbeg cend
(>= pos cbeg
)
5674 (or (< pos cend
) (and (= pos cend
) (eobp))))
5675 (narrow-to-region cbeg cend
)
5676 (throw 'objects-forbidden element
))))
5677 ;; At a parsed keyword, objects are located within value.
5679 (if (not (member (org-element-property :key element
)
5680 org-element-document-properties
))
5681 (throw 'objects-forbidden element
)
5683 (search-forward ":")
5684 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5685 (narrow-to-region (point) (line-end-position))
5686 (throw 'objects-forbidden element
))))
5687 ;; At a planning line, if point is at a timestamp, return it,
5688 ;; otherwise, return element.
5689 ((eq type
'planning
)
5690 (dolist (p '(:closed
:deadline
:scheduled
))
5691 (let ((timestamp (org-element-property p element
)))
5692 (when (and timestamp
5693 (<= (org-element-property :begin timestamp
) pos
)
5694 (> (org-element-property :end timestamp
) pos
))
5695 (throw 'objects-forbidden timestamp
))))
5696 ;; All other locations cannot contain objects: bail out.
5697 (throw 'objects-forbidden element
))
5698 (t (throw 'objects-forbidden element
)))
5699 (goto-char (point-min))
5700 (let ((restriction (org-element-restriction type
))
5702 (cache (cond ((not (org-element--cache-active-p)) nil
)
5703 (org-element--cache-objects
5704 (gethash element org-element--cache-objects
))
5705 (t (org-element-cache-reset) nil
)))
5706 next object-data last
)
5710 ;; When entering PARENT for the first time, get list
5711 ;; of objects within known so far. Store it in
5714 (let ((data (assq parent cache
)))
5715 (if data
(setq object-data data
)
5716 (push (setq object-data
(list parent nil
)) cache
))))
5717 ;; Find NEXT object for analysis.
5719 ;; If NEXT is non-nil, we already exhausted the
5720 ;; cache so we can parse buffer to find the object
5722 (if next
(setq next
(org-element--object-lex restriction
))
5723 ;; Otherwise, check if cache can help us.
5724 (let ((objects (cddr object-data
))
5725 (completep (nth 1 object-data
)))
5727 ((and (not objects
) completep
) (throw 'exit parent
))
5729 (setq next
(org-element--object-lex restriction
)))
5732 (org-element-property :end
(car objects
))))
5733 (if (>= cache-limit pos
)
5734 ;; Cache contains the information needed.
5735 (dolist (object objects
(throw 'exit parent
))
5736 (when (<= (org-element-property :begin object
)
5738 (if (>= (org-element-property :end object
)
5740 (throw 'found
(setq next object
))
5741 (throw 'exit parent
))))
5742 (goto-char cache-limit
)
5744 (org-element--object-lex restriction
))))))))
5745 ;; If we have a new object to analyze, store it in
5746 ;; cache. Otherwise record that there is nothing
5747 ;; more to parse in this element at this depth.
5749 (progn (org-element-put-property next
:parent parent
)
5750 (push next
(cddr object-data
)))
5751 (setcar (cdr object-data
) t
)))
5752 ;; Process NEXT, if any, in order to know if we need
5753 ;; to skip it, return it or move into it.
5754 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5755 (throw 'exit
(or last parent
))
5756 (let ((end (org-element-property :end next
))
5757 (cbeg (org-element-property :contents-begin next
))
5758 (cend (org-element-property :contents-end next
)))
5760 ;; Skip objects ending before point. Also skip
5761 ;; objects ending at point unless it is also the
5762 ;; end of buffer, since we want to return the
5763 ;; innermost object.
5764 ((and (<= end pos
) (/= (point-max) end
))
5766 ;; For convenience, when object ends at POS,
5767 ;; without any space, store it in LAST, as we
5768 ;; will return it if no object starts here.
5769 (when (and (= end pos
)
5770 (not (memq (char-before) '(?\s ?
\t))))
5772 ;; If POS is within a container object, move
5773 ;; into that object.
5777 ;; At contents' end, if there is no
5778 ;; space before point, also move into
5779 ;; object, for consistency with
5780 ;; convenience feature above.
5782 (or (= (point-max) pos
)
5783 (not (memq (char-before pos
)
5786 (narrow-to-region (point) cend
)
5788 restriction
(org-element-restriction next
)
5791 ;; Otherwise, return NEXT.
5792 (t (throw 'exit next
)))))))
5793 ;; Store results in cache, if applicable.
5794 (org-element--cache-put element cache
)))))))
5796 (defun org-element-nested-p (elem-A elem-B
)
5797 "Non-nil when elements ELEM-A and ELEM-B are nested."
5798 (let ((beg-A (org-element-property :begin elem-A
))
5799 (beg-B (org-element-property :begin elem-B
))
5800 (end-A (org-element-property :end elem-A
))
5801 (end-B (org-element-property :end elem-B
)))
5802 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5803 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5805 (defun org-element-swap-A-B (elem-A elem-B
)
5806 "Swap elements ELEM-A and ELEM-B.
5807 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5809 (goto-char (org-element-property :begin elem-A
))
5810 ;; There are two special cases when an element doesn't start at bol:
5811 ;; the first paragraph in an item or in a footnote definition.
5812 (let ((specialp (not (bolp))))
5813 ;; Only a paragraph without any affiliated keyword can be moved at
5814 ;; ELEM-A position in such a situation. Note that the case of
5815 ;; a footnote definition is impossible: it cannot contain two
5816 ;; paragraphs in a row because it cannot contain a blank line.
5818 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5819 (/= (org-element-property :begin elem-B
)
5820 (org-element-property :contents-begin elem-B
))))
5821 (error "Cannot swap elements"))
5822 ;; In a special situation, ELEM-A will have no indentation. We'll
5823 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5824 (let* ((ind-B (when specialp
5825 (goto-char (org-element-property :begin elem-B
))
5826 (org-get-indentation)))
5827 (beg-A (org-element-property :begin elem-A
))
5828 (end-A (save-excursion
5829 (goto-char (org-element-property :end elem-A
))
5830 (skip-chars-backward " \r\t\n")
5832 (beg-B (org-element-property :begin elem-B
))
5833 (end-B (save-excursion
5834 (goto-char (org-element-property :end elem-B
))
5835 (skip-chars-backward " \r\t\n")
5837 ;; Store overlays responsible for visibility status. We
5838 ;; also need to store their boundaries as they will be
5839 ;; removed from buffer.
5842 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5843 (overlays-in beg-A end-A
))
5844 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5845 (overlays-in beg-B end-B
))))
5847 (body-A (buffer-substring beg-A end-A
))
5848 (body-B (delete-and-extract-region beg-B end-B
)))
5851 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5852 (org-indent-to-column ind-B
))
5854 ;; Restore ex ELEM-A overlays.
5855 (let ((offset (- beg-B beg-A
)))
5858 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5861 (delete-region beg-A end-A
)
5863 ;; Restore ex ELEM-B overlays.
5866 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5868 (goto-char (org-element-property :end elem-B
)))))
5870 (defun org-element-remove-indentation (s &optional n
)
5871 "Remove maximum common indentation in string S and return it.
5872 When optional argument N is a positive integer, remove exactly
5873 that much characters from indentation, if possible, or return
5874 S as-is otherwise. Unlike to `org-remove-indentation', this
5875 function doesn't call `untabify' on S."
5879 (goto-char (point-min))
5880 ;; Find maximum common indentation, if not specified.
5882 (let ((min-ind (point-max)))
5884 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5885 (let ((ind (1- (current-column))))
5886 (if (zerop ind
) (throw 'exit s
)
5887 (setq min-ind
(min min-ind ind
))))))
5890 ;; Remove exactly N indentation, but give up if not possible.
5892 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5893 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5894 ((< ind n
) (throw 'exit s
))
5895 (t (org-indent-line-to (- ind n
))))
5901 (provide 'org-element
)
5904 ;; generated-autoload-file: "org-loaddefs.el"
5907 ;;; org-element.el ends here