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 footnote-reference italic link subscript radio-target strike-through
198 superscript 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 "Alist between element types and location of secondary value.")
347 (defconst org-element-object-variables
'(org-link-abbrev-alist-local)
348 "List of buffer-local variables used when parsing objects.
349 These variables are copied to the temporary buffer created by
350 `org-export-secondary-string'.")
354 ;;; Accessors and Setters
356 ;; Provide four accessors: `org-element-type', `org-element-property'
357 ;; `org-element-contents' and `org-element-restriction'.
359 ;; Setter functions allow to modify elements by side effect. There is
360 ;; `org-element-put-property', `org-element-set-contents'. These
361 ;; low-level functions are useful to build a parse tree.
363 ;; `org-element-adopt-element', `org-element-set-element',
364 ;; `org-element-extract-element' and `org-element-insert-before' are
365 ;; high-level functions useful to modify a parse tree.
367 ;; `org-element-secondary-p' is a predicate used to know if a given
368 ;; object belongs to a secondary string.
370 (defsubst org-element-type
(element)
371 "Return type of ELEMENT.
373 The function returns the type of the element or object provided.
374 It can also return the following special value:
375 `plain-text' for a string
376 `org-data' for a complete document
377 nil in any other case."
379 ((not (consp element
)) (and (stringp element
) 'plain-text
))
380 ((symbolp (car element
)) (car element
))))
382 (defsubst org-element-property
(property element
)
383 "Extract the value from the PROPERTY of an ELEMENT."
384 (if (stringp element
) (get-text-property 0 property element
)
385 (plist-get (nth 1 element
) property
)))
387 (defsubst org-element-contents
(element)
388 "Extract contents from an ELEMENT."
389 (cond ((not (consp element
)) nil
)
390 ((symbolp (car element
)) (nthcdr 2 element
))
393 (defsubst org-element-restriction
(element)
394 "Return restriction associated to ELEMENT.
395 ELEMENT can be an element, an object or a symbol representing an
396 element or object type."
397 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
398 org-element-object-restrictions
)))
400 (defsubst org-element-put-property
(element property value
)
401 "In ELEMENT set PROPERTY to VALUE.
402 Return modified element."
403 (if (stringp element
) (org-add-props element nil property value
)
404 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
407 (defsubst org-element-set-contents
(element &rest contents
)
408 "Set ELEMENT contents to CONTENTS.
409 Return modified element."
410 (cond ((not element
) (list contents
))
411 ((not (symbolp (car element
))) contents
)
412 ((cdr element
) (setcdr (cdr element
) contents
))
413 (t (nconc element contents
))))
415 (defun org-element-secondary-p (object)
416 "Non-nil when OBJECT belongs to a secondary string.
417 Return value is the property name, as a keyword, or nil."
418 (let* ((parent (org-element-property :parent object
))
419 (property (cdr (assq (org-element-type parent
)
420 org-element-secondary-value-alist
))))
422 (memq object
(org-element-property property parent
))
425 (defsubst org-element-adopt-elements
(parent &rest children
)
426 "Append elements to the contents of another element.
428 PARENT is an element or object. CHILDREN can be elements,
429 objects, or a strings.
431 The function takes care of setting `:parent' property for CHILD.
432 Return parent element."
433 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
434 ;; string: parent is the list itself.
435 (mapc (lambda (child)
436 (org-element-put-property child
:parent
(or parent children
)))
438 ;; Add CHILDREN at the end of PARENT contents.
440 (apply 'org-element-set-contents
442 (nconc (org-element-contents parent
) children
)))
443 ;; Return modified PARENT element.
444 (or parent children
))
446 (defun org-element-extract-element (element)
447 "Extract ELEMENT from parse tree.
448 Remove element from the parse tree by side-effect, and return it
449 with its `:parent' property stripped out."
450 (let ((parent (org-element-property :parent element
))
451 (secondary (org-element-secondary-p element
)))
453 (org-element-put-property
455 (delq element
(org-element-property secondary parent
)))
456 (apply #'org-element-set-contents
458 (delq element
(org-element-contents parent
))))
459 ;; Return ELEMENT with its :parent removed.
460 (org-element-put-property element
:parent nil
)))
462 (defun org-element-insert-before (element location
)
463 "Insert ELEMENT before LOCATION in parse tree.
464 LOCATION is an element, object or string within the parse tree.
465 Parse tree is modified by side effect."
466 (let* ((parent (org-element-property :parent location
))
467 (property (org-element-secondary-p location
))
468 (siblings (if property
(org-element-property property parent
)
469 (org-element-contents parent
)))
470 ;; Special case: LOCATION is the first element of an
471 ;; independent secondary string (e.g. :title property). Add
473 (specialp (and (not property
)
475 (eq (car parent
) location
))))
476 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
478 ((or (null siblings
) (eq (car siblings
) location
))
479 (push element siblings
))
480 ((null location
) (nconc siblings
(list element
)))
481 (t (let ((previous (cadr (memq location
(reverse siblings
)))))
483 (error "No location found to insert element")
484 (let ((next (memq previous siblings
)))
485 (setcdr next
(cons element
(cdr next
))))))))
486 ;; Store SIBLINGS at appropriate place in parse tree.
488 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
489 (property (org-element-put-property parent property siblings
))
490 (t (apply #'org-element-set-contents parent siblings
)))
491 ;; Set appropriate :parent property.
492 (org-element-put-property element
:parent parent
)))
494 (defun org-element-set-element (old new
)
495 "Replace element or object OLD with element or object NEW.
496 The function takes care of setting `:parent' property for NEW."
497 ;; Ensure OLD and NEW have the same parent.
498 (org-element-put-property new
:parent
(org-element-property :parent old
))
499 (if (or (memq (org-element-type old
) '(plain-text nil
))
500 (memq (org-element-type new
) '(plain-text nil
)))
501 ;; We cannot replace OLD with NEW since one of them is not an
502 ;; object or element. We take the long path.
503 (progn (org-element-insert-before new old
)
504 (org-element-extract-element old
))
505 ;; Since OLD is going to be changed into NEW by side-effect, first
506 ;; make sure that every element or object within NEW has OLD as
508 (dolist (blob (org-element-contents new
))
509 (org-element-put-property blob
:parent old
))
510 ;; Transfer contents.
511 (apply #'org-element-set-contents old
(org-element-contents new
))
512 ;; Overwrite OLD's properties with NEW's.
513 (setcar (cdr old
) (nth 1 new
))
515 (setcar old
(car new
))))
521 ;; For each greater element type, we define a parser and an
524 ;; A parser returns the element or object as the list described above.
525 ;; Most of them accepts no argument. Though, exceptions exist. Hence
526 ;; every element containing a secondary string (see
527 ;; `org-element-secondary-value-alist') will accept an optional
528 ;; argument to toggle parsing of that secondary string. Moreover,
529 ;; `item' parser requires current list's structure as its first
532 ;; An interpreter accepts two arguments: the list representation of
533 ;; the element or object, and its contents. The latter may be nil,
534 ;; depending on the element or object considered. It returns the
535 ;; appropriate Org syntax, as a string.
537 ;; Parsing functions must follow the naming convention:
538 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
539 ;; defined in `org-element-greater-elements'.
541 ;; Similarly, interpreting functions must follow the naming
542 ;; convention: org-element-TYPE-interpreter.
544 ;; With the exception of `headline' and `item' types, greater elements
545 ;; cannot contain other greater elements of their own type.
547 ;; Beside implementing a parser and an interpreter, adding a new
548 ;; greater element requires to tweak `org-element--current-element'.
549 ;; Moreover, the newly defined type must be added to both
550 ;; `org-element-all-elements' and `org-element-greater-elements'.
555 (defun org-element-center-block-parser (limit affiliated
)
556 "Parse a center block.
558 LIMIT bounds the search. AFFILIATED is a list of which CAR is
559 the buffer position at the beginning of the first affiliated
560 keyword and CDR is a plist of affiliated keywords along with
563 Return a list whose CAR is `center-block' and CDR is a plist
564 containing `:begin', `:end', `:contents-begin', `:contents-end',
565 `:post-blank' and `:post-affiliated' keywords.
567 Assume point is at the beginning of the block."
568 (let ((case-fold-search t
))
569 (if (not (save-excursion
570 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
571 ;; Incomplete block: parse it as a paragraph.
572 (org-element-paragraph-parser limit affiliated
)
573 (let ((block-end-line (match-beginning 0)))
574 (let* ((begin (car affiliated
))
575 (post-affiliated (point))
576 ;; Empty blocks have no contents.
577 (contents-begin (progn (forward-line)
578 (and (< (point) block-end-line
)
580 (contents-end (and contents-begin block-end-line
))
581 (pos-before-blank (progn (goto-char block-end-line
)
585 (skip-chars-forward " \r\t\n" limit
)
586 (if (eobp) (point) (line-beginning-position)))))
591 :contents-begin contents-begin
592 :contents-end contents-end
593 :post-blank
(count-lines pos-before-blank end
)
594 :post-affiliated post-affiliated
)
595 (cdr affiliated
))))))))
597 (defun org-element-center-block-interpreter (center-block contents
)
598 "Interpret CENTER-BLOCK element as Org syntax.
599 CONTENTS is the contents of the element."
600 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
605 (defun org-element-drawer-parser (limit affiliated
)
608 LIMIT bounds the search. AFFILIATED is a list of which CAR is
609 the buffer position at the beginning of the first affiliated
610 keyword and CDR is a plist of affiliated keywords along with
613 Return a list whose CAR is `drawer' and CDR is a plist containing
614 `:drawer-name', `:begin', `:end', `:contents-begin',
615 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
617 Assume point is at beginning of drawer."
618 (let ((case-fold-search t
))
619 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
620 ;; Incomplete drawer: parse it as a paragraph.
621 (org-element-paragraph-parser limit affiliated
)
623 (let* ((drawer-end-line (match-beginning 0))
624 (name (progn (looking-at org-drawer-regexp
)
625 (org-match-string-no-properties 1)))
626 (begin (car affiliated
))
627 (post-affiliated (point))
628 ;; Empty drawers have no contents.
629 (contents-begin (progn (forward-line)
630 (and (< (point) drawer-end-line
)
632 (contents-end (and contents-begin drawer-end-line
))
633 (pos-before-blank (progn (goto-char drawer-end-line
)
636 (end (progn (skip-chars-forward " \r\t\n" limit
)
637 (if (eobp) (point) (line-beginning-position)))))
643 :contents-begin contents-begin
644 :contents-end contents-end
645 :post-blank
(count-lines pos-before-blank end
)
646 :post-affiliated post-affiliated
)
647 (cdr affiliated
))))))))
649 (defun org-element-drawer-interpreter (drawer contents
)
650 "Interpret DRAWER element as Org syntax.
651 CONTENTS is the contents of the element."
652 (format ":%s:\n%s:END:"
653 (org-element-property :drawer-name drawer
)
659 (defun org-element-dynamic-block-parser (limit affiliated
)
660 "Parse a dynamic block.
662 LIMIT bounds the search. AFFILIATED is a list of which CAR is
663 the buffer position at the beginning of the first affiliated
664 keyword and CDR is a plist of affiliated keywords along with
667 Return a list whose CAR is `dynamic-block' and CDR is a plist
668 containing `:block-name', `:begin', `:end', `:contents-begin',
669 `:contents-end', `:arguments', `:post-blank' and
670 `:post-affiliated' keywords.
672 Assume point is at beginning of dynamic block."
673 (let ((case-fold-search t
))
674 (if (not (save-excursion
675 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
676 ;; Incomplete block: parse it as a paragraph.
677 (org-element-paragraph-parser limit affiliated
)
678 (let ((block-end-line (match-beginning 0)))
680 (let* ((name (progn (looking-at org-dblock-start-re
)
681 (org-match-string-no-properties 1)))
682 (arguments (org-match-string-no-properties 3))
683 (begin (car affiliated
))
684 (post-affiliated (point))
685 ;; Empty blocks have no contents.
686 (contents-begin (progn (forward-line)
687 (and (< (point) block-end-line
)
689 (contents-end (and contents-begin block-end-line
))
690 (pos-before-blank (progn (goto-char block-end-line
)
693 (end (progn (skip-chars-forward " \r\t\n" limit
)
694 (if (eobp) (point) (line-beginning-position)))))
701 :contents-begin contents-begin
702 :contents-end contents-end
703 :post-blank
(count-lines pos-before-blank end
)
704 :post-affiliated post-affiliated
)
705 (cdr affiliated
)))))))))
707 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
708 "Interpret DYNAMIC-BLOCK element as Org syntax.
709 CONTENTS is the contents of the element."
710 (format "#+BEGIN: %s%s\n%s#+END:"
711 (org-element-property :block-name dynamic-block
)
712 (let ((args (org-element-property :arguments dynamic-block
)))
713 (and args
(concat " " args
)))
717 ;;;; Footnote Definition
719 (defun org-element-footnote-definition-parser (limit affiliated
)
720 "Parse a footnote definition.
722 LIMIT bounds the search. AFFILIATED is a list of which CAR is
723 the buffer position at the beginning of the first affiliated
724 keyword and CDR is a plist of affiliated keywords along with
727 Return a list whose CAR is `footnote-definition' and CDR is
728 a plist containing `:label', `:begin' `:end', `:contents-begin',
729 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
731 Assume point is at the beginning of the footnote definition."
733 (let* ((label (progn (looking-at org-footnote-definition-re
)
734 (org-match-string-no-properties 1)))
735 (begin (car affiliated
))
736 (post-affiliated (point))
737 (ending (save-excursion
741 (concat org-outline-regexp-bol
"\\|"
742 org-footnote-definition-re
"\\|"
743 "^\\([ \t]*\n\\)\\{2,\\}") limit
'move
))
746 (contents-begin (progn
748 (skip-chars-forward " \r\t\n" ending
)
749 (cond ((= (point) ending
) nil
)
750 ((= (line-beginning-position) begin
) (point))
751 (t (line-beginning-position)))))
752 (contents-end (and contents-begin ending
))
753 (end (progn (goto-char ending
)
754 (skip-chars-forward " \r\t\n" limit
)
755 (if (eobp) (point) (line-beginning-position)))))
756 (list 'footnote-definition
761 :contents-begin contents-begin
762 :contents-end contents-end
763 :post-blank
(count-lines ending end
)
764 :post-affiliated post-affiliated
)
765 (cdr affiliated
))))))
767 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
768 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
769 CONTENTS is the contents of the footnote-definition."
770 (concat (format "[%s]" (org-element-property :label footnote-definition
))
777 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
780 Return a list whose CAR is `headline' and CDR is a plist
781 containing `:raw-value', `:title', `:alt-title', `:begin',
782 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
783 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
784 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
785 and `:footnote-section-p' keywords.
787 The plist also contains any property set in the property drawer,
788 with its name in upper cases and colons added at the
789 beginning (e.g., `:CUSTOM_ID').
791 LIMIT is a buffer position bounding the search.
793 When RAW-SECONDARY-P is non-nil, headline's title will not be
794 parsed as a secondary string, but as a plain string instead.
796 Assume point is at beginning of the headline."
798 (let* ((components (org-heading-components))
799 (level (nth 1 components
))
800 (todo (nth 2 components
))
802 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
803 (tags (let ((raw-tags (nth 5 components
)))
804 (and raw-tags
(org-split-string raw-tags
":"))))
805 (raw-value (or (nth 4 components
) ""))
807 (let ((case-fold-search nil
))
808 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
810 (archivedp (member org-archive-tag tags
))
811 (footnote-section-p (and org-footnote-section
812 (string= org-footnote-section raw-value
)))
814 ;; Find property drawer associated to current headline and
815 ;; extract properties.
817 ;; Upcase property names. It avoids confusion between
818 ;; properties obtained through property drawer and default
819 ;; properties from the parser (e.g. `:end' and :END:)
820 (let ((end (save-excursion
821 (org-with-limited-levels (outline-next-heading))
825 (while (and (null plist
)
826 (re-search-forward org-property-start-re end t
))
827 (let ((drawer (org-element-at-point)))
828 (when (and (eq (org-element-type drawer
) 'property-drawer
)
829 ;; Make sure drawer is not associated
832 (while (and (setq p
(org-element-property
834 (not (eq (org-element-type p
)
837 (let ((end (org-element-property :contents-end drawer
)))
840 (while (< (point) end
)
841 (when (looking-at org-property-re
)
846 (concat ":" (upcase (match-string 2))))
847 (org-match-string-no-properties 3))))
851 ;; Read time properties on the line below the headline.
854 (when (looking-at org-planning-or-clock-line-re
)
855 (let ((end (line-end-position)) plist
)
856 (while (re-search-forward
857 org-keyword-time-not-clock-regexp end t
)
858 (goto-char (match-end 1))
859 (skip-chars-forward " \t")
860 (let ((keyword (match-string 1))
861 (time (org-element-timestamp-parser)))
862 (cond ((equal keyword org-scheduled-string
)
863 (setq plist
(plist-put plist
:scheduled time
)))
864 ((equal keyword org-deadline-string
)
865 (setq plist
(plist-put plist
:deadline time
)))
866 (t (setq plist
(plist-put plist
:closed time
))))))
869 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
870 (pos-after-head (progn (forward-line) (point)))
871 (contents-begin (save-excursion
872 (skip-chars-forward " \r\t\n" end
)
873 (and (/= (point) end
) (line-beginning-position))))
874 (contents-end (and contents-begin
875 (progn (goto-char end
)
876 (skip-chars-backward " \r\t\n")
879 ;; Clean RAW-VALUE from any comment string.
881 (let ((case-fold-search nil
))
883 (replace-regexp-in-string
884 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
887 ;; Clean TAGS from archive tag, if any.
888 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
892 (list :raw-value raw-value
896 (if (not contents-begin
) 0
897 (count-lines pos-after-head contents-begin
))
898 :contents-begin contents-begin
899 :contents-end contents-end
901 :priority
(nth 3 components
)
905 :post-blank
(count-lines
906 (or contents-end pos-after-head
)
908 :footnote-section-p footnote-section-p
910 :commentedp commentedp
)
913 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
915 (org-element-put-property
917 (if raw-secondary-p alt-title
918 (org-element-parse-secondary-string
919 alt-title
(org-element-restriction 'headline
) headline
)))))
920 (org-element-put-property
922 (if raw-secondary-p raw-value
923 (org-element-parse-secondary-string
924 raw-value
(org-element-restriction 'headline
) headline
)))))))
926 (defun org-element-headline-interpreter (headline contents
)
927 "Interpret HEADLINE element as Org syntax.
928 CONTENTS is the contents of the element."
929 (let* ((level (org-element-property :level headline
))
930 (todo (org-element-property :todo-keyword headline
))
931 (priority (org-element-property :priority headline
))
932 (title (org-element-interpret-data
933 (org-element-property :title headline
)))
934 (tags (let ((tag-list (if (org-element-property :archivedp headline
)
935 (cons org-archive-tag
936 (org-element-property :tags headline
))
937 (org-element-property :tags headline
))))
939 (format ":%s:" (mapconcat 'identity tag-list
":")))))
940 (commentedp (org-element-property :commentedp headline
))
941 (pre-blank (or (org-element-property :pre-blank headline
) 0))
942 (heading (concat (make-string (org-reduced-level level
) ?
*)
943 (and todo
(concat " " todo
))
944 (and commentedp
(concat " " org-comment-string
))
946 (format " [#%s]" (char-to-string priority
)))
947 (cond ((and org-footnote-section
948 (org-element-property
949 :footnote-section-p headline
))
950 (concat " " org-footnote-section
))
951 (title (concat " " title
))))))
956 ((zerop org-tags-column
) (format " %s" tags
))
957 ((< org-tags-column
0)
960 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
965 (make-string (max (- org-tags-column
(length heading
)) 1) ?
)
967 (make-string (1+ pre-blank
) 10)
973 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
974 "Parse an inline task.
976 Return a list whose CAR is `inlinetask' and CDR is a plist
977 containing `:title', `:begin', `:end', `:contents-begin' and
978 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
979 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
980 `:closed' and `:post-blank' keywords.
982 The plist also contains any property set in the property drawer,
983 with its name in upper cases and colons added at the
984 beginning (e.g., `:CUSTOM_ID').
986 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
987 title will not be parsed as a secondary string, but as a plain
990 Assume point is at beginning of the inline task."
992 (let* ((begin (point))
993 (components (org-heading-components))
994 (todo (nth 2 components
))
996 (if (member todo org-done-keywords
) 'done
'todo
)))
997 (tags (let ((raw-tags (nth 5 components
)))
998 (and raw-tags
(org-split-string raw-tags
":"))))
999 (raw-value (or (nth 4 components
) ""))
1000 (task-end (save-excursion
1002 (and (re-search-forward org-outline-regexp-bol limit t
)
1003 (org-looking-at-p "END[ \t]*$")
1004 (line-beginning-position))))
1006 ;; Read time properties on the line below the inlinetask
1010 (when (progn (forward-line)
1011 (looking-at org-planning-or-clock-line-re
))
1012 (let ((end (line-end-position)) plist
)
1013 (while (re-search-forward
1014 org-keyword-time-not-clock-regexp end t
)
1015 (goto-char (match-end 1))
1016 (skip-chars-forward " \t")
1017 (let ((keyword (match-string 1))
1018 (time (org-element-timestamp-parser)))
1019 (cond ((equal keyword org-scheduled-string
)
1020 (setq plist
(plist-put plist
:scheduled time
)))
1021 ((equal keyword org-deadline-string
)
1022 (setq plist
(plist-put plist
:deadline time
)))
1023 (t (setq plist
(plist-put plist
:closed time
))))))
1025 (contents-begin (progn (forward-line)
1026 (and task-end
(< (point) task-end
) (point))))
1027 (contents-end (and contents-begin task-end
))
1028 (before-blank (if (not task-end
) (point)
1029 (goto-char task-end
)
1032 (end (progn (skip-chars-forward " \r\t\n" limit
)
1033 (if (eobp) (point) (line-beginning-position))))
1035 ;; Find property drawer associated to current inlinetask
1036 ;; and extract properties.
1038 ;; HACK: Calling `org-element-at-point' triggers a parsing
1039 ;; of this inlinetask and, thus, an infloop. To avoid the
1040 ;; problem, we extract contents of the inlinetask and
1041 ;; parse them in a new buffer.
1043 ;; Upcase property names. It avoids confusion between
1044 ;; properties obtained through property drawer and default
1045 ;; properties from the parser (e.g. `:end' and :END:)
1046 (when contents-begin
1047 (let ((contents (buffer-substring contents-begin contents-end
))
1050 (let ((org-inhibit-startup t
)) (org-mode))
1052 (goto-char (point-min))
1053 (while (and (null plist
)
1055 org-property-start-re task-end t
))
1056 (let ((d (org-element-at-point)))
1057 (when (eq (org-element-type d
) 'property-drawer
)
1058 (let ((end (org-element-property :contents-end d
)))
1061 (while (< (point) end
)
1062 (when (looking-at org-property-re
)
1067 (concat ":" (upcase (match-string 2))))
1068 (org-match-string-no-properties 3))))
1069 (forward-line))))))))
1074 (list :raw-value raw-value
1077 :contents-begin contents-begin
1078 :contents-end contents-end
1079 :level
(nth 1 components
)
1080 :priority
(nth 3 components
)
1083 :todo-type todo-type
1084 :post-blank
(count-lines before-blank end
))
1087 (org-element-put-property
1089 (if raw-secondary-p raw-value
1090 (org-element-parse-secondary-string
1092 (org-element-restriction 'inlinetask
)
1095 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1096 "Interpret INLINETASK element as Org syntax.
1097 CONTENTS is the contents of inlinetask."
1098 (let* ((level (org-element-property :level inlinetask
))
1099 (todo (org-element-property :todo-keyword inlinetask
))
1100 (priority (org-element-property :priority inlinetask
))
1101 (title (org-element-interpret-data
1102 (org-element-property :title inlinetask
)))
1103 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1105 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1106 (task (concat (make-string level ?
*)
1107 (and todo
(concat " " todo
))
1109 (format " [#%s]" (char-to-string priority
)))
1110 (and title
(concat " " title
)))))
1115 ((zerop org-tags-column
) (format " %s" tags
))
1116 ((< org-tags-column
0)
1119 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1124 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1126 ;; Prefer degenerate inlinetasks when there are no
1131 (make-string level ?
*) " END")))))
1136 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1139 STRUCT is the structure of the plain list.
1141 Return a list whose CAR is `item' and CDR is a plist containing
1142 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1143 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1146 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1147 any, will not be parsed as a secondary string, but as a plain
1150 Assume point is at the beginning of the item."
1153 (looking-at org-list-full-item-re
)
1154 (let* ((begin (point))
1155 (bullet (org-match-string-no-properties 1))
1156 (checkbox (let ((box (org-match-string-no-properties 3)))
1157 (cond ((equal "[ ]" box
) 'off
)
1158 ((equal "[X]" box
) 'on
)
1159 ((equal "[-]" box
) 'trans
))))
1160 (counter (let ((c (org-match-string-no-properties 2)))
1164 ((string-match "[A-Za-z]" c
)
1165 (- (string-to-char (upcase (match-string 0 c
)))
1167 ((string-match "[0-9]+" c
)
1168 (string-to-number (match-string 0 c
)))))))
1169 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1170 (unless (bolp) (forward-line))
1174 ;; Ignore tags in un-ordered lists: they are just
1175 ;; a part of item's body.
1176 (if (and (match-beginning 4)
1177 (save-match-data (string-match "[.)]" bullet
)))
1180 (skip-chars-forward " \r\t\n" limit
)
1181 ;; If first line isn't empty, contents really start
1182 ;; at the text after item's meta-data.
1183 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1184 (contents-end (progn (goto-char end
)
1185 (skip-chars-backward " \r\t\n")
1190 (list :bullet bullet
1193 ;; CONTENTS-BEGIN and CONTENTS-END may be
1194 ;; mixed up in the case of an empty item
1195 ;; separated from the next by a blank line.
1196 ;; Thus ensure the former is always the
1198 :contents-begin
(min contents-begin contents-end
)
1199 :contents-end
(max contents-begin contents-end
)
1203 :post-blank
(count-lines contents-end end
)))))
1204 (org-element-put-property
1206 (let ((raw-tag (org-list-get-tag begin struct
)))
1208 (if raw-secondary-p raw-tag
1209 (org-element-parse-secondary-string
1210 raw-tag
(org-element-restriction 'item
) item
))))))))
1212 (defun org-element-item-interpreter (item contents
)
1213 "Interpret ITEM element as Org syntax.
1214 CONTENTS is the contents of the element."
1215 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1216 (org-list-bullet-string
1217 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1218 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1220 (checkbox (org-element-property :checkbox item
))
1221 (counter (org-element-property :counter item
))
1222 (tag (let ((tag (org-element-property :tag item
)))
1223 (and tag
(org-element-interpret-data tag
))))
1224 ;; Compute indentation.
1225 (ind (make-string (length bullet
) 32))
1226 (item-starts-with-par-p
1227 (eq (org-element-type (car (org-element-contents item
)))
1232 (and counter
(format "[@%d] " counter
))
1237 (and tag
(format "%s :: " tag
))
1239 (let ((contents (replace-regexp-in-string
1240 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1241 (if item-starts-with-par-p
(org-trim contents
)
1242 (concat "\n" contents
)))))))
1247 (defun org-element--list-struct (limit)
1248 ;; Return structure of list at point. Internal function. See
1249 ;; `org-list-struct' for details.
1250 (let ((case-fold-search t
)
1252 (item-re (org-item-re))
1253 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1259 ;; At limit: end all items.
1262 (let ((end (progn (skip-chars-backward " \r\t\n")
1265 (dolist (item items
(sort (nconc items struct
)
1266 'car-less-than-car
))
1267 (setcar (nthcdr 6 item
) end
)))))
1268 ;; At list end: end all items.
1269 ((looking-at org-list-end-re
)
1270 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1271 'car-less-than-car
))
1272 (setcar (nthcdr 6 item
) (point)))))
1273 ;; At a new item: end previous sibling.
1274 ((looking-at item-re
)
1275 (let ((ind (save-excursion (skip-chars-forward " \t")
1277 (setq top-ind
(min top-ind ind
))
1278 (while (and items
(<= ind
(nth 1 (car items
))))
1279 (let ((item (pop items
)))
1280 (setcar (nthcdr 6 item
) (point))
1281 (push item struct
)))
1282 (push (progn (looking-at org-list-full-item-re
)
1283 (let ((bullet (match-string-no-properties 1)))
1287 (match-string-no-properties 2) ; counter
1288 (match-string-no-properties 3) ; checkbox
1290 (and (save-match-data
1291 (string-match "[-+*]" bullet
))
1292 (match-string-no-properties 4))
1293 ;; Ending position, unknown so far.
1297 ;; Skip empty lines.
1298 ((looking-at "^[ \t]*$") (forward-line))
1299 ;; Skip inline tasks and blank lines along the way.
1300 ((and inlinetask-re
(looking-at inlinetask-re
))
1302 (let ((origin (point)))
1303 (when (re-search-forward inlinetask-re limit t
)
1304 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1305 (goto-char origin
)))))
1306 ;; At some text line. Check if it ends any previous item.
1308 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1309 (when (<= ind top-ind
)
1310 (skip-chars-backward " \r\t\n")
1312 (while (<= ind
(nth 1 (car items
)))
1313 (let ((item (pop items
)))
1314 (setcar (nthcdr 6 item
) (line-beginning-position))
1317 (throw 'exit
(sort struct
'car-less-than-car
))))))
1318 ;; Skip blocks (any type) and drawers contents.
1320 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1322 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1324 ((and (looking-at org-drawer-regexp
)
1325 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1326 (forward-line))))))))
1328 (defun org-element-plain-list-parser (limit affiliated structure
)
1329 "Parse a plain list.
1331 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1332 the buffer position at the beginning of the first affiliated
1333 keyword and CDR is a plist of affiliated keywords along with
1334 their value. STRUCTURE is the structure of the plain list being
1337 Return a list whose CAR is `plain-list' and CDR is a plist
1338 containing `:type', `:begin', `:end', `:contents-begin' and
1339 `:contents-end', `:structure', `:post-blank' and
1340 `:post-affiliated' keywords.
1342 Assume point is at the beginning of the list."
1344 (let* ((struct (or structure
(org-element--list-struct limit
)))
1345 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1346 ((nth 5 (assq (point) struct
)) 'descriptive
)
1348 (contents-begin (point))
1349 (begin (car affiliated
))
1350 (contents-end (let* ((item (assq contents-begin struct
))
1353 (while (and (setq item
(assq pos struct
))
1354 (= (nth 1 item
) ind
))
1355 (setq pos
(nth 6 item
)))
1357 (end (progn (goto-char contents-end
)
1358 (skip-chars-forward " \r\t\n" limit
)
1359 (if (= (point) limit
) limit
(line-beginning-position)))))
1366 :contents-begin contents-begin
1367 :contents-end contents-end
1369 :post-blank
(count-lines contents-end end
)
1370 :post-affiliated contents-begin
)
1371 (cdr affiliated
))))))
1373 (defun org-element-plain-list-interpreter (plain-list contents
)
1374 "Interpret PLAIN-LIST element as Org syntax.
1375 CONTENTS is the contents of the element."
1378 (goto-char (point-min))
1383 ;;;; Property Drawer
1385 (defun org-element-property-drawer-parser (limit affiliated
)
1386 "Parse a property drawer.
1388 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1389 the buffer position at the beginning of the first affiliated
1390 keyword and CDR is a plist of affiliated keywords along with
1393 Return a list whose CAR is `property-drawer' and CDR is a plist
1394 containing `:begin', `:end', `:contents-begin', `:contents-end',
1395 `:post-blank' and `:post-affiliated' keywords.
1397 Assume point is at the beginning of the property drawer."
1399 (let ((case-fold-search t
))
1400 (if (not (save-excursion
1401 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1402 ;; Incomplete drawer: parse it as a paragraph.
1403 (org-element-paragraph-parser limit affiliated
)
1405 (let* ((drawer-end-line (match-beginning 0))
1406 (begin (car affiliated
))
1407 (post-affiliated (point))
1408 (contents-begin (progn (forward-line)
1409 (and (< (point) drawer-end-line
)
1411 (contents-end (and contents-begin drawer-end-line
))
1412 (pos-before-blank (progn (goto-char drawer-end-line
)
1415 (end (progn (skip-chars-forward " \r\t\n" limit
)
1416 (if (eobp) (point) (line-beginning-position)))))
1417 (list 'property-drawer
1421 :contents-begin contents-begin
1422 :contents-end contents-end
1423 :post-blank
(count-lines pos-before-blank end
)
1424 :post-affiliated post-affiliated
)
1425 (cdr affiliated
)))))))))
1427 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1428 "Interpret PROPERTY-DRAWER element as Org syntax.
1429 CONTENTS is the properties within the drawer."
1430 (format ":PROPERTIES:\n%s:END:" contents
))
1435 (defun org-element-quote-block-parser (limit affiliated
)
1436 "Parse a quote block.
1438 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1439 the buffer position at the beginning of the first affiliated
1440 keyword and CDR is a plist of affiliated keywords along with
1443 Return a list whose CAR is `quote-block' and CDR is a plist
1444 containing `:begin', `:end', `:contents-begin', `:contents-end',
1445 `:post-blank' and `:post-affiliated' keywords.
1447 Assume point is at the beginning of the block."
1448 (let ((case-fold-search t
))
1449 (if (not (save-excursion
1450 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1451 ;; Incomplete block: parse it as a paragraph.
1452 (org-element-paragraph-parser limit affiliated
)
1453 (let ((block-end-line (match-beginning 0)))
1455 (let* ((begin (car affiliated
))
1456 (post-affiliated (point))
1457 ;; Empty blocks have no contents.
1458 (contents-begin (progn (forward-line)
1459 (and (< (point) block-end-line
)
1461 (contents-end (and contents-begin block-end-line
))
1462 (pos-before-blank (progn (goto-char block-end-line
)
1465 (end (progn (skip-chars-forward " \r\t\n" limit
)
1466 (if (eobp) (point) (line-beginning-position)))))
1471 :contents-begin contents-begin
1472 :contents-end contents-end
1473 :post-blank
(count-lines pos-before-blank end
)
1474 :post-affiliated post-affiliated
)
1475 (cdr affiliated
)))))))))
1477 (defun org-element-quote-block-interpreter (quote-block contents
)
1478 "Interpret QUOTE-BLOCK element as Org syntax.
1479 CONTENTS is the contents of the element."
1480 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1485 (defun org-element-section-parser (limit)
1488 LIMIT bounds the search.
1490 Return a list whose CAR is `section' and CDR is a plist
1491 containing `:begin', `:end', `:contents-begin', `contents-end'
1492 and `:post-blank' keywords."
1494 ;; Beginning of section is the beginning of the first non-blank
1495 ;; line after previous headline.
1496 (let ((begin (point))
1497 (end (progn (org-with-limited-levels (outline-next-heading))
1499 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1505 :contents-begin begin
1506 :contents-end pos-before-blank
1507 :post-blank
(count-lines pos-before-blank end
))))))
1509 (defun org-element-section-interpreter (section contents
)
1510 "Interpret SECTION element as Org syntax.
1511 CONTENTS is the contents of the element."
1517 (defun org-element-special-block-parser (limit affiliated
)
1518 "Parse a special block.
1520 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1521 the buffer position at the beginning of the first affiliated
1522 keyword and CDR is a plist of affiliated keywords along with
1525 Return a list whose CAR is `special-block' and CDR is a plist
1526 containing `:type', `:begin', `:end', `:contents-begin',
1527 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1529 Assume point is at the beginning of the block."
1530 (let* ((case-fold-search t
)
1531 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1532 (upcase (match-string-no-properties 1)))))
1533 (if (not (save-excursion
1535 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1537 ;; Incomplete block: parse it as a paragraph.
1538 (org-element-paragraph-parser limit affiliated
)
1539 (let ((block-end-line (match-beginning 0)))
1541 (let* ((begin (car affiliated
))
1542 (post-affiliated (point))
1543 ;; Empty blocks have no contents.
1544 (contents-begin (progn (forward-line)
1545 (and (< (point) block-end-line
)
1547 (contents-end (and contents-begin block-end-line
))
1548 (pos-before-blank (progn (goto-char block-end-line
)
1551 (end (progn (skip-chars-forward " \r\t\n" limit
)
1552 (if (eobp) (point) (line-beginning-position)))))
1553 (list 'special-block
1558 :contents-begin contents-begin
1559 :contents-end contents-end
1560 :post-blank
(count-lines pos-before-blank end
)
1561 :post-affiliated post-affiliated
)
1562 (cdr affiliated
)))))))))
1564 (defun org-element-special-block-interpreter (special-block contents
)
1565 "Interpret SPECIAL-BLOCK element as Org syntax.
1566 CONTENTS is the contents of the element."
1567 (let ((block-type (org-element-property :type special-block
)))
1568 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1574 ;; For each element, a parser and an interpreter are also defined.
1575 ;; Both follow the same naming convention used for greater elements.
1577 ;; Also, as for greater elements, adding a new element type is done
1578 ;; through the following steps: implement a parser and an interpreter,
1579 ;; tweak `org-element--current-element' so that it recognizes the new
1580 ;; type and add that new type to `org-element-all-elements'.
1582 ;; As a special case, when the newly defined type is a block type,
1583 ;; `org-element-block-name-alist' has to be modified accordingly.
1588 (defun org-element-babel-call-parser (limit affiliated
)
1589 "Parse a babel call.
1591 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1592 the buffer position at the beginning of the first affiliated
1593 keyword and CDR is a plist of affiliated keywords along with
1596 Return a list whose CAR is `babel-call' and CDR is a plist
1597 containing `:begin', `:end', `:value', `:post-blank' and
1598 `:post-affiliated' as keywords."
1600 (let ((begin (car affiliated
))
1601 (post-affiliated (point))
1602 (value (progn (let ((case-fold-search t
))
1603 (re-search-forward "call:[ \t]*" nil t
))
1604 (buffer-substring-no-properties (point)
1605 (line-end-position))))
1606 (pos-before-blank (progn (forward-line) (point)))
1607 (end (progn (skip-chars-forward " \r\t\n" limit
)
1608 (if (eobp) (point) (line-beginning-position)))))
1614 :post-blank
(count-lines pos-before-blank end
)
1615 :post-affiliated post-affiliated
)
1616 (cdr affiliated
))))))
1618 (defun org-element-babel-call-interpreter (babel-call contents
)
1619 "Interpret BABEL-CALL element as Org syntax.
1621 (concat "#+CALL: " (org-element-property :value babel-call
)))
1626 (defun org-element-clock-parser (limit)
1629 LIMIT bounds the search.
1631 Return a list whose CAR is `clock' and CDR is a plist containing
1632 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1635 (let* ((case-fold-search nil
)
1637 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1638 (skip-chars-forward " \t")
1639 (org-element-timestamp-parser)))
1640 (duration (and (search-forward " => " (line-end-position) t
)
1641 (progn (skip-chars-forward " \t")
1642 (looking-at "\\(\\S-+\\)[ \t]*$"))
1643 (org-match-string-no-properties 1)))
1644 (status (if duration
'closed
'running
))
1645 (post-blank (let ((before-blank (progn (forward-line) (point))))
1646 (skip-chars-forward " \r\t\n" limit
)
1647 (skip-chars-backward " \t")
1648 (unless (bolp) (end-of-line))
1649 (count-lines before-blank
(point))))
1652 (list :status status
1657 :post-blank post-blank
)))))
1659 (defun org-element-clock-interpreter (clock contents
)
1660 "Interpret CLOCK element as Org syntax.
1662 (concat org-clock-string
" "
1663 (org-element-timestamp-interpreter
1664 (org-element-property :value clock
) nil
)
1665 (let ((duration (org-element-property :duration clock
)))
1670 (org-split-string duration
":")))))))
1675 (defun org-element-comment-parser (limit affiliated
)
1678 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1679 the buffer position at the beginning of the first affiliated
1680 keyword and CDR is a plist of affiliated keywords along with
1683 Return a list whose CAR is `comment' and CDR is a plist
1684 containing `:begin', `:end', `:value', `:post-blank',
1685 `:post-affiliated' keywords.
1687 Assume point is at comment beginning."
1689 (let* ((begin (car affiliated
))
1690 (post-affiliated (point))
1691 (value (prog2 (looking-at "[ \t]*# ?")
1692 (buffer-substring-no-properties
1693 (match-end 0) (line-end-position))
1696 ;; Get comments ending.
1698 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1699 ;; Accumulate lines without leading hash and first
1704 (buffer-substring-no-properties
1705 (match-end 0) (line-end-position))))
1708 (end (progn (goto-char com-end
)
1709 (skip-chars-forward " \r\t\n" limit
)
1710 (if (eobp) (point) (line-beginning-position)))))
1716 :post-blank
(count-lines com-end end
)
1717 :post-affiliated post-affiliated
)
1718 (cdr affiliated
))))))
1720 (defun org-element-comment-interpreter (comment contents
)
1721 "Interpret COMMENT element as Org syntax.
1723 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1728 (defun org-element-comment-block-parser (limit affiliated
)
1729 "Parse an export block.
1731 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1732 the buffer position at the beginning of the first affiliated
1733 keyword and CDR is a plist of affiliated keywords along with
1736 Return a list whose CAR is `comment-block' and CDR is a plist
1737 containing `:begin', `:end', `:value', `:post-blank' and
1738 `:post-affiliated' keywords.
1740 Assume point is at comment block beginning."
1741 (let ((case-fold-search t
))
1742 (if (not (save-excursion
1743 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1744 ;; Incomplete block: parse it as a paragraph.
1745 (org-element-paragraph-parser limit affiliated
)
1746 (let ((contents-end (match-beginning 0)))
1748 (let* ((begin (car affiliated
))
1749 (post-affiliated (point))
1750 (contents-begin (progn (forward-line) (point)))
1751 (pos-before-blank (progn (goto-char contents-end
)
1754 (end (progn (skip-chars-forward " \r\t\n" limit
)
1755 (if (eobp) (point) (line-beginning-position))))
1756 (value (buffer-substring-no-properties
1757 contents-begin contents-end
)))
1758 (list 'comment-block
1763 :post-blank
(count-lines pos-before-blank end
)
1764 :post-affiliated post-affiliated
)
1765 (cdr affiliated
)))))))))
1767 (defun org-element-comment-block-interpreter (comment-block contents
)
1768 "Interpret COMMENT-BLOCK element as Org syntax.
1770 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1771 (org-remove-indentation (org-element-property :value comment-block
))))
1776 (defun org-element-diary-sexp-parser (limit affiliated
)
1777 "Parse a diary sexp.
1779 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1780 the buffer position at the beginning of the first affiliated
1781 keyword and CDR is a plist of affiliated keywords along with
1784 Return a list whose CAR is `diary-sexp' and CDR is a plist
1785 containing `:begin', `:end', `:value', `:post-blank' and
1786 `:post-affiliated' keywords."
1788 (let ((begin (car affiliated
))
1789 (post-affiliated (point))
1790 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1791 (org-match-string-no-properties 1)))
1792 (pos-before-blank (progn (forward-line) (point)))
1793 (end (progn (skip-chars-forward " \r\t\n" limit
)
1794 (if (eobp) (point) (line-beginning-position)))))
1800 :post-blank
(count-lines pos-before-blank end
)
1801 :post-affiliated post-affiliated
)
1802 (cdr affiliated
))))))
1804 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1805 "Interpret DIARY-SEXP as Org syntax.
1807 (org-element-property :value diary-sexp
))
1812 (defun org-element-example-block-parser (limit affiliated
)
1813 "Parse an example block.
1815 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1816 the buffer position at the beginning of the first affiliated
1817 keyword and CDR is a plist of affiliated keywords along with
1820 Return a list whose CAR is `example-block' and CDR is a plist
1821 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1822 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1823 `:value', `:post-blank' and `:post-affiliated' keywords."
1824 (let ((case-fold-search t
))
1825 (if (not (save-excursion
1826 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1827 ;; Incomplete block: parse it as a paragraph.
1828 (org-element-paragraph-parser limit affiliated
)
1829 (let ((contents-end (match-beginning 0)))
1833 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1834 (org-match-string-no-properties 1)))
1835 ;; Switches analysis
1837 (cond ((not switches
) nil
)
1838 ((string-match "-n\\>" switches
) 'new
)
1839 ((string-match "+n\\>" switches
) 'continued
)))
1841 (and switches
(string-match "-i\\>" switches
)))
1842 ;; Should labels be retained in (or stripped from) example
1846 (not (string-match "-r\\>" switches
))
1847 (and number-lines
(string-match "-k\\>" switches
))))
1848 ;; What should code-references use - labels or
1853 (not (string-match "-k\\>" switches
)))))
1856 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1857 (match-string 1 switches
)))
1858 ;; Standard block parsing.
1859 (begin (car affiliated
))
1860 (post-affiliated (point))
1861 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1862 (contents-begin (progn (forward-line) (point)))
1863 (value (org-element-remove-indentation
1864 (org-unescape-code-in-string
1865 (buffer-substring-no-properties
1866 contents-begin contents-end
))
1868 (pos-before-blank (progn (goto-char contents-end
)
1871 (end (progn (skip-chars-forward " \r\t\n" limit
)
1872 (if (eobp) (point) (line-beginning-position)))))
1873 (list 'example-block
1879 :number-lines number-lines
1880 :preserve-indent preserve-indent
1881 :retain-labels retain-labels
1882 :use-labels use-labels
1883 :label-fmt label-fmt
1884 :post-blank
(count-lines pos-before-blank end
)
1885 :post-affiliated post-affiliated
)
1886 (cdr affiliated
)))))))))
1888 (defun org-element-example-block-interpreter (example-block contents
)
1889 "Interpret EXAMPLE-BLOCK element as Org syntax.
1891 (let ((switches (org-element-property :switches example-block
))
1892 (value (org-element-property :value example-block
)))
1893 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1894 (org-escape-code-in-string
1895 (if (or org-src-preserve-indentation
1896 (org-element-property :preserve-indent example-block
))
1898 (org-element-remove-indentation value
)))
1904 (defun org-element-export-block-parser (limit affiliated
)
1905 "Parse an export block.
1907 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1908 the buffer position at the beginning of the first affiliated
1909 keyword and CDR is a plist of affiliated keywords along with
1912 Return a list whose CAR is `export-block' and CDR is a plist
1913 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1914 `:post-affiliated' keywords.
1916 Assume point is at export-block beginning."
1917 (let* ((case-fold-search t
)
1918 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1919 (upcase (org-match-string-no-properties 1)))))
1920 (if (not (save-excursion
1922 (format "^[ \t]*#\\+END_%s[ \t]*$" type
) limit t
)))
1923 ;; Incomplete block: parse it as a paragraph.
1924 (org-element-paragraph-parser limit affiliated
)
1925 (let ((contents-end (match-beginning 0)))
1927 (let* ((begin (car affiliated
))
1928 (post-affiliated (point))
1929 (contents-begin (progn (forward-line) (point)))
1930 (pos-before-blank (progn (goto-char contents-end
)
1933 (end (progn (skip-chars-forward " \r\t\n" limit
)
1934 (if (eobp) (point) (line-beginning-position))))
1935 (value (buffer-substring-no-properties contents-begin
1943 :post-blank
(count-lines pos-before-blank end
)
1944 :post-affiliated post-affiliated
)
1945 (cdr affiliated
)))))))))
1947 (defun org-element-export-block-interpreter (export-block contents
)
1948 "Interpret EXPORT-BLOCK element as Org syntax.
1950 (let ((type (org-element-property :type export-block
)))
1951 (concat (format "#+BEGIN_%s\n" type
)
1952 (org-element-property :value export-block
)
1953 (format "#+END_%s" type
))))
1958 (defun org-element-fixed-width-parser (limit affiliated
)
1959 "Parse a fixed-width section.
1961 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1962 the buffer position at the beginning of the first affiliated
1963 keyword and CDR is a plist of affiliated keywords along with
1966 Return a list whose CAR is `fixed-width' and CDR is a plist
1967 containing `:begin', `:end', `:value', `:post-blank' and
1968 `:post-affiliated' keywords.
1970 Assume point is at the beginning of the fixed-width area."
1972 (let* ((begin (car affiliated
))
1973 (post-affiliated (point))
1977 (while (and (< (point) limit
)
1978 (looking-at "[ \t]*:\\( \\|$\\)"))
1979 ;; Accumulate text without starting colons.
1982 (buffer-substring-no-properties
1983 (match-end 0) (point-at-eol))
1987 (end (progn (skip-chars-forward " \r\t\n" limit
)
1988 (if (eobp) (point) (line-beginning-position)))))
1994 :post-blank
(count-lines end-area end
)
1995 :post-affiliated post-affiliated
)
1996 (cdr affiliated
))))))
1998 (defun org-element-fixed-width-interpreter (fixed-width contents
)
1999 "Interpret FIXED-WIDTH element as Org syntax.
2001 (let ((value (org-element-property :value fixed-width
)))
2003 (replace-regexp-in-string
2005 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
2008 ;;;; Horizontal Rule
2010 (defun org-element-horizontal-rule-parser (limit affiliated
)
2011 "Parse an horizontal rule.
2013 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2014 the buffer position at the beginning of the first affiliated
2015 keyword and CDR is a plist of affiliated keywords along with
2018 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2019 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2022 (let ((begin (car affiliated
))
2023 (post-affiliated (point))
2024 (post-hr (progn (forward-line) (point)))
2025 (end (progn (skip-chars-forward " \r\t\n" limit
)
2026 (if (eobp) (point) (line-beginning-position)))))
2027 (list 'horizontal-rule
2031 :post-blank
(count-lines post-hr end
)
2032 :post-affiliated post-affiliated
)
2033 (cdr affiliated
))))))
2035 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
2036 "Interpret HORIZONTAL-RULE element as Org syntax.
2043 (defun org-element-keyword-parser (limit affiliated
)
2044 "Parse a keyword at point.
2046 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2047 the buffer position at the beginning of the first affiliated
2048 keyword and CDR is a plist of affiliated keywords along with
2051 Return a list whose CAR is `keyword' and CDR is a plist
2052 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2053 `:post-affiliated' keywords."
2055 ;; An orphaned affiliated keyword is considered as a regular
2056 ;; keyword. In this case AFFILIATED is nil, so we take care of
2057 ;; this corner case.
2058 (let ((begin (or (car affiliated
) (point)))
2059 (post-affiliated (point))
2060 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2061 (upcase (org-match-string-no-properties 1))))
2062 (value (org-trim (buffer-substring-no-properties
2063 (match-end 0) (point-at-eol))))
2064 (pos-before-blank (progn (forward-line) (point)))
2065 (end (progn (skip-chars-forward " \r\t\n" limit
)
2066 (if (eobp) (point) (line-beginning-position)))))
2073 :post-blank
(count-lines pos-before-blank end
)
2074 :post-affiliated post-affiliated
)
2075 (cdr affiliated
))))))
2077 (defun org-element-keyword-interpreter (keyword contents
)
2078 "Interpret KEYWORD element as Org syntax.
2081 (org-element-property :key keyword
)
2082 (org-element-property :value keyword
)))
2085 ;;;; Latex Environment
2087 (defconst org-element--latex-begin-environment
2088 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2089 "Regexp matching the beginning of a LaTeX environment.
2090 The environment is captured by the first group.
2092 See also `org-element--latex-end-environment'.")
2094 (defconst org-element--latex-end-environment
2095 "\\\\end{%s}[ \t]*$"
2096 "Format string matching the ending of a LaTeX environment.
2097 See also `org-element--latex-begin-environment'.")
2099 (defun org-element-latex-environment-parser (limit affiliated
)
2100 "Parse a LaTeX environment.
2102 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2103 the buffer position at the beginning of the first affiliated
2104 keyword and CDR is a plist of affiliated keywords along with
2107 Return a list whose CAR is `latex-environment' and CDR is a plist
2108 containing `:begin', `:end', `:value', `:post-blank' and
2109 `:post-affiliated' keywords.
2111 Assume point is at the beginning of the latex environment."
2113 (let ((case-fold-search t
)
2114 (code-begin (point)))
2115 (looking-at org-element--latex-begin-environment
)
2116 (if (not (re-search-forward (format org-element--latex-end-environment
2117 (regexp-quote (match-string 1)))
2119 ;; Incomplete latex environment: parse it as a paragraph.
2120 (org-element-paragraph-parser limit affiliated
)
2121 (let* ((code-end (progn (forward-line) (point)))
2122 (begin (car affiliated
))
2123 (value (buffer-substring-no-properties code-begin code-end
))
2124 (end (progn (skip-chars-forward " \r\t\n" limit
)
2125 (if (eobp) (point) (line-beginning-position)))))
2126 (list 'latex-environment
2131 :post-blank
(count-lines code-end end
)
2132 :post-affiliated code-begin
)
2133 (cdr affiliated
))))))))
2135 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2136 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2138 (org-element-property :value latex-environment
))
2143 (defun org-element-node-property-parser (limit)
2144 "Parse a node-property at point.
2146 LIMIT bounds the search.
2148 Return a list whose CAR is `node-property' and CDR is a plist
2149 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2152 (looking-at org-property-re
)
2153 (let ((case-fold-search t
)
2155 (key (org-match-string-no-properties 2))
2156 (value (org-match-string-no-properties 3))
2157 (pos-before-blank (progn (forward-line) (point)))
2158 (end (progn (skip-chars-forward " \r\t\n" limit
)
2159 (if (eobp) (point) (point-at-bol)))))
2160 (list 'node-property
2165 :post-blank
(count-lines pos-before-blank end
))))))
2167 (defun org-element-node-property-interpreter (node-property contents
)
2168 "Interpret NODE-PROPERTY element as Org syntax.
2170 (format org-property-format
2171 (format ":%s:" (org-element-property :key node-property
))
2172 (org-element-property :value node-property
)))
2177 (defun org-element-paragraph-parser (limit affiliated
)
2180 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2181 the buffer position at the beginning of the first affiliated
2182 keyword and CDR is a plist of affiliated keywords along with
2185 Return a list whose CAR is `paragraph' and CDR is a plist
2186 containing `:begin', `:end', `:contents-begin' and
2187 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2189 Assume point is at the beginning of the paragraph."
2191 (let* ((begin (car affiliated
))
2192 (contents-begin (point))
2194 (let ((case-fold-search t
))
2196 (if (not (re-search-forward
2197 org-element-paragraph-separate limit
'm
))
2199 ;; A matching `org-element-paragraph-separate' is not
2200 ;; necessarily the end of the paragraph. In
2201 ;; particular, lines starting with # or : as a first
2202 ;; non-space character are ambiguous. We have to
2203 ;; check if they are valid Org syntax (e.g., not an
2204 ;; incomplete keyword).
2208 ;; There's no ambiguity for other symbols or
2209 ;; empty lines: stop here.
2210 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2211 ;; Stop at valid fixed-width areas.
2212 (looking-at "[ \t]*:\\(?: \\|$\\)")
2214 (and (looking-at org-drawer-regexp
)
2217 "^[ \t]*:END:[ \t]*$" limit t
)))
2218 ;; Stop at valid comments.
2219 (looking-at "[ \t]*#\\(?: \\|$\\)")
2220 ;; Stop at valid dynamic blocks.
2221 (and (looking-at org-dblock-start-re
)
2224 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2225 ;; Stop at valid blocks.
2226 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2229 (format "^[ \t]*#\\+END_%s[ \t]*$"
2231 (org-match-string-no-properties 1)))
2233 ;; Stop at valid latex environments.
2234 (and (looking-at org-element--latex-begin-environment
)
2237 (format org-element--latex-end-environment
2239 (org-match-string-no-properties 1)))
2241 ;; Stop at valid keywords.
2242 (looking-at "[ \t]*#\\+\\S-+:")
2243 ;; Skip everything else.
2247 (re-search-forward org-element-paragraph-separate
2249 (beginning-of-line)))
2250 (if (= (point) limit
) limit
2251 (goto-char (line-beginning-position)))))
2252 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2255 (end (progn (skip-chars-forward " \r\t\n" limit
)
2256 (if (eobp) (point) (line-beginning-position)))))
2261 :contents-begin contents-begin
2262 :contents-end contents-end
2263 :post-blank
(count-lines before-blank end
)
2264 :post-affiliated contents-begin
)
2265 (cdr affiliated
))))))
2267 (defun org-element-paragraph-interpreter (paragraph contents
)
2268 "Interpret PARAGRAPH element as Org syntax.
2269 CONTENTS is the contents of the element."
2275 (defun org-element-planning-parser (limit)
2278 LIMIT bounds the search.
2280 Return a list whose CAR is `planning' and CDR is a plist
2281 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2282 and `:post-blank' keywords."
2284 (let* ((case-fold-search nil
)
2286 (post-blank (let ((before-blank (progn (forward-line) (point))))
2287 (skip-chars-forward " \r\t\n" limit
)
2288 (skip-chars-backward " \t")
2289 (unless (bolp) (end-of-line))
2290 (count-lines before-blank
(point))))
2292 closed deadline scheduled
)
2294 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2295 (goto-char (match-end 1))
2296 (skip-chars-forward " \t" end
)
2297 (let ((keyword (match-string 1))
2298 (time (org-element-timestamp-parser)))
2299 (cond ((equal keyword org-closed-string
) (setq closed time
))
2300 ((equal keyword org-deadline-string
) (setq deadline time
))
2301 (t (setq scheduled time
)))))
2303 (list :closed closed
2305 :scheduled scheduled
2308 :post-blank post-blank
)))))
2310 (defun org-element-planning-interpreter (planning contents
)
2311 "Interpret PLANNING element as Org syntax.
2316 (list (let ((deadline (org-element-property :deadline planning
)))
2318 (concat org-deadline-string
" "
2319 (org-element-timestamp-interpreter deadline nil
))))
2320 (let ((scheduled (org-element-property :scheduled planning
)))
2322 (concat org-scheduled-string
" "
2323 (org-element-timestamp-interpreter scheduled nil
))))
2324 (let ((closed (org-element-property :closed planning
)))
2326 (concat org-closed-string
" "
2327 (org-element-timestamp-interpreter closed nil
))))))
2333 (defun org-element-src-block-parser (limit affiliated
)
2336 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2337 the buffer position at the beginning of the first affiliated
2338 keyword and CDR is a plist of affiliated keywords along with
2341 Return a list whose CAR is `src-block' and CDR is a plist
2342 containing `:language', `:switches', `:parameters', `:begin',
2343 `:end', `:number-lines', `:retain-labels', `:use-labels',
2344 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2345 `:post-affiliated' keywords.
2347 Assume point is at the beginning of the block."
2348 (let ((case-fold-search t
))
2349 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2351 ;; Incomplete block: parse it as a paragraph.
2352 (org-element-paragraph-parser limit affiliated
)
2353 (let ((contents-end (match-beginning 0)))
2355 (let* ((begin (car affiliated
))
2356 (post-affiliated (point))
2357 ;; Get language as a string.
2361 (concat "^[ \t]*#\\+BEGIN_SRC"
2362 "\\(?: +\\(\\S-+\\)\\)?"
2363 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2365 (org-match-string-no-properties 1)))
2367 (switches (org-match-string-no-properties 2))
2369 (parameters (org-match-string-no-properties 3))
2370 ;; Switches analysis
2372 (cond ((not switches
) nil
)
2373 ((string-match "-n\\>" switches
) 'new
)
2374 ((string-match "+n\\>" switches
) 'continued
)))
2375 (preserve-indent (and switches
2376 (string-match "-i\\>" switches
)))
2379 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2380 (match-string 1 switches
)))
2381 ;; Should labels be retained in (or stripped from)
2385 (not (string-match "-r\\>" switches
))
2386 (and number-lines
(string-match "-k\\>" switches
))))
2387 ;; What should code-references use - labels or
2392 (not (string-match "-k\\>" switches
)))))
2394 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2396 (value (org-element-remove-indentation
2397 (org-unescape-code-in-string
2398 (buffer-substring-no-properties
2399 (progn (forward-line) (point)) contents-end
))
2401 (pos-before-blank (progn (goto-char contents-end
)
2404 ;; Get position after ending blank lines.
2405 (end (progn (skip-chars-forward " \r\t\n" limit
)
2406 (if (eobp) (point) (line-beginning-position)))))
2409 (list :language language
2410 :switches
(and (org-string-nw-p switches
)
2411 (org-trim switches
))
2412 :parameters
(and (org-string-nw-p parameters
)
2413 (org-trim parameters
))
2416 :number-lines number-lines
2417 :preserve-indent preserve-indent
2418 :retain-labels retain-labels
2419 :use-labels use-labels
2420 :label-fmt label-fmt
2422 :post-blank
(count-lines pos-before-blank end
)
2423 :post-affiliated post-affiliated
)
2424 (cdr affiliated
)))))))))
2426 (defun org-element-src-block-interpreter (src-block contents
)
2427 "Interpret SRC-BLOCK element as Org syntax.
2429 (let ((lang (org-element-property :language src-block
))
2430 (switches (org-element-property :switches src-block
))
2431 (params (org-element-property :parameters src-block
))
2433 (let ((val (org-element-property :value src-block
)))
2435 ((or org-src-preserve-indentation
2436 (org-element-property :preserve-indent src-block
))
2438 ((zerop org-edit-src-content-indentation
) val
)
2440 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2441 (replace-regexp-in-string
2442 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2443 (concat (format "#+BEGIN_SRC%s\n"
2444 (concat (and lang
(concat " " lang
))
2445 (and switches
(concat " " switches
))
2446 (and params
(concat " " params
))))
2447 (org-escape-code-in-string value
)
2453 (defun org-element-table-parser (limit affiliated
)
2454 "Parse a table at point.
2456 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2457 the buffer position at the beginning of the first affiliated
2458 keyword and CDR is a plist of affiliated keywords along with
2461 Return a list whose CAR is `table' and CDR is a plist containing
2462 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2463 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2466 Assume point is at the beginning of the table."
2468 (let* ((case-fold-search t
)
2469 (table-begin (point))
2470 (type (if (org-at-table.el-p
) 'table.el
'org
))
2471 (begin (car affiliated
))
2473 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2474 (goto-char (match-beginning 0))
2477 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2478 (push (org-match-string-no-properties 1) acc
)
2481 (pos-before-blank (point))
2482 (end (progn (skip-chars-forward " \r\t\n" limit
)
2483 (if (eobp) (point) (line-beginning-position)))))
2490 ;; Only `org' tables have contents. `table.el' tables
2491 ;; use a `:value' property to store raw table as
2493 :contents-begin
(and (eq type
'org
) table-begin
)
2494 :contents-end
(and (eq type
'org
) table-end
)
2495 :value
(and (eq type
'table.el
)
2496 (buffer-substring-no-properties
2497 table-begin table-end
))
2498 :post-blank
(count-lines pos-before-blank end
)
2499 :post-affiliated table-begin
)
2500 (cdr affiliated
))))))
2502 (defun org-element-table-interpreter (table contents
)
2503 "Interpret TABLE element as Org syntax.
2505 (if (eq (org-element-property :type table
) 'table.el
)
2506 (org-remove-indentation (org-element-property :value table
))
2507 (concat (with-temp-buffer (insert contents
)
2510 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2511 (reverse (org-element-property :tblfm table
))
2517 (defun org-element-table-row-parser (limit)
2518 "Parse table row at point.
2520 LIMIT bounds the search.
2522 Return a list whose CAR is `table-row' and CDR is a plist
2523 containing `:begin', `:end', `:contents-begin', `:contents-end',
2524 `:type' and `:post-blank' keywords."
2526 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2528 ;; A table rule has no contents. In that case, ensure
2529 ;; CONTENTS-BEGIN matches CONTENTS-END.
2530 (contents-begin (and (eq type
'standard
)
2531 (search-forward "|")
2533 (contents-end (and (eq type
'standard
)
2536 (skip-chars-backward " \t")
2538 (end (progn (forward-line) (point))))
2543 :contents-begin contents-begin
2544 :contents-end contents-end
2547 (defun org-element-table-row-interpreter (table-row contents
)
2548 "Interpret TABLE-ROW element as Org syntax.
2549 CONTENTS is the contents of the table row."
2550 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2551 (concat "| " contents
)))
2556 (defun org-element-verse-block-parser (limit affiliated
)
2557 "Parse a verse block.
2559 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2560 the buffer position at the beginning of the first affiliated
2561 keyword and CDR is a plist of affiliated keywords along with
2564 Return a list whose CAR is `verse-block' and CDR is a plist
2565 containing `:begin', `:end', `:contents-begin', `:contents-end',
2566 `:post-blank' and `:post-affiliated' keywords.
2568 Assume point is at beginning of the block."
2569 (let ((case-fold-search t
))
2570 (if (not (save-excursion
2571 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2572 ;; Incomplete block: parse it as a paragraph.
2573 (org-element-paragraph-parser limit affiliated
)
2574 (let ((contents-end (match-beginning 0)))
2576 (let* ((begin (car affiliated
))
2577 (post-affiliated (point))
2578 (contents-begin (progn (forward-line) (point)))
2579 (pos-before-blank (progn (goto-char contents-end
)
2582 (end (progn (skip-chars-forward " \r\t\n" limit
)
2583 (if (eobp) (point) (line-beginning-position)))))
2588 :contents-begin contents-begin
2589 :contents-end contents-end
2590 :post-blank
(count-lines pos-before-blank end
)
2591 :post-affiliated post-affiliated
)
2592 (cdr affiliated
)))))))))
2594 (defun org-element-verse-block-interpreter (verse-block contents
)
2595 "Interpret VERSE-BLOCK element as Org syntax.
2596 CONTENTS is verse block contents."
2597 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2603 ;; Unlike to elements, raw text can be found between objects. Hence,
2604 ;; `org-element--object-lex' is provided to find the next object in
2607 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2608 ;; object types they can contain will be specified in
2609 ;; `org-element-object-restrictions'.
2611 ;; Creating a new type of object requires to alter
2612 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2613 ;; new type in `org-element-all-objects', and possibly add
2614 ;; restrictions in `org-element-object-restrictions'.
2618 (defun org-element-bold-parser ()
2619 "Parse bold object at point, if any.
2621 When at a bold object, return a list whose car is `bold' and cdr
2622 is a plist with `:begin', `:end', `:contents-begin' and
2623 `:contents-end' and `:post-blank' keywords. Otherwise, return
2626 Assume point is at the first star marker."
2628 (unless (bolp) (backward-char 1))
2629 (when (looking-at org-emph-re
)
2630 (let ((begin (match-beginning 2))
2631 (contents-begin (match-beginning 4))
2632 (contents-end (match-end 4))
2633 (post-blank (progn (goto-char (match-end 2))
2634 (skip-chars-forward " \t")))
2639 :contents-begin contents-begin
2640 :contents-end contents-end
2641 :post-blank post-blank
))))))
2643 (defun org-element-bold-interpreter (bold contents
)
2644 "Interpret BOLD object as Org syntax.
2645 CONTENTS is the contents of the object."
2646 (format "*%s*" contents
))
2651 (defun org-element-code-parser ()
2652 "Parse code object at point, if any.
2654 When at a code object, return a list whose car is `code' and cdr
2655 is a plist with `:value', `:begin', `:end' and `:post-blank'
2656 keywords. Otherwise, return nil.
2658 Assume point is at the first tilde marker."
2660 (unless (bolp) (backward-char 1))
2661 (when (looking-at org-emph-re
)
2662 (let ((begin (match-beginning 2))
2663 (value (org-match-string-no-properties 4))
2664 (post-blank (progn (goto-char (match-end 2))
2665 (skip-chars-forward " \t")))
2671 :post-blank post-blank
))))))
2673 (defun org-element-code-interpreter (code contents
)
2674 "Interpret CODE object as Org syntax.
2676 (format "~%s~" (org-element-property :value code
)))
2681 (defun org-element-entity-parser ()
2682 "Parse entity at point, if any.
2684 When at an entity, return a list whose car is `entity' and cdr
2685 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2686 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2687 `:post-blank' as keywords. Otherwise, return nil.
2689 Assume point is at the beginning of the entity."
2691 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2693 (let* ((value (or (org-entity-get (match-string 1))
2694 (throw 'no-object nil
)))
2695 (begin (match-beginning 0))
2696 (bracketsp (string= (match-string 2) "{}"))
2697 (post-blank (progn (goto-char (match-end 1))
2698 (when bracketsp
(forward-char 2))
2699 (skip-chars-forward " \t")))
2702 (list :name
(car value
)
2703 :latex
(nth 1 value
)
2704 :latex-math-p
(nth 2 value
)
2706 :ascii
(nth 4 value
)
2707 :latin1
(nth 5 value
)
2708 :utf-8
(nth 6 value
)
2711 :use-brackets-p bracketsp
2712 :post-blank post-blank
)))))))
2714 (defun org-element-entity-interpreter (entity contents
)
2715 "Interpret ENTITY object as Org syntax.
2718 (org-element-property :name entity
)
2719 (when (org-element-property :use-brackets-p entity
) "{}")))
2724 (defun org-element-export-snippet-parser ()
2725 "Parse export snippet at point.
2727 When at an export snippet, return a list whose car is
2728 `export-snippet' and cdr a plist with `:begin', `:end',
2729 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2732 Assume point is at the beginning of the snippet."
2735 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2737 (save-match-data (goto-char (match-end 0))
2738 (re-search-forward "@@" nil t
)
2739 (match-beginning 0))))
2740 (let* ((begin (match-beginning 0))
2741 (back-end (org-match-string-no-properties 1))
2742 (value (buffer-substring-no-properties
2743 (match-end 0) contents-end
))
2744 (post-blank (skip-chars-forward " \t"))
2746 (list 'export-snippet
2747 (list :back-end back-end
2751 :post-blank post-blank
)))))))
2753 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2754 "Interpret EXPORT-SNIPPET object as Org syntax.
2757 (org-element-property :back-end export-snippet
)
2758 (org-element-property :value export-snippet
)))
2761 ;;;; Footnote Reference
2763 (defun org-element-footnote-reference-parser ()
2764 "Parse footnote reference at point, if any.
2766 When at a footnote reference, return a list whose car is
2767 `footnote-reference' and cdr a plist with `:label', `:type',
2768 `:begin', `:end', `:content-begin', `:contents-end' and
2769 `:post-blank' as keywords. Otherwise, return nil."
2771 (when (looking-at org-footnote-re
)
2773 (let* ((begin (point))
2775 (or (org-match-string-no-properties 2)
2776 (org-match-string-no-properties 3)
2777 (and (match-string 1)
2778 (concat "fn:" (org-match-string-no-properties 1)))))
2779 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2780 (inner-begin (match-end 0))
2784 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2785 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2786 (unless (zerop count
) (throw 'no-object nil
))
2788 (post-blank (progn (goto-char (1+ inner-end
))
2789 (skip-chars-forward " \t")))
2791 (list 'footnote-reference
2796 :contents-begin
(and (eq type
'inline
) inner-begin
)
2797 :contents-end
(and (eq type
'inline
) inner-end
)
2798 :post-blank post-blank
)))))))
2800 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2801 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2802 CONTENTS is its definition, when inline, or nil."
2804 (concat (or (org-element-property :label footnote-reference
) "fn:")
2805 (and contents
(concat ":" contents
)))))
2808 ;;;; Inline Babel Call
2810 (defun org-element-inline-babel-call-parser ()
2811 "Parse inline babel call at point, if any.
2813 When at an inline babel call, return a list whose car is
2814 `inline-babel-call' and cdr a plist with `:begin', `:end',
2815 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2817 Assume point is at the beginning of the babel call."
2819 (unless (bolp) (backward-char))
2820 (when (let ((case-fold-search t
))
2821 (looking-at org-babel-inline-lob-one-liner-regexp
))
2822 (let ((begin (match-end 1))
2823 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2824 (post-blank (progn (goto-char (match-end 0))
2825 (skip-chars-forward " \t")))
2827 (list 'inline-babel-call
2831 :post-blank post-blank
))))))
2833 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2834 "Interpret INLINE-BABEL-CALL object as Org syntax.
2836 (org-element-property :value inline-babel-call
))
2839 ;;;; Inline Src Block
2841 (defun org-element-inline-src-block-parser ()
2842 "Parse inline source block at point, if any.
2844 When at an inline source block, return a list whose car is
2845 `inline-src-block' and cdr a plist with `:begin', `:end',
2846 `:language', `:value', `:parameters' and `:post-blank' as
2847 keywords. Otherwise, return nil.
2849 Assume point is at the beginning of the inline src block."
2851 (unless (bolp) (backward-char))
2852 (when (looking-at org-babel-inline-src-block-regexp
)
2853 (let ((begin (match-beginning 1))
2854 (language (org-match-string-no-properties 2))
2855 (parameters (org-match-string-no-properties 4))
2856 (value (org-match-string-no-properties 5))
2857 (post-blank (progn (goto-char (match-end 0))
2858 (skip-chars-forward " \t")))
2860 (list 'inline-src-block
2861 (list :language language
2863 :parameters parameters
2866 :post-blank post-blank
))))))
2868 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2869 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2871 (let ((language (org-element-property :language inline-src-block
))
2872 (arguments (org-element-property :parameters inline-src-block
))
2873 (body (org-element-property :value inline-src-block
)))
2874 (format "src_%s%s{%s}"
2876 (if arguments
(format "[%s]" arguments
) "")
2881 (defun org-element-italic-parser ()
2882 "Parse italic object at point, if any.
2884 When at an italic object, return a list whose car is `italic' and
2885 cdr is a plist with `:begin', `:end', `:contents-begin' and
2886 `:contents-end' and `:post-blank' keywords. Otherwise, return
2889 Assume point is at the first slash marker."
2891 (unless (bolp) (backward-char 1))
2892 (when (looking-at org-emph-re
)
2893 (let ((begin (match-beginning 2))
2894 (contents-begin (match-beginning 4))
2895 (contents-end (match-end 4))
2896 (post-blank (progn (goto-char (match-end 2))
2897 (skip-chars-forward " \t")))
2902 :contents-begin contents-begin
2903 :contents-end contents-end
2904 :post-blank post-blank
))))))
2906 (defun org-element-italic-interpreter (italic contents
)
2907 "Interpret ITALIC object as Org syntax.
2908 CONTENTS is the contents of the object."
2909 (format "/%s/" contents
))
2914 (defun org-element-latex-fragment-parser ()
2915 "Parse LaTeX fragment at point, if any.
2917 When at a LaTeX fragment, return a list whose car is
2918 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2919 and `:post-blank' as keywords. Otherwise, return nil.
2921 Assume point is at the beginning of the LaTeX fragment."
2924 (let* ((begin (point))
2926 (if (eq (char-after) ?$
)
2927 (if (eq (char-after (1+ (point))) ?$
)
2928 (search-forward "$$" nil t
2)
2929 (and (not (eq (char-before) ?$
))
2930 (search-forward "$" nil t
2)
2931 (not (memq (char-before (match-beginning 0))
2932 '(?\s ?
\t ?
\n ?
, ?.
)))
2933 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2935 (case (char-after (1+ (point)))
2936 (?\
( (search-forward "\\)" nil t
))
2937 (?\
[ (search-forward "\\]" nil t
))
2940 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2942 (post-blank (if (not after-fragment
) (throw 'no-object nil
)
2943 (goto-char after-fragment
)
2944 (skip-chars-forward " \t")))
2946 (list 'latex-fragment
2947 (list :value
(buffer-substring-no-properties begin after-fragment
)
2950 :post-blank post-blank
))))))
2952 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2953 "Interpret LATEX-FRAGMENT object as Org syntax.
2955 (org-element-property :value latex-fragment
))
2959 (defun org-element-line-break-parser ()
2960 "Parse line break at point, if any.
2962 When at a line break, return a list whose car is `line-break',
2963 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2964 Otherwise, return nil.
2966 Assume point is at the beginning of the line break."
2967 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2968 (not (eq (char-before) ?
\\)))
2970 (list :begin
(point)
2971 :end
(progn (forward-line) (point))
2974 (defun org-element-line-break-interpreter (line-break contents
)
2975 "Interpret LINE-BREAK object as Org syntax.
2982 (defun org-element-link-parser ()
2983 "Parse link at point, if any.
2985 When at a link, return a list whose car is `link' and cdr a plist
2986 with `:type', `:path', `:raw-link', `:application',
2987 `:search-option', `:begin', `:end', `:contents-begin',
2988 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2991 Assume point is at the beginning of the link."
2993 (let ((begin (point))
2994 end contents-begin contents-end link-end post-blank path type
2995 raw-link link search-option application
)
2997 ;; Type 1: Text targeted from a radio target.
2998 ((and org-target-link-regexp
2999 (save-excursion (or (bolp) (backward-char))
3000 (looking-at org-target-link-regexp
)))
3002 link-end
(match-end 1)
3003 path
(org-match-string-no-properties 1)
3004 contents-begin
(match-beginning 1)
3005 contents-end
(match-end 1)))
3006 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3007 ((looking-at org-bracket-link-regexp
)
3008 (setq contents-begin
(match-beginning 3)
3009 contents-end
(match-end 3)
3010 link-end
(match-end 0)
3011 ;; RAW-LINK is the original link. Expand any
3012 ;; abbreviation in it.
3013 raw-link
(org-translate-link
3014 (org-link-expand-abbrev
3015 (org-match-string-no-properties 1))))
3016 ;; Determine TYPE of link and set PATH accordingly.
3019 ((or (file-name-absolute-p raw-link
)
3020 (string-match "^\\.\\.?/" raw-link
))
3021 (setq type
"file" path raw-link
))
3022 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3023 ((string-match org-link-re-with-space3 raw-link
)
3024 (setq type
(match-string 1 raw-link
) path
(match-string 2 raw-link
)))
3025 ;; Id type: PATH is the id.
3026 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link
)
3027 (setq type
"id" path
(match-string 1 raw-link
)))
3028 ;; Code-ref type: PATH is the name of the reference.
3029 ((string-match "^(\\(.*\\))$" raw-link
)
3030 (setq type
"coderef" path
(match-string 1 raw-link
)))
3031 ;; Custom-id type: PATH is the name of the custom id.
3032 ((= (aref raw-link
0) ?
#)
3033 (setq type
"custom-id" path
(substring raw-link
1)))
3034 ;; Fuzzy type: Internal link either matches a target, an
3035 ;; headline name or nothing. PATH is the target or
3037 (t (setq type
"fuzzy" path raw-link
))))
3038 ;; Type 3: Plain link, e.g., http://orgmode.org
3039 ((looking-at org-plain-link-re
)
3040 (setq raw-link
(org-match-string-no-properties 0)
3041 type
(org-match-string-no-properties 1)
3042 link-end
(match-end 0)
3043 path
(org-match-string-no-properties 2)))
3044 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3045 ((looking-at org-angle-link-re
)
3046 (setq raw-link
(buffer-substring-no-properties
3047 (match-beginning 1) (match-end 2))
3048 type
(org-match-string-no-properties 1)
3049 link-end
(match-end 0)
3050 path
(org-match-string-no-properties 2)))
3051 (t (throw 'no-object nil
)))
3052 ;; In any case, deduce end point after trailing white space from
3053 ;; LINK-END variable.
3055 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3057 ;; Special "file" type link processing.
3058 (when (member type org-element-link-type-is-file
)
3059 ;; Extract opening application and search option.
3060 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3061 (setq application
(match-string 1 type
)))
3062 ((not (string-match "^file" type
))
3063 (setq application type
)))
3064 (when (string-match "::\\(.*\\)\\'" path
)
3065 (setq search-option
(match-string 1 path
)
3066 path
(replace-match "" nil nil path
)))
3068 (when (and (file-name-absolute-p path
)
3069 (not (org-string-match-p "\\`[/~]/" path
)))
3070 (setq path
(concat "//" path
)))
3071 ;; Make sure TYPE always reports "file".
3076 :raw-link
(or raw-link path
)
3077 :application application
3078 :search-option search-option
3081 :contents-begin contents-begin
3082 :contents-end contents-end
3083 :post-blank post-blank
))))))
3085 (defun org-element-link-interpreter (link contents
)
3086 "Interpret LINK object as Org syntax.
3087 CONTENTS is the contents of the object, or nil."
3088 (let ((type (org-element-property :type link
))
3089 (raw-link (org-element-property :raw-link link
)))
3090 (if (string= type
"radio") raw-link
3093 (if contents
(format "[%s]" contents
) "")))))
3098 (defun org-element-macro-parser ()
3099 "Parse macro at point, if any.
3101 When at a macro, return a list whose car is `macro' and cdr
3102 a plist with `:key', `:args', `:begin', `:end', `:value' and
3103 `:post-blank' as keywords. Otherwise, return nil.
3105 Assume point is at the macro."
3107 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3108 (let ((begin (point))
3109 (key (downcase (org-match-string-no-properties 1)))
3110 (value (org-match-string-no-properties 0))
3111 (post-blank (progn (goto-char (match-end 0))
3112 (skip-chars-forward " \t")))
3114 (args (let ((args (org-match-string-no-properties 3)))
3116 ;; Do not use `org-split-string' since empty
3117 ;; strings are meaningful here.
3119 (replace-regexp-in-string
3120 "\\(\\\\*\\)\\(,\\)"
3122 (let ((len (length (match-string 1 str
))))
3123 (concat (make-string (/ len
2) ?
\\)
3124 (if (zerop (mod len
2)) "\000" ","))))
3133 :post-blank post-blank
))))))
3135 (defun org-element-macro-interpreter (macro contents
)
3136 "Interpret MACRO object as Org syntax.
3138 (org-element-property :value macro
))
3143 (defun org-element-radio-target-parser ()
3144 "Parse radio target at point, if any.
3146 When at a radio target, return a list whose car is `radio-target'
3147 and cdr a plist with `:begin', `:end', `:contents-begin',
3148 `:contents-end', `:value' and `:post-blank' as keywords.
3149 Otherwise, return nil.
3151 Assume point is at the radio target."
3153 (when (looking-at org-radio-target-regexp
)
3154 (let ((begin (point))
3155 (contents-begin (match-beginning 1))
3156 (contents-end (match-end 1))
3157 (value (org-match-string-no-properties 1))
3158 (post-blank (progn (goto-char (match-end 0))
3159 (skip-chars-forward " \t")))
3164 :contents-begin contents-begin
3165 :contents-end contents-end
3166 :post-blank post-blank
3169 (defun org-element-radio-target-interpreter (target contents
)
3170 "Interpret TARGET object as Org syntax.
3171 CONTENTS is the contents of the object."
3172 (concat "<<<" contents
">>>"))
3175 ;;;; Statistics Cookie
3177 (defun org-element-statistics-cookie-parser ()
3178 "Parse statistics cookie at point, if any.
3180 When at a statistics cookie, return a list whose car is
3181 `statistics-cookie', and cdr a plist with `:begin', `:end',
3182 `:value' and `:post-blank' keywords. Otherwise, return nil.
3184 Assume point is at the beginning of the statistics-cookie."
3186 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3187 (let* ((begin (point))
3188 (value (buffer-substring-no-properties
3189 (match-beginning 0) (match-end 0)))
3190 (post-blank (progn (goto-char (match-end 0))
3191 (skip-chars-forward " \t")))
3193 (list 'statistics-cookie
3197 :post-blank post-blank
))))))
3199 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3200 "Interpret STATISTICS-COOKIE object as Org syntax.
3202 (org-element-property :value statistics-cookie
))
3207 (defun org-element-strike-through-parser ()
3208 "Parse strike-through object at point, if any.
3210 When at a strike-through object, return a list whose car is
3211 `strike-through' and cdr is a plist with `:begin', `:end',
3212 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3213 Otherwise, return nil.
3215 Assume point is at the first plus sign marker."
3217 (unless (bolp) (backward-char 1))
3218 (when (looking-at org-emph-re
)
3219 (let ((begin (match-beginning 2))
3220 (contents-begin (match-beginning 4))
3221 (contents-end (match-end 4))
3222 (post-blank (progn (goto-char (match-end 2))
3223 (skip-chars-forward " \t")))
3225 (list 'strike-through
3228 :contents-begin contents-begin
3229 :contents-end contents-end
3230 :post-blank post-blank
))))))
3232 (defun org-element-strike-through-interpreter (strike-through contents
)
3233 "Interpret STRIKE-THROUGH object as Org syntax.
3234 CONTENTS is the contents of the object."
3235 (format "+%s+" contents
))
3240 (defun org-element-subscript-parser ()
3241 "Parse subscript at point, if any.
3243 When at a subscript object, return a list whose car is
3244 `subscript' and cdr a plist with `:begin', `:end',
3245 `:contents-begin', `:contents-end', `:use-brackets-p' and
3246 `:post-blank' as keywords. Otherwise, return nil.
3248 Assume point is at the underscore."
3250 (unless (bolp) (backward-char))
3251 (when (looking-at org-match-substring-regexp
)
3252 (let ((bracketsp (match-beginning 4))
3253 (begin (match-beginning 2))
3254 (contents-begin (or (match-beginning 4)
3255 (match-beginning 3)))
3256 (contents-end (or (match-end 4) (match-end 3)))
3257 (post-blank (progn (goto-char (match-end 0))
3258 (skip-chars-forward " \t")))
3263 :use-brackets-p bracketsp
3264 :contents-begin contents-begin
3265 :contents-end contents-end
3266 :post-blank post-blank
))))))
3268 (defun org-element-subscript-interpreter (subscript contents
)
3269 "Interpret SUBSCRIPT object as Org syntax.
3270 CONTENTS is the contents of the object."
3272 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3278 (defun org-element-superscript-parser ()
3279 "Parse superscript at point, if any.
3281 When at a superscript object, return a list whose car is
3282 `superscript' and cdr a plist with `:begin', `:end',
3283 `:contents-begin', `:contents-end', `:use-brackets-p' and
3284 `:post-blank' as keywords. Otherwise, return nil.
3286 Assume point is at the caret."
3288 (unless (bolp) (backward-char))
3289 (when (looking-at org-match-substring-regexp
)
3290 (let ((bracketsp (match-beginning 4))
3291 (begin (match-beginning 2))
3292 (contents-begin (or (match-beginning 4)
3293 (match-beginning 3)))
3294 (contents-end (or (match-end 4) (match-end 3)))
3295 (post-blank (progn (goto-char (match-end 0))
3296 (skip-chars-forward " \t")))
3301 :use-brackets-p bracketsp
3302 :contents-begin contents-begin
3303 :contents-end contents-end
3304 :post-blank post-blank
))))))
3306 (defun org-element-superscript-interpreter (superscript contents
)
3307 "Interpret SUPERSCRIPT object as Org syntax.
3308 CONTENTS is the contents of the object."
3310 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3316 (defun org-element-table-cell-parser ()
3317 "Parse table cell at point.
3318 Return a list whose car is `table-cell' and cdr is a plist
3319 containing `:begin', `:end', `:contents-begin', `:contents-end'
3320 and `:post-blank' keywords."
3321 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3322 (let* ((begin (match-beginning 0))
3324 (contents-begin (match-beginning 1))
3325 (contents-end (match-end 1)))
3329 :contents-begin contents-begin
3330 :contents-end contents-end
3333 (defun org-element-table-cell-interpreter (table-cell contents
)
3334 "Interpret TABLE-CELL element as Org syntax.
3335 CONTENTS is the contents of the cell, or nil."
3336 (concat " " contents
" |"))
3341 (defun org-element-target-parser ()
3342 "Parse target at point, if any.
3344 When at a target, return a list whose car is `target' and cdr
3345 a plist with `:begin', `:end', `:value' and `:post-blank' as
3346 keywords. Otherwise, return nil.
3348 Assume point is at the target."
3350 (when (looking-at org-target-regexp
)
3351 (let ((begin (point))
3352 (value (org-match-string-no-properties 1))
3353 (post-blank (progn (goto-char (match-end 0))
3354 (skip-chars-forward " \t")))
3360 :post-blank post-blank
))))))
3362 (defun org-element-target-interpreter (target contents
)
3363 "Interpret TARGET object as Org syntax.
3365 (format "<<%s>>" (org-element-property :value target
)))
3370 (defconst org-element--timestamp-regexp
3371 (concat org-ts-regexp-both
3373 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3375 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3376 "Regexp matching any timestamp type object.")
3378 (defun org-element-timestamp-parser ()
3379 "Parse time stamp at point, if any.
3381 When at a time stamp, return a list whose car is `timestamp', and
3382 cdr a plist with `:type', `:raw-value', `:year-start',
3383 `:month-start', `:day-start', `:hour-start', `:minute-start',
3384 `:year-end', `:month-end', `:day-end', `:hour-end',
3385 `:minute-end', `:repeater-type', `:repeater-value',
3386 `:repeater-unit', `:warning-type', `:warning-value',
3387 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3388 Otherwise, return nil.
3390 Assume point is at the beginning of the timestamp."
3391 (when (org-looking-at-p org-element--timestamp-regexp
)
3393 (let* ((begin (point))
3394 (activep (eq (char-after) ?
<))
3397 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3398 (match-string-no-properties 0)))
3399 (date-start (match-string-no-properties 1))
3400 (date-end (match-string 3))
3401 (diaryp (match-beginning 2))
3402 (post-blank (progn (goto-char (match-end 0))
3403 (skip-chars-forward " \t")))
3408 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3410 (cons (string-to-number (match-string 2 date-start
))
3411 (string-to-number (match-string 3 date-start
)))))
3412 (type (cond (diaryp 'diary
)
3413 ((and activep
(or date-end time-range
)) 'active-range
)
3415 ((or date-end time-range
) 'inactive-range
)
3419 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3423 (let ((type (match-string 1 raw-value
)))
3424 (cond ((equal "++" type
) 'catch-up
)
3425 ((equal ".+" type
) 'restart
)
3427 :repeater-value
(string-to-number (match-string 2 raw-value
))
3429 (case (string-to-char (match-string 3 raw-value
))
3430 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3433 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3435 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3436 :warning-value
(string-to-number (match-string 2 raw-value
))
3438 (case (string-to-char (match-string 3 raw-value
))
3439 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3440 year-start month-start day-start hour-start minute-start year-end
3441 month-end day-end hour-end minute-end
)
3442 ;; Parse date-start.
3444 (let ((date (org-parse-time-string date-start t
)))
3445 (setq year-start
(nth 5 date
)
3446 month-start
(nth 4 date
)
3447 day-start
(nth 3 date
)
3448 hour-start
(nth 2 date
)
3449 minute-start
(nth 1 date
))))
3450 ;; Compute date-end. It can be provided directly in time-stamp,
3451 ;; or extracted from time range. Otherwise, it defaults to the
3452 ;; same values as date-start.
3454 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3455 (setq year-end
(or (nth 5 date
) year-start
)
3456 month-end
(or (nth 4 date
) month-start
)
3457 day-end
(or (nth 3 date
) day-start
)
3458 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3459 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3461 (nconc (list :type type
3462 :raw-value raw-value
3463 :year-start year-start
3464 :month-start month-start
3465 :day-start day-start
3466 :hour-start hour-start
3467 :minute-start minute-start
3469 :month-end month-end
3472 :minute-end minute-end
3475 :post-blank post-blank
)
3479 (defun org-element-timestamp-interpreter (timestamp contents
)
3480 "Interpret TIMESTAMP object as Org syntax.
3482 (let* ((repeat-string
3484 (case (org-element-property :repeater-type timestamp
)
3485 (cumulate "+") (catch-up "++") (restart ".+"))
3486 (let ((val (org-element-property :repeater-value timestamp
)))
3487 (and val
(number-to-string val
)))
3488 (case (org-element-property :repeater-unit timestamp
)
3489 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3492 (case (org-element-property :warning-type timestamp
)
3495 (let ((val (org-element-property :warning-value timestamp
)))
3496 (and val
(number-to-string val
)))
3497 (case (org-element-property :warning-unit timestamp
)
3498 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3500 ;; Build an Org timestamp string from TIME. ACTIVEP is
3501 ;; non-nil when time stamp is active. If WITH-TIME-P is
3502 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3503 ;; specify a time range in the timestamp. REPEAT-STRING is
3504 ;; the repeater string, if any.
3505 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3506 (let ((ts (format-time-string
3507 (funcall (if with-time-p
'cdr
'car
)
3508 org-time-stamp-formats
)
3510 (when (and hour-end minute-end
)
3511 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3514 (format "\\&-%02d:%02d" hour-end minute-end
)
3516 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3517 (dolist (s (list repeat-string warning-string
))
3518 (when (org-string-nw-p s
)
3519 (setq ts
(concat (substring ts
0 -
1)
3522 (substring ts -
1)))))
3525 (type (org-element-property :type timestamp
)))
3528 (let* ((minute-start (org-element-property :minute-start timestamp
))
3529 (minute-end (org-element-property :minute-end timestamp
))
3530 (hour-start (org-element-property :hour-start timestamp
))
3531 (hour-end (org-element-property :hour-end timestamp
))
3532 (time-range-p (and hour-start hour-end minute-start minute-end
3533 (or (/= hour-start hour-end
)
3534 (/= minute-start minute-end
)))))
3540 (org-element-property :day-start timestamp
)
3541 (org-element-property :month-start timestamp
)
3542 (org-element-property :year-start timestamp
))
3544 (and hour-start minute-start
)
3545 (and time-range-p hour-end
)
3546 (and time-range-p minute-end
))))
3547 ((active-range inactive-range
)
3548 (let ((minute-start (org-element-property :minute-start timestamp
))
3549 (minute-end (org-element-property :minute-end timestamp
))
3550 (hour-start (org-element-property :hour-start timestamp
))
3551 (hour-end (org-element-property :hour-end timestamp
)))
3554 build-ts-string
(encode-time
3558 (org-element-property :day-start timestamp
)
3559 (org-element-property :month-start timestamp
)
3560 (org-element-property :year-start timestamp
))
3561 (eq type
'active-range
)
3562 (and hour-start minute-start
))
3564 (funcall build-ts-string
3568 (org-element-property :day-end timestamp
)
3569 (org-element-property :month-end timestamp
)
3570 (org-element-property :year-end timestamp
))
3571 (eq type
'active-range
)
3572 (and hour-end minute-end
))))))))
3577 (defun org-element-underline-parser ()
3578 "Parse underline object at point, if any.
3580 When at an underline object, return a list whose car is
3581 `underline' and cdr is a plist with `:begin', `:end',
3582 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3583 Otherwise, return nil.
3585 Assume point is at the first underscore marker."
3587 (unless (bolp) (backward-char 1))
3588 (when (looking-at org-emph-re
)
3589 (let ((begin (match-beginning 2))
3590 (contents-begin (match-beginning 4))
3591 (contents-end (match-end 4))
3592 (post-blank (progn (goto-char (match-end 2))
3593 (skip-chars-forward " \t")))
3598 :contents-begin contents-begin
3599 :contents-end contents-end
3600 :post-blank post-blank
))))))
3602 (defun org-element-underline-interpreter (underline contents
)
3603 "Interpret UNDERLINE object as Org syntax.
3604 CONTENTS is the contents of the object."
3605 (format "_%s_" contents
))
3610 (defun org-element-verbatim-parser ()
3611 "Parse verbatim object at point, if any.
3613 When at a verbatim object, return a list whose car is `verbatim'
3614 and cdr is a plist with `:value', `:begin', `:end' and
3615 `:post-blank' keywords. Otherwise, return nil.
3617 Assume point is at the first equal sign marker."
3619 (unless (bolp) (backward-char 1))
3620 (when (looking-at org-emph-re
)
3621 (let ((begin (match-beginning 2))
3622 (value (org-match-string-no-properties 4))
3623 (post-blank (progn (goto-char (match-end 2))
3624 (skip-chars-forward " \t")))
3630 :post-blank post-blank
))))))
3632 (defun org-element-verbatim-interpreter (verbatim contents
)
3633 "Interpret VERBATIM object as Org syntax.
3635 (format "=%s=" (org-element-property :value verbatim
)))
3639 ;;; Parsing Element Starting At Point
3641 ;; `org-element--current-element' is the core function of this section.
3642 ;; It returns the Lisp representation of the element starting at
3645 ;; `org-element--current-element' makes use of special modes. They
3646 ;; are activated for fixed element chaining (e.g., `plain-list' >
3647 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3648 ;; `section'). Special modes are: `first-section', `item',
3649 ;; `node-property', `section' and `table-row'.
3651 (defun org-element--current-element
3652 (limit &optional granularity special structure
)
3653 "Parse the element starting at point.
3655 Return value is a list like (TYPE PROPS) where TYPE is the type
3656 of the element and PROPS a plist of properties associated to the
3659 Possible types are defined in `org-element-all-elements'.
3661 LIMIT bounds the search.
3663 Optional argument GRANULARITY determines the depth of the
3664 recursion. Allowed values are `headline', `greater-element',
3665 `element', `object' or nil. When it is broader than `object' (or
3666 nil), secondary values will not be parsed, since they only
3669 Optional argument SPECIAL, when non-nil, can be either
3670 `first-section', `item', `node-property', `section', and
3673 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3676 This function assumes point is always at the beginning of the
3677 element it has to parse."
3679 (let ((case-fold-search t
)
3680 ;; Determine if parsing depth allows for secondary strings
3681 ;; parsing. It only applies to elements referenced in
3682 ;; `org-element-secondary-value-alist'.
3683 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3687 (org-element-item-parser limit structure raw-secondary-p
))
3689 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3691 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3693 ((org-with-limited-levels (org-at-heading-p))
3694 (org-element-headline-parser limit raw-secondary-p
))
3695 ;; Sections (must be checked after headline).
3696 ((eq special
'section
) (org-element-section-parser limit
))
3697 ((eq special
'first-section
)
3698 (org-element-section-parser
3699 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3701 ;; When not at bol, point is at the beginning of an item or
3702 ;; a footnote definition: next item is always a paragraph.
3703 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3704 ;; Planning and Clock.
3705 ((looking-at org-planning-or-clock-line-re
)
3706 (if (equal (match-string 1) org-clock-string
)
3707 (org-element-clock-parser limit
)
3708 (org-element-planning-parser limit
)))
3711 (org-element-inlinetask-parser limit raw-secondary-p
))
3712 ;; From there, elements can have affiliated keywords.
3713 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3715 ;; Jumping over affiliated keywords put point off-limits.
3716 ;; Parse them as regular keywords.
3717 ((and (cdr affiliated
) (>= (point) limit
))
3718 (goto-char (car affiliated
))
3719 (org-element-keyword-parser limit nil
))
3720 ;; LaTeX Environment.
3721 ((looking-at org-element--latex-begin-environment
)
3722 (org-element-latex-environment-parser limit affiliated
))
3723 ;; Drawer and Property Drawer.
3724 ((looking-at org-drawer-regexp
)
3725 (if (equal (match-string 1) "PROPERTIES")
3726 (org-element-property-drawer-parser limit affiliated
)
3727 (org-element-drawer-parser limit affiliated
)))
3729 ((looking-at "[ \t]*:\\( \\|$\\)")
3730 (org-element-fixed-width-parser limit affiliated
))
3731 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3733 ((looking-at "[ \t]*#")
3734 (goto-char (match-end 0))
3735 (cond ((looking-at "\\(?: \\|$\\)")
3737 (org-element-comment-parser limit affiliated
))
3738 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3740 (let ((parser (assoc (upcase (match-string 1))
3741 org-element-block-name-alist
)))
3742 (if parser
(funcall (cdr parser
) limit affiliated
)
3743 (org-element-special-block-parser limit affiliated
))))
3744 ((looking-at "\\+CALL:")
3746 (org-element-babel-call-parser limit affiliated
))
3747 ((looking-at "\\+BEGIN:? ")
3749 (org-element-dynamic-block-parser limit affiliated
))
3750 ((looking-at "\\+\\S-+:")
3752 (org-element-keyword-parser limit affiliated
))
3755 (org-element-paragraph-parser limit affiliated
))))
3756 ;; Footnote Definition.
3757 ((looking-at org-footnote-definition-re
)
3758 (org-element-footnote-definition-parser limit affiliated
))
3760 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3761 (org-element-horizontal-rule-parser limit affiliated
))
3764 (org-element-diary-sexp-parser limit affiliated
))
3766 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3768 ((looking-at (org-item-re))
3769 (org-element-plain-list-parser
3771 (or structure
(org-element--list-struct limit
))))
3772 ;; Default element: Paragraph.
3773 (t (org-element-paragraph-parser limit affiliated
)))))))))
3776 ;; Most elements can have affiliated keywords. When looking for an
3777 ;; element beginning, we want to move before them, as they belong to
3778 ;; that element, and, in the meantime, collect information they give
3779 ;; into appropriate properties. Hence the following function.
3781 (defun org-element--collect-affiliated-keywords (limit)
3782 "Collect affiliated keywords from point down to LIMIT.
3784 Return a list whose CAR is the position at the first of them and
3785 CDR a plist of keywords and values and move point to the
3786 beginning of the first line after them.
3788 As a special case, if element doesn't start at the beginning of
3789 the line (e.g., a paragraph starting an item), CAR is current
3790 position of point and CDR is nil."
3791 (if (not (bolp)) (list (point))
3792 (let ((case-fold-search t
)
3794 ;; RESTRICT is the list of objects allowed in parsed
3796 (restrict (org-element-restriction 'keyword
))
3798 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3799 (let* ((raw-kwd (upcase (match-string 1)))
3800 ;; Apply translation to RAW-KWD. From there, KWD is
3801 ;; the official keyword.
3802 (kwd (or (cdr (assoc raw-kwd
3803 org-element-keyword-translation-alist
))
3805 ;; Find main value for any keyword.
3809 (buffer-substring-no-properties
3810 (match-end 0) (point-at-eol)))))
3811 ;; PARSEDP is non-nil when keyword should have its
3813 (parsedp (member kwd org-element-parsed-keywords
))
3814 ;; If KWD is a dual keyword, find its secondary
3815 ;; value. Maybe parse it.
3816 (dualp (member kwd org-element-dual-keywords
))
3819 (let ((sec (org-match-string-no-properties 2)))
3820 (if (or (not sec
) (not parsedp
)) sec
3821 (org-element-parse-secondary-string sec restrict
)))))
3822 ;; Attribute a property name to KWD.
3823 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3824 ;; Now set final shape for VALUE.
3826 (setq value
(org-element-parse-secondary-string value restrict
)))
3828 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3829 (when (or (member kwd org-element-multiple-keywords
)
3830 ;; Attributes can always appear on multiple lines.
3831 (string-match "^ATTR_" kwd
))
3832 (setq value
(cons value
(plist-get output kwd-sym
))))
3833 ;; Eventually store the new value in OUTPUT.
3834 (setq output
(plist-put output kwd-sym value
))
3835 ;; Move to next keyword.
3837 ;; If affiliated keywords are orphaned: move back to first one.
3838 ;; They will be parsed as a paragraph.
3839 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3841 (cons origin output
))))
3847 ;; The two major functions here are `org-element-parse-buffer', which
3848 ;; parses Org syntax inside the current buffer, taking into account
3849 ;; region, narrowing, or even visibility if specified, and
3850 ;; `org-element-parse-secondary-string', which parses objects within
3853 ;; The (almost) almighty `org-element-map' allows to apply a function
3854 ;; on elements or objects matching some type, and accumulate the
3855 ;; resulting values. In an export situation, it also skips unneeded
3856 ;; parts of the parse tree.
3858 (defun org-element-parse-buffer (&optional granularity visible-only
)
3859 "Recursively parse the buffer and return structure.
3860 If narrowing is in effect, only parse the visible part of the
3863 Optional argument GRANULARITY determines the depth of the
3864 recursion. It can be set to the following symbols:
3866 `headline' Only parse headlines.
3867 `greater-element' Don't recurse into greater elements excepted
3868 headlines and sections. Thus, elements
3869 parsed are the top-level ones.
3870 `element' Parse everything but objects and plain text.
3871 `object' Parse the complete buffer (default).
3873 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3876 An element or an objects is represented as a list with the
3877 pattern (TYPE PROPERTIES CONTENTS), where :
3879 TYPE is a symbol describing the element or object. See
3880 `org-element-all-elements' and `org-element-all-objects' for an
3881 exhaustive list of such symbols. One can retrieve it with
3882 `org-element-type' function.
3884 PROPERTIES is the list of attributes attached to the element or
3885 object, as a plist. Although most of them are specific to the
3886 element or object type, all types share `:begin', `:end',
3887 `:post-blank' and `:parent' properties, which respectively
3888 refer to buffer position where the element or object starts,
3889 ends, the number of white spaces or blank lines after it, and
3890 the element or object containing it. Properties values can be
3891 obtained by using `org-element-property' function.
3893 CONTENTS is a list of elements, objects or raw strings
3894 contained in the current element or object, when applicable.
3895 One can access them with `org-element-contents' function.
3897 The Org buffer has `org-data' as type and nil as properties.
3898 `org-element-map' function can be used to find specific elements
3899 or objects within the parse tree.
3901 This function assumes that current major mode is `org-mode'."
3903 (goto-char (point-min))
3904 (org-skip-whitespace)
3905 (org-element--parse-elements
3906 (point-at-bol) (point-max)
3907 ;; Start in `first-section' mode so text before the first
3908 ;; headline belongs to a section.
3909 'first-section nil granularity visible-only
(list 'org-data nil
))))
3911 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3912 "Recursively parse objects in STRING and return structure.
3914 RESTRICTION is a symbol limiting the object types that will be
3917 Optional argument PARENT, when non-nil, is the element or object
3918 containing the secondary string. It is used to set correctly
3919 `:parent' property within the string."
3920 ;; Copy buffer-local variables listed in
3921 ;; `org-element-object-variables' into temporary buffer. This is
3922 ;; required since object parsing is dependent on these variables.
3923 (let ((pairs (delq nil
(mapcar (lambda (var)
3925 (cons var
(symbol-value var
))))
3926 org-element-object-variables
))))
3928 (mapc (lambda (pair) (org-set-local (car pair
) (cdr pair
))) pairs
)
3930 (let ((secondary (org-element--parse-objects
3931 (point-min) (point-max) nil restriction
)))
3933 (mapc (lambda (obj) (org-element-put-property obj
:parent parent
))
3937 (defun org-element-map
3938 (data types fun
&optional info first-match no-recursion with-affiliated
)
3939 "Map a function on selected elements or objects.
3941 DATA is a parse tree, an element, an object, a string, or a list
3942 of such constructs. TYPES is a symbol or list of symbols of
3943 elements or objects types (see `org-element-all-elements' and
3944 `org-element-all-objects' for a complete list of types). FUN is
3945 the function called on the matching element or object. It has to
3946 accept one argument: the element or object itself.
3948 When optional argument INFO is non-nil, it should be a plist
3949 holding export options. In that case, parts of the parse tree
3950 not exportable according to that property list will be skipped.
3952 When optional argument FIRST-MATCH is non-nil, stop at the first
3953 match for which FUN doesn't return nil, and return that value.
3955 Optional argument NO-RECURSION is a symbol or a list of symbols
3956 representing elements or objects types. `org-element-map' won't
3957 enter any recursive element or object whose type belongs to that
3958 list. Though, FUN can still be applied on them.
3960 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3961 apply to matching objects within parsed affiliated keywords (see
3962 `org-element-parsed-keywords').
3964 Nil values returned from FUN do not appear in the results.
3970 Assuming TREE is a variable containing an Org buffer parse tree,
3971 the following example will return a flat list of all `src-block'
3972 and `example-block' elements in it:
3974 \(org-element-map tree '(example-block src-block) 'identity)
3976 The following snippet will find the first headline with a level
3977 of 1 and a \"phone\" tag, and will return its beginning position:
3979 \(org-element-map tree 'headline
3981 \(and (= (org-element-property :level hl) 1)
3982 \(member \"phone\" (org-element-property :tags hl))
3983 \(org-element-property :begin hl)))
3986 The next example will return a flat list of all `plain-list' type
3987 elements in TREE that are not a sub-list themselves:
3989 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3991 Eventually, this example will return a flat list of all `bold'
3992 type objects containing a `latex-snippet' type object, even
3993 looking into captions:
3995 \(org-element-map tree 'bold
3997 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3999 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4000 (unless (listp types
) (setq types
(list types
)))
4001 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
4002 ;; Recursion depth is determined by --CATEGORY.
4005 (let ((category 'greater-elements
))
4006 (mapc (lambda (type)
4007 (cond ((or (memq type org-element-all-objects
)
4008 (eq type
'plain-text
))
4009 ;; If one object is found, the function
4010 ;; has to recurse into every object.
4011 (throw 'found
'objects
))
4012 ((not (memq type org-element-greater-elements
))
4013 ;; If one regular element is found, the
4014 ;; function has to recurse, at least,
4015 ;; into every element it encounters.
4016 (and (not (eq category
'elements
))
4017 (setq category
'elements
)))))
4020 ;; Compute properties for affiliated keywords if necessary.
4022 (and with-affiliated
4023 (mapcar (lambda (kwd)
4024 (cons kwd
(intern (concat ":" (downcase kwd
)))))
4025 org-element-affiliated-keywords
)))
4031 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4032 ;; holding contextual information.
4033 (let ((--type (org-element-type --data
)))
4036 ;; Ignored element in an export context.
4037 ((and info
(memq --data
(plist-get info
:ignore-list
))))
4038 ;; List of elements or objects.
4039 ((not --type
) (mapc --walk-tree --data
))
4040 ;; Unconditionally enter parse trees.
4041 ((eq --type
'org-data
)
4042 (mapc --walk-tree
(org-element-contents --data
)))
4044 ;; Check if TYPE is matching among TYPES. If so,
4045 ;; apply FUN to --DATA and accumulate return value
4046 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4047 (when (memq --type types
)
4048 (let ((result (funcall fun --data
)))
4049 (cond ((not result
))
4050 (first-match (throw '--map-first-match result
))
4051 (t (push result --acc
)))))
4052 ;; If --DATA has a secondary string that can contain
4053 ;; objects with their type among TYPES, look into it.
4054 (when (and (eq --category
'objects
) (not (stringp --data
)))
4056 (assq --type org-element-secondary-value-alist
)))
4058 (funcall --walk-tree
4059 (org-element-property (cdr sec-prop
) --data
)))))
4060 ;; If --DATA has any affiliated keywords and
4061 ;; WITH-AFFILIATED is non-nil, look for objects in
4063 (when (and with-affiliated
4064 (eq --category
'objects
)
4065 (memq --type org-element-all-elements
))
4066 (mapc (lambda (kwd-pair)
4067 (let ((kwd (car kwd-pair
))
4068 (value (org-element-property
4069 (cdr kwd-pair
) --data
)))
4070 ;; Pay attention to the type of value.
4071 ;; Preserve order for multiple keywords.
4074 ((and (member kwd org-element-multiple-keywords
)
4075 (member kwd org-element-dual-keywords
))
4076 (mapc (lambda (line)
4077 (funcall --walk-tree
(cdr line
))
4078 (funcall --walk-tree
(car line
)))
4080 ((member kwd org-element-multiple-keywords
)
4081 (mapc (lambda (line) (funcall --walk-tree line
))
4083 ((member kwd org-element-dual-keywords
)
4084 (funcall --walk-tree
(cdr value
))
4085 (funcall --walk-tree
(car value
)))
4086 (t (funcall --walk-tree value
)))))
4087 --affiliated-alist
))
4088 ;; Determine if a recursion into --DATA is possible.
4090 ;; --TYPE is explicitly removed from recursion.
4091 ((memq --type no-recursion
))
4092 ;; --DATA has no contents.
4093 ((not (org-element-contents --data
)))
4094 ;; Looking for greater elements but --DATA is simply
4095 ;; an element or an object.
4096 ((and (eq --category
'greater-elements
)
4097 (not (memq --type org-element-greater-elements
))))
4098 ;; Looking for elements but --DATA is an object.
4099 ((and (eq --category
'elements
)
4100 (memq --type org-element-all-objects
)))
4101 ;; In any other case, map contents.
4102 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4103 (catch '--map-first-match
4104 (funcall --walk-tree data
)
4105 ;; Return value in a proper order.
4107 (put 'org-element-map
'lisp-indent-function
2)
4109 ;; The following functions are internal parts of the parser.
4111 ;; The first one, `org-element--parse-elements' acts at the element's
4114 ;; The second one, `org-element--parse-objects' applies on all objects
4115 ;; of a paragraph or a secondary string.
4117 ;; More precisely, that function looks for every allowed object type
4118 ;; first. Then, it discards failed searches, keeps further matches,
4119 ;; and searches again types matched behind point, for subsequent
4120 ;; calls. Thus, searching for a given type fails only once, and every
4121 ;; object is searched only once at top level (but sometimes more for
4124 (defun org-element--parse-elements
4125 (beg end special structure granularity visible-only acc
)
4126 "Parse elements between BEG and END positions.
4128 SPECIAL prioritize some elements over the others. It can be set
4129 to `first-section', `section' `item' or `table-row'.
4131 When value is `item', STRUCTURE will be used as the current list
4134 GRANULARITY determines the depth of the recursion. See
4135 `org-element-parse-buffer' for more information.
4137 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4140 Elements are accumulated into ACC."
4143 ;; Visible only: skip invisible parts at the beginning of the
4145 (when (and visible-only
(org-invisible-p2))
4146 (goto-char (min (1+ (org-find-visible)) end
)))
4147 ;; When parsing only headlines, skip any text before first one.
4148 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4149 (org-with-limited-levels (outline-next-heading)))
4151 (while (< (point) end
)
4152 ;; Find current element's type and parse it accordingly to
4154 (let* ((element (org-element--current-element
4155 end granularity special structure
))
4156 (type (org-element-type element
))
4157 (cbeg (org-element-property :contents-begin element
)))
4158 (goto-char (org-element-property :end element
))
4159 ;; Visible only: skip invisible parts between siblings.
4160 (when (and visible-only
(org-invisible-p2))
4161 (goto-char (min (1+ (org-find-visible)) end
)))
4162 ;; Fill ELEMENT contents by side-effect.
4164 ;; If element has no contents, don't modify it.
4166 ;; Greater element: parse it between `contents-begin' and
4167 ;; `contents-end'. Make sure GRANULARITY allows the
4168 ;; recursion, or ELEMENT is a headline, in which case going
4169 ;; inside is mandatory, in order to get sub-level headings.
4170 ((and (memq type org-element-greater-elements
)
4171 (or (memq granularity
'(element object nil
))
4172 (and (eq granularity
'greater-element
)
4174 (eq type
'headline
)))
4175 (org-element--parse-elements
4176 cbeg
(org-element-property :contents-end element
)
4177 ;; Possibly switch to a special mode.
4181 (property-drawer 'node-property
)
4183 (and (memq type
'(item plain-list
))
4184 (org-element-property :structure element
))
4185 granularity visible-only element
))
4186 ;; ELEMENT has contents. Parse objects inside, if
4187 ;; GRANULARITY allows it.
4188 ((memq granularity
'(object nil
))
4189 (org-element--parse-objects
4190 cbeg
(org-element-property :contents-end element
) element
4191 (org-element-restriction type
))))
4192 (org-element-adopt-elements acc element
)))
4196 (defconst org-element--object-regexp
4197 (mapconcat #'identity
4198 (let ((link-types (regexp-opt org-link-types
)))
4201 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4202 ;; Bold, code, italic, strike-through, underline and
4205 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4207 (concat "\\<" link-types
":")
4208 ;; Objects starting with "[": regular link, footnote
4209 ;; reference, statistics cookie, timestamp (inactive).
4210 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4211 ;; Objects starting with "@": export snippets.
4213 ;; Objects starting with "{": macro.
4215 ;; Objects starting with "<" : timestamp (active,
4216 ;; diary), target, radio target and angular links.
4217 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4218 ;; Objects starting with "$": latex fragment.
4220 ;; Objects starting with "\": line break, entity,
4222 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4223 ;; Objects starting with raw text: inline Babel
4224 ;; source block, inline Babel call.
4225 "\\(?:call\\|src\\)_"))
4227 "Regexp possibly matching the beginning of an object.
4228 This regexp allows false positives. Dedicated parser (e.g.,
4229 `org-export-bold-parser') will take care of further filtering.
4230 Radio links are not matched by this regexp, as they are treated
4231 specially in `org-element--object-lex'.")
4233 (defun org-element--object-lex (restriction)
4234 "Return next object in current buffer or nil.
4235 RESTRICTION is a list of object types, as symbols, that should be
4236 looked after. This function assumes that the buffer is narrowed
4237 to an appropriate container (e.g., a paragraph)."
4238 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4240 (let ((limit (and org-target-link-regexp
4242 (or (bolp) (backward-char))
4243 (re-search-forward org-target-link-regexp nil t
))
4244 (match-beginning 1)))
4246 (while (and (not found
)
4247 (re-search-forward org-element--object-regexp limit t
))
4248 (goto-char (match-beginning 0))
4249 (let ((result (match-string 0)))
4252 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4253 (and (memq 'inline-babel-call restriction
)
4254 (org-element-inline-babel-call-parser)))
4255 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4256 (and (memq 'inline-src-block restriction
)
4257 (org-element-inline-src-block-parser)))
4260 (?^
(and (memq 'superscript restriction
)
4261 (org-element-superscript-parser)))
4262 (?_
(or (and (memq 'subscript restriction
)
4263 (org-element-subscript-parser))
4264 (and (memq 'underline restriction
)
4265 (org-element-underline-parser))))
4266 (?
* (and (memq 'bold restriction
)
4267 (org-element-bold-parser)))
4268 (?
/ (and (memq 'italic restriction
)
4269 (org-element-italic-parser)))
4270 (?~
(and (memq 'code restriction
)
4271 (org-element-code-parser)))
4272 (?
= (and (memq 'verbatim restriction
)
4273 (org-element-verbatim-parser)))
4274 (?
+ (and (memq 'strike-through restriction
)
4275 (org-element-strike-through-parser)))
4276 (?
@ (and (memq 'export-snippet restriction
)
4277 (org-element-export-snippet-parser)))
4278 (?
{ (and (memq 'macro restriction
)
4279 (org-element-macro-parser)))
4280 (?$
(and (memq 'latex-fragment restriction
)
4281 (org-element-latex-fragment-parser)))
4283 (if (eq (aref result
1) ?
<)
4284 (or (and (memq 'radio-target restriction
)
4285 (org-element-radio-target-parser))
4286 (and (memq 'target restriction
)
4287 (org-element-target-parser)))
4288 (or (and (memq 'timestamp restriction
)
4289 (org-element-timestamp-parser))
4290 (and (memq 'link restriction
)
4291 (org-element-link-parser)))))
4293 (if (eq (aref result
1) ?
\\)
4294 (and (memq 'line-break restriction
)
4295 (org-element-line-break-parser))
4296 (or (and (memq 'entity restriction
)
4297 (org-element-entity-parser))
4298 (and (memq 'latex-fragment restriction
)
4299 (org-element-latex-fragment-parser)))))
4301 (if (eq (aref result
1) ?\
[)
4302 (and (memq 'link restriction
)
4303 (org-element-link-parser))
4304 (or (and (memq 'footnote-reference restriction
)
4305 (org-element-footnote-reference-parser))
4306 (and (memq 'timestamp restriction
)
4307 (org-element-timestamp-parser))
4308 (and (memq 'statistics-cookie restriction
)
4309 (org-element-statistics-cookie-parser)))))
4310 ;; This is probably a plain link.
4311 (otherwise (and (or (memq 'link restriction
)
4312 (memq 'plain-link restriction
))
4313 (org-element-link-parser)))))))
4314 (or (eobp) (forward-char))))
4317 ((and limit
(memq 'link restriction
))
4318 (goto-char limit
) (org-element-link-parser)))))))
4320 (defun org-element--parse-objects (beg end acc restriction
)
4321 "Parse objects between BEG and END and return recursive structure.
4323 Objects are accumulated in ACC.
4325 RESTRICTION is a list of object successors which are allowed in
4326 the current object."
4329 (narrow-to-region beg end
)
4330 (goto-char (point-min))
4332 (while (and (not (eobp))
4333 (setq next-object
(org-element--object-lex restriction
)))
4334 ;; 1. Text before any object. Untabify it.
4335 (let ((obj-beg (org-element-property :begin next-object
)))
4336 (unless (= (point) obj-beg
)
4338 (org-element-adopt-elements
4340 (replace-regexp-in-string
4341 "\t" (make-string tab-width ?
)
4342 (buffer-substring-no-properties (point) obj-beg
))))))
4344 (let ((obj-end (org-element-property :end next-object
))
4345 (cont-beg (org-element-property :contents-begin next-object
)))
4346 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4347 ;; a recursive type.
4349 (memq (car next-object
) org-element-recursive-objects
))
4350 (org-element--parse-objects
4351 cont-beg
(org-element-property :contents-end next-object
)
4352 next-object
(org-element-restriction next-object
)))
4353 (setq acc
(org-element-adopt-elements acc next-object
))
4354 (goto-char obj-end
))))
4355 ;; 3. Text after last object. Untabify it.
4358 (org-element-adopt-elements
4360 (replace-regexp-in-string
4361 "\t" (make-string tab-width ?
)
4362 (buffer-substring-no-properties (point) end
)))))
4368 ;;; Towards A Bijective Process
4370 ;; The parse tree obtained with `org-element-parse-buffer' is really
4371 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4372 ;; interpreted and expanded into a string with canonical Org syntax.
4373 ;; Hence `org-element-interpret-data'.
4375 ;; The function relies internally on
4376 ;; `org-element--interpret-affiliated-keywords'.
4379 (defun org-element-interpret-data (data &optional pseudo-objects
)
4380 "Interpret DATA as Org syntax.
4382 DATA is a parse tree, an element, an object or a secondary string
4385 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4386 new types that should be treated as objects. An unknown type not
4387 belonging to this list is seen as a pseudo-element instead. Both
4388 pseudo-objects and pseudo-elements are transparent entities, i.e.
4389 only their contents are interpreted.
4391 Return Org syntax as a string."
4392 (org-element--interpret-data-1 data nil pseudo-objects
))
4394 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4395 "Interpret DATA as Org syntax.
4397 DATA is a parse tree, an element, an object or a secondary string
4398 to interpret. PARENT is used for recursive calls. It contains
4399 the element or object containing data, or nil. PSEUDO-OBJECTS
4400 are list of symbols defining new element or object types.
4401 Unknown types that don't belong to this list are treated as
4402 pseudo-elements instead.
4404 Return Org syntax as a string."
4405 (let* ((type (org-element-type data
))
4406 ;; Find interpreter for current object or element. If it
4407 ;; doesn't exist (e.g. this is a pseudo object or element),
4408 ;; return contents, if any.
4410 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4411 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4414 ;; Secondary string.
4418 (org-element--interpret-data-1 obj parent pseudo-objects
))
4420 ;; Full Org document.
4421 ((eq type
'org-data
)
4424 (org-element--interpret-data-1 obj parent pseudo-objects
))
4425 (org-element-contents data
) ""))
4426 ;; Plain text: return it.
4427 ((stringp data
) data
)
4428 ;; Element or object without contents.
4429 ((not (org-element-contents data
)) (funcall interpret data nil
))
4430 ;; Element or object with contents.
4432 (funcall interpret data
4433 ;; Recursively interpret contents.
4436 (org-element--interpret-data-1 obj data pseudo-objects
))
4437 (org-element-contents
4438 (if (not (memq type
'(paragraph verse-block
)))
4440 ;; Fix indentation of elements containing
4441 ;; objects. We ignore `table-row' elements
4442 ;; as they are one line long anyway.
4443 (org-element-normalize-contents
4445 ;; When normalizing first paragraph of an
4446 ;; item or a footnote-definition, ignore
4447 ;; first line's indentation.
4448 (and (eq type
'paragraph
)
4449 (equal data
(car (org-element-contents parent
)))
4450 (memq (org-element-type parent
)
4451 '(footnote-definition item
))))))
4453 (if (memq type
'(org-data plain-text nil
)) results
4454 ;; Build white spaces. If no `:post-blank' property is
4455 ;; specified, assume its value is 0.
4456 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4457 (if (or (memq type org-element-all-objects
)
4458 (memq type pseudo-objects
))
4459 (concat results
(make-string post-blank ?\s
))
4461 (org-element--interpret-affiliated-keywords data
)
4462 (org-element-normalize-string results
)
4463 (make-string post-blank ?
\n)))))))
4465 (defun org-element--interpret-affiliated-keywords (element)
4466 "Return ELEMENT's affiliated keywords as Org syntax.
4467 If there is no affiliated keyword, return the empty string."
4468 (let ((keyword-to-org
4472 (when (member key org-element-dual-keywords
)
4473 (setq dual
(cdr value
) value
(car value
)))
4476 (format "[%s]" (org-element-interpret-data dual
)))
4478 (if (member key org-element-parsed-keywords
)
4479 (org-element-interpret-data value
)
4484 (let ((value (org-element-property prop element
))
4485 (keyword (upcase (substring (symbol-name prop
) 1))))
4487 (if (or (member keyword org-element-multiple-keywords
)
4488 ;; All attribute keywords can have multiple lines.
4489 (string-match "^ATTR_" keyword
))
4490 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4493 (funcall keyword-to-org keyword value
)))))
4494 ;; List all ELEMENT's properties matching an attribute line or an
4495 ;; affiliated keyword, but ignore translated keywords since they
4496 ;; cannot belong to the property list.
4497 (loop for prop in
(nth 1 element
) by
'cddr
4498 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4499 (or (string-match "^ATTR_" keyword
)
4501 (member keyword org-element-affiliated-keywords
)
4503 org-element-keyword-translation-alist
)))))
4507 ;; Because interpretation of the parse tree must return the same
4508 ;; number of blank lines between elements and the same number of white
4509 ;; space after objects, some special care must be given to white
4512 ;; The first function, `org-element-normalize-string', ensures any
4513 ;; string different from the empty string will end with a single
4514 ;; newline character.
4516 ;; The second function, `org-element-normalize-contents', removes
4517 ;; global indentation from the contents of the current element.
4519 (defun org-element-normalize-string (s)
4520 "Ensure string S ends with a single newline character.
4522 If S isn't a string return it unchanged. If S is the empty
4523 string, return it. Otherwise, return a new string with a single
4524 newline character at its end."
4526 ((not (stringp s
)) s
)
4528 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4529 (replace-match "\n" nil nil s
)))))
4531 (defun org-element-normalize-contents (element &optional ignore-first
)
4532 "Normalize plain text in ELEMENT's contents.
4534 ELEMENT must only contain plain text and objects.
4536 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4537 indentation to compute maximal common indentation.
4539 Return the normalized element that is element with global
4540 indentation removed from its contents. The function assumes that
4541 indentation is not done with TAB characters."
4542 (let* ((min-ind most-positive-fixnum
)
4543 find-min-ind
; For byte-compiler.
4546 ;; Return minimal common indentation within BLOB. This is
4547 ;; done by walking recursively BLOB and updating MIN-IND
4548 ;; along the way. FIRST-FLAG is non-nil when the first
4549 ;; string hasn't been seen yet. It is required as this
4550 ;; string is the only one whose indentation doesn't happen
4551 ;; after a newline character.
4552 (lambda (blob first-flag
)
4553 (dolist (object (org-element-contents blob
))
4554 (when (and first-flag
(stringp object
))
4555 (setq first-flag nil
)
4556 (string-match "\\`\\( *\\)" object
)
4557 (let ((len (length (match-string 1 object
))))
4558 ;; An indentation of zero means no string will be
4559 ;; modified. Quit the process.
4560 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4561 (setq min-ind
(min len min-ind
)))))
4564 (dolist (line (delq "" (cdr (org-split-string object
" *\n"))))
4565 (setq min-ind
(min (org-get-indentation line
) min-ind
))))
4566 ((memq (org-element-type object
) org-element-recursive-objects
)
4567 (funcall find-min-ind object first-flag
))))))))
4568 ;; Find minimal indentation in ELEMENT.
4569 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4570 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4571 ;; Build ELEMENT back, replacing each string with the same
4572 ;; string minus common indentation.
4573 (let* (build ; For byte compiler.
4576 (lambda (blob first-flag
)
4577 ;; Return BLOB with all its strings indentation
4578 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4579 ;; is non-nil when the first string hasn't been seen
4584 (when (and first-flag
(stringp object
))
4585 (setq first-flag nil
)
4587 (replace-regexp-in-string
4588 (format "\\` \\{%d\\}" min-ind
)
4592 (replace-regexp-in-string
4593 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4594 ((memq (org-element-type object
)
4595 org-element-recursive-objects
)
4596 (funcall build object first-flag
))
4598 (org-element-contents blob
)))
4600 (funcall build element
(not ignore-first
))))))
4606 ;; Implement a caching mechanism for `org-element-at-point' and
4607 ;; `org-element-context', which see.
4609 ;; A single public function is provided: `org-element-cache-reset'.
4611 ;; Cache is enabled by default, but can be disabled globally with
4612 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4613 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4614 ;; can be tweaked to control caching behaviour.
4616 ;; Internally, parsed elements are stored in an AVL tree,
4617 ;; `org-element--cache'. This tree is updated lazily: whenever
4618 ;; a change happens to the buffer, a synchronization request is
4619 ;; registered in `org-element--cache-sync-requests' (see
4620 ;; `org-element--cache-submit-request'). During idle time, requests
4621 ;; are processed by `org-element--cache-sync'. Synchronization also
4622 ;; happens when an element is required from the cache. In this case,
4623 ;; the process stops as soon as the needed element is up-to-date.
4625 ;; A synchronization request can only apply on a synchronized part of
4626 ;; the cache. Therefore, the cache is updated at least to the
4627 ;; location where the new request applies. Thus, requests are ordered
4628 ;; from left to right and all elements starting before the first
4629 ;; request are correct. This property is used by functions like
4630 ;; `org-element--cache-find' to retrieve elements in the part of the
4631 ;; cache that can be trusted.
4633 ;; A request applies to every element, starting from its original
4634 ;; location (or key, see below). When a request is processed, it
4635 ;; moves forward and may collide the next one. In this case, both
4636 ;; requests are merged into a new one that starts from that element.
4637 ;; As a consequence, the whole synchronization complexity does not
4638 ;; depend on the number of pending requests, but on the number of
4639 ;; elements the very first request will be applied on.
4641 ;; Elements cannot be accessed through their beginning position, which
4642 ;; may or may not be up-to-date. Instead, each element in the tree is
4643 ;; associated to a key, obtained with `org-element--cache-key'. This
4644 ;; mechanism is robust enough to preserve total order among elements
4645 ;; even when the tree is only partially synchronized.
4647 ;; Objects contained in an element are stored in a hash table,
4648 ;; `org-element--cache-objects'.
4651 (defvar org-element-use-cache t
4652 "Non nil when Org parser should cache its results.
4653 This is mostly for debugging purpose.")
4655 (defvar org-element-cache-sync-idle-time
0.6
4656 "Length, in seconds, of idle time before syncing cache.")
4658 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4659 "Maximum duration, as a time value, for a cache synchronization.
4660 If the synchronization is not over after this delay, the process
4661 pauses and resumes after `org-element-cache-sync-break'
4664 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4665 "Duration, as a time value, of the pause between synchronizations.
4666 See `org-element-cache-sync-duration' for more information.")
4671 (defvar org-element--cache nil
4672 "AVL tree used to cache elements.
4673 Each node of the tree contains an element. Comparison is done
4674 with `org-element--cache-compare'. This cache is used in
4675 `org-element-at-point'.")
4677 (defvar org-element--cache-objects nil
4678 "Hash table used as to cache objects.
4679 Key is an element, as returned by `org-element-at-point', and
4680 value is an alist where each association is:
4682 \(PARENT COMPLETEP . OBJECTS)
4684 where PARENT is an element or object, COMPLETEP is a boolean,
4685 non-nil when all direct children of parent are already cached and
4686 OBJECTS is a list of such children, as objects, from farthest to
4689 In the following example, \\alpha, bold object and \\beta are
4690 contained within a paragraph
4694 If the paragraph is completely parsed, OBJECTS-DATA will be
4696 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4697 \(BOLD-OBJECT t ENTITY-OBJECT))
4699 whereas in a partially parsed paragraph, it could be
4701 \((PARAGRAPH nil ENTITY-OBJECT))
4703 This cache is used in `org-element-context'.")
4705 (defvar org-element--cache-sync-requests nil
4706 "List of pending synchronization requests.
4708 A request is a vector with the following pattern:
4710 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4712 Processing a synchronization request consists of three phases:
4714 0. Delete modified elements,
4715 1. Fill missing area in cache,
4716 2. Shift positions and re-parent elements after the changes.
4718 During phase 0, NEXT is the key of the first element to be
4719 removed, BEG and END is buffer position delimiting the
4720 modifications. Elements starting between them (inclusive) are
4721 removed and so are those contained within OUTREACH. PARENT, when
4722 non-nil, is the parent of the first element to be removed.
4724 During phase 1, NEXT is the key of the next known element in
4725 cache and BEG its beginning position. Parse buffer between that
4726 element and the one before it in order to determine the parent of
4727 the next element. Set PARENT to the element containing NEXT.
4729 During phase 2, NEXT is the key of the next element to shift in
4730 the parse tree. All elements starting from this one have their
4731 properties relatives to buffer positions shifted by integer
4732 OFFSET and, if they belong to element PARENT, are adopted by it.
4734 PHASE specifies the phase number, as an integer.")
4736 (defvar org-element--cache-sync-timer nil
4737 "Timer used for cache synchronization.")
4739 (defvar org-element--cache-sync-keys nil
4740 "Hash table used to store keys during synchronization.
4741 See `org-element--cache-key' for more information.")
4743 (defsubst org-element--cache-key
(element)
4744 "Return a unique key for ELEMENT in cache tree.
4746 Keys are used to keep a total order among elements in the cache.
4747 Comparison is done with `org-element--cache-key-less-p'.
4749 When no synchronization is taking place, a key is simply the
4750 beginning position of the element, or that position plus one in
4751 the case of an first item (respectively row) in
4752 a list (respectively a table).
4754 During a synchronization, the key is the one the element had when
4755 the cache was synchronized for the last time. Elements added to
4756 cache during the synchronization get a new key generated with
4757 `org-element--cache-generate-key'.
4759 Such keys are stored in `org-element--cache-sync-keys'. The hash
4760 table is cleared once the synchronization is complete."
4761 (or (gethash element org-element--cache-sync-keys
)
4762 (let* ((begin (org-element-property :begin element
))
4763 ;; Increase beginning position of items (respectively
4764 ;; table rows) by one, so the first item can get
4765 ;; a different key from its parent list (respectively
4767 (key (if (memq (org-element-type element
) '(item table-row
))
4770 (if org-element--cache-sync-requests
4771 (puthash element key org-element--cache-sync-keys
)
4774 (defun org-element--cache-generate-key (lower upper
)
4775 "Generate a key between LOWER and UPPER.
4777 LOWER and UPPER are integers or lists, possibly empty.
4779 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4780 a unique key, as an integer or a list of integers, according to
4781 the following rules:
4783 - LOWER and UPPER are compared level-wise until values differ.
4785 - If, at a given level, LOWER and UPPER differ from more than
4786 2, the new key shares all the levels above with LOWER and
4787 gets a new level. Its value is the mean between LOWER and
4790 \(1 2) + (1 4) --> (1 3)
4792 - If LOWER has no value to compare with, it is assumed that its
4793 value is `most-negative-fixnum'. E.g.,
4801 where m is `most-negative-fixnum'. Likewise, if UPPER is
4802 short of levels, the current value is `most-positive-fixnum'.
4804 - If they differ from only one, the new key inherits from
4805 current LOWER level and fork it at the next level. E.g.,
4813 where M is `most-positive-fixnum'.
4815 - If the key is only one level long, it is returned as an
4818 \(1 2) + (3 2) --> 2
4820 When they are not equals, the function assumes that LOWER is
4821 lesser than UPPER, per `org-element--cache-key-less-p'."
4822 (if (equal lower upper
) lower
4823 (let ((lower (if (integerp lower
) (list lower
) lower
))
4824 (upper (if (integerp upper
) (list upper
) upper
))
4828 (let ((min (or (car lower
) most-negative-fixnum
))
4829 (max (cond (skip-upper most-positive-fixnum
)
4831 (t most-positive-fixnum
))))
4832 (if (< (1+ min
) max
)
4833 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4834 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4835 (when (and (< min max
) (not skip-upper
))
4836 ;; When at a given level, LOWER and UPPER differ from
4837 ;; 1, ignore UPPER altogether. Instead create a key
4838 ;; between LOWER and the greatest key with the same
4839 ;; prefix as LOWER so far.
4840 (setq skip-upper t
))
4842 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
4844 (defsubst org-element--cache-key-less-p
(a b
)
4845 "Non-nil if key A is less than key B.
4846 A and B are either integers or lists of integers, as returned by
4847 `org-element--cache-key'."
4848 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4849 (if (integerp b
) (< (car a
) b
)
4852 (cond ((car-less-than-car a b
) (throw 'exit t
))
4853 ((car-less-than-car b a
) (throw 'exit nil
))
4854 (t (setq a
(cdr a
) b
(cdr b
)))))
4855 ;; If A is empty, either keys are equal (B is also empty) and
4856 ;; we return nil, or A is lesser than B (B is longer) and we
4857 ;; return a non-nil value.
4859 ;; If A is not empty, B is necessarily empty and A is greater
4860 ;; than B (A is longer). Therefore, return nil.
4861 (and (null a
) b
)))))
4863 (defun org-element--cache-compare (a b
)
4864 "Non-nil when element A is located before element B."
4865 (org-element--cache-key-less-p (org-element--cache-key a
)
4866 (org-element--cache-key b
)))
4868 (defsubst org-element--cache-root
()
4869 "Return root value in cache.
4870 This function assumes `org-element--cache' is a valid AVL tree."
4871 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4876 (defsubst org-element--cache-active-p
()
4877 "Non-nil when cache is active in current buffer."
4878 (and org-element-use-cache
4879 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4881 (defun org-element--cache-find (pos &optional side
)
4882 "Find element in cache starting at POS or before.
4884 POS refers to a buffer position.
4886 When optional argument SIDE is non-nil, the function checks for
4887 elements starting at or past POS instead. If SIDE is `both', the
4888 function returns a cons cell where car is the first element
4889 starting at or before POS and cdr the first element starting
4892 The function can only find elements in the synchronized part of
4894 (let ((limit (and org-element--cache-sync-requests
4895 (aref (car org-element--cache-sync-requests
) 0)))
4896 (node (org-element--cache-root))
4899 (let* ((element (avl-tree--node-data node
))
4900 (begin (org-element-property :begin element
)))
4903 (not (org-element--cache-key-less-p
4904 (org-element--cache-key element
) limit
)))
4905 (setq node
(avl-tree--node-left node
)))
4908 node
(avl-tree--node-left node
)))
4911 node
(avl-tree--node-right node
)))
4912 ;; We found an element in cache starting at POS. If `side'
4913 ;; is `both' we also want the next one in order to generate
4914 ;; a key in-between.
4916 ;; If the element is the first row or item in a table or
4917 ;; a plain list, we always return the table or the plain
4920 ;; In any other case, we return the element found.
4922 (setq lower element
)
4923 (setq node
(avl-tree--node-right node
)))
4924 ((and (memq (org-element-type element
) '(item table-row
))
4925 (let ((parent (org-element-property :parent element
)))
4926 (and (= (org-element-property :begin element
)
4927 (org-element-property :contents-begin parent
))
4936 (both (cons lower upper
))
4938 (otherwise upper
))))
4940 (defun org-element--cache-put (element &optional data
)
4941 "Store ELEMENT in current buffer's cache, if allowed.
4942 When optional argument DATA is non-nil, assume is it object data
4943 relative to ELEMENT and store it in the objects cache."
4944 (cond ((not (org-element--cache-active-p)) nil
)
4946 (when org-element--cache-sync-requests
4947 ;; During synchronization, first build an appropriate key
4948 ;; for the new element so `avl-tree-enter' can insert it at
4949 ;; the right spot in the cache.
4950 (let ((keys (org-element--cache-find
4951 (org-element-property :begin element
) 'both
)))
4953 (org-element--cache-generate-key
4954 (and (car keys
) (org-element--cache-key (car keys
)))
4955 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4956 (org-element--cache-sync-requests
4957 (aref (car org-element--cache-sync-requests
) 0))))
4958 org-element--cache-sync-keys
)))
4959 (avl-tree-enter org-element--cache element
))
4960 ;; Headlines are not stored in cache, so objects in titles are
4961 ;; not stored either.
4962 ((eq (org-element-type element
) 'headline
) nil
)
4963 (t (puthash element data org-element--cache-objects
))))
4965 (defsubst org-element--cache-remove
(element)
4966 "Remove ELEMENT from cache.
4967 Assume ELEMENT belongs to cache and that a cache is active."
4968 (avl-tree-delete org-element--cache element
)
4969 (remhash element org-element--cache-objects
))
4972 ;;;; Synchronization
4974 (defsubst org-element--cache-set-timer
(buffer)
4975 "Set idle timer for cache synchronization in BUFFER."
4976 (when org-element--cache-sync-timer
4977 (cancel-timer org-element--cache-sync-timer
))
4978 (setq org-element--cache-sync-timer
4979 (run-with-idle-timer
4980 (let ((idle (current-idle-time)))
4981 (if idle
(time-add idle org-element-cache-sync-break
)
4982 org-element-cache-sync-idle-time
))
4984 #'org-element--cache-sync
4987 (defsubst org-element--cache-interrupt-p
(time-limit)
4988 "Non-nil when synchronization process should be interrupted.
4989 TIME-LIMIT is a time value or nil."
4991 (or (input-pending-p)
4992 (time-less-p time-limit
(current-time)))))
4994 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
4995 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4997 Properties containing buffer positions are `:begin', `:end',
4998 `:contents-begin', `:contents-end' and `:structure'. When
4999 optional argument PROPS is a list of keywords, only shift
5000 properties provided in that list.
5002 Properties are modified by side-effect."
5003 (let ((properties (nth 1 element
)))
5004 ;; Shift `:structure' property for the first plain list only: it
5005 ;; is the only one that really matters and it prevents from
5006 ;; shifting it more than once.
5007 (when (and (or (not props
) (memq :structure props
))
5008 (eq (org-element-type element
) 'plain-list
)
5009 (not (eq (org-element-type (plist-get properties
:parent
))
5011 (dolist (item (plist-get properties
:structure
))
5012 (incf (car item
) offset
)
5013 (incf (nth 6 item
) offset
)))
5014 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
5015 (let ((value (and (or (not props
) (memq key props
))
5016 (plist-get properties key
))))
5017 (and value
(plist-put properties key
(+ offset value
)))))))
5019 (defun org-element--cache-sync (buffer &optional threshold future-change
)
5020 "Synchronize cache with recent modification in BUFFER.
5022 When optional argument THRESHOLD is non-nil, do the
5023 synchronization for all elements starting before or at threshold,
5024 then exit. Otherwise, synchronize cache for as long as
5025 `org-element-cache-sync-duration' or until Emacs leaves idle
5028 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5029 not registered yet in the cache are going to happen. It is used
5030 in `org-element--cache-submit-request', where cache is partially
5031 updated before current modification are actually submitted."
5032 (when (buffer-live-p buffer
)
5033 (with-current-buffer buffer
5034 (let ((inhibit-quit t
) request next
)
5035 (when org-element--cache-sync-timer
5036 (cancel-timer org-element--cache-sync-timer
))
5038 (while org-element--cache-sync-requests
5039 (setq request
(car org-element--cache-sync-requests
)
5040 next
(nth 1 org-element--cache-sync-requests
))
5041 (org-element--cache-process-request
5043 (and next
(aref next
0))
5045 (and (not threshold
)
5046 (time-add (current-time)
5047 org-element-cache-sync-duration
))
5049 ;; Request processed. Merge current and next offsets and
5050 ;; transfer ending position.
5052 (incf (aref next
3) (aref request
3))
5053 (aset next
2 (aref request
2)))
5054 (setq org-element--cache-sync-requests
5055 (cdr org-element--cache-sync-requests
))))
5056 ;; If more requests are awaiting, set idle timer accordingly.
5057 ;; Otherwise, reset keys.
5058 (if org-element--cache-sync-requests
5059 (org-element--cache-set-timer buffer
)
5060 (clrhash org-element--cache-sync-keys
))))))
5062 (defun org-element--cache-process-request
5063 (request next threshold time-limit future-change
)
5064 "Process synchronization REQUEST for all entries before NEXT.
5066 REQUEST is a vector, built by `org-element--cache-submit-request'.
5068 NEXT is a cache key, as returned by `org-element--cache-key'.
5070 When non-nil, THRESHOLD is a buffer position. Synchronization
5071 stops as soon as a shifted element begins after it.
5073 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5074 after this time or when Emacs exits idle state.
5076 When non-nil, FUTURE-CHANGE is a buffer position where changes
5077 not registered yet in the cache are going to happen. See
5078 `org-element--cache-submit-request' for more information.
5080 Throw `interrupt' if the process stops before completing the
5083 (when (= (aref request
6) 0)
5086 ;; Delete all elements starting after BEG, but not after buffer
5087 ;; position END or past element with key NEXT.
5089 ;; At each iteration, we start again at tree root since
5090 ;; a deletion modifies structure of the balanced tree.
5092 (let ((beg (aref request
0))
5093 (end (aref request
2))
5094 (outreach (aref request
4)))
5096 (when (org-element--cache-interrupt-p time-limit
)
5097 (throw 'interrupt nil
))
5098 ;; Find first element in cache with key BEG or after it.
5099 (let ((node (org-element--cache-root)) data data-key
)
5101 (let* ((element (avl-tree--node-data node
))
5102 (key (org-element--cache-key element
)))
5104 ((org-element--cache-key-less-p key beg
)
5105 (setq node
(avl-tree--node-right node
)))
5106 ((org-element--cache-key-less-p beg key
)
5109 node
(avl-tree--node-left node
)))
5110 (t (setq data element
5114 (let ((pos (org-element-property :begin data
)))
5115 (if (if (or (not next
)
5116 (org-element--cache-key-less-p data-key next
))
5119 (while (and up
(not (eq up outreach
)))
5120 (setq up
(org-element-property :parent up
)))
5122 (org-element--cache-remove data
)
5123 (aset request
0 data-key
)
5124 (aset request
1 pos
)
5126 (throw 'end-phase nil
)))
5127 ;; No element starting after modifications left in
5128 ;; cache: further processing is futile.
5129 (throw 'quit t
)))))))
5130 (when (= (aref request
6) 1)
5133 ;; Phase 0 left a hole in the cache. Some elements after it
5134 ;; could have parents within. For example, in the following
5144 ;; if we remove a blank line between "item" and "Paragraph1",
5145 ;; everything down to "Paragraph2" is removed from cache. But
5146 ;; the paragraph now belongs to the list, and its `:parent'
5147 ;; property no longer is accurate.
5149 ;; Therefore we need to parse again elements in the hole, or at
5150 ;; least in its last section, so that we can re-parent
5151 ;; subsequent elements, during phase 2.
5153 ;; Note that we only need to get the parent from the first
5154 ;; element in cache after the hole.
5156 ;; When next key is lesser or equal to the current one, delegate
5157 ;; phase 1 processing to next request in order to preserve key
5158 ;; order among requests.
5159 (let ((key (aref request
0)))
5160 (when (and next
(not (org-element--cache-key-less-p key next
)))
5161 (let ((next-request (nth 1 org-element--cache-sync-requests
)))
5162 (aset next-request
0 key
)
5163 (aset next-request
1 (aref request
1))
5164 (aset next-request
6 1))
5166 ;; Next element will start at its beginning position plus
5167 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5168 ;; contains the real beginning position of the first element to
5169 ;; shift and re-parent.
5170 (let ((limit (+ (aref request
1) (aref request
3))))
5171 (cond ((and threshold
(> limit threshold
)) (throw 'interrupt nil
))
5172 ((and future-change
(>= limit future-change
))
5173 ;; Changes are going to happen around this element and
5174 ;; they will trigger another phase 1 request. Skip the
5178 (let ((parent (org-element--parse-to limit t time-limit
)))
5179 (aset request
5 parent
)
5180 (aset request
6 2))))))
5183 ;; Shift all elements starting from key START, but before NEXT, by
5184 ;; OFFSET, and re-parent them when appropriate.
5186 ;; Elements are modified by side-effect so the tree structure
5189 ;; Once THRESHOLD, if any, is reached, or once there is an input
5190 ;; pending, exit. Before leaving, the current synchronization
5191 ;; request is updated.
5192 (let ((start (aref request
0))
5193 (offset (aref request
3))
5194 (parent (aref request
5))
5195 (node (org-element--cache-root))
5199 ;; No re-parenting nor shifting planned: request is over.
5200 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5202 (let* ((data (avl-tree--node-data node
))
5203 (key (org-element--cache-key data
)))
5204 (if (and leftp
(avl-tree--node-left node
)
5205 (not (org-element--cache-key-less-p key start
)))
5206 (progn (push node stack
)
5207 (setq node
(avl-tree--node-left node
)))
5208 (unless (org-element--cache-key-less-p key start
)
5209 ;; We reached NEXT. Request is complete.
5210 (when (equal key next
) (throw 'quit t
))
5211 ;; Handle interruption request. Update current request.
5212 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5213 (aset request
0 key
)
5214 (aset request
5 parent
)
5215 (throw 'interrupt nil
))
5217 (unless (zerop offset
)
5218 (org-element--cache-shift-positions data offset
)
5219 ;; Shift associated objects data, if any.
5220 (dolist (object-data (gethash data org-element--cache-objects
))
5221 (dolist (object (cddr object-data
))
5222 (org-element--cache-shift-positions object offset
))))
5223 (let ((begin (org-element-property :begin data
)))
5224 ;; Update PARENT and re-parent DATA, only when
5225 ;; necessary. Propagate new structures for lists.
5227 (<= (org-element-property :end parent
) begin
))
5228 (setq parent
(org-element-property :parent parent
)))
5229 (cond ((and (not parent
) (zerop offset
)) (throw 'quit nil
))
5231 (let ((p (org-element-property :parent data
)))
5233 (< (org-element-property :begin p
)
5234 (org-element-property :begin parent
)))))
5235 (org-element-put-property data
:parent parent
)
5236 (let ((s (org-element-property :structure parent
)))
5237 (when (and s
(org-element-property :structure data
))
5238 (org-element-put-property data
:structure s
)))))
5239 ;; Cache is up-to-date past THRESHOLD. Request
5241 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5242 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5243 (avl-tree--node-right node
)
5245 ;; We reached end of tree: synchronization complete.
5248 (defun org-element--parse-to (pos &optional syncp time-limit
)
5249 "Parse elements in current section, down to POS.
5251 Start parsing from the closest between the last known element in
5252 cache or headline above. Return the smallest element containing
5255 When optional argument SYNCP is non-nil, return the parent of the
5256 element containing POS instead. In that case, it is also
5257 possible to provide TIME-LIMIT, which is a time value specifying
5258 when the parsing should stop. The function throws `interrupt' if
5259 the process stopped before finding the expected result."
5261 (org-with-wide-buffer
5263 (let* ((cached (and (org-element--cache-active-p)
5264 (org-element--cache-find pos nil
)))
5265 (begin (org-element-property :begin cached
))
5268 ;; Nothing in cache before point: start parsing from first
5269 ;; element following headline above, or first element in
5272 (when (org-with-limited-levels (outline-previous-heading))
5274 (skip-chars-forward " \r\t\n")
5275 (beginning-of-line))
5276 ;; Cache returned exact match: return it.
5278 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5279 ;; There's a headline between cached value and POS: cached
5280 ;; value is invalid. Start parsing from first element
5281 ;; following the headline.
5282 ((re-search-backward
5283 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5285 (skip-chars-forward " \r\t\n")
5286 (beginning-of-line))
5287 ;; Check if CACHED or any of its ancestors contain point.
5289 ;; If there is such an element, we inspect it in order to know
5290 ;; if we return it or if we need to parse its contents.
5291 ;; Otherwise, we just start parsing from current location,
5292 ;; which is right after the top-most element containing
5295 ;; As a special case, if POS is at the end of the buffer, we
5296 ;; want to return the innermost element ending there.
5298 ;; Also, if we find an ancestor and discover that we need to
5299 ;; parse its contents, make sure we don't start from
5300 ;; `:contents-begin', as we would otherwise go past CACHED
5301 ;; again. Instead, in that situation, we will resume parsing
5302 ;; from NEXT, which is located after CACHED or its higher
5303 ;; ancestor not containing point.
5306 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5307 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5308 (while (let ((end (org-element-property :end up
)))
5311 (setq up
(org-element-property :parent up
)))))
5313 ((eobp) (setq element up
))
5314 (t (setq element up next
(point)))))))
5315 ;; Parse successively each element until we reach POS.
5316 (let ((end (or (org-element-property :end element
)
5318 (org-with-limited-levels (outline-next-heading))
5324 (cond ((= (point) pos
) (throw 'exit parent
))
5325 ((org-element--cache-interrupt-p time-limit
)
5326 (throw 'interrupt nil
))))
5328 (setq element
(org-element--current-element
5329 end
'element special-flag
5330 (org-element-property :structure parent
)))
5331 (org-element-put-property element
:parent parent
)
5332 (org-element--cache-put element
))
5333 (let ((elem-end (org-element-property :end element
))
5334 (type (org-element-type element
)))
5336 ;; Skip any element ending before point. Also skip
5337 ;; element ending at point (unless it is also the end of
5338 ;; buffer) since we're sure that another element begins
5340 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5341 (goto-char elem-end
))
5342 ;; A non-greater element contains point: return it.
5343 ((not (memq type org-element-greater-elements
))
5344 (throw 'exit element
))
5345 ;; Otherwise, we have to decide if ELEMENT really
5346 ;; contains POS. In that case we start parsing from
5347 ;; contents' beginning.
5349 ;; If POS is at contents' beginning but it is also at
5350 ;; the beginning of the first item in a list or a table.
5351 ;; In that case, we need to create an anchor for that
5352 ;; list or table, so return it.
5354 ;; Also, if POS is at the end of the buffer, no element
5355 ;; can start after it, but more than one may end there.
5356 ;; Arbitrarily, we choose to return the innermost of
5358 ((let ((cbeg (org-element-property :contents-begin element
))
5359 (cend (org-element-property :contents-end element
)))
5364 (not (memq type
'(plain-list table
)))))
5366 (and (= cend pos
) (= (point-max) pos
)))))
5367 (goto-char (or next cbeg
))
5369 special-flag
(case type
5371 (property-drawer 'node-property
)
5375 ;; Otherwise, return ELEMENT as it is the smallest
5376 ;; element containing POS.
5377 (t (throw 'exit element
))))
5378 (setq element nil
)))))))
5381 ;;;; Staging Buffer Changes
5383 (defconst org-element--cache-sensitive-re
5385 org-outline-regexp-bol
"\\|"
5388 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5389 ;; LaTeX environments.
5390 "\\\\\\(?:begin{[A-Za-z0-9]+\\*?}\\|end{[A-Za-z0-9]+\\*?}[ \t]*$\\)" "\\|"
5394 "Regexp matching a sensitive line, structure wise.
5395 A sensitive line is a headline, inlinetask, block, drawer, or
5396 latex-environment boundary. When such a line is modified,
5397 structure changes in the document may propagate in the whole
5398 section, possibly making cache invalid.")
5400 (defvar org-element--cache-change-warning nil
5401 "Non-nil when a sensitive line is about to be changed.
5402 It is a symbol among nil, t and `headline'.")
5404 (defun org-element--cache-before-change (beg end
)
5405 "Request extension of area going to be modified if needed.
5406 BEG and END are the beginning and end of the range of changed
5407 text. See `before-change-functions' for more information."
5408 (when (org-element--cache-active-p)
5409 (org-with-wide-buffer
5412 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5413 (setq org-element--cache-change-warning
5415 (if (and (org-with-limited-levels (org-at-heading-p))
5416 (= (line-end-position) bottom
))
5418 (let ((case-fold-search t
))
5420 org-element--cache-sensitive-re bottom t
)))))))))
5422 (defun org-element--cache-after-change (beg end pre
)
5423 "Update buffer modifications for current buffer.
5424 BEG and END are the beginning and end of the range of changed
5425 text, and the length in bytes of the pre-change text replaced by
5426 that range. See `after-change-functions' for more information."
5427 (when (org-element--cache-active-p)
5428 (org-with-wide-buffer
5433 (bottom (save-excursion (goto-char end
) (line-end-position))))
5434 ;; Determine if modified area needs to be extended, according
5435 ;; to both previous and current state. We make a special
5436 ;; case for headline editing: if a headline is modified but
5437 ;; not removed, do not extend.
5438 (when (case org-element--cache-change-warning
5441 (not (and (org-with-limited-levels (org-at-heading-p))
5442 (= (line-end-position) bottom
))))
5444 (let ((case-fold-search t
))
5446 org-element--cache-sensitive-re bottom t
))))
5447 ;; Effectively extend modified area.
5448 (org-with-limited-levels
5449 (setq top
(progn (goto-char top
)
5450 (when (outline-previous-heading) (forward-line))
5452 (setq bottom
(progn (goto-char bottom
)
5453 (if (outline-next-heading) (1- (point))
5455 ;; Store synchronization request.
5456 (let ((offset (- end beg pre
)))
5457 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5458 ;; Activate a timer to process the request during idle time.
5459 (org-element--cache-set-timer (current-buffer))))
5461 (defun org-element--cache-for-removal (beg end offset
)
5462 "Return first element to remove from cache.
5464 BEG and END are buffer positions delimiting buffer modifications.
5465 OFFSET is the size of the changes.
5467 Returned element is usually the first element in cache containing
5468 any position between BEG and END. As an exception, greater
5469 elements around the changes that are robust to contents
5470 modifications are preserved and updated according to the
5472 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5473 (before (car elements
))
5474 (after (cdr elements
)))
5475 (if (not before
) after
5479 (if (and (memq (org-element-type up
)
5480 '(center-block drawer dynamic-block
5481 property-drawer quote-block
5483 (<= (org-element-property :contents-begin up
) beg
)
5484 (> (org-element-property :contents-end up
) end
))
5485 ;; UP is a robust greater element containing changes.
5486 ;; We only need to extend its ending boundaries.
5487 (org-element--cache-shift-positions
5488 up offset
'(:contents-end
:end
))
5490 (when robust-flag
(setq robust-flag nil
)))
5491 (setq up
(org-element-property :parent up
)))
5492 ;; We're at top level element containing ELEMENT: if it's
5493 ;; altered by buffer modifications, it is first element in
5494 ;; cache to be removed. Otherwise, that first element is the
5497 ;; As a special case, do not remove BEFORE if it is a robust
5498 ;; container for current changes.
5499 (if (or (< (org-element-property :end before
) beg
) robust-flag
) after
5502 (defun org-element--cache-submit-request (beg end offset
)
5503 "Submit a new cache synchronization request for current buffer.
5504 BEG and END are buffer positions delimiting the minimal area
5505 where cache data should be removed. OFFSET is the size of the
5506 change, as an integer."
5507 (let ((next (car org-element--cache-sync-requests
))
5508 delete-to delete-from
)
5510 (zerop (aref next
6))
5511 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5512 (<= (setq delete-from
(aref next
1)) end
))
5513 ;; Current changes can be merged with first sync request: we
5514 ;; can save a partial cache synchronization.
5516 (incf (aref next
3) offset
)
5517 ;; If last change happened within area to be removed, extend
5518 ;; boundaries of robust parents, if any. Otherwise, find
5519 ;; first element to remove and update request accordingly.
5520 (if (> beg delete-from
)
5521 (let ((up (aref next
5)))
5523 (org-element--cache-shift-positions
5524 up offset
'(:contents-end
:end
))
5525 (setq up
(org-element-property :parent up
))))
5526 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5528 (aset next
0 (org-element--cache-key first
))
5529 (aset next
1 (org-element-property :begin first
))
5530 (aset next
5 (org-element-property :parent first
))))))
5531 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5532 ;; if any, is no longer a 0-phase request, thus ensuring that
5533 ;; phases are properly ordered. We need to provide OFFSET as
5534 ;; optional parameter since current modifications are not known
5535 ;; yet to the otherwise correct part of the cache (i.e, before
5536 ;; the first request).
5537 (when next
(org-element--cache-sync (current-buffer) end beg
))
5538 (let ((first (org-element--cache-for-removal beg end offset
)))
5540 (push (let ((beg (org-element-property :begin first
))
5541 (key (org-element--cache-key first
)))
5543 ;; When changes happen before the first known
5544 ;; element, re-parent and shift the rest of the
5546 ((> beg end
) (vector key beg nil offset nil nil
1))
5547 ;; Otherwise, we find the first non robust
5548 ;; element containing END. All elements between
5549 ;; FIRST and this one are to be removed.
5551 ;; Among them, some could be located outside the
5552 ;; synchronized part of the cache, in which case
5553 ;; comparing buffer positions to find them is
5554 ;; useless. Instead, we store the element
5555 ;; containing them in the request itself. All
5556 ;; its children will be removed.
5557 ((let ((first-end (org-element-property :end first
)))
5558 (and (> first-end end
)
5559 (vector key beg first-end offset first
5560 (org-element-property :parent first
) 0))))
5562 (let* ((element (org-element--cache-find end
))
5563 (end (org-element-property :end element
))
5565 (while (and (setq up
(org-element-property :parent up
))
5566 (>= (org-element-property :begin up
) beg
))
5567 (setq end
(org-element-property :end up
)
5569 (vector key beg end offset element
5570 (org-element-property :parent first
) 0)))))
5571 org-element--cache-sync-requests
)
5572 ;; No element to remove. No need to re-parent either.
5573 ;; Simply shift additional elements, if any, by OFFSET.
5574 (when org-element--cache-sync-requests
5575 (incf (aref (car org-element--cache-sync-requests
) 3) offset
)))))))
5578 ;;;; Public Functions
5581 (defun org-element-cache-reset (&optional all
)
5582 "Reset cache in current buffer.
5583 When optional argument ALL is non-nil, reset cache in all Org
5586 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5587 (with-current-buffer buffer
5588 (when (org-element--cache-active-p)
5589 (org-set-local 'org-element--cache
5590 (avl-tree-create #'org-element--cache-compare
))
5591 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5592 (org-set-local 'org-element--cache-sync-keys
5593 (make-hash-table :weakness
'key
:test
#'eq
))
5594 (org-set-local 'org-element--cache-change-warning nil
)
5595 (org-set-local 'org-element--cache-sync-requests nil
)
5596 (org-set-local 'org-element--cache-sync-timer nil
)
5597 (add-hook 'before-change-functions
5598 #'org-element--cache-before-change nil t
)
5599 (add-hook 'after-change-functions
5600 #'org-element--cache-after-change nil t
)))))
5603 (defun org-element-cache-refresh (pos)
5604 "Refresh cache at position POS."
5605 (when (org-element--cache-active-p)
5606 (org-element--cache-sync (current-buffer) pos
)
5607 (org-element--cache-submit-request pos pos
0)
5608 (org-element--cache-set-timer (current-buffer))))
5614 ;; The first move is to implement a way to obtain the smallest element
5615 ;; containing point. This is the job of `org-element-at-point'. It
5616 ;; basically jumps back to the beginning of section containing point
5617 ;; and proceed, one element after the other, with
5618 ;; `org-element--current-element' until the container is found. Note:
5619 ;; When using `org-element-at-point', secondary values are never
5620 ;; parsed since the function focuses on elements, not on objects.
5622 ;; At a deeper level, `org-element-context' lists all elements and
5623 ;; objects containing point.
5625 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5626 ;; internally by navigation and manipulation tools.
5630 (defun org-element-at-point ()
5631 "Determine closest element around point.
5633 Return value is a list like (TYPE PROPS) where TYPE is the type
5634 of the element and PROPS a plist of properties associated to the
5637 Possible types are defined in `org-element-all-elements'.
5638 Properties depend on element or object type, but always include
5639 `:begin', `:end', `:parent' and `:post-blank' properties.
5641 As a special case, if point is at the very beginning of the first
5642 item in a list or sub-list, returned element will be that list
5643 instead of the item. Likewise, if point is at the beginning of
5644 the first row of a table, returned element will be the table
5645 instead of the first row.
5647 When point is at the end of the buffer, return the innermost
5648 element ending there."
5649 (org-with-wide-buffer
5650 (let ((origin (point)))
5652 (skip-chars-backward " \r\t\n")
5654 ;; Within blank lines at the beginning of buffer, return nil.
5656 ;; Within blank lines right after a headline, return that
5658 ((org-with-limited-levels (org-at-heading-p))
5660 (org-element-headline-parser (point-max) t
))
5661 ;; Otherwise parse until we find element containing ORIGIN.
5663 (when (org-element--cache-active-p)
5664 (if (not org-element--cache
) (org-element-cache-reset)
5665 (org-element--cache-sync (current-buffer) origin
)))
5666 (org-element--parse-to origin
))))))
5669 (defun org-element-context (&optional element
)
5670 "Return smallest element or object around point.
5672 Return value is a list like (TYPE PROPS) where TYPE is the type
5673 of the element or object and PROPS a plist of properties
5676 Possible types are defined in `org-element-all-elements' and
5677 `org-element-all-objects'. Properties depend on element or
5678 object type, but always include `:begin', `:end', `:parent' and
5681 As a special case, if point is right after an object and not at
5682 the beginning of any other object, return that object.
5684 Optional argument ELEMENT, when non-nil, is the closest element
5685 containing point, as returned by `org-element-at-point'.
5686 Providing it allows for quicker computation."
5687 (catch 'objects-forbidden
5688 (org-with-wide-buffer
5689 (let* ((pos (point))
5690 (element (or element
(org-element-at-point)))
5691 (type (org-element-type element
)))
5692 ;; If point is inside an element containing objects or
5693 ;; a secondary string, narrow buffer to the container and
5694 ;; proceed with parsing. Otherwise, return ELEMENT.
5696 ;; At a parsed affiliated keyword, check if we're inside main
5698 ((let ((post (org-element-property :post-affiliated element
)))
5699 (and post
(< pos post
)))
5701 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5703 ((not (member-ignore-case (match-string 1)
5704 org-element-parsed-keywords
))
5705 (throw 'objects-forbidden element
))
5706 ((< (match-end 0) pos
)
5707 (narrow-to-region (match-end 0) (line-end-position)))
5708 ((and (match-beginning 2)
5709 (>= pos
(match-beginning 2))
5710 (< pos
(match-end 2)))
5711 (narrow-to-region (match-beginning 2) (match-end 2)))
5712 (t (throw 'objects-forbidden element
)))
5713 ;; Also change type to retrieve correct restrictions.
5714 (setq type
'keyword
))
5715 ;; At an item, objects can only be located within tag, if any.
5717 (let ((tag (org-element-property :tag element
)))
5718 (if (not tag
) (throw 'objects-forbidden element
)
5720 (search-forward tag
(line-end-position))
5721 (goto-char (match-beginning 0))
5722 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5723 (narrow-to-region (point) (match-end 0))
5724 (throw 'objects-forbidden element
)))))
5725 ;; At an headline or inlinetask, objects are in title.
5726 ((memq type
'(headline inlinetask
))
5727 (goto-char (org-element-property :begin element
))
5728 (skip-chars-forward "*")
5729 (if (and (> pos
(point)) (< pos
(line-end-position)))
5730 (narrow-to-region (point) (line-end-position))
5731 (throw 'objects-forbidden element
)))
5732 ;; At a paragraph, a table-row or a verse block, objects are
5733 ;; located within their contents.
5734 ((memq type
'(paragraph table-row verse-block
))
5735 (let ((cbeg (org-element-property :contents-begin element
))
5736 (cend (org-element-property :contents-end element
)))
5737 ;; CBEG is nil for table rules.
5738 (if (and cbeg cend
(>= pos cbeg
)
5739 (or (< pos cend
) (and (= pos cend
) (eobp))))
5740 (narrow-to-region cbeg cend
)
5741 (throw 'objects-forbidden element
))))
5742 ;; At a parsed keyword, objects are located within value.
5744 (if (not (member (org-element-property :key element
)
5745 org-element-document-properties
))
5746 (throw 'objects-forbidden element
)
5748 (search-forward ":")
5749 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5750 (narrow-to-region (point) (line-end-position))
5751 (throw 'objects-forbidden element
))))
5752 ;; At a planning line, if point is at a timestamp, return it,
5753 ;; otherwise, return element.
5754 ((eq type
'planning
)
5755 (dolist (p '(:closed
:deadline
:scheduled
))
5756 (let ((timestamp (org-element-property p element
)))
5757 (when (and timestamp
5758 (<= (org-element-property :begin timestamp
) pos
)
5759 (> (org-element-property :end timestamp
) pos
))
5760 (throw 'objects-forbidden timestamp
))))
5761 ;; All other locations cannot contain objects: bail out.
5762 (throw 'objects-forbidden element
))
5763 (t (throw 'objects-forbidden element
)))
5764 (goto-char (point-min))
5765 (let ((restriction (org-element-restriction type
))
5767 (cache (cond ((not (org-element--cache-active-p)) nil
)
5768 (org-element--cache-objects
5769 (gethash element org-element--cache-objects
))
5770 (t (org-element-cache-reset) nil
)))
5771 next object-data last
)
5775 ;; When entering PARENT for the first time, get list
5776 ;; of objects within known so far. Store it in
5779 (let ((data (assq parent cache
)))
5780 (if data
(setq object-data data
)
5781 (push (setq object-data
(list parent nil
)) cache
))))
5782 ;; Find NEXT object for analysis.
5784 ;; If NEXT is non-nil, we already exhausted the
5785 ;; cache so we can parse buffer to find the object
5787 (if next
(setq next
(org-element--object-lex restriction
))
5788 ;; Otherwise, check if cache can help us.
5789 (let ((objects (cddr object-data
))
5790 (completep (nth 1 object-data
)))
5792 ((and (not objects
) completep
) (throw 'exit parent
))
5794 (setq next
(org-element--object-lex restriction
)))
5797 (org-element-property :end
(car objects
))))
5798 (if (>= cache-limit pos
)
5799 ;; Cache contains the information needed.
5800 (dolist (object objects
(throw 'exit parent
))
5801 (when (<= (org-element-property :begin object
)
5803 (if (>= (org-element-property :end object
)
5805 (throw 'found
(setq next object
))
5806 (throw 'exit parent
))))
5807 (goto-char cache-limit
)
5809 (org-element--object-lex restriction
))))))))
5810 ;; If we have a new object to analyze, store it in
5811 ;; cache. Otherwise record that there is nothing
5812 ;; more to parse in this element at this depth.
5814 (progn (org-element-put-property next
:parent parent
)
5815 (push next
(cddr object-data
)))
5816 (setcar (cdr object-data
) t
)))
5817 ;; Process NEXT, if any, in order to know if we need
5818 ;; to skip it, return it or move into it.
5819 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5820 (throw 'exit
(or last parent
))
5821 (let ((end (org-element-property :end next
))
5822 (cbeg (org-element-property :contents-begin next
))
5823 (cend (org-element-property :contents-end next
)))
5825 ;; Skip objects ending before point. Also skip
5826 ;; objects ending at point unless it is also the
5827 ;; end of buffer, since we want to return the
5828 ;; innermost object.
5829 ((and (<= end pos
) (/= (point-max) end
))
5831 ;; For convenience, when object ends at POS,
5832 ;; without any space, store it in LAST, as we
5833 ;; will return it if no object starts here.
5834 (when (and (= end pos
)
5835 (not (memq (char-before) '(?\s ?
\t))))
5837 ;; If POS is within a container object, move
5838 ;; into that object.
5842 ;; At contents' end, if there is no
5843 ;; space before point, also move into
5844 ;; object, for consistency with
5845 ;; convenience feature above.
5847 (or (= (point-max) pos
)
5848 (not (memq (char-before pos
)
5851 (narrow-to-region (point) cend
)
5853 restriction
(org-element-restriction next
)
5856 ;; Otherwise, return NEXT.
5857 (t (throw 'exit next
)))))))
5858 ;; Store results in cache, if applicable.
5859 (org-element--cache-put element cache
)))))))
5861 (defun org-element-nested-p (elem-A elem-B
)
5862 "Non-nil when elements ELEM-A and ELEM-B are nested."
5863 (let ((beg-A (org-element-property :begin elem-A
))
5864 (beg-B (org-element-property :begin elem-B
))
5865 (end-A (org-element-property :end elem-A
))
5866 (end-B (org-element-property :end elem-B
)))
5867 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5868 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5870 (defun org-element-swap-A-B (elem-A elem-B
)
5871 "Swap elements ELEM-A and ELEM-B.
5872 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5874 (goto-char (org-element-property :begin elem-A
))
5875 ;; There are two special cases when an element doesn't start at bol:
5876 ;; the first paragraph in an item or in a footnote definition.
5877 (let ((specialp (not (bolp))))
5878 ;; Only a paragraph without any affiliated keyword can be moved at
5879 ;; ELEM-A position in such a situation. Note that the case of
5880 ;; a footnote definition is impossible: it cannot contain two
5881 ;; paragraphs in a row because it cannot contain a blank line.
5883 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5884 (/= (org-element-property :begin elem-B
)
5885 (org-element-property :contents-begin elem-B
))))
5886 (error "Cannot swap elements"))
5887 ;; In a special situation, ELEM-A will have no indentation. We'll
5888 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5889 (let* ((ind-B (when specialp
5890 (goto-char (org-element-property :begin elem-B
))
5891 (org-get-indentation)))
5892 (beg-A (org-element-property :begin elem-A
))
5893 (end-A (save-excursion
5894 (goto-char (org-element-property :end elem-A
))
5895 (skip-chars-backward " \r\t\n")
5897 (beg-B (org-element-property :begin elem-B
))
5898 (end-B (save-excursion
5899 (goto-char (org-element-property :end elem-B
))
5900 (skip-chars-backward " \r\t\n")
5902 ;; Store overlays responsible for visibility status. We
5903 ;; also need to store their boundaries as they will be
5904 ;; removed from buffer.
5907 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5908 (overlays-in beg-A end-A
))
5909 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5910 (overlays-in beg-B end-B
))))
5912 (body-A (buffer-substring beg-A end-A
))
5913 (body-B (delete-and-extract-region beg-B end-B
)))
5916 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5917 (org-indent-to-column ind-B
))
5919 ;; Restore ex ELEM-A overlays.
5920 (let ((offset (- beg-B beg-A
)))
5923 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5926 (delete-region beg-A end-A
)
5928 ;; Restore ex ELEM-B overlays.
5931 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5933 (goto-char (org-element-property :end elem-B
)))))
5935 (defun org-element-remove-indentation (s &optional n
)
5936 "Remove maximum common indentation in string S and return it.
5937 When optional argument N is a positive integer, remove exactly
5938 that much characters from indentation, if possible, or return
5939 S as-is otherwise. Unlike to `org-remove-indentation', this
5940 function doesn't call `untabify' on S."
5944 (goto-char (point-min))
5945 ;; Find maximum common indentation, if not specified.
5947 (let ((min-ind (point-max)))
5949 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5950 (let ((ind (1- (current-column))))
5951 (if (zerop ind
) (throw 'exit s
)
5952 (setq min-ind
(min min-ind ind
))))))
5955 ;; Remove exactly N indentation, but give up if not possible.
5957 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5958 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5959 ((< ind n
) (throw 'exit s
))
5960 (t (org-indent-line-to (- ind n
))))
5966 (provide 'org-element
)
5969 ;; generated-autoload-file: "org-loaddefs.el"
5972 ;;; org-element.el ends here