1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; Elements are related to the structure of the document. Indeed, all
29 ;; elements are a cover for the document: each position within belongs
30 ;; to at least one element.
32 ;; An element always starts and ends at the beginning of a line. With
33 ;; a few exceptions (`clock', `headline', `inlinetask', `item',
34 ;; `planning', `node-property', `section' and `table-row' types), it
35 ;; can also accept a fixed set of keywords as attributes. Those are
36 ;; called "affiliated keywords" to distinguish them from other
37 ;; keywords, which are full-fledged elements. Almost all affiliated
38 ;; keywords are referenced in `org-element-affiliated-keywords'; the
39 ;; others are export attributes and start with "ATTR_" prefix.
41 ;; Element containing other elements (and only elements) are called
42 ;; greater elements. Concerned types are: `center-block', `drawer',
43 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
44 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
45 ;; and `special-block'.
47 ;; Other element types are: `babel-call', `clock', `comment',
48 ;; `comment-block', `diary-sexp', `example-block', `export-block',
49 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
50 ;; `node-property', `paragraph', `planning', `src-block', `table',
51 ;; `table-row' and `verse-block'. Among them, `paragraph' and
52 ;; `verse-block' types can contain Org objects and plain text.
54 ;; Objects are related to document's contents. Some of them are
55 ;; recursive. Associated types are of the following: `bold', `code',
56 ;; `entity', `export-snippet', `footnote-reference',
57 ;; `inline-babel-call', `inline-src-block', `italic',
58 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
59 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
60 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
62 ;; Some elements also have special properties whose value can hold
63 ;; objects themselves (e.g. an item tag or a headline name). Such
64 ;; values are called "secondary strings". Any object belongs to
65 ;; either an element or a secondary string.
67 ;; Notwithstanding affiliated keywords, each greater element, element
68 ;; and object has a fixed set of properties attached to it. Among
69 ;; them, four are shared by all types: `:begin' and `:end', which
70 ;; refer to the beginning and ending buffer positions of the
71 ;; considered element or object, `:post-blank', which holds the number
72 ;; of blank lines, or white spaces, at its end and `:parent' which
73 ;; refers to the element or object containing it. Greater elements,
74 ;; elements and objects containing objects will also have
75 ;; `:contents-begin' and `:contents-end' properties to delimit
76 ;; contents. Eventually, greater elements and elements accepting
77 ;; affiliated keywords will have a `:post-affiliated' property,
78 ;; referring to the buffer position after all such keywords.
80 ;; At the lowest level, a `:parent' property is also attached to any
81 ;; string, as a text property.
83 ;; Lisp-wise, an element or an object can be represented as a list.
84 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
85 ;; TYPE is a symbol describing the Org element or object.
86 ;; PROPERTIES is the property list attached to it. See docstring of
87 ;; appropriate parsing function to get an exhaustive
89 ;; CONTENTS is a list of elements, objects or raw strings contained
90 ;; in the current element or object, when applicable.
92 ;; An Org buffer is a nested list of such elements and objects, whose
93 ;; type is `org-data' and properties is nil.
95 ;; The first part of this file defines Org syntax, while the second
96 ;; one provide accessors and setters functions.
98 ;; The next part implements a parser and an interpreter for each
99 ;; element and object type in Org syntax.
101 ;; The following part creates a fully recursive buffer parser. It
102 ;; also provides a tool to map a function to elements or objects
103 ;; matching some criteria in the parse tree. Functions of interest
104 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
105 ;; extent, `org-element-parse-secondary-string'.
107 ;; The penultimate part is the cradle of an interpreter for the
108 ;; obtained parse tree: `org-element-interpret-data'.
110 ;; The library ends by furnishing `org-element-at-point' function, and
111 ;; a way to give information about document structure around point
112 ;; with `org-element-context'. A cache mechanism is also provided for
118 (eval-when-compile (require 'cl
))
124 ;;; Definitions And Rules
126 ;; Define elements, greater elements and specify recursive objects,
127 ;; along with the affiliated keywords recognized. Also set up
128 ;; restrictions on recursive objects combinations.
130 ;; These variables really act as a control center for the parsing
133 (defconst org-element-paragraph-separate
135 ;; Headlines, inlinetasks.
136 org-outline-regexp
"\\|"
137 ;; Footnote definitions.
138 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
144 ;; Tables (any type).
145 "\\(?:|\\|\\+-[-+]\\)" "\\|"
146 ;; Blocks (any type), Babel calls and keywords. Note: this
147 ;; is only an indication and need some thorough check.
148 "#\\(?:[+ ]\\|$\\)" "\\|"
149 ;; Drawers (any type) and fixed-width areas. This is also
150 ;; only an indication.
153 "-\\{5,\\}[ \t]*$" "\\|"
154 ;; LaTeX environments.
155 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
156 ;; Planning and Clock lines.
157 (regexp-opt (list org-scheduled-string
163 (let ((term (case org-plain-list-ordered-item-terminator
164 (?\
) ")") (?.
"\\.") (otherwise "[.)]")))
165 (alpha (and org-list-allow-alphabetical
"\\|[A-Za-z]")))
166 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha
"\\)" term
"\\)"
167 "\\(?:[ \t]\\|$\\)"))
169 "Regexp to separate paragraphs in an Org buffer.
170 In the case of lines starting with \"#\" and \":\", this regexp
171 is not sufficient to know if point is at a paragraph ending. See
172 `org-element-paragraph-parser' for more information.")
174 (defconst org-element-all-elements
175 '(babel-call center-block clock comment comment-block diary-sexp drawer
176 dynamic-block example-block export-block fixed-width
177 footnote-definition headline horizontal-rule inlinetask item
178 keyword latex-environment node-property paragraph plain-list
179 planning property-drawer quote-block section
180 special-block src-block table table-row verse-block
)
181 "Complete list of element types.")
183 (defconst org-element-greater-elements
184 '(center-block drawer dynamic-block footnote-definition headline inlinetask
185 item plain-list property-drawer quote-block section
187 "List of recursive element types aka Greater Elements.")
189 (defconst org-element-all-objects
190 '(bold code entity export-snippet footnote-reference inline-babel-call
191 inline-src-block italic line-break latex-fragment link macro
192 radio-target statistics-cookie strike-through subscript superscript
193 table-cell target timestamp underline verbatim
)
194 "Complete list of object types.")
196 (defconst org-element-recursive-objects
197 '(bold italic link subscript radio-target strike-through superscript
198 table-cell underline
)
199 "List of recursive object types.")
201 (defvar org-element-block-name-alist
202 '(("CENTER" . org-element-center-block-parser
)
203 ("COMMENT" . org-element-comment-block-parser
)
204 ("EXAMPLE" . org-element-example-block-parser
)
205 ("QUOTE" . org-element-quote-block-parser
)
206 ("SRC" . org-element-src-block-parser
)
207 ("VERSE" . org-element-verse-block-parser
))
208 "Alist between block names and the associated parsing function.
209 Names must be uppercase. Any block whose name has no association
210 is parsed with `org-element-special-block-parser'.")
212 (defconst org-element-link-type-is-file
213 '("file" "file+emacs" "file+sys" "docview")
214 "List of link types equivalent to \"file\".
215 Only these types can accept search options and an explicit
216 application to open them.")
218 (defconst org-element-affiliated-keywords
219 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
220 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
221 "List of affiliated keywords as strings.
222 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
223 are affiliated keywords and need not to be in this list.")
225 (defconst org-element-keyword-translation-alist
226 '(("DATA" .
"NAME") ("LABEL" .
"NAME") ("RESNAME" .
"NAME")
227 ("SOURCE" .
"NAME") ("SRCNAME" .
"NAME") ("TBLNAME" .
"NAME")
228 ("RESULT" .
"RESULTS") ("HEADERS" .
"HEADER"))
229 "Alist of usual translations for keywords.
230 The key is the old name and the value the new one. The property
231 holding their value will be named after the translated name.")
233 (defconst org-element-multiple-keywords
'("CAPTION" "HEADER")
234 "List of affiliated keywords that can occur more than once in an element.
236 Their value will be consed into a list of strings, which will be
237 returned as the value of the property.
239 This list is checked after translations have been applied. See
240 `org-element-keyword-translation-alist'.
242 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
243 allow multiple occurrences and need not to be in this list.")
245 (defconst org-element-parsed-keywords
'("CAPTION")
246 "List of affiliated keywords whose value can be parsed.
248 Their value will be stored as a secondary string: a list of
251 This list is checked after translations have been applied. See
252 `org-element-keyword-translation-alist'.")
254 (defconst org-element-dual-keywords
'("CAPTION" "RESULTS")
255 "List of affiliated keywords which can have a secondary value.
257 In Org syntax, they can be written with optional square brackets
258 before the colons. For example, RESULTS keyword can be
259 associated to a hash value with the following:
261 #+RESULTS[hash-string]: some-source
263 This list is checked after translations have been applied. See
264 `org-element-keyword-translation-alist'.")
266 (defconst org-element-document-properties
'("AUTHOR" "DATE" "TITLE")
267 "List of properties associated to the whole document.
268 Any keyword in this list will have its value parsed and stored as
269 a secondary string.")
271 (defconst org-element--affiliated-re
272 (format "[ \t]*#\\+\\(?:%s\\):\\(?: \\|$\\)"
274 ;; Dual affiliated keywords.
275 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
276 (regexp-opt org-element-dual-keywords
))
278 ;; Regular affiliated keywords.
279 (format "\\(?1:%s\\)"
283 (member keyword org-element-dual-keywords
))
284 org-element-affiliated-keywords
)))
286 ;; Export attributes.
287 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
288 "Regexp matching any affiliated keyword.
290 Keyword name is put in match group 1. Moreover, if keyword
291 belongs to `org-element-dual-keywords', put the dual value in
294 Don't modify it, set `org-element-affiliated-keywords' instead.")
296 (defconst org-element-object-restrictions
297 (let* ((standard-set (remq 'table-cell org-element-all-objects
))
298 (standard-set-no-line-break (remq 'line-break standard-set
)))
299 `((bold ,@standard-set
)
300 (footnote-reference ,@standard-set
)
301 (headline ,@standard-set-no-line-break
)
302 (inlinetask ,@standard-set-no-line-break
)
303 (italic ,@standard-set
)
304 (item ,@standard-set-no-line-break
)
305 (keyword ,@standard-set
)
306 ;; Ignore all links excepted plain links in a link description.
307 ;; Also ignore radio-targets and line breaks.
308 (link bold code entity export-snippet inline-babel-call inline-src-block
309 italic latex-fragment macro plain-link statistics-cookie
310 strike-through subscript superscript underline verbatim
)
311 (paragraph ,@standard-set
)
312 ;; Remove any variable object from radio target as it would
313 ;; prevent it from being properly recognized.
314 (radio-target bold code entity italic latex-fragment strike-through
315 subscript superscript underline superscript
)
316 (strike-through ,@standard-set
)
317 (subscript ,@standard-set
)
318 (superscript ,@standard-set
)
319 ;; Ignore inline babel call and inline src block as formulas are
320 ;; possible. Also ignore line breaks and statistics cookies.
321 (table-cell bold code entity export-snippet footnote-reference italic
322 latex-fragment link macro radio-target strike-through
323 subscript superscript target timestamp underline verbatim
)
324 (table-row table-cell
)
325 (underline ,@standard-set
)
326 (verse-block ,@standard-set
)))
327 "Alist of objects restrictions.
329 key is an element or object type containing objects and value is
330 a list of types that can be contained within an element or object
333 For example, in a `radio-target' object, one can only find
334 entities, latex-fragments, subscript, superscript and text
337 This alist also applies to secondary string. For example, an
338 `headline' type element doesn't directly contain objects, but
339 still has an entry since one of its properties (`:title') does.")
341 (defconst org-element-secondary-value-alist
342 '((headline .
:title
)
343 (inlinetask .
:title
)
345 (footnote-reference .
:inline-definition
))
346 "Alist between element types and location of secondary value.")
348 (defconst org-element-object-variables
'(org-link-abbrev-alist-local)
349 "List of buffer-local variables used when parsing objects.
350 These variables are copied to the temporary buffer created by
351 `org-export-secondary-string'.")
355 ;;; Accessors and Setters
357 ;; Provide four accessors: `org-element-type', `org-element-property'
358 ;; `org-element-contents' and `org-element-restriction'.
360 ;; Setter functions allow to modify elements by side effect. There is
361 ;; `org-element-put-property', `org-element-set-contents'. These
362 ;; low-level functions are useful to build a parse tree.
364 ;; `org-element-adopt-element', `org-element-set-element',
365 ;; `org-element-extract-element' and `org-element-insert-before' are
366 ;; high-level functions useful to modify a parse tree.
368 ;; `org-element-secondary-p' is a predicate used to know if a given
369 ;; object belongs to a secondary string.
371 (defsubst org-element-type
(element)
372 "Return type of ELEMENT.
374 The function returns the type of the element or object provided.
375 It can also return the following special value:
376 `plain-text' for a string
377 `org-data' for a complete document
378 nil in any other case."
380 ((not (consp element
)) (and (stringp element
) 'plain-text
))
381 ((symbolp (car element
)) (car element
))))
383 (defsubst org-element-property
(property element
)
384 "Extract the value from the PROPERTY of an ELEMENT."
385 (if (stringp element
) (get-text-property 0 property element
)
386 (plist-get (nth 1 element
) property
)))
388 (defsubst org-element-contents
(element)
389 "Extract contents from an ELEMENT."
390 (cond ((not (consp element
)) nil
)
391 ((symbolp (car element
)) (nthcdr 2 element
))
394 (defsubst org-element-restriction
(element)
395 "Return restriction associated to ELEMENT.
396 ELEMENT can be an element, an object or a symbol representing an
397 element or object type."
398 (cdr (assq (if (symbolp element
) element
(org-element-type element
))
399 org-element-object-restrictions
)))
401 (defsubst org-element-put-property
(element property value
)
402 "In ELEMENT set PROPERTY to VALUE.
403 Return modified element."
404 (if (stringp element
) (org-add-props element nil property value
)
405 (setcar (cdr element
) (plist-put (nth 1 element
) property value
))
408 (defsubst org-element-set-contents
(element &rest contents
)
409 "Set ELEMENT contents to CONTENTS.
410 Return modified element."
411 (cond ((not element
) (list contents
))
412 ((not (symbolp (car element
))) contents
)
413 ((cdr element
) (setcdr (cdr element
) contents
))
414 (t (nconc element contents
))))
416 (defun org-element-secondary-p (object)
417 "Non-nil when OBJECT belongs to a secondary string.
418 Return value is the property name, as a keyword, or nil."
419 (let* ((parent (org-element-property :parent object
))
420 (property (cdr (assq (org-element-type parent
)
421 org-element-secondary-value-alist
))))
423 (memq object
(org-element-property property parent
))
426 (defsubst org-element-adopt-elements
(parent &rest children
)
427 "Append elements to the contents of another element.
429 PARENT is an element or object. CHILDREN can be elements,
430 objects, or a strings.
432 The function takes care of setting `:parent' property for CHILD.
433 Return parent element."
434 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
435 ;; string: parent is the list itself.
436 (mapc (lambda (child)
437 (org-element-put-property child
:parent
(or parent children
)))
439 ;; Add CHILDREN at the end of PARENT contents.
441 (apply 'org-element-set-contents
443 (nconc (org-element-contents parent
) children
)))
444 ;; Return modified PARENT element.
445 (or parent children
))
447 (defun org-element-extract-element (element)
448 "Extract ELEMENT from parse tree.
449 Remove element from the parse tree by side-effect, and return it
450 with its `:parent' property stripped out."
451 (let ((parent (org-element-property :parent element
))
452 (secondary (org-element-secondary-p element
)))
454 (org-element-put-property
456 (delq element
(org-element-property secondary parent
)))
457 (apply #'org-element-set-contents
459 (delq element
(org-element-contents parent
))))
460 ;; Return ELEMENT with its :parent removed.
461 (org-element-put-property element
:parent nil
)))
463 (defun org-element-insert-before (element location
)
464 "Insert ELEMENT before LOCATION in parse tree.
465 LOCATION is an element, object or string within the parse tree.
466 Parse tree is modified by side effect."
467 (let* ((parent (org-element-property :parent location
))
468 (property (org-element-secondary-p location
))
469 (siblings (if property
(org-element-property property parent
)
470 (org-element-contents parent
)))
471 ;; Special case: LOCATION is the first element of an
472 ;; independent secondary string (e.g. :title property). Add
474 (specialp (and (not property
)
476 (eq (car parent
) location
))))
477 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
479 ((or (null siblings
) (eq (car siblings
) location
))
480 (push element siblings
))
481 ((null location
) (nconc siblings
(list element
)))
482 (t (let ((previous (cadr (memq location
(reverse siblings
)))))
484 (error "No location found to insert element")
485 (let ((next (memq previous siblings
)))
486 (setcdr next
(cons element
(cdr next
))))))))
487 ;; Store SIBLINGS at appropriate place in parse tree.
489 (specialp (setcdr parent
(copy-sequence parent
)) (setcar parent element
))
490 (property (org-element-put-property parent property siblings
))
491 (t (apply #'org-element-set-contents parent siblings
)))
492 ;; Set appropriate :parent property.
493 (org-element-put-property element
:parent parent
)))
495 (defun org-element-set-element (old new
)
496 "Replace element or object OLD with element or object NEW.
497 The function takes care of setting `:parent' property for NEW."
498 ;; Ensure OLD and NEW have the same parent.
499 (org-element-put-property new
:parent
(org-element-property :parent old
))
500 (if (or (memq (org-element-type old
) '(plain-text nil
))
501 (memq (org-element-type new
) '(plain-text nil
)))
502 ;; We cannot replace OLD with NEW since one of them is not an
503 ;; object or element. We take the long path.
504 (progn (org-element-insert-before new old
)
505 (org-element-extract-element old
))
506 ;; Since OLD is going to be changed into NEW by side-effect, first
507 ;; make sure that every element or object within NEW has OLD as
509 (dolist (blob (org-element-contents new
))
510 (org-element-put-property blob
:parent old
))
511 ;; Transfer contents.
512 (apply #'org-element-set-contents old
(org-element-contents new
))
513 ;; Overwrite OLD's properties with NEW's.
514 (setcar (cdr old
) (nth 1 new
))
516 (setcar old
(car new
))))
522 ;; For each greater element type, we define a parser and an
525 ;; A parser returns the element or object as the list described above.
526 ;; Most of them accepts no argument. Though, exceptions exist. Hence
527 ;; every element containing a secondary string (see
528 ;; `org-element-secondary-value-alist') will accept an optional
529 ;; argument to toggle parsing of that secondary string. Moreover,
530 ;; `item' parser requires current list's structure as its first
533 ;; An interpreter accepts two arguments: the list representation of
534 ;; the element or object, and its contents. The latter may be nil,
535 ;; depending on the element or object considered. It returns the
536 ;; appropriate Org syntax, as a string.
538 ;; Parsing functions must follow the naming convention:
539 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
540 ;; defined in `org-element-greater-elements'.
542 ;; Similarly, interpreting functions must follow the naming
543 ;; convention: org-element-TYPE-interpreter.
545 ;; With the exception of `headline' and `item' types, greater elements
546 ;; cannot contain other greater elements of their own type.
548 ;; Beside implementing a parser and an interpreter, adding a new
549 ;; greater element requires to tweak `org-element--current-element'.
550 ;; Moreover, the newly defined type must be added to both
551 ;; `org-element-all-elements' and `org-element-greater-elements'.
556 (defun org-element-center-block-parser (limit affiliated
)
557 "Parse a center block.
559 LIMIT bounds the search. AFFILIATED is a list of which CAR is
560 the buffer position at the beginning of the first affiliated
561 keyword and CDR is a plist of affiliated keywords along with
564 Return a list whose CAR is `center-block' and CDR is a plist
565 containing `:begin', `:end', `:contents-begin', `:contents-end',
566 `:post-blank' and `:post-affiliated' keywords.
568 Assume point is at the beginning of the block."
569 (let ((case-fold-search t
))
570 (if (not (save-excursion
571 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t
)))
572 ;; Incomplete block: parse it as a paragraph.
573 (org-element-paragraph-parser limit affiliated
)
574 (let ((block-end-line (match-beginning 0)))
575 (let* ((begin (car affiliated
))
576 (post-affiliated (point))
577 ;; Empty blocks have no contents.
578 (contents-begin (progn (forward-line)
579 (and (< (point) block-end-line
)
581 (contents-end (and contents-begin block-end-line
))
582 (pos-before-blank (progn (goto-char block-end-line
)
586 (skip-chars-forward " \r\t\n" limit
)
587 (if (eobp) (point) (line-beginning-position)))))
592 :contents-begin contents-begin
593 :contents-end contents-end
594 :post-blank
(count-lines pos-before-blank end
)
595 :post-affiliated post-affiliated
)
596 (cdr affiliated
))))))))
598 (defun org-element-center-block-interpreter (center-block contents
)
599 "Interpret CENTER-BLOCK element as Org syntax.
600 CONTENTS is the contents of the element."
601 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents
))
606 (defun org-element-drawer-parser (limit affiliated
)
609 LIMIT bounds the search. AFFILIATED is a list of which CAR is
610 the buffer position at the beginning of the first affiliated
611 keyword and CDR is a plist of affiliated keywords along with
614 Return a list whose CAR is `drawer' and CDR is a plist containing
615 `:drawer-name', `:begin', `:end', `:contents-begin',
616 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
618 Assume point is at beginning of drawer."
619 (let ((case-fold-search t
))
620 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
621 ;; Incomplete drawer: parse it as a paragraph.
622 (org-element-paragraph-parser limit affiliated
)
624 (let* ((drawer-end-line (match-beginning 0))
625 (name (progn (looking-at org-drawer-regexp
)
626 (org-match-string-no-properties 1)))
627 (begin (car affiliated
))
628 (post-affiliated (point))
629 ;; Empty drawers have no contents.
630 (contents-begin (progn (forward-line)
631 (and (< (point) drawer-end-line
)
633 (contents-end (and contents-begin drawer-end-line
))
634 (pos-before-blank (progn (goto-char drawer-end-line
)
637 (end (progn (skip-chars-forward " \r\t\n" limit
)
638 (if (eobp) (point) (line-beginning-position)))))
644 :contents-begin contents-begin
645 :contents-end contents-end
646 :post-blank
(count-lines pos-before-blank end
)
647 :post-affiliated post-affiliated
)
648 (cdr affiliated
))))))))
650 (defun org-element-drawer-interpreter (drawer contents
)
651 "Interpret DRAWER element as Org syntax.
652 CONTENTS is the contents of the element."
653 (format ":%s:\n%s:END:"
654 (org-element-property :drawer-name drawer
)
660 (defun org-element-dynamic-block-parser (limit affiliated
)
661 "Parse a dynamic block.
663 LIMIT bounds the search. AFFILIATED is a list of which CAR is
664 the buffer position at the beginning of the first affiliated
665 keyword and CDR is a plist of affiliated keywords along with
668 Return a list whose CAR is `dynamic-block' and CDR is a plist
669 containing `:block-name', `:begin', `:end', `:contents-begin',
670 `:contents-end', `:arguments', `:post-blank' and
671 `:post-affiliated' keywords.
673 Assume point is at beginning of dynamic block."
674 (let ((case-fold-search t
))
675 (if (not (save-excursion
676 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
677 ;; Incomplete block: parse it as a paragraph.
678 (org-element-paragraph-parser limit affiliated
)
679 (let ((block-end-line (match-beginning 0)))
681 (let* ((name (progn (looking-at org-dblock-start-re
)
682 (org-match-string-no-properties 1)))
683 (arguments (org-match-string-no-properties 3))
684 (begin (car affiliated
))
685 (post-affiliated (point))
686 ;; Empty blocks have no contents.
687 (contents-begin (progn (forward-line)
688 (and (< (point) block-end-line
)
690 (contents-end (and contents-begin block-end-line
))
691 (pos-before-blank (progn (goto-char block-end-line
)
694 (end (progn (skip-chars-forward " \r\t\n" limit
)
695 (if (eobp) (point) (line-beginning-position)))))
702 :contents-begin contents-begin
703 :contents-end contents-end
704 :post-blank
(count-lines pos-before-blank end
)
705 :post-affiliated post-affiliated
)
706 (cdr affiliated
)))))))))
708 (defun org-element-dynamic-block-interpreter (dynamic-block contents
)
709 "Interpret DYNAMIC-BLOCK element as Org syntax.
710 CONTENTS is the contents of the element."
711 (format "#+BEGIN: %s%s\n%s#+END:"
712 (org-element-property :block-name dynamic-block
)
713 (let ((args (org-element-property :arguments dynamic-block
)))
714 (and args
(concat " " args
)))
718 ;;;; Footnote Definition
720 (defun org-element-footnote-definition-parser (limit affiliated
)
721 "Parse a footnote definition.
723 LIMIT bounds the search. AFFILIATED is a list of which CAR is
724 the buffer position at the beginning of the first affiliated
725 keyword and CDR is a plist of affiliated keywords along with
728 Return a list whose CAR is `footnote-definition' and CDR is
729 a plist containing `:label', `:begin' `:end', `:contents-begin',
730 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
732 Assume point is at the beginning of the footnote definition."
734 (let* ((label (progn (looking-at org-footnote-definition-re
)
735 (org-match-string-no-properties 1)))
736 (begin (car affiliated
))
737 (post-affiliated (point))
738 (ending (save-excursion
742 (concat org-outline-regexp-bol
"\\|"
743 org-footnote-definition-re
"\\|"
744 "^\\([ \t]*\n\\)\\{2,\\}") limit
'move
))
747 (contents-begin (progn
749 (skip-chars-forward " \r\t\n" ending
)
750 (cond ((= (point) ending
) nil
)
751 ((= (line-beginning-position) begin
) (point))
752 (t (line-beginning-position)))))
753 (contents-end (and contents-begin ending
))
754 (end (progn (goto-char ending
)
755 (skip-chars-forward " \r\t\n" limit
)
756 (if (eobp) (point) (line-beginning-position)))))
757 (list 'footnote-definition
762 :contents-begin contents-begin
763 :contents-end contents-end
764 :post-blank
(count-lines ending end
)
765 :post-affiliated post-affiliated
)
766 (cdr affiliated
))))))
768 (defun org-element-footnote-definition-interpreter (footnote-definition contents
)
769 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
770 CONTENTS is the contents of the footnote-definition."
771 (concat (format "[%s]" (org-element-property :label footnote-definition
))
778 (defun org-element-headline-parser (limit &optional raw-secondary-p
)
781 Return a list whose CAR is `headline' and CDR is a plist
782 containing `:raw-value', `:title', `:alt-title', `:begin',
783 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
784 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
785 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
786 and `:footnote-section-p' keywords.
788 The plist also contains any property set in the property drawer,
789 with its name in upper cases and colons added at the
790 beginning (e.g., `:CUSTOM_ID').
792 LIMIT is a buffer position bounding the search.
794 When RAW-SECONDARY-P is non-nil, headline's title will not be
795 parsed as a secondary string, but as a plain string instead.
797 Assume point is at beginning of the headline."
799 (let* ((components (org-heading-components))
800 (level (nth 1 components
))
801 (todo (nth 2 components
))
803 (and todo
(if (member todo org-done-keywords
) 'done
'todo
)))
804 (tags (let ((raw-tags (nth 5 components
)))
805 (and raw-tags
(org-split-string raw-tags
":"))))
806 (raw-value (or (nth 4 components
) ""))
808 (let ((case-fold-search nil
))
809 (string-match (format "^%s\\( \\|$\\)" org-comment-string
)
811 (archivedp (member org-archive-tag tags
))
812 (footnote-section-p (and org-footnote-section
813 (string= org-footnote-section raw-value
)))
815 ;; Find property drawer associated to current headline and
816 ;; extract properties.
818 ;; Upcase property names. It avoids confusion between
819 ;; properties obtained through property drawer and default
820 ;; properties from the parser (e.g. `:end' and :END:)
821 (let ((end (save-excursion
822 (org-with-limited-levels (outline-next-heading))
826 (while (and (null plist
)
827 (re-search-forward org-property-start-re end t
))
828 (let ((drawer (org-element-at-point)))
829 (when (and (eq (org-element-type drawer
) 'property-drawer
)
830 ;; Make sure drawer is not associated
833 (while (and (setq p
(org-element-property
835 (not (eq (org-element-type p
)
838 (let ((end (org-element-property :contents-end drawer
)))
841 (while (< (point) end
)
842 (when (looking-at org-property-re
)
847 (concat ":" (upcase (match-string 2))))
848 (org-match-string-no-properties 3))))
852 ;; Read time properties on the line below the headline.
855 (when (looking-at org-planning-or-clock-line-re
)
856 (let ((end (line-end-position)) plist
)
857 (while (re-search-forward
858 org-keyword-time-not-clock-regexp end t
)
859 (goto-char (match-end 1))
860 (skip-chars-forward " \t")
861 (let ((keyword (match-string 1))
862 (time (org-element-timestamp-parser)))
863 (cond ((equal keyword org-scheduled-string
)
864 (setq plist
(plist-put plist
:scheduled time
)))
865 ((equal keyword org-deadline-string
)
866 (setq plist
(plist-put plist
:deadline time
)))
867 (t (setq plist
(plist-put plist
:closed time
))))))
870 (end (min (save-excursion (org-end-of-subtree t t
)) limit
))
871 (pos-after-head (progn (forward-line) (point)))
872 (contents-begin (save-excursion
873 (skip-chars-forward " \r\t\n" end
)
874 (and (/= (point) end
) (line-beginning-position))))
875 (contents-end (and contents-begin
876 (progn (goto-char end
)
877 (skip-chars-backward " \r\t\n")
880 ;; Clean RAW-VALUE from any comment string.
882 (let ((case-fold-search nil
))
884 (replace-regexp-in-string
885 (concat (regexp-quote org-comment-string
) "\\(?: \\|$\\)")
888 ;; Clean TAGS from archive tag, if any.
889 (when archivedp
(setq tags
(delete org-archive-tag tags
)))
893 (list :raw-value raw-value
897 (if (not contents-begin
) 0
898 (count-lines pos-after-head contents-begin
))
899 :contents-begin contents-begin
900 :contents-end contents-end
902 :priority
(nth 3 components
)
906 :post-blank
(count-lines
907 (or contents-end pos-after-head
)
909 :footnote-section-p footnote-section-p
911 :commentedp commentedp
)
914 (let ((alt-title (org-element-property :ALT_TITLE headline
)))
916 (org-element-put-property
918 (if raw-secondary-p alt-title
919 (org-element-parse-secondary-string
920 alt-title
(org-element-restriction 'headline
) headline
)))))
921 (org-element-put-property
923 (if raw-secondary-p raw-value
924 (org-element-parse-secondary-string
925 raw-value
(org-element-restriction 'headline
) headline
)))))))
927 (defun org-element-headline-interpreter (headline contents
)
928 "Interpret HEADLINE element as Org syntax.
929 CONTENTS is the contents of the element."
930 (let* ((level (org-element-property :level headline
))
931 (todo (org-element-property :todo-keyword headline
))
932 (priority (org-element-property :priority headline
))
933 (title (org-element-interpret-data
934 (org-element-property :title headline
)))
935 (tags (let ((tag-list (if (org-element-property :archivedp headline
)
936 (cons org-archive-tag
937 (org-element-property :tags headline
))
938 (org-element-property :tags headline
))))
940 (format ":%s:" (mapconcat 'identity tag-list
":")))))
941 (commentedp (org-element-property :commentedp headline
))
942 (pre-blank (or (org-element-property :pre-blank headline
) 0))
943 (heading (concat (make-string (org-reduced-level level
) ?
*)
944 (and todo
(concat " " todo
))
945 (and commentedp
(concat " " org-comment-string
))
947 (format " [#%s]" (char-to-string priority
)))
948 (cond ((and org-footnote-section
949 (org-element-property
950 :footnote-section-p headline
))
951 (concat " " org-footnote-section
))
952 (title (concat " " title
))))))
957 ((zerop org-tags-column
) (format " %s" tags
))
958 ((< org-tags-column
0)
961 (max (- (+ org-tags-column
(length heading
) (length tags
))) 1)
966 (make-string (max (- org-tags-column
(length heading
)) 1) ?
)
968 (make-string (1+ pre-blank
) 10)
974 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p
)
975 "Parse an inline task.
977 Return a list whose CAR is `inlinetask' and CDR is a plist
978 containing `:title', `:begin', `:end', `:contents-begin' and
979 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
980 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
981 `:closed' and `:post-blank' keywords.
983 The plist also contains any property set in the property drawer,
984 with its name in upper cases and colons added at the
985 beginning (e.g., `:CUSTOM_ID').
987 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
988 title will not be parsed as a secondary string, but as a plain
991 Assume point is at beginning of the inline task."
993 (let* ((begin (point))
994 (components (org-heading-components))
995 (todo (nth 2 components
))
997 (if (member todo org-done-keywords
) 'done
'todo
)))
998 (tags (let ((raw-tags (nth 5 components
)))
999 (and raw-tags
(org-split-string raw-tags
":"))))
1000 (raw-value (or (nth 4 components
) ""))
1001 (task-end (save-excursion
1003 (and (re-search-forward org-outline-regexp-bol limit t
)
1004 (org-looking-at-p "END[ \t]*$")
1005 (line-beginning-position))))
1007 ;; Read time properties on the line below the inlinetask
1011 (when (progn (forward-line)
1012 (looking-at org-planning-or-clock-line-re
))
1013 (let ((end (line-end-position)) plist
)
1014 (while (re-search-forward
1015 org-keyword-time-not-clock-regexp end t
)
1016 (goto-char (match-end 1))
1017 (skip-chars-forward " \t")
1018 (let ((keyword (match-string 1))
1019 (time (org-element-timestamp-parser)))
1020 (cond ((equal keyword org-scheduled-string
)
1021 (setq plist
(plist-put plist
:scheduled time
)))
1022 ((equal keyword org-deadline-string
)
1023 (setq plist
(plist-put plist
:deadline time
)))
1024 (t (setq plist
(plist-put plist
:closed time
))))))
1026 (contents-begin (progn (forward-line)
1027 (and task-end
(< (point) task-end
) (point))))
1028 (contents-end (and contents-begin task-end
))
1029 (before-blank (if (not task-end
) (point)
1030 (goto-char task-end
)
1033 (end (progn (skip-chars-forward " \r\t\n" limit
)
1034 (if (eobp) (point) (line-beginning-position))))
1036 ;; Find property drawer associated to current inlinetask
1037 ;; and extract properties.
1039 ;; HACK: Calling `org-element-at-point' triggers a parsing
1040 ;; of this inlinetask and, thus, an infloop. To avoid the
1041 ;; problem, we extract contents of the inlinetask and
1042 ;; parse them in a new buffer.
1044 ;; Upcase property names. It avoids confusion between
1045 ;; properties obtained through property drawer and default
1046 ;; properties from the parser (e.g. `:end' and :END:)
1047 (when contents-begin
1048 (let ((contents (buffer-substring contents-begin contents-end
))
1051 (let ((org-inhibit-startup t
)) (org-mode))
1053 (goto-char (point-min))
1054 (while (and (null plist
)
1056 org-property-start-re task-end t
))
1057 (let ((d (org-element-at-point)))
1058 (when (eq (org-element-type d
) 'property-drawer
)
1059 (let ((end (org-element-property :contents-end d
)))
1062 (while (< (point) end
)
1063 (when (looking-at org-property-re
)
1068 (concat ":" (upcase (match-string 2))))
1069 (org-match-string-no-properties 3))))
1070 (forward-line))))))))
1075 (list :raw-value raw-value
1078 :contents-begin contents-begin
1079 :contents-end contents-end
1080 :level
(nth 1 components
)
1081 :priority
(nth 3 components
)
1084 :todo-type todo-type
1085 :post-blank
(count-lines before-blank end
))
1088 (org-element-put-property
1090 (if raw-secondary-p raw-value
1091 (org-element-parse-secondary-string
1093 (org-element-restriction 'inlinetask
)
1096 (defun org-element-inlinetask-interpreter (inlinetask contents
)
1097 "Interpret INLINETASK element as Org syntax.
1098 CONTENTS is the contents of inlinetask."
1099 (let* ((level (org-element-property :level inlinetask
))
1100 (todo (org-element-property :todo-keyword inlinetask
))
1101 (priority (org-element-property :priority inlinetask
))
1102 (title (org-element-interpret-data
1103 (org-element-property :title inlinetask
)))
1104 (tags (let ((tag-list (org-element-property :tags inlinetask
)))
1106 (format ":%s:" (mapconcat 'identity tag-list
":")))))
1107 (task (concat (make-string level ?
*)
1108 (and todo
(concat " " todo
))
1110 (format " [#%s]" (char-to-string priority
)))
1111 (and title
(concat " " title
)))))
1116 ((zerop org-tags-column
) (format " %s" tags
))
1117 ((< org-tags-column
0)
1120 (max (- (+ org-tags-column
(length task
) (length tags
))) 1)
1125 (make-string (max (- org-tags-column
(length task
)) 1) ?
)
1127 ;; Prefer degenerate inlinetasks when there are no
1132 (make-string level ?
*) " END")))))
1137 (defun org-element-item-parser (limit struct
&optional raw-secondary-p
)
1140 STRUCT is the structure of the plain list.
1142 Return a list whose CAR is `item' and CDR is a plist containing
1143 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1144 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1147 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1148 any, will not be parsed as a secondary string, but as a plain
1151 Assume point is at the beginning of the item."
1154 (looking-at org-list-full-item-re
)
1155 (let* ((begin (point))
1156 (bullet (org-match-string-no-properties 1))
1157 (checkbox (let ((box (org-match-string-no-properties 3)))
1158 (cond ((equal "[ ]" box
) 'off
)
1159 ((equal "[X]" box
) 'on
)
1160 ((equal "[-]" box
) 'trans
))))
1161 (counter (let ((c (org-match-string-no-properties 2)))
1165 ((string-match "[A-Za-z]" c
)
1166 (- (string-to-char (upcase (match-string 0 c
)))
1168 ((string-match "[0-9]+" c
)
1169 (string-to-number (match-string 0 c
)))))))
1170 (end (progn (goto-char (nth 6 (assq (point) struct
)))
1171 (unless (bolp) (forward-line))
1175 ;; Ignore tags in un-ordered lists: they are just
1176 ;; a part of item's body.
1177 (if (and (match-beginning 4)
1178 (save-match-data (string-match "[.)]" bullet
)))
1181 (skip-chars-forward " \r\t\n" limit
)
1182 ;; If first line isn't empty, contents really start
1183 ;; at the text after item's meta-data.
1184 (if (= (point-at-bol) begin
) (point) (point-at-bol))))
1185 (contents-end (progn (goto-char end
)
1186 (skip-chars-backward " \r\t\n")
1191 (list :bullet bullet
1194 ;; CONTENTS-BEGIN and CONTENTS-END may be
1195 ;; mixed up in the case of an empty item
1196 ;; separated from the next by a blank line.
1197 ;; Thus ensure the former is always the
1199 :contents-begin
(min contents-begin contents-end
)
1200 :contents-end
(max contents-begin contents-end
)
1204 :post-blank
(count-lines contents-end end
)))))
1205 (org-element-put-property
1207 (let ((raw-tag (org-list-get-tag begin struct
)))
1209 (if raw-secondary-p raw-tag
1210 (org-element-parse-secondary-string
1211 raw-tag
(org-element-restriction 'item
) item
))))))))
1213 (defun org-element-item-interpreter (item contents
)
1214 "Interpret ITEM element as Org syntax.
1215 CONTENTS is the contents of the element."
1216 (let* ((bullet (let ((bullet (org-element-property :bullet item
)))
1217 (org-list-bullet-string
1218 (cond ((not (string-match "[0-9a-zA-Z]" bullet
)) "- ")
1219 ((eq org-plain-list-ordered-item-terminator ?\
)) "1)")
1221 (checkbox (org-element-property :checkbox item
))
1222 (counter (org-element-property :counter item
))
1223 (tag (let ((tag (org-element-property :tag item
)))
1224 (and tag
(org-element-interpret-data tag
))))
1225 ;; Compute indentation.
1226 (ind (make-string (length bullet
) 32))
1227 (item-starts-with-par-p
1228 (eq (org-element-type (car (org-element-contents item
)))
1233 (and counter
(format "[@%d] " counter
))
1238 (and tag
(format "%s :: " tag
))
1240 (let ((contents (replace-regexp-in-string
1241 "\\(^\\)[ \t]*\\S-" ind contents nil nil
1)))
1242 (if item-starts-with-par-p
(org-trim contents
)
1243 (concat "\n" contents
)))))))
1248 (defun org-element--list-struct (limit)
1249 ;; Return structure of list at point. Internal function. See
1250 ;; `org-list-struct' for details.
1251 (let ((case-fold-search t
)
1253 (item-re (org-item-re))
1254 (inlinetask-re (and (featurep 'org-inlinetask
) "^\\*+ "))
1260 ;; At limit: end all items.
1263 (let ((end (progn (skip-chars-backward " \r\t\n")
1266 (dolist (item items
(sort (nconc items struct
)
1267 'car-less-than-car
))
1268 (setcar (nthcdr 6 item
) end
)))))
1269 ;; At list end: end all items.
1270 ((looking-at org-list-end-re
)
1271 (throw 'exit
(dolist (item items
(sort (nconc items struct
)
1272 'car-less-than-car
))
1273 (setcar (nthcdr 6 item
) (point)))))
1274 ;; At a new item: end previous sibling.
1275 ((looking-at item-re
)
1276 (let ((ind (save-excursion (skip-chars-forward " \t")
1278 (setq top-ind
(min top-ind ind
))
1279 (while (and items
(<= ind
(nth 1 (car items
))))
1280 (let ((item (pop items
)))
1281 (setcar (nthcdr 6 item
) (point))
1282 (push item struct
)))
1283 (push (progn (looking-at org-list-full-item-re
)
1284 (let ((bullet (match-string-no-properties 1)))
1288 (match-string-no-properties 2) ; counter
1289 (match-string-no-properties 3) ; checkbox
1291 (and (save-match-data
1292 (string-match "[-+*]" bullet
))
1293 (match-string-no-properties 4))
1294 ;; Ending position, unknown so far.
1298 ;; Skip empty lines.
1299 ((looking-at "^[ \t]*$") (forward-line))
1300 ;; Skip inline tasks and blank lines along the way.
1301 ((and inlinetask-re
(looking-at inlinetask-re
))
1303 (let ((origin (point)))
1304 (when (re-search-forward inlinetask-re limit t
)
1305 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1306 (goto-char origin
)))))
1307 ;; At some text line. Check if it ends any previous item.
1309 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1310 (when (<= ind top-ind
)
1311 (skip-chars-backward " \r\t\n")
1313 (while (<= ind
(nth 1 (car items
)))
1314 (let ((item (pop items
)))
1315 (setcar (nthcdr 6 item
) (line-beginning-position))
1318 (throw 'exit
(sort struct
'car-less-than-car
))))))
1319 ;; Skip blocks (any type) and drawers contents.
1321 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1323 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1325 ((and (looking-at org-drawer-regexp
)
1326 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
))))
1327 (forward-line))))))))
1329 (defun org-element-plain-list-parser (limit affiliated structure
)
1330 "Parse a plain list.
1332 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1333 the buffer position at the beginning of the first affiliated
1334 keyword and CDR is a plist of affiliated keywords along with
1335 their value. STRUCTURE is the structure of the plain list being
1338 Return a list whose CAR is `plain-list' and CDR is a plist
1339 containing `:type', `:begin', `:end', `:contents-begin' and
1340 `:contents-end', `:structure', `:post-blank' and
1341 `:post-affiliated' keywords.
1343 Assume point is at the beginning of the list."
1345 (let* ((struct (or structure
(org-element--list-struct limit
)))
1346 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered
)
1347 ((nth 5 (assq (point) struct
)) 'descriptive
)
1349 (contents-begin (point))
1350 (begin (car affiliated
))
1351 (contents-end (let* ((item (assq contents-begin struct
))
1354 (while (and (setq item
(assq pos struct
))
1355 (= (nth 1 item
) ind
))
1356 (setq pos
(nth 6 item
)))
1358 (end (progn (goto-char contents-end
)
1359 (skip-chars-forward " \r\t\n" limit
)
1360 (if (= (point) limit
) limit
(line-beginning-position)))))
1367 :contents-begin contents-begin
1368 :contents-end contents-end
1370 :post-blank
(count-lines contents-end end
)
1371 :post-affiliated contents-begin
)
1372 (cdr affiliated
))))))
1374 (defun org-element-plain-list-interpreter (plain-list contents
)
1375 "Interpret PLAIN-LIST element as Org syntax.
1376 CONTENTS is the contents of the element."
1379 (goto-char (point-min))
1384 ;;;; Property Drawer
1386 (defun org-element-property-drawer-parser (limit affiliated
)
1387 "Parse a property drawer.
1389 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1390 the buffer position at the beginning of the first affiliated
1391 keyword and CDR is a plist of affiliated keywords along with
1394 Return a list whose CAR is `property-drawer' and CDR is a plist
1395 containing `:begin', `:end', `:contents-begin', `:contents-end',
1396 `:post-blank' and `:post-affiliated' keywords.
1398 Assume point is at the beginning of the property drawer."
1400 (let ((case-fold-search t
))
1401 (if (not (save-excursion
1402 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t
)))
1403 ;; Incomplete drawer: parse it as a paragraph.
1404 (org-element-paragraph-parser limit affiliated
)
1406 (let* ((drawer-end-line (match-beginning 0))
1407 (begin (car affiliated
))
1408 (post-affiliated (point))
1409 (contents-begin (progn (forward-line)
1410 (and (< (point) drawer-end-line
)
1412 (contents-end (and contents-begin drawer-end-line
))
1413 (pos-before-blank (progn (goto-char drawer-end-line
)
1416 (end (progn (skip-chars-forward " \r\t\n" limit
)
1417 (if (eobp) (point) (line-beginning-position)))))
1418 (list 'property-drawer
1422 :contents-begin contents-begin
1423 :contents-end contents-end
1424 :post-blank
(count-lines pos-before-blank end
)
1425 :post-affiliated post-affiliated
)
1426 (cdr affiliated
)))))))))
1428 (defun org-element-property-drawer-interpreter (property-drawer contents
)
1429 "Interpret PROPERTY-DRAWER element as Org syntax.
1430 CONTENTS is the properties within the drawer."
1431 (format ":PROPERTIES:\n%s:END:" contents
))
1436 (defun org-element-quote-block-parser (limit affiliated
)
1437 "Parse a quote block.
1439 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1440 the buffer position at the beginning of the first affiliated
1441 keyword and CDR is a plist of affiliated keywords along with
1444 Return a list whose CAR is `quote-block' and CDR is a plist
1445 containing `:begin', `:end', `:contents-begin', `:contents-end',
1446 `:post-blank' and `:post-affiliated' keywords.
1448 Assume point is at the beginning of the block."
1449 (let ((case-fold-search t
))
1450 (if (not (save-excursion
1451 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t
)))
1452 ;; Incomplete block: parse it as a paragraph.
1453 (org-element-paragraph-parser limit affiliated
)
1454 (let ((block-end-line (match-beginning 0)))
1456 (let* ((begin (car affiliated
))
1457 (post-affiliated (point))
1458 ;; Empty blocks have no contents.
1459 (contents-begin (progn (forward-line)
1460 (and (< (point) block-end-line
)
1462 (contents-end (and contents-begin block-end-line
))
1463 (pos-before-blank (progn (goto-char block-end-line
)
1466 (end (progn (skip-chars-forward " \r\t\n" limit
)
1467 (if (eobp) (point) (line-beginning-position)))))
1472 :contents-begin contents-begin
1473 :contents-end contents-end
1474 :post-blank
(count-lines pos-before-blank end
)
1475 :post-affiliated post-affiliated
)
1476 (cdr affiliated
)))))))))
1478 (defun org-element-quote-block-interpreter (quote-block contents
)
1479 "Interpret QUOTE-BLOCK element as Org syntax.
1480 CONTENTS is the contents of the element."
1481 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents
))
1486 (defun org-element-section-parser (limit)
1489 LIMIT bounds the search.
1491 Return a list whose CAR is `section' and CDR is a plist
1492 containing `:begin', `:end', `:contents-begin', `contents-end'
1493 and `:post-blank' keywords."
1495 ;; Beginning of section is the beginning of the first non-blank
1496 ;; line after previous headline.
1497 (let ((begin (point))
1498 (end (progn (org-with-limited-levels (outline-next-heading))
1500 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1506 :contents-begin begin
1507 :contents-end pos-before-blank
1508 :post-blank
(count-lines pos-before-blank end
))))))
1510 (defun org-element-section-interpreter (section contents
)
1511 "Interpret SECTION element as Org syntax.
1512 CONTENTS is the contents of the element."
1518 (defun org-element-special-block-parser (limit affiliated
)
1519 "Parse a special block.
1521 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1522 the buffer position at the beginning of the first affiliated
1523 keyword and CDR is a plist of affiliated keywords along with
1526 Return a list whose CAR is `special-block' and CDR is a plist
1527 containing `:type', `:begin', `:end', `:contents-begin',
1528 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1530 Assume point is at the beginning of the block."
1531 (let* ((case-fold-search t
)
1532 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1533 (upcase (match-string-no-properties 1)))))
1534 (if (not (save-excursion
1536 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type
))
1538 ;; Incomplete block: parse it as a paragraph.
1539 (org-element-paragraph-parser limit affiliated
)
1540 (let ((block-end-line (match-beginning 0)))
1542 (let* ((begin (car affiliated
))
1543 (post-affiliated (point))
1544 ;; Empty blocks have no contents.
1545 (contents-begin (progn (forward-line)
1546 (and (< (point) block-end-line
)
1548 (contents-end (and contents-begin block-end-line
))
1549 (pos-before-blank (progn (goto-char block-end-line
)
1552 (end (progn (skip-chars-forward " \r\t\n" limit
)
1553 (if (eobp) (point) (line-beginning-position)))))
1554 (list 'special-block
1559 :contents-begin contents-begin
1560 :contents-end contents-end
1561 :post-blank
(count-lines pos-before-blank end
)
1562 :post-affiliated post-affiliated
)
1563 (cdr affiliated
)))))))))
1565 (defun org-element-special-block-interpreter (special-block contents
)
1566 "Interpret SPECIAL-BLOCK element as Org syntax.
1567 CONTENTS is the contents of the element."
1568 (let ((block-type (org-element-property :type special-block
)))
1569 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type
)))
1575 ;; For each element, a parser and an interpreter are also defined.
1576 ;; Both follow the same naming convention used for greater elements.
1578 ;; Also, as for greater elements, adding a new element type is done
1579 ;; through the following steps: implement a parser and an interpreter,
1580 ;; tweak `org-element--current-element' so that it recognizes the new
1581 ;; type and add that new type to `org-element-all-elements'.
1583 ;; As a special case, when the newly defined type is a block type,
1584 ;; `org-element-block-name-alist' has to be modified accordingly.
1589 (defun org-element-babel-call-parser (limit affiliated
)
1590 "Parse a babel call.
1592 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1593 the buffer position at the beginning of the first affiliated
1594 keyword and CDR is a plist of affiliated keywords along with
1597 Return a list whose CAR is `babel-call' and CDR is a plist
1598 containing `:begin', `:end', `:value', `:post-blank' and
1599 `:post-affiliated' as keywords."
1601 (let ((begin (car affiliated
))
1602 (post-affiliated (point))
1603 (value (progn (let ((case-fold-search t
))
1604 (re-search-forward "call:[ \t]*" nil t
))
1605 (buffer-substring-no-properties (point)
1606 (line-end-position))))
1607 (pos-before-blank (progn (forward-line) (point)))
1608 (end (progn (skip-chars-forward " \r\t\n" limit
)
1609 (if (eobp) (point) (line-beginning-position)))))
1615 :post-blank
(count-lines pos-before-blank end
)
1616 :post-affiliated post-affiliated
)
1617 (cdr affiliated
))))))
1619 (defun org-element-babel-call-interpreter (babel-call contents
)
1620 "Interpret BABEL-CALL element as Org syntax.
1622 (concat "#+CALL: " (org-element-property :value babel-call
)))
1627 (defun org-element-clock-parser (limit)
1630 LIMIT bounds the search.
1632 Return a list whose CAR is `clock' and CDR is a plist containing
1633 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1636 (let* ((case-fold-search nil
)
1638 (value (progn (search-forward org-clock-string
(line-end-position) t
)
1639 (skip-chars-forward " \t")
1640 (org-element-timestamp-parser)))
1641 (duration (and (search-forward " => " (line-end-position) t
)
1642 (progn (skip-chars-forward " \t")
1643 (looking-at "\\(\\S-+\\)[ \t]*$"))
1644 (org-match-string-no-properties 1)))
1645 (status (if duration
'closed
'running
))
1646 (post-blank (let ((before-blank (progn (forward-line) (point))))
1647 (skip-chars-forward " \r\t\n" limit
)
1648 (skip-chars-backward " \t")
1649 (unless (bolp) (end-of-line))
1650 (count-lines before-blank
(point))))
1653 (list :status status
1658 :post-blank post-blank
)))))
1660 (defun org-element-clock-interpreter (clock contents
)
1661 "Interpret CLOCK element as Org syntax.
1663 (concat org-clock-string
" "
1664 (org-element-timestamp-interpreter
1665 (org-element-property :value clock
) nil
)
1666 (let ((duration (org-element-property :duration clock
)))
1671 (org-split-string duration
":")))))))
1676 (defun org-element-comment-parser (limit affiliated
)
1679 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1680 the buffer position at the beginning of the first affiliated
1681 keyword and CDR is a plist of affiliated keywords along with
1684 Return a list whose CAR is `comment' and CDR is a plist
1685 containing `:begin', `:end', `:value', `:post-blank',
1686 `:post-affiliated' keywords.
1688 Assume point is at comment beginning."
1690 (let* ((begin (car affiliated
))
1691 (post-affiliated (point))
1692 (value (prog2 (looking-at "[ \t]*# ?")
1693 (buffer-substring-no-properties
1694 (match-end 0) (line-end-position))
1697 ;; Get comments ending.
1699 (while (and (< (point) limit
) (looking-at "[ \t]*#\\( \\|$\\)"))
1700 ;; Accumulate lines without leading hash and first
1705 (buffer-substring-no-properties
1706 (match-end 0) (line-end-position))))
1709 (end (progn (goto-char com-end
)
1710 (skip-chars-forward " \r\t\n" limit
)
1711 (if (eobp) (point) (line-beginning-position)))))
1717 :post-blank
(count-lines com-end end
)
1718 :post-affiliated post-affiliated
)
1719 (cdr affiliated
))))))
1721 (defun org-element-comment-interpreter (comment contents
)
1722 "Interpret COMMENT element as Org syntax.
1724 (replace-regexp-in-string "^" "# " (org-element-property :value comment
)))
1729 (defun org-element-comment-block-parser (limit affiliated
)
1730 "Parse an export block.
1732 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1733 the buffer position at the beginning of the first affiliated
1734 keyword and CDR is a plist of affiliated keywords along with
1737 Return a list whose CAR is `comment-block' and CDR is a plist
1738 containing `:begin', `:end', `:value', `:post-blank' and
1739 `:post-affiliated' keywords.
1741 Assume point is at comment block beginning."
1742 (let ((case-fold-search t
))
1743 (if (not (save-excursion
1744 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t
)))
1745 ;; Incomplete block: parse it as a paragraph.
1746 (org-element-paragraph-parser limit affiliated
)
1747 (let ((contents-end (match-beginning 0)))
1749 (let* ((begin (car affiliated
))
1750 (post-affiliated (point))
1751 (contents-begin (progn (forward-line) (point)))
1752 (pos-before-blank (progn (goto-char contents-end
)
1755 (end (progn (skip-chars-forward " \r\t\n" limit
)
1756 (if (eobp) (point) (line-beginning-position))))
1757 (value (buffer-substring-no-properties
1758 contents-begin contents-end
)))
1759 (list 'comment-block
1764 :post-blank
(count-lines pos-before-blank end
)
1765 :post-affiliated post-affiliated
)
1766 (cdr affiliated
)))))))))
1768 (defun org-element-comment-block-interpreter (comment-block contents
)
1769 "Interpret COMMENT-BLOCK element as Org syntax.
1771 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1772 (org-remove-indentation (org-element-property :value comment-block
))))
1777 (defun org-element-diary-sexp-parser (limit affiliated
)
1778 "Parse a diary sexp.
1780 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1781 the buffer position at the beginning of the first affiliated
1782 keyword and CDR is a plist of affiliated keywords along with
1785 Return a list whose CAR is `diary-sexp' and CDR is a plist
1786 containing `:begin', `:end', `:value', `:post-blank' and
1787 `:post-affiliated' keywords."
1789 (let ((begin (car affiliated
))
1790 (post-affiliated (point))
1791 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1792 (org-match-string-no-properties 1)))
1793 (pos-before-blank (progn (forward-line) (point)))
1794 (end (progn (skip-chars-forward " \r\t\n" limit
)
1795 (if (eobp) (point) (line-beginning-position)))))
1801 :post-blank
(count-lines pos-before-blank end
)
1802 :post-affiliated post-affiliated
)
1803 (cdr affiliated
))))))
1805 (defun org-element-diary-sexp-interpreter (diary-sexp contents
)
1806 "Interpret DIARY-SEXP as Org syntax.
1808 (org-element-property :value diary-sexp
))
1813 (defun org-element-example-block-parser (limit affiliated
)
1814 "Parse an example block.
1816 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1817 the buffer position at the beginning of the first affiliated
1818 keyword and CDR is a plist of affiliated keywords along with
1821 Return a list whose CAR is `example-block' and CDR is a plist
1822 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1823 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1824 `:value', `:post-blank' and `:post-affiliated' keywords."
1825 (let ((case-fold-search t
))
1826 (if (not (save-excursion
1827 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t
)))
1828 ;; Incomplete block: parse it as a paragraph.
1829 (org-element-paragraph-parser limit affiliated
)
1830 (let ((contents-end (match-beginning 0)))
1834 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1835 (org-match-string-no-properties 1)))
1836 ;; Switches analysis
1838 (cond ((not switches
) nil
)
1839 ((string-match "-n\\>" switches
) 'new
)
1840 ((string-match "+n\\>" switches
) 'continued
)))
1842 (and switches
(string-match "-i\\>" switches
)))
1843 ;; Should labels be retained in (or stripped from) example
1847 (not (string-match "-r\\>" switches
))
1848 (and number-lines
(string-match "-k\\>" switches
))))
1849 ;; What should code-references use - labels or
1854 (not (string-match "-k\\>" switches
)))))
1857 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
1858 (match-string 1 switches
)))
1859 ;; Standard block parsing.
1860 (begin (car affiliated
))
1861 (post-affiliated (point))
1862 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1863 (contents-begin (progn (forward-line) (point)))
1864 (value (org-element-remove-indentation
1865 (org-unescape-code-in-string
1866 (buffer-substring-no-properties
1867 contents-begin contents-end
))
1869 (pos-before-blank (progn (goto-char contents-end
)
1872 (end (progn (skip-chars-forward " \r\t\n" limit
)
1873 (if (eobp) (point) (line-beginning-position)))))
1874 (list 'example-block
1880 :number-lines number-lines
1881 :preserve-indent preserve-indent
1882 :retain-labels retain-labels
1883 :use-labels use-labels
1884 :label-fmt label-fmt
1885 :post-blank
(count-lines pos-before-blank end
)
1886 :post-affiliated post-affiliated
)
1887 (cdr affiliated
)))))))))
1889 (defun org-element-example-block-interpreter (example-block contents
)
1890 "Interpret EXAMPLE-BLOCK element as Org syntax.
1892 (let ((switches (org-element-property :switches example-block
))
1893 (value (org-element-property :value example-block
)))
1894 (concat "#+BEGIN_EXAMPLE" (and switches
(concat " " switches
)) "\n"
1895 (org-escape-code-in-string
1896 (if (or org-src-preserve-indentation
1897 (org-element-property :preserve-indent example-block
))
1899 (org-element-remove-indentation value
)))
1905 (defun org-element-export-block-parser (limit affiliated
)
1906 "Parse an export block.
1908 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1909 the buffer position at the beginning of the first affiliated
1910 keyword and CDR is a plist of affiliated keywords along with
1913 Return a list whose CAR is `export-block' and CDR is a plist
1914 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1915 `:post-affiliated' keywords.
1917 Assume point is at export-block beginning."
1918 (let* ((case-fold-search t
)
1919 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1920 (upcase (org-match-string-no-properties 1)))))
1921 (if (not (save-excursion
1923 (format "^[ \t]*#\\+END_%s[ \t]*$" type
) limit t
)))
1924 ;; Incomplete block: parse it as a paragraph.
1925 (org-element-paragraph-parser limit affiliated
)
1926 (let ((contents-end (match-beginning 0)))
1928 (let* ((begin (car affiliated
))
1929 (post-affiliated (point))
1930 (contents-begin (progn (forward-line) (point)))
1931 (pos-before-blank (progn (goto-char contents-end
)
1934 (end (progn (skip-chars-forward " \r\t\n" limit
)
1935 (if (eobp) (point) (line-beginning-position))))
1936 (value (buffer-substring-no-properties contents-begin
1944 :post-blank
(count-lines pos-before-blank end
)
1945 :post-affiliated post-affiliated
)
1946 (cdr affiliated
)))))))))
1948 (defun org-element-export-block-interpreter (export-block contents
)
1949 "Interpret EXPORT-BLOCK element as Org syntax.
1951 (let ((type (org-element-property :type export-block
)))
1952 (concat (format "#+BEGIN_%s\n" type
)
1953 (org-element-property :value export-block
)
1954 (format "#+END_%s" type
))))
1959 (defun org-element-fixed-width-parser (limit affiliated
)
1960 "Parse a fixed-width section.
1962 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1963 the buffer position at the beginning of the first affiliated
1964 keyword and CDR is a plist of affiliated keywords along with
1967 Return a list whose CAR is `fixed-width' and CDR is a plist
1968 containing `:begin', `:end', `:value', `:post-blank' and
1969 `:post-affiliated' keywords.
1971 Assume point is at the beginning of the fixed-width area."
1973 (let* ((begin (car affiliated
))
1974 (post-affiliated (point))
1978 (while (and (< (point) limit
)
1979 (looking-at "[ \t]*:\\( \\|$\\)"))
1980 ;; Accumulate text without starting colons.
1983 (buffer-substring-no-properties
1984 (match-end 0) (point-at-eol))
1988 (end (progn (skip-chars-forward " \r\t\n" limit
)
1989 (if (eobp) (point) (line-beginning-position)))))
1995 :post-blank
(count-lines end-area end
)
1996 :post-affiliated post-affiliated
)
1997 (cdr affiliated
))))))
1999 (defun org-element-fixed-width-interpreter (fixed-width contents
)
2000 "Interpret FIXED-WIDTH element as Org syntax.
2002 (let ((value (org-element-property :value fixed-width
)))
2004 (replace-regexp-in-string
2006 (if (string-match "\n\\'" value
) (substring value
0 -
1) value
)))))
2009 ;;;; Horizontal Rule
2011 (defun org-element-horizontal-rule-parser (limit affiliated
)
2012 "Parse an horizontal rule.
2014 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2015 the buffer position at the beginning of the first affiliated
2016 keyword and CDR is a plist of affiliated keywords along with
2019 Return a list whose CAR is `horizontal-rule' and CDR is a plist
2020 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
2023 (let ((begin (car affiliated
))
2024 (post-affiliated (point))
2025 (post-hr (progn (forward-line) (point)))
2026 (end (progn (skip-chars-forward " \r\t\n" limit
)
2027 (if (eobp) (point) (line-beginning-position)))))
2028 (list 'horizontal-rule
2032 :post-blank
(count-lines post-hr end
)
2033 :post-affiliated post-affiliated
)
2034 (cdr affiliated
))))))
2036 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents
)
2037 "Interpret HORIZONTAL-RULE element as Org syntax.
2044 (defun org-element-keyword-parser (limit affiliated
)
2045 "Parse a keyword at point.
2047 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2048 the buffer position at the beginning of the first affiliated
2049 keyword and CDR is a plist of affiliated keywords along with
2052 Return a list whose CAR is `keyword' and CDR is a plist
2053 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2054 `:post-affiliated' keywords."
2056 ;; An orphaned affiliated keyword is considered as a regular
2057 ;; keyword. In this case AFFILIATED is nil, so we take care of
2058 ;; this corner case.
2059 (let ((begin (or (car affiliated
) (point)))
2060 (post-affiliated (point))
2061 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2062 (upcase (org-match-string-no-properties 1))))
2063 (value (org-trim (buffer-substring-no-properties
2064 (match-end 0) (point-at-eol))))
2065 (pos-before-blank (progn (forward-line) (point)))
2066 (end (progn (skip-chars-forward " \r\t\n" limit
)
2067 (if (eobp) (point) (line-beginning-position)))))
2074 :post-blank
(count-lines pos-before-blank end
)
2075 :post-affiliated post-affiliated
)
2076 (cdr affiliated
))))))
2078 (defun org-element-keyword-interpreter (keyword contents
)
2079 "Interpret KEYWORD element as Org syntax.
2082 (org-element-property :key keyword
)
2083 (org-element-property :value keyword
)))
2086 ;;;; Latex Environment
2088 (defun org-element-latex-environment-parser (limit affiliated
)
2089 "Parse a LaTeX environment.
2091 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2092 the buffer position at the beginning of the first affiliated
2093 keyword and CDR is a plist of affiliated keywords along with
2096 Return a list whose CAR is `latex-environment' and CDR is a plist
2097 containing `:begin', `:end', `:value', `:post-blank' and
2098 `:post-affiliated' keywords.
2100 Assume point is at the beginning of the latex environment."
2102 (let ((case-fold-search t
)
2103 (code-begin (point)))
2104 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2105 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2106 (regexp-quote (match-string 1)))
2108 ;; Incomplete latex environment: parse it as a paragraph.
2109 (org-element-paragraph-parser limit affiliated
)
2110 (let* ((code-end (progn (forward-line) (point)))
2111 (begin (car affiliated
))
2112 (value (buffer-substring-no-properties code-begin code-end
))
2113 (end (progn (skip-chars-forward " \r\t\n" limit
)
2114 (if (eobp) (point) (line-beginning-position)))))
2115 (list 'latex-environment
2120 :post-blank
(count-lines code-end end
)
2121 :post-affiliated code-begin
)
2122 (cdr affiliated
))))))))
2124 (defun org-element-latex-environment-interpreter (latex-environment contents
)
2125 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2127 (org-element-property :value latex-environment
))
2132 (defun org-element-node-property-parser (limit)
2133 "Parse a node-property at point.
2135 LIMIT bounds the search.
2137 Return a list whose CAR is `node-property' and CDR is a plist
2138 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2141 (looking-at org-property-re
)
2142 (let ((case-fold-search t
)
2144 (key (org-match-string-no-properties 2))
2145 (value (org-match-string-no-properties 3))
2146 (pos-before-blank (progn (forward-line) (point)))
2147 (end (progn (skip-chars-forward " \r\t\n" limit
)
2148 (if (eobp) (point) (point-at-bol)))))
2149 (list 'node-property
2154 :post-blank
(count-lines pos-before-blank end
))))))
2156 (defun org-element-node-property-interpreter (node-property contents
)
2157 "Interpret NODE-PROPERTY element as Org syntax.
2159 (format org-property-format
2160 (format ":%s:" (org-element-property :key node-property
))
2161 (org-element-property :value node-property
)))
2166 (defun org-element-paragraph-parser (limit affiliated
)
2169 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2170 the buffer position at the beginning of the first affiliated
2171 keyword and CDR is a plist of affiliated keywords along with
2174 Return a list whose CAR is `paragraph' and CDR is a plist
2175 containing `:begin', `:end', `:contents-begin' and
2176 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2178 Assume point is at the beginning of the paragraph."
2180 (let* ((begin (car affiliated
))
2181 (contents-begin (point))
2183 (let ((case-fold-search t
))
2185 (if (not (re-search-forward
2186 org-element-paragraph-separate limit
'm
))
2188 ;; A matching `org-element-paragraph-separate' is not
2189 ;; necessarily the end of the paragraph. In
2190 ;; particular, lines starting with # or : as a first
2191 ;; non-space character are ambiguous. We have to
2192 ;; check if they are valid Org syntax (e.g., not an
2193 ;; incomplete keyword).
2197 ;; There's no ambiguity for other symbols or
2198 ;; empty lines: stop here.
2199 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2200 ;; Stop at valid fixed-width areas.
2201 (looking-at "[ \t]*:\\(?: \\|$\\)")
2203 (and (looking-at org-drawer-regexp
)
2206 "^[ \t]*:END:[ \t]*$" limit t
)))
2207 ;; Stop at valid comments.
2208 (looking-at "[ \t]*#\\(?: \\|$\\)")
2209 ;; Stop at valid dynamic blocks.
2210 (and (looking-at org-dblock-start-re
)
2213 "^[ \t]*#\\+END:?[ \t]*$" limit t
)))
2214 ;; Stop at valid blocks.
2215 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2218 (format "^[ \t]*#\\+END_%s[ \t]*$"
2220 (org-match-string-no-properties 1)))
2222 ;; Stop at valid latex environments.
2224 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2227 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2229 (org-match-string-no-properties 1)))
2231 ;; Stop at valid keywords.
2232 (looking-at "[ \t]*#\\+\\S-+:")
2233 ;; Skip everything else.
2237 (re-search-forward org-element-paragraph-separate
2239 (beginning-of-line)))
2240 (if (= (point) limit
) limit
2241 (goto-char (line-beginning-position)))))
2242 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin
)
2245 (end (progn (skip-chars-forward " \r\t\n" limit
)
2246 (if (eobp) (point) (line-beginning-position)))))
2251 :contents-begin contents-begin
2252 :contents-end contents-end
2253 :post-blank
(count-lines before-blank end
)
2254 :post-affiliated contents-begin
)
2255 (cdr affiliated
))))))
2257 (defun org-element-paragraph-interpreter (paragraph contents
)
2258 "Interpret PARAGRAPH element as Org syntax.
2259 CONTENTS is the contents of the element."
2265 (defun org-element-planning-parser (limit)
2268 LIMIT bounds the search.
2270 Return a list whose CAR is `planning' and CDR is a plist
2271 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2272 and `:post-blank' keywords."
2274 (let* ((case-fold-search nil
)
2276 (post-blank (let ((before-blank (progn (forward-line) (point))))
2277 (skip-chars-forward " \r\t\n" limit
)
2278 (skip-chars-backward " \t")
2279 (unless (bolp) (end-of-line))
2280 (count-lines before-blank
(point))))
2282 closed deadline scheduled
)
2284 (while (re-search-forward org-keyword-time-not-clock-regexp end t
)
2285 (goto-char (match-end 1))
2286 (skip-chars-forward " \t" end
)
2287 (let ((keyword (match-string 1))
2288 (time (org-element-timestamp-parser)))
2289 (cond ((equal keyword org-closed-string
) (setq closed time
))
2290 ((equal keyword org-deadline-string
) (setq deadline time
))
2291 (t (setq scheduled time
)))))
2293 (list :closed closed
2295 :scheduled scheduled
2298 :post-blank post-blank
)))))
2300 (defun org-element-planning-interpreter (planning contents
)
2301 "Interpret PLANNING element as Org syntax.
2306 (list (let ((deadline (org-element-property :deadline planning
)))
2308 (concat org-deadline-string
" "
2309 (org-element-timestamp-interpreter deadline nil
))))
2310 (let ((scheduled (org-element-property :scheduled planning
)))
2312 (concat org-scheduled-string
" "
2313 (org-element-timestamp-interpreter scheduled nil
))))
2314 (let ((closed (org-element-property :closed planning
)))
2316 (concat org-closed-string
" "
2317 (org-element-timestamp-interpreter closed nil
))))))
2323 (defun org-element-src-block-parser (limit affiliated
)
2326 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2327 the buffer position at the beginning of the first affiliated
2328 keyword and CDR is a plist of affiliated keywords along with
2331 Return a list whose CAR is `src-block' and CDR is a plist
2332 containing `:language', `:switches', `:parameters', `:begin',
2333 `:end', `:number-lines', `:retain-labels', `:use-labels',
2334 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2335 `:post-affiliated' keywords.
2337 Assume point is at the beginning of the block."
2338 (let ((case-fold-search t
))
2339 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2341 ;; Incomplete block: parse it as a paragraph.
2342 (org-element-paragraph-parser limit affiliated
)
2343 (let ((contents-end (match-beginning 0)))
2345 (let* ((begin (car affiliated
))
2346 (post-affiliated (point))
2347 ;; Get language as a string.
2351 (concat "^[ \t]*#\\+BEGIN_SRC"
2352 "\\(?: +\\(\\S-+\\)\\)?"
2353 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2355 (org-match-string-no-properties 1)))
2357 (switches (org-match-string-no-properties 2))
2359 (parameters (org-match-string-no-properties 3))
2360 ;; Switches analysis
2362 (cond ((not switches
) nil
)
2363 ((string-match "-n\\>" switches
) 'new
)
2364 ((string-match "+n\\>" switches
) 'continued
)))
2365 (preserve-indent (and switches
2366 (string-match "-i\\>" switches
)))
2369 (string-match "-l +\"\\([^\"\n]+\\)\"" switches
)
2370 (match-string 1 switches
)))
2371 ;; Should labels be retained in (or stripped from)
2375 (not (string-match "-r\\>" switches
))
2376 (and number-lines
(string-match "-k\\>" switches
))))
2377 ;; What should code-references use - labels or
2382 (not (string-match "-k\\>" switches
)))))
2384 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2386 (value (org-element-remove-indentation
2387 (org-unescape-code-in-string
2388 (buffer-substring-no-properties
2389 (progn (forward-line) (point)) contents-end
))
2391 (pos-before-blank (progn (goto-char contents-end
)
2394 ;; Get position after ending blank lines.
2395 (end (progn (skip-chars-forward " \r\t\n" limit
)
2396 (if (eobp) (point) (line-beginning-position)))))
2399 (list :language language
2400 :switches
(and (org-string-nw-p switches
)
2401 (org-trim switches
))
2402 :parameters
(and (org-string-nw-p parameters
)
2403 (org-trim parameters
))
2406 :number-lines number-lines
2407 :preserve-indent preserve-indent
2408 :retain-labels retain-labels
2409 :use-labels use-labels
2410 :label-fmt label-fmt
2412 :post-blank
(count-lines pos-before-blank end
)
2413 :post-affiliated post-affiliated
)
2414 (cdr affiliated
)))))))))
2416 (defun org-element-src-block-interpreter (src-block contents
)
2417 "Interpret SRC-BLOCK element as Org syntax.
2419 (let ((lang (org-element-property :language src-block
))
2420 (switches (org-element-property :switches src-block
))
2421 (params (org-element-property :parameters src-block
))
2423 (let ((val (org-element-property :value src-block
)))
2425 ((or org-src-preserve-indentation
2426 (org-element-property :preserve-indent src-block
))
2428 ((zerop org-edit-src-content-indentation
) val
)
2430 (let ((ind (make-string org-edit-src-content-indentation ?\s
)))
2431 (replace-regexp-in-string
2432 "\\(^\\)[ \t]*\\S-" ind val nil nil
1)))))))
2433 (concat (format "#+BEGIN_SRC%s\n"
2434 (concat (and lang
(concat " " lang
))
2435 (and switches
(concat " " switches
))
2436 (and params
(concat " " params
))))
2437 (org-escape-code-in-string value
)
2443 (defun org-element-table-parser (limit affiliated
)
2444 "Parse a table at point.
2446 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2447 the buffer position at the beginning of the first affiliated
2448 keyword and CDR is a plist of affiliated keywords along with
2451 Return a list whose CAR is `table' and CDR is a plist containing
2452 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2453 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2456 Assume point is at the beginning of the table."
2458 (let* ((case-fold-search t
)
2459 (table-begin (point))
2460 (type (if (org-at-table.el-p
) 'table.el
'org
))
2461 (begin (car affiliated
))
2463 (if (re-search-forward org-table-any-border-regexp limit
'm
)
2464 (goto-char (match-beginning 0))
2467 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2468 (push (org-match-string-no-properties 1) acc
)
2471 (pos-before-blank (point))
2472 (end (progn (skip-chars-forward " \r\t\n" limit
)
2473 (if (eobp) (point) (line-beginning-position)))))
2480 ;; Only `org' tables have contents. `table.el' tables
2481 ;; use a `:value' property to store raw table as
2483 :contents-begin
(and (eq type
'org
) table-begin
)
2484 :contents-end
(and (eq type
'org
) table-end
)
2485 :value
(and (eq type
'table.el
)
2486 (buffer-substring-no-properties
2487 table-begin table-end
))
2488 :post-blank
(count-lines pos-before-blank end
)
2489 :post-affiliated table-begin
)
2490 (cdr affiliated
))))))
2492 (defun org-element-table-interpreter (table contents
)
2493 "Interpret TABLE element as Org syntax.
2495 (if (eq (org-element-property :type table
) 'table.el
)
2496 (org-remove-indentation (org-element-property :value table
))
2497 (concat (with-temp-buffer (insert contents
)
2500 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm
))
2501 (reverse (org-element-property :tblfm table
))
2507 (defun org-element-table-row-parser (limit)
2508 "Parse table row at point.
2510 LIMIT bounds the search.
2512 Return a list whose CAR is `table-row' and CDR is a plist
2513 containing `:begin', `:end', `:contents-begin', `:contents-end',
2514 `:type' and `:post-blank' keywords."
2516 (let* ((type (if (looking-at "^[ \t]*|-") 'rule
'standard
))
2518 ;; A table rule has no contents. In that case, ensure
2519 ;; CONTENTS-BEGIN matches CONTENTS-END.
2520 (contents-begin (and (eq type
'standard
)
2521 (search-forward "|")
2523 (contents-end (and (eq type
'standard
)
2526 (skip-chars-backward " \t")
2528 (end (progn (forward-line) (point))))
2533 :contents-begin contents-begin
2534 :contents-end contents-end
2537 (defun org-element-table-row-interpreter (table-row contents
)
2538 "Interpret TABLE-ROW element as Org syntax.
2539 CONTENTS is the contents of the table row."
2540 (if (eq (org-element-property :type table-row
) 'rule
) "|-"
2541 (concat "| " contents
)))
2546 (defun org-element-verse-block-parser (limit affiliated
)
2547 "Parse a verse block.
2549 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2550 the buffer position at the beginning of the first affiliated
2551 keyword and CDR is a plist of affiliated keywords along with
2554 Return a list whose CAR is `verse-block' and CDR is a plist
2555 containing `:begin', `:end', `:contents-begin', `:contents-end',
2556 `:post-blank' and `:post-affiliated' keywords.
2558 Assume point is at beginning of the block."
2559 (let ((case-fold-search t
))
2560 (if (not (save-excursion
2561 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t
)))
2562 ;; Incomplete block: parse it as a paragraph.
2563 (org-element-paragraph-parser limit affiliated
)
2564 (let ((contents-end (match-beginning 0)))
2566 (let* ((begin (car affiliated
))
2567 (post-affiliated (point))
2568 (contents-begin (progn (forward-line) (point)))
2569 (pos-before-blank (progn (goto-char contents-end
)
2572 (end (progn (skip-chars-forward " \r\t\n" limit
)
2573 (if (eobp) (point) (line-beginning-position)))))
2578 :contents-begin contents-begin
2579 :contents-end contents-end
2580 :post-blank
(count-lines pos-before-blank end
)
2581 :post-affiliated post-affiliated
)
2582 (cdr affiliated
)))))))))
2584 (defun org-element-verse-block-interpreter (verse-block contents
)
2585 "Interpret VERSE-BLOCK element as Org syntax.
2586 CONTENTS is verse block contents."
2587 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents
))
2593 ;; Unlike to elements, raw text can be found between objects. Hence,
2594 ;; `org-element--object-lex' is provided to find the next object in
2597 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2598 ;; object types they can contain will be specified in
2599 ;; `org-element-object-restrictions'.
2601 ;; Creating a new type of object requires to alter
2602 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2603 ;; new type in `org-element-all-objects', and possibly add
2604 ;; restrictions in `org-element-object-restrictions'.
2608 (defun org-element-bold-parser ()
2609 "Parse bold object at point, if any.
2611 When at a bold object, return a list whose car is `bold' and cdr
2612 is a plist with `:begin', `:end', `:contents-begin' and
2613 `:contents-end' and `:post-blank' keywords. Otherwise, return
2616 Assume point is at the first star marker."
2618 (unless (bolp) (backward-char 1))
2619 (when (looking-at org-emph-re
)
2620 (let ((begin (match-beginning 2))
2621 (contents-begin (match-beginning 4))
2622 (contents-end (match-end 4))
2623 (post-blank (progn (goto-char (match-end 2))
2624 (skip-chars-forward " \t")))
2629 :contents-begin contents-begin
2630 :contents-end contents-end
2631 :post-blank post-blank
))))))
2633 (defun org-element-bold-interpreter (bold contents
)
2634 "Interpret BOLD object as Org syntax.
2635 CONTENTS is the contents of the object."
2636 (format "*%s*" contents
))
2641 (defun org-element-code-parser ()
2642 "Parse code object at point, if any.
2644 When at a code object, return a list whose car is `code' and cdr
2645 is a plist with `:value', `:begin', `:end' and `:post-blank'
2646 keywords. Otherwise, return nil.
2648 Assume point is at the first tilde marker."
2650 (unless (bolp) (backward-char 1))
2651 (when (looking-at org-emph-re
)
2652 (let ((begin (match-beginning 2))
2653 (value (org-match-string-no-properties 4))
2654 (post-blank (progn (goto-char (match-end 2))
2655 (skip-chars-forward " \t")))
2661 :post-blank post-blank
))))))
2663 (defun org-element-code-interpreter (code contents
)
2664 "Interpret CODE object as Org syntax.
2666 (format "~%s~" (org-element-property :value code
)))
2671 (defun org-element-entity-parser ()
2672 "Parse entity at point, if any.
2674 When at an entity, return a list whose car is `entity' and cdr
2675 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2676 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2677 `:post-blank' as keywords. Otherwise, return nil.
2679 Assume point is at the beginning of the entity."
2681 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2683 (let* ((value (or (org-entity-get (match-string 1))
2684 (throw 'no-object nil
)))
2685 (begin (match-beginning 0))
2686 (bracketsp (string= (match-string 2) "{}"))
2687 (post-blank (progn (goto-char (match-end 1))
2688 (when bracketsp
(forward-char 2))
2689 (skip-chars-forward " \t")))
2692 (list :name
(car value
)
2693 :latex
(nth 1 value
)
2694 :latex-math-p
(nth 2 value
)
2696 :ascii
(nth 4 value
)
2697 :latin1
(nth 5 value
)
2698 :utf-8
(nth 6 value
)
2701 :use-brackets-p bracketsp
2702 :post-blank post-blank
)))))))
2704 (defun org-element-entity-interpreter (entity contents
)
2705 "Interpret ENTITY object as Org syntax.
2708 (org-element-property :name entity
)
2709 (when (org-element-property :use-brackets-p entity
) "{}")))
2714 (defun org-element-export-snippet-parser ()
2715 "Parse export snippet at point.
2717 When at an export snippet, return a list whose car is
2718 `export-snippet' and cdr a plist with `:begin', `:end',
2719 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2722 Assume point is at the beginning of the snippet."
2725 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2727 (save-match-data (goto-char (match-end 0))
2728 (re-search-forward "@@" nil t
)
2729 (match-beginning 0))))
2730 (let* ((begin (match-beginning 0))
2731 (back-end (org-match-string-no-properties 1))
2732 (value (buffer-substring-no-properties
2733 (match-end 0) contents-end
))
2734 (post-blank (skip-chars-forward " \t"))
2736 (list 'export-snippet
2737 (list :back-end back-end
2741 :post-blank post-blank
)))))))
2743 (defun org-element-export-snippet-interpreter (export-snippet contents
)
2744 "Interpret EXPORT-SNIPPET object as Org syntax.
2747 (org-element-property :back-end export-snippet
)
2748 (org-element-property :value export-snippet
)))
2751 ;;;; Footnote Reference
2753 (defun org-element-footnote-reference-parser ()
2754 "Parse footnote reference at point, if any.
2756 When at a footnote reference, return a list whose car is
2757 `footnote-reference' and cdr a plist with `:label', `:type',
2758 `:inline-definition', `:begin', `:end' and `:post-blank' as
2759 keywords. Otherwise, return nil."
2761 (when (looking-at org-footnote-re
)
2763 (let* ((begin (point))
2764 (label (or (org-match-string-no-properties 2)
2765 (org-match-string-no-properties 3)
2766 (and (match-string 1)
2767 (concat "fn:" (org-match-string-no-properties 1)))))
2768 (type (if (or (not label
) (match-string 1)) 'inline
'standard
))
2769 (inner-begin (match-end 0))
2773 (while (and (> count
0) (re-search-forward "[][]" nil t
))
2774 (if (equal (match-string 0) "[") (incf count
) (decf count
)))
2775 (unless (zerop count
) (throw 'no-object nil
))
2777 (post-blank (progn (goto-char (1+ inner-end
))
2778 (skip-chars-forward " \t")))
2781 (list 'footnote-reference
2786 :post-blank post-blank
))))
2787 (org-element-put-property
2788 footnote-reference
:inline-definition
2789 (and (eq type
'inline
)
2790 (org-element-parse-secondary-string
2791 (buffer-substring inner-begin inner-end
)
2792 (org-element-restriction 'footnote-reference
)
2793 footnote-reference
))))))))
2795 (defun org-element-footnote-reference-interpreter (footnote-reference contents
)
2796 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2798 (let ((label (or (org-element-property :label footnote-reference
) "fn:"))
2801 (org-element-property :inline-definition footnote-reference
)))
2802 (if (not inline-def
) ""
2803 (concat ":" (org-element-interpret-data inline-def
))))))
2804 (format "[%s]" (concat label def
))))
2807 ;;;; Inline Babel Call
2809 (defun org-element-inline-babel-call-parser ()
2810 "Parse inline babel call at point, if any.
2812 When at an inline babel call, return a list whose car is
2813 `inline-babel-call' and cdr a plist with `:begin', `:end',
2814 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2816 Assume point is at the beginning of the babel call."
2818 (unless (bolp) (backward-char))
2819 (when (let ((case-fold-search t
))
2820 (looking-at org-babel-inline-lob-one-liner-regexp
))
2821 (let ((begin (match-end 1))
2822 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2823 (post-blank (progn (goto-char (match-end 0))
2824 (skip-chars-forward " \t")))
2826 (list 'inline-babel-call
2830 :post-blank post-blank
))))))
2832 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents
)
2833 "Interpret INLINE-BABEL-CALL object as Org syntax.
2835 (org-element-property :value inline-babel-call
))
2838 ;;;; Inline Src Block
2840 (defun org-element-inline-src-block-parser ()
2841 "Parse inline source block at point, if any.
2843 When at an inline source block, return a list whose car is
2844 `inline-src-block' and cdr a plist with `:begin', `:end',
2845 `:language', `:value', `:parameters' and `:post-blank' as
2846 keywords. Otherwise, return nil.
2848 Assume point is at the beginning of the inline src block."
2850 (unless (bolp) (backward-char))
2851 (when (looking-at org-babel-inline-src-block-regexp
)
2852 (let ((begin (match-beginning 1))
2853 (language (org-match-string-no-properties 2))
2854 (parameters (org-match-string-no-properties 4))
2855 (value (org-match-string-no-properties 5))
2856 (post-blank (progn (goto-char (match-end 0))
2857 (skip-chars-forward " \t")))
2859 (list 'inline-src-block
2860 (list :language language
2862 :parameters parameters
2865 :post-blank post-blank
))))))
2867 (defun org-element-inline-src-block-interpreter (inline-src-block contents
)
2868 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2870 (let ((language (org-element-property :language inline-src-block
))
2871 (arguments (org-element-property :parameters inline-src-block
))
2872 (body (org-element-property :value inline-src-block
)))
2873 (format "src_%s%s{%s}"
2875 (if arguments
(format "[%s]" arguments
) "")
2880 (defun org-element-italic-parser ()
2881 "Parse italic object at point, if any.
2883 When at an italic object, return a list whose car is `italic' and
2884 cdr is a plist with `:begin', `:end', `:contents-begin' and
2885 `:contents-end' and `:post-blank' keywords. Otherwise, return
2888 Assume point is at the first slash marker."
2890 (unless (bolp) (backward-char 1))
2891 (when (looking-at org-emph-re
)
2892 (let ((begin (match-beginning 2))
2893 (contents-begin (match-beginning 4))
2894 (contents-end (match-end 4))
2895 (post-blank (progn (goto-char (match-end 2))
2896 (skip-chars-forward " \t")))
2901 :contents-begin contents-begin
2902 :contents-end contents-end
2903 :post-blank post-blank
))))))
2905 (defun org-element-italic-interpreter (italic contents
)
2906 "Interpret ITALIC object as Org syntax.
2907 CONTENTS is the contents of the object."
2908 (format "/%s/" contents
))
2913 (defun org-element-latex-fragment-parser ()
2914 "Parse LaTeX fragment at point, if any.
2916 When at a LaTeX fragment, return a list whose car is
2917 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2918 and `:post-blank' as keywords. Otherwise, return nil.
2920 Assume point is at the beginning of the LaTeX fragment."
2923 (let* ((begin (point))
2926 (dolist (e (cdr org-latex-regexps
))
2927 (let ((latex-regexp (nth 1 e
)))
2928 (when (or (looking-at latex-regexp
)
2932 (looking-at latex-regexp
))))
2933 (throw 'exit
(nth 2 e
))))))
2935 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2937 ;; No fragment found.
2938 (throw 'no-object nil
)))
2939 (value (org-match-string-no-properties substring-match
))
2940 (post-blank (progn (goto-char (match-end substring-match
))
2941 (skip-chars-forward " \t")))
2943 (list 'latex-fragment
2947 :post-blank post-blank
))))))
2949 (defun org-element-latex-fragment-interpreter (latex-fragment contents
)
2950 "Interpret LATEX-FRAGMENT object as Org syntax.
2952 (org-element-property :value latex-fragment
))
2956 (defun org-element-line-break-parser ()
2957 "Parse line break at point, if any.
2959 When at a line break, return a list whose car is `line-break',
2960 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2961 Otherwise, return nil.
2963 Assume point is at the beginning of the line break."
2964 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2965 (not (eq (char-before) ?
\\)))
2967 (list :begin
(point)
2968 :end
(progn (forward-line) (point))
2971 (defun org-element-line-break-interpreter (line-break contents
)
2972 "Interpret LINE-BREAK object as Org syntax.
2979 (defun org-element-link-parser ()
2980 "Parse link at point, if any.
2982 When at a link, return a list whose car is `link' and cdr a plist
2983 with `:type', `:path', `:raw-link', `:application',
2984 `:search-option', `:begin', `:end', `:contents-begin',
2985 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2988 Assume point is at the beginning of the link."
2990 (let ((begin (point))
2991 end contents-begin contents-end link-end post-blank path type
2992 raw-link link search-option application
)
2994 ;; Type 1: Text targeted from a radio target.
2995 ((and org-target-link-regexp
2996 (save-excursion (or (bolp) (backward-char))
2997 (looking-at org-target-link-regexp
)))
2999 link-end
(match-end 1)
3000 path
(org-match-string-no-properties 1)
3001 contents-begin
(match-beginning 1)
3002 contents-end
(match-end 1)))
3003 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3004 ((looking-at org-bracket-link-regexp
)
3005 (setq contents-begin
(match-beginning 3)
3006 contents-end
(match-end 3)
3007 link-end
(match-end 0)
3008 ;; RAW-LINK is the original link. Expand any
3009 ;; abbreviation in it.
3010 raw-link
(org-translate-link
3011 (org-link-expand-abbrev
3012 (org-match-string-no-properties 1))))
3013 ;; Determine TYPE of link and set PATH accordingly.
3016 ((or (file-name-absolute-p raw-link
)
3017 (string-match "^\\.\\.?/" raw-link
))
3018 (setq type
"file" path raw-link
))
3019 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3020 ((string-match org-link-re-with-space3 raw-link
)
3021 (setq type
(match-string 1 raw-link
) path
(match-string 2 raw-link
)))
3022 ;; Id type: PATH is the id.
3023 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link
)
3024 (setq type
"id" path
(match-string 1 raw-link
)))
3025 ;; Code-ref type: PATH is the name of the reference.
3026 ((string-match "^(\\(.*\\))$" raw-link
)
3027 (setq type
"coderef" path
(match-string 1 raw-link
)))
3028 ;; Custom-id type: PATH is the name of the custom id.
3029 ((= (aref raw-link
0) ?
#)
3030 (setq type
"custom-id" path
(substring raw-link
1)))
3031 ;; Fuzzy type: Internal link either matches a target, an
3032 ;; headline name or nothing. PATH is the target or
3034 (t (setq type
"fuzzy" path raw-link
))))
3035 ;; Type 3: Plain link, e.g., http://orgmode.org
3036 ((looking-at org-plain-link-re
)
3037 (setq raw-link
(org-match-string-no-properties 0)
3038 type
(org-match-string-no-properties 1)
3039 link-end
(match-end 0)
3040 path
(org-match-string-no-properties 2)))
3041 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3042 ((looking-at org-angle-link-re
)
3043 (setq raw-link
(buffer-substring-no-properties
3044 (match-beginning 1) (match-end 2))
3045 type
(org-match-string-no-properties 1)
3046 link-end
(match-end 0)
3047 path
(org-match-string-no-properties 2)))
3048 (t (throw 'no-object nil
)))
3049 ;; In any case, deduce end point after trailing white space from
3050 ;; LINK-END variable.
3052 (setq post-blank
(progn (goto-char link-end
) (skip-chars-forward " \t"))
3054 ;; Special "file" type link processing.
3055 (when (member type org-element-link-type-is-file
)
3056 ;; Extract opening application and search option.
3057 (cond ((string-match "^file\\+\\(.*\\)$" type
)
3058 (setq application
(match-string 1 type
)))
3059 ((not (string-match "^file" type
))
3060 (setq application type
)))
3061 (when (string-match "::\\(.*\\)\\'" path
)
3062 (setq search-option
(match-string 1 path
)
3063 path
(replace-match "" nil nil path
)))
3065 (when (and (file-name-absolute-p path
)
3066 (not (org-string-match-p "\\`[/~]/" path
)))
3067 (setq path
(concat "//" path
)))
3068 ;; Make sure TYPE always reports "file".
3073 :raw-link
(or raw-link path
)
3074 :application application
3075 :search-option search-option
3078 :contents-begin contents-begin
3079 :contents-end contents-end
3080 :post-blank post-blank
))))))
3082 (defun org-element-link-interpreter (link contents
)
3083 "Interpret LINK object as Org syntax.
3084 CONTENTS is the contents of the object, or nil."
3085 (let ((type (org-element-property :type link
))
3086 (raw-link (org-element-property :raw-link link
)))
3087 (if (string= type
"radio") raw-link
3090 (if contents
(format "[%s]" contents
) "")))))
3095 (defun org-element-macro-parser ()
3096 "Parse macro at point, if any.
3098 When at a macro, return a list whose car is `macro' and cdr
3099 a plist with `:key', `:args', `:begin', `:end', `:value' and
3100 `:post-blank' as keywords. Otherwise, return nil.
3102 Assume point is at the macro."
3104 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3105 (let ((begin (point))
3106 (key (downcase (org-match-string-no-properties 1)))
3107 (value (org-match-string-no-properties 0))
3108 (post-blank (progn (goto-char (match-end 0))
3109 (skip-chars-forward " \t")))
3111 (args (let ((args (org-match-string-no-properties 3)))
3113 ;; Do not use `org-split-string' since empty
3114 ;; strings are meaningful here.
3116 (replace-regexp-in-string
3117 "\\(\\\\*\\)\\(,\\)"
3119 (let ((len (length (match-string 1 str
))))
3120 (concat (make-string (/ len
2) ?
\\)
3121 (if (zerop (mod len
2)) "\000" ","))))
3130 :post-blank post-blank
))))))
3132 (defun org-element-macro-interpreter (macro contents
)
3133 "Interpret MACRO object as Org syntax.
3135 (org-element-property :value macro
))
3140 (defun org-element-radio-target-parser ()
3141 "Parse radio target at point, if any.
3143 When at a radio target, return a list whose car is `radio-target'
3144 and cdr a plist with `:begin', `:end', `:contents-begin',
3145 `:contents-end', `:value' and `:post-blank' as keywords.
3146 Otherwise, return nil.
3148 Assume point is at the radio target."
3150 (when (looking-at org-radio-target-regexp
)
3151 (let ((begin (point))
3152 (contents-begin (match-beginning 1))
3153 (contents-end (match-end 1))
3154 (value (org-match-string-no-properties 1))
3155 (post-blank (progn (goto-char (match-end 0))
3156 (skip-chars-forward " \t")))
3161 :contents-begin contents-begin
3162 :contents-end contents-end
3163 :post-blank post-blank
3166 (defun org-element-radio-target-interpreter (target contents
)
3167 "Interpret TARGET object as Org syntax.
3168 CONTENTS is the contents of the object."
3169 (concat "<<<" contents
">>>"))
3172 ;;;; Statistics Cookie
3174 (defun org-element-statistics-cookie-parser ()
3175 "Parse statistics cookie at point, if any.
3177 When at a statistics cookie, return a list whose car is
3178 `statistics-cookie', and cdr a plist with `:begin', `:end',
3179 `:value' and `:post-blank' keywords. Otherwise, return nil.
3181 Assume point is at the beginning of the statistics-cookie."
3183 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3184 (let* ((begin (point))
3185 (value (buffer-substring-no-properties
3186 (match-beginning 0) (match-end 0)))
3187 (post-blank (progn (goto-char (match-end 0))
3188 (skip-chars-forward " \t")))
3190 (list 'statistics-cookie
3194 :post-blank post-blank
))))))
3196 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents
)
3197 "Interpret STATISTICS-COOKIE object as Org syntax.
3199 (org-element-property :value statistics-cookie
))
3204 (defun org-element-strike-through-parser ()
3205 "Parse strike-through object at point, if any.
3207 When at a strike-through object, return a list whose car is
3208 `strike-through' and cdr is a plist with `:begin', `:end',
3209 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3210 Otherwise, return nil.
3212 Assume point is at the first plus sign marker."
3214 (unless (bolp) (backward-char 1))
3215 (when (looking-at org-emph-re
)
3216 (let ((begin (match-beginning 2))
3217 (contents-begin (match-beginning 4))
3218 (contents-end (match-end 4))
3219 (post-blank (progn (goto-char (match-end 2))
3220 (skip-chars-forward " \t")))
3222 (list 'strike-through
3225 :contents-begin contents-begin
3226 :contents-end contents-end
3227 :post-blank post-blank
))))))
3229 (defun org-element-strike-through-interpreter (strike-through contents
)
3230 "Interpret STRIKE-THROUGH object as Org syntax.
3231 CONTENTS is the contents of the object."
3232 (format "+%s+" contents
))
3237 (defun org-element-subscript-parser ()
3238 "Parse subscript at point, if any.
3240 When at a subscript object, return a list whose car is
3241 `subscript' and cdr a plist with `:begin', `:end',
3242 `:contents-begin', `:contents-end', `:use-brackets-p' and
3243 `:post-blank' as keywords. Otherwise, return nil.
3245 Assume point is at the underscore."
3247 (unless (bolp) (backward-char))
3248 (when (looking-at org-match-substring-regexp
)
3249 (let ((bracketsp (match-beginning 4))
3250 (begin (match-beginning 2))
3251 (contents-begin (or (match-beginning 4)
3252 (match-beginning 3)))
3253 (contents-end (or (match-end 4) (match-end 3)))
3254 (post-blank (progn (goto-char (match-end 0))
3255 (skip-chars-forward " \t")))
3260 :use-brackets-p bracketsp
3261 :contents-begin contents-begin
3262 :contents-end contents-end
3263 :post-blank post-blank
))))))
3265 (defun org-element-subscript-interpreter (subscript contents
)
3266 "Interpret SUBSCRIPT object as Org syntax.
3267 CONTENTS is the contents of the object."
3269 (if (org-element-property :use-brackets-p subscript
) "_{%s}" "_%s")
3275 (defun org-element-superscript-parser ()
3276 "Parse superscript at point, if any.
3278 When at a superscript object, return a list whose car is
3279 `superscript' and cdr a plist with `:begin', `:end',
3280 `:contents-begin', `:contents-end', `:use-brackets-p' and
3281 `:post-blank' as keywords. Otherwise, return nil.
3283 Assume point is at the caret."
3285 (unless (bolp) (backward-char))
3286 (when (looking-at org-match-substring-regexp
)
3287 (let ((bracketsp (match-beginning 4))
3288 (begin (match-beginning 2))
3289 (contents-begin (or (match-beginning 4)
3290 (match-beginning 3)))
3291 (contents-end (or (match-end 4) (match-end 3)))
3292 (post-blank (progn (goto-char (match-end 0))
3293 (skip-chars-forward " \t")))
3298 :use-brackets-p bracketsp
3299 :contents-begin contents-begin
3300 :contents-end contents-end
3301 :post-blank post-blank
))))))
3303 (defun org-element-superscript-interpreter (superscript contents
)
3304 "Interpret SUPERSCRIPT object as Org syntax.
3305 CONTENTS is the contents of the object."
3307 (if (org-element-property :use-brackets-p superscript
) "^{%s}" "^%s")
3313 (defun org-element-table-cell-parser ()
3314 "Parse table cell at point.
3315 Return a list whose car is `table-cell' and cdr is a plist
3316 containing `:begin', `:end', `:contents-begin', `:contents-end'
3317 and `:post-blank' keywords."
3318 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3319 (let* ((begin (match-beginning 0))
3321 (contents-begin (match-beginning 1))
3322 (contents-end (match-end 1)))
3326 :contents-begin contents-begin
3327 :contents-end contents-end
3330 (defun org-element-table-cell-interpreter (table-cell contents
)
3331 "Interpret TABLE-CELL element as Org syntax.
3332 CONTENTS is the contents of the cell, or nil."
3333 (concat " " contents
" |"))
3338 (defun org-element-target-parser ()
3339 "Parse target at point, if any.
3341 When at a target, return a list whose car is `target' and cdr
3342 a plist with `:begin', `:end', `:value' and `:post-blank' as
3343 keywords. Otherwise, return nil.
3345 Assume point is at the target."
3347 (when (looking-at org-target-regexp
)
3348 (let ((begin (point))
3349 (value (org-match-string-no-properties 1))
3350 (post-blank (progn (goto-char (match-end 0))
3351 (skip-chars-forward " \t")))
3357 :post-blank post-blank
))))))
3359 (defun org-element-target-interpreter (target contents
)
3360 "Interpret TARGET object as Org syntax.
3362 (format "<<%s>>" (org-element-property :value target
)))
3367 (defconst org-element--timestamp-regexp
3368 (concat org-ts-regexp-both
3370 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3372 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3373 "Regexp matching any timestamp type object.")
3375 (defun org-element-timestamp-parser ()
3376 "Parse time stamp at point, if any.
3378 When at a time stamp, return a list whose car is `timestamp', and
3379 cdr a plist with `:type', `:raw-value', `:year-start',
3380 `:month-start', `:day-start', `:hour-start', `:minute-start',
3381 `:year-end', `:month-end', `:day-end', `:hour-end',
3382 `:minute-end', `:repeater-type', `:repeater-value',
3383 `:repeater-unit', `:warning-type', `:warning-value',
3384 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3385 Otherwise, return nil.
3387 Assume point is at the beginning of the timestamp."
3388 (when (org-looking-at-p org-element--timestamp-regexp
)
3390 (let* ((begin (point))
3391 (activep (eq (char-after) ?
<))
3394 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3395 (match-string-no-properties 0)))
3396 (date-start (match-string-no-properties 1))
3397 (date-end (match-string 3))
3398 (diaryp (match-beginning 2))
3399 (post-blank (progn (goto-char (match-end 0))
3400 (skip-chars-forward " \t")))
3405 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3407 (cons (string-to-number (match-string 2 date-start
))
3408 (string-to-number (match-string 3 date-start
)))))
3409 (type (cond (diaryp 'diary
)
3410 ((and activep
(or date-end time-range
)) 'active-range
)
3412 ((or date-end time-range
) 'inactive-range
)
3416 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3420 (let ((type (match-string 1 raw-value
)))
3421 (cond ((equal "++" type
) 'catch-up
)
3422 ((equal ".+" type
) 'restart
)
3424 :repeater-value
(string-to-number (match-string 2 raw-value
))
3426 (case (string-to-char (match-string 3 raw-value
))
3427 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3430 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value
)
3432 :warning-type
(if (match-string 1 raw-value
) 'first
'all
)
3433 :warning-value
(string-to-number (match-string 2 raw-value
))
3435 (case (string-to-char (match-string 3 raw-value
))
3436 (?h
'hour
) (?d
'day
) (?w
'week
) (?m
'month
) (t 'year
)))))
3437 year-start month-start day-start hour-start minute-start year-end
3438 month-end day-end hour-end minute-end
)
3439 ;; Parse date-start.
3441 (let ((date (org-parse-time-string date-start t
)))
3442 (setq year-start
(nth 5 date
)
3443 month-start
(nth 4 date
)
3444 day-start
(nth 3 date
)
3445 hour-start
(nth 2 date
)
3446 minute-start
(nth 1 date
))))
3447 ;; Compute date-end. It can be provided directly in time-stamp,
3448 ;; or extracted from time range. Otherwise, it defaults to the
3449 ;; same values as date-start.
3451 (let ((date (and date-end
(org-parse-time-string date-end t
))))
3452 (setq year-end
(or (nth 5 date
) year-start
)
3453 month-end
(or (nth 4 date
) month-start
)
3454 day-end
(or (nth 3 date
) day-start
)
3455 hour-end
(or (nth 2 date
) (car time-range
) hour-start
)
3456 minute-end
(or (nth 1 date
) (cdr time-range
) minute-start
))))
3458 (nconc (list :type type
3459 :raw-value raw-value
3460 :year-start year-start
3461 :month-start month-start
3462 :day-start day-start
3463 :hour-start hour-start
3464 :minute-start minute-start
3466 :month-end month-end
3469 :minute-end minute-end
3472 :post-blank post-blank
)
3476 (defun org-element-timestamp-interpreter (timestamp contents
)
3477 "Interpret TIMESTAMP object as Org syntax.
3479 (let* ((repeat-string
3481 (case (org-element-property :repeater-type timestamp
)
3482 (cumulate "+") (catch-up "++") (restart ".+"))
3483 (let ((val (org-element-property :repeater-value timestamp
)))
3484 (and val
(number-to-string val
)))
3485 (case (org-element-property :repeater-unit timestamp
)
3486 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3489 (case (org-element-property :warning-type timestamp
)
3492 (let ((val (org-element-property :warning-value timestamp
)))
3493 (and val
(number-to-string val
)))
3494 (case (org-element-property :warning-unit timestamp
)
3495 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3497 ;; Build an Org timestamp string from TIME. ACTIVEP is
3498 ;; non-nil when time stamp is active. If WITH-TIME-P is
3499 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3500 ;; specify a time range in the timestamp. REPEAT-STRING is
3501 ;; the repeater string, if any.
3502 (lambda (time activep
&optional with-time-p hour-end minute-end
)
3503 (let ((ts (format-time-string
3504 (funcall (if with-time-p
'cdr
'car
)
3505 org-time-stamp-formats
)
3507 (when (and hour-end minute-end
)
3508 (string-match "[012]?[0-9]:[0-5][0-9]" ts
)
3511 (format "\\&-%02d:%02d" hour-end minute-end
)
3513 (unless activep
(setq ts
(format "[%s]" (substring ts
1 -
1))))
3514 (dolist (s (list repeat-string warning-string
))
3515 (when (org-string-nw-p s
)
3516 (setq ts
(concat (substring ts
0 -
1)
3519 (substring ts -
1)))))
3522 (type (org-element-property :type timestamp
)))
3525 (let* ((minute-start (org-element-property :minute-start timestamp
))
3526 (minute-end (org-element-property :minute-end timestamp
))
3527 (hour-start (org-element-property :hour-start timestamp
))
3528 (hour-end (org-element-property :hour-end timestamp
))
3529 (time-range-p (and hour-start hour-end minute-start minute-end
3530 (or (/= hour-start hour-end
)
3531 (/= minute-start minute-end
)))))
3537 (org-element-property :day-start timestamp
)
3538 (org-element-property :month-start timestamp
)
3539 (org-element-property :year-start timestamp
))
3541 (and hour-start minute-start
)
3542 (and time-range-p hour-end
)
3543 (and time-range-p minute-end
))))
3544 ((active-range inactive-range
)
3545 (let ((minute-start (org-element-property :minute-start timestamp
))
3546 (minute-end (org-element-property :minute-end timestamp
))
3547 (hour-start (org-element-property :hour-start timestamp
))
3548 (hour-end (org-element-property :hour-end timestamp
)))
3551 build-ts-string
(encode-time
3555 (org-element-property :day-start timestamp
)
3556 (org-element-property :month-start timestamp
)
3557 (org-element-property :year-start timestamp
))
3558 (eq type
'active-range
)
3559 (and hour-start minute-start
))
3561 (funcall build-ts-string
3565 (org-element-property :day-end timestamp
)
3566 (org-element-property :month-end timestamp
)
3567 (org-element-property :year-end timestamp
))
3568 (eq type
'active-range
)
3569 (and hour-end minute-end
))))))))
3574 (defun org-element-underline-parser ()
3575 "Parse underline object at point, if any.
3577 When at an underline object, return a list whose car is
3578 `underline' and cdr is a plist with `:begin', `:end',
3579 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3580 Otherwise, return nil.
3582 Assume point is at the first underscore marker."
3584 (unless (bolp) (backward-char 1))
3585 (when (looking-at org-emph-re
)
3586 (let ((begin (match-beginning 2))
3587 (contents-begin (match-beginning 4))
3588 (contents-end (match-end 4))
3589 (post-blank (progn (goto-char (match-end 2))
3590 (skip-chars-forward " \t")))
3595 :contents-begin contents-begin
3596 :contents-end contents-end
3597 :post-blank post-blank
))))))
3599 (defun org-element-underline-interpreter (underline contents
)
3600 "Interpret UNDERLINE object as Org syntax.
3601 CONTENTS is the contents of the object."
3602 (format "_%s_" contents
))
3607 (defun org-element-verbatim-parser ()
3608 "Parse verbatim object at point, if any.
3610 When at a verbatim object, return a list whose car is `verbatim'
3611 and cdr is a plist with `:value', `:begin', `:end' and
3612 `:post-blank' keywords. Otherwise, return nil.
3614 Assume point is at the first equal sign marker."
3616 (unless (bolp) (backward-char 1))
3617 (when (looking-at org-emph-re
)
3618 (let ((begin (match-beginning 2))
3619 (value (org-match-string-no-properties 4))
3620 (post-blank (progn (goto-char (match-end 2))
3621 (skip-chars-forward " \t")))
3627 :post-blank post-blank
))))))
3629 (defun org-element-verbatim-interpreter (verbatim contents
)
3630 "Interpret VERBATIM object as Org syntax.
3632 (format "=%s=" (org-element-property :value verbatim
)))
3636 ;;; Parsing Element Starting At Point
3638 ;; `org-element--current-element' is the core function of this section.
3639 ;; It returns the Lisp representation of the element starting at
3642 ;; `org-element--current-element' makes use of special modes. They
3643 ;; are activated for fixed element chaining (e.g., `plain-list' >
3644 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3645 ;; `section'). Special modes are: `first-section', `item',
3646 ;; `node-property', `section' and `table-row'.
3648 (defun org-element--current-element
3649 (limit &optional granularity special structure
)
3650 "Parse the element starting at point.
3652 Return value is a list like (TYPE PROPS) where TYPE is the type
3653 of the element and PROPS a plist of properties associated to the
3656 Possible types are defined in `org-element-all-elements'.
3658 LIMIT bounds the search.
3660 Optional argument GRANULARITY determines the depth of the
3661 recursion. Allowed values are `headline', `greater-element',
3662 `element', `object' or nil. When it is broader than `object' (or
3663 nil), secondary values will not be parsed, since they only
3666 Optional argument SPECIAL, when non-nil, can be either
3667 `first-section', `item', `node-property', `section', and
3670 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3673 This function assumes point is always at the beginning of the
3674 element it has to parse."
3676 (let ((case-fold-search t
)
3677 ;; Determine if parsing depth allows for secondary strings
3678 ;; parsing. It only applies to elements referenced in
3679 ;; `org-element-secondary-value-alist'.
3680 (raw-secondary-p (and granularity
(not (eq granularity
'object
)))))
3684 (org-element-item-parser limit structure raw-secondary-p
))
3686 ((eq special
'table-row
) (org-element-table-row-parser limit
))
3688 ((eq special
'node-property
) (org-element-node-property-parser limit
))
3690 ((org-with-limited-levels (org-at-heading-p))
3691 (org-element-headline-parser limit raw-secondary-p
))
3692 ;; Sections (must be checked after headline).
3693 ((eq special
'section
) (org-element-section-parser limit
))
3694 ((eq special
'first-section
)
3695 (org-element-section-parser
3696 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3698 ;; When not at bol, point is at the beginning of an item or
3699 ;; a footnote definition: next item is always a paragraph.
3700 ((not (bolp)) (org-element-paragraph-parser limit
(list (point))))
3701 ;; Planning and Clock.
3702 ((looking-at org-planning-or-clock-line-re
)
3703 (if (equal (match-string 1) org-clock-string
)
3704 (org-element-clock-parser limit
)
3705 (org-element-planning-parser limit
)))
3708 (org-element-inlinetask-parser limit raw-secondary-p
))
3709 ;; From there, elements can have affiliated keywords.
3710 (t (let ((affiliated (org-element--collect-affiliated-keywords limit
)))
3712 ;; Jumping over affiliated keywords put point off-limits.
3713 ;; Parse them as regular keywords.
3714 ((and (cdr affiliated
) (>= (point) limit
))
3715 (goto-char (car affiliated
))
3716 (org-element-keyword-parser limit nil
))
3717 ;; LaTeX Environment.
3719 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3720 (org-element-latex-environment-parser limit affiliated
))
3721 ;; Drawer and Property Drawer.
3722 ((looking-at org-drawer-regexp
)
3723 (if (equal (match-string 1) "PROPERTIES")
3724 (org-element-property-drawer-parser limit affiliated
)
3725 (org-element-drawer-parser limit affiliated
)))
3727 ((looking-at "[ \t]*:\\( \\|$\\)")
3728 (org-element-fixed-width-parser limit affiliated
))
3729 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3731 ((looking-at "[ \t]*#")
3732 (goto-char (match-end 0))
3733 (cond ((looking-at "\\(?: \\|$\\)")
3735 (org-element-comment-parser limit affiliated
))
3736 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3738 (let ((parser (assoc (upcase (match-string 1))
3739 org-element-block-name-alist
)))
3740 (if parser
(funcall (cdr parser
) limit affiliated
)
3741 (org-element-special-block-parser limit affiliated
))))
3742 ((looking-at "\\+CALL:")
3744 (org-element-babel-call-parser limit affiliated
))
3745 ((looking-at "\\+BEGIN:? ")
3747 (org-element-dynamic-block-parser limit affiliated
))
3748 ((looking-at "\\+\\S-+:")
3750 (org-element-keyword-parser limit affiliated
))
3753 (org-element-paragraph-parser limit affiliated
))))
3754 ;; Footnote Definition.
3755 ((looking-at org-footnote-definition-re
)
3756 (org-element-footnote-definition-parser limit affiliated
))
3758 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3759 (org-element-horizontal-rule-parser limit affiliated
))
3762 (org-element-diary-sexp-parser limit affiliated
))
3764 ((org-at-table-p t
) (org-element-table-parser limit affiliated
))
3766 ((looking-at (org-item-re))
3767 (org-element-plain-list-parser
3769 (or structure
(org-element--list-struct limit
))))
3770 ;; Default element: Paragraph.
3771 (t (org-element-paragraph-parser limit affiliated
)))))))))
3774 ;; Most elements can have affiliated keywords. When looking for an
3775 ;; element beginning, we want to move before them, as they belong to
3776 ;; that element, and, in the meantime, collect information they give
3777 ;; into appropriate properties. Hence the following function.
3779 (defun org-element--collect-affiliated-keywords (limit)
3780 "Collect affiliated keywords from point down to LIMIT.
3782 Return a list whose CAR is the position at the first of them and
3783 CDR a plist of keywords and values and move point to the
3784 beginning of the first line after them.
3786 As a special case, if element doesn't start at the beginning of
3787 the line (e.g., a paragraph starting an item), CAR is current
3788 position of point and CDR is nil."
3789 (if (not (bolp)) (list (point))
3790 (let ((case-fold-search t
)
3792 ;; RESTRICT is the list of objects allowed in parsed
3794 (restrict (org-element-restriction 'keyword
))
3796 (while (and (< (point) limit
) (looking-at org-element--affiliated-re
))
3797 (let* ((raw-kwd (upcase (match-string 1)))
3798 ;; Apply translation to RAW-KWD. From there, KWD is
3799 ;; the official keyword.
3800 (kwd (or (cdr (assoc raw-kwd
3801 org-element-keyword-translation-alist
))
3803 ;; Find main value for any keyword.
3807 (buffer-substring-no-properties
3808 (match-end 0) (point-at-eol)))))
3809 ;; PARSEDP is non-nil when keyword should have its
3811 (parsedp (member kwd org-element-parsed-keywords
))
3812 ;; If KWD is a dual keyword, find its secondary
3813 ;; value. Maybe parse it.
3814 (dualp (member kwd org-element-dual-keywords
))
3817 (let ((sec (org-match-string-no-properties 2)))
3818 (if (or (not sec
) (not parsedp
)) sec
3819 (org-element-parse-secondary-string sec restrict
)))))
3820 ;; Attribute a property name to KWD.
3821 (kwd-sym (and kwd
(intern (concat ":" (downcase kwd
))))))
3822 ;; Now set final shape for VALUE.
3824 (setq value
(org-element-parse-secondary-string value restrict
)))
3826 (setq value
(and (or value dual-value
) (cons value dual-value
))))
3827 (when (or (member kwd org-element-multiple-keywords
)
3828 ;; Attributes can always appear on multiple lines.
3829 (string-match "^ATTR_" kwd
))
3830 (setq value
(cons value
(plist-get output kwd-sym
))))
3831 ;; Eventually store the new value in OUTPUT.
3832 (setq output
(plist-put output kwd-sym value
))
3833 ;; Move to next keyword.
3835 ;; If affiliated keywords are orphaned: move back to first one.
3836 ;; They will be parsed as a paragraph.
3837 (when (looking-at "[ \t]*$") (goto-char origin
) (setq output nil
))
3839 (cons origin output
))))
3845 ;; The two major functions here are `org-element-parse-buffer', which
3846 ;; parses Org syntax inside the current buffer, taking into account
3847 ;; region, narrowing, or even visibility if specified, and
3848 ;; `org-element-parse-secondary-string', which parses objects within
3851 ;; The (almost) almighty `org-element-map' allows to apply a function
3852 ;; on elements or objects matching some type, and accumulate the
3853 ;; resulting values. In an export situation, it also skips unneeded
3854 ;; parts of the parse tree.
3856 (defun org-element-parse-buffer (&optional granularity visible-only
)
3857 "Recursively parse the buffer and return structure.
3858 If narrowing is in effect, only parse the visible part of the
3861 Optional argument GRANULARITY determines the depth of the
3862 recursion. It can be set to the following symbols:
3864 `headline' Only parse headlines.
3865 `greater-element' Don't recurse into greater elements excepted
3866 headlines and sections. Thus, elements
3867 parsed are the top-level ones.
3868 `element' Parse everything but objects and plain text.
3869 `object' Parse the complete buffer (default).
3871 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3874 An element or an objects is represented as a list with the
3875 pattern (TYPE PROPERTIES CONTENTS), where :
3877 TYPE is a symbol describing the element or object. See
3878 `org-element-all-elements' and `org-element-all-objects' for an
3879 exhaustive list of such symbols. One can retrieve it with
3880 `org-element-type' function.
3882 PROPERTIES is the list of attributes attached to the element or
3883 object, as a plist. Although most of them are specific to the
3884 element or object type, all types share `:begin', `:end',
3885 `:post-blank' and `:parent' properties, which respectively
3886 refer to buffer position where the element or object starts,
3887 ends, the number of white spaces or blank lines after it, and
3888 the element or object containing it. Properties values can be
3889 obtained by using `org-element-property' function.
3891 CONTENTS is a list of elements, objects or raw strings
3892 contained in the current element or object, when applicable.
3893 One can access them with `org-element-contents' function.
3895 The Org buffer has `org-data' as type and nil as properties.
3896 `org-element-map' function can be used to find specific elements
3897 or objects within the parse tree.
3899 This function assumes that current major mode is `org-mode'."
3901 (goto-char (point-min))
3902 (org-skip-whitespace)
3903 (org-element--parse-elements
3904 (point-at-bol) (point-max)
3905 ;; Start in `first-section' mode so text before the first
3906 ;; headline belongs to a section.
3907 'first-section nil granularity visible-only
(list 'org-data nil
))))
3909 (defun org-element-parse-secondary-string (string restriction
&optional parent
)
3910 "Recursively parse objects in STRING and return structure.
3912 RESTRICTION is a symbol limiting the object types that will be
3915 Optional argument PARENT, when non-nil, is the element or object
3916 containing the secondary string. It is used to set correctly
3917 `:parent' property within the string."
3918 ;; Copy buffer-local variables listed in
3919 ;; `org-element-object-variables' into temporary buffer. This is
3920 ;; required since object parsing is dependent on these variables.
3921 (let ((pairs (delq nil
(mapcar (lambda (var)
3923 (cons var
(symbol-value var
))))
3924 org-element-object-variables
))))
3926 (mapc (lambda (pair) (org-set-local (car pair
) (cdr pair
))) pairs
)
3928 (let ((secondary (org-element--parse-objects
3929 (point-min) (point-max) nil restriction
)))
3931 (mapc (lambda (obj) (org-element-put-property obj
:parent parent
))
3935 (defun org-element-map
3936 (data types fun
&optional info first-match no-recursion with-affiliated
)
3937 "Map a function on selected elements or objects.
3939 DATA is a parse tree, an element, an object, a string, or a list
3940 of such constructs. TYPES is a symbol or list of symbols of
3941 elements or objects types (see `org-element-all-elements' and
3942 `org-element-all-objects' for a complete list of types). FUN is
3943 the function called on the matching element or object. It has to
3944 accept one argument: the element or object itself.
3946 When optional argument INFO is non-nil, it should be a plist
3947 holding export options. In that case, parts of the parse tree
3948 not exportable according to that property list will be skipped.
3950 When optional argument FIRST-MATCH is non-nil, stop at the first
3951 match for which FUN doesn't return nil, and return that value.
3953 Optional argument NO-RECURSION is a symbol or a list of symbols
3954 representing elements or objects types. `org-element-map' won't
3955 enter any recursive element or object whose type belongs to that
3956 list. Though, FUN can still be applied on them.
3958 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3959 apply to matching objects within parsed affiliated keywords (see
3960 `org-element-parsed-keywords').
3962 Nil values returned from FUN do not appear in the results.
3968 Assuming TREE is a variable containing an Org buffer parse tree,
3969 the following example will return a flat list of all `src-block'
3970 and `example-block' elements in it:
3972 \(org-element-map tree '(example-block src-block) 'identity)
3974 The following snippet will find the first headline with a level
3975 of 1 and a \"phone\" tag, and will return its beginning position:
3977 \(org-element-map tree 'headline
3979 \(and (= (org-element-property :level hl) 1)
3980 \(member \"phone\" (org-element-property :tags hl))
3981 \(org-element-property :begin hl)))
3984 The next example will return a flat list of all `plain-list' type
3985 elements in TREE that are not a sub-list themselves:
3987 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3989 Eventually, this example will return a flat list of all `bold'
3990 type objects containing a `latex-snippet' type object, even
3991 looking into captions:
3993 \(org-element-map tree 'bold
3995 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3997 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3998 (unless (listp types
) (setq types
(list types
)))
3999 (unless (listp no-recursion
) (setq no-recursion
(list no-recursion
)))
4000 ;; Recursion depth is determined by --CATEGORY.
4003 (let ((category 'greater-elements
))
4004 (mapc (lambda (type)
4005 (cond ((or (memq type org-element-all-objects
)
4006 (eq type
'plain-text
))
4007 ;; If one object is found, the function
4008 ;; has to recurse into every object.
4009 (throw 'found
'objects
))
4010 ((not (memq type org-element-greater-elements
))
4011 ;; If one regular element is found, the
4012 ;; function has to recurse, at least,
4013 ;; into every element it encounters.
4014 (and (not (eq category
'elements
))
4015 (setq category
'elements
)))))
4018 ;; Compute properties for affiliated keywords if necessary.
4020 (and with-affiliated
4021 (mapcar (lambda (kwd)
4022 (cons kwd
(intern (concat ":" (downcase kwd
)))))
4023 org-element-affiliated-keywords
)))
4029 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4030 ;; holding contextual information.
4031 (let ((--type (org-element-type --data
)))
4034 ;; Ignored element in an export context.
4035 ((and info
(memq --data
(plist-get info
:ignore-list
))))
4036 ;; List of elements or objects.
4037 ((not --type
) (mapc --walk-tree --data
))
4038 ;; Unconditionally enter parse trees.
4039 ((eq --type
'org-data
)
4040 (mapc --walk-tree
(org-element-contents --data
)))
4042 ;; Check if TYPE is matching among TYPES. If so,
4043 ;; apply FUN to --DATA and accumulate return value
4044 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4045 (when (memq --type types
)
4046 (let ((result (funcall fun --data
)))
4047 (cond ((not result
))
4048 (first-match (throw '--map-first-match result
))
4049 (t (push result --acc
)))))
4050 ;; If --DATA has a secondary string that can contain
4051 ;; objects with their type among TYPES, look into it.
4052 (when (and (eq --category
'objects
) (not (stringp --data
)))
4054 (assq --type org-element-secondary-value-alist
)))
4056 (funcall --walk-tree
4057 (org-element-property (cdr sec-prop
) --data
)))))
4058 ;; If --DATA has any affiliated keywords and
4059 ;; WITH-AFFILIATED is non-nil, look for objects in
4061 (when (and with-affiliated
4062 (eq --category
'objects
)
4063 (memq --type org-element-all-elements
))
4064 (mapc (lambda (kwd-pair)
4065 (let ((kwd (car kwd-pair
))
4066 (value (org-element-property
4067 (cdr kwd-pair
) --data
)))
4068 ;; Pay attention to the type of value.
4069 ;; Preserve order for multiple keywords.
4072 ((and (member kwd org-element-multiple-keywords
)
4073 (member kwd org-element-dual-keywords
))
4074 (mapc (lambda (line)
4075 (funcall --walk-tree
(cdr line
))
4076 (funcall --walk-tree
(car line
)))
4078 ((member kwd org-element-multiple-keywords
)
4079 (mapc (lambda (line) (funcall --walk-tree line
))
4081 ((member kwd org-element-dual-keywords
)
4082 (funcall --walk-tree
(cdr value
))
4083 (funcall --walk-tree
(car value
)))
4084 (t (funcall --walk-tree value
)))))
4085 --affiliated-alist
))
4086 ;; Determine if a recursion into --DATA is possible.
4088 ;; --TYPE is explicitly removed from recursion.
4089 ((memq --type no-recursion
))
4090 ;; --DATA has no contents.
4091 ((not (org-element-contents --data
)))
4092 ;; Looking for greater elements but --DATA is simply
4093 ;; an element or an object.
4094 ((and (eq --category
'greater-elements
)
4095 (not (memq --type org-element-greater-elements
))))
4096 ;; Looking for elements but --DATA is an object.
4097 ((and (eq --category
'elements
)
4098 (memq --type org-element-all-objects
)))
4099 ;; In any other case, map contents.
4100 (t (mapc --walk-tree
(org-element-contents --data
)))))))))))
4101 (catch '--map-first-match
4102 (funcall --walk-tree data
)
4103 ;; Return value in a proper order.
4105 (put 'org-element-map
'lisp-indent-function
2)
4107 ;; The following functions are internal parts of the parser.
4109 ;; The first one, `org-element--parse-elements' acts at the element's
4112 ;; The second one, `org-element--parse-objects' applies on all objects
4113 ;; of a paragraph or a secondary string.
4115 ;; More precisely, that function looks for every allowed object type
4116 ;; first. Then, it discards failed searches, keeps further matches,
4117 ;; and searches again types matched behind point, for subsequent
4118 ;; calls. Thus, searching for a given type fails only once, and every
4119 ;; object is searched only once at top level (but sometimes more for
4122 (defun org-element--parse-elements
4123 (beg end special structure granularity visible-only acc
)
4124 "Parse elements between BEG and END positions.
4126 SPECIAL prioritize some elements over the others. It can be set
4127 to `first-section', `section' `item' or `table-row'.
4129 When value is `item', STRUCTURE will be used as the current list
4132 GRANULARITY determines the depth of the recursion. See
4133 `org-element-parse-buffer' for more information.
4135 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4138 Elements are accumulated into ACC."
4141 ;; Visible only: skip invisible parts at the beginning of the
4143 (when (and visible-only
(org-invisible-p2))
4144 (goto-char (min (1+ (org-find-visible)) end
)))
4145 ;; When parsing only headlines, skip any text before first one.
4146 (when (and (eq granularity
'headline
) (not (org-at-heading-p)))
4147 (org-with-limited-levels (outline-next-heading)))
4149 (while (< (point) end
)
4150 ;; Find current element's type and parse it accordingly to
4152 (let* ((element (org-element--current-element
4153 end granularity special structure
))
4154 (type (org-element-type element
))
4155 (cbeg (org-element-property :contents-begin element
)))
4156 (goto-char (org-element-property :end element
))
4157 ;; Visible only: skip invisible parts between siblings.
4158 (when (and visible-only
(org-invisible-p2))
4159 (goto-char (min (1+ (org-find-visible)) end
)))
4160 ;; Fill ELEMENT contents by side-effect.
4162 ;; If element has no contents, don't modify it.
4164 ;; Greater element: parse it between `contents-begin' and
4165 ;; `contents-end'. Make sure GRANULARITY allows the
4166 ;; recursion, or ELEMENT is a headline, in which case going
4167 ;; inside is mandatory, in order to get sub-level headings.
4168 ((and (memq type org-element-greater-elements
)
4169 (or (memq granularity
'(element object nil
))
4170 (and (eq granularity
'greater-element
)
4172 (eq type
'headline
)))
4173 (org-element--parse-elements
4174 cbeg
(org-element-property :contents-end element
)
4175 ;; Possibly switch to a special mode.
4179 (property-drawer 'node-property
)
4181 (and (memq type
'(item plain-list
))
4182 (org-element-property :structure element
))
4183 granularity visible-only element
))
4184 ;; ELEMENT has contents. Parse objects inside, if
4185 ;; GRANULARITY allows it.
4186 ((memq granularity
'(object nil
))
4187 (org-element--parse-objects
4188 cbeg
(org-element-property :contents-end element
) element
4189 (org-element-restriction type
))))
4190 (org-element-adopt-elements acc element
)))
4194 (defconst org-element--object-regexp
4195 (mapconcat #'identity
4196 (let ((link-types (regexp-opt org-link-types
)))
4199 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4200 ;; Bold, code, italic, strike-through, underline and
4203 (format "[^%s]" (nth 2 org-emphasis-regexp-components
)))
4205 (concat "\\<" link-types
":")
4206 ;; Objects starting with "[": regular link, footnote
4207 ;; reference, statistics cookie, timestamp (inactive).
4208 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4209 ;; Objects starting with "@": export snippets.
4211 ;; Objects starting with "{": macro.
4213 ;; Objects starting with "<" : timestamp (active,
4214 ;; diary), target, radio target and angular links.
4215 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types
"\\)")
4216 ;; Objects starting with "$": latex fragment.
4218 ;; Objects starting with "\": line break, entity,
4220 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4221 ;; Objects starting with raw text: inline Babel
4222 ;; source block, inline Babel call.
4223 "\\(?:call\\|src\\)_"))
4225 "Regexp possibly matching the beginning of an object.
4226 This regexp allows false positives. Dedicated parser (e.g.,
4227 `org-export-bold-parser') will take care of further filtering.
4228 Radio links are not matched by this regexp, as they are treated
4229 specially in `org-element--object-lex'.")
4231 (defun org-element--object-lex (restriction)
4232 "Return next object in current buffer or nil.
4233 RESTRICTION is a list of object types, as symbols, that should be
4234 looked after. This function assumes that the buffer is narrowed
4235 to an appropriate container (e.g., a paragraph)."
4236 (if (memq 'table-cell restriction
) (org-element-table-cell-parser)
4238 (let ((limit (and org-target-link-regexp
4240 (or (bolp) (backward-char))
4241 (re-search-forward org-target-link-regexp nil t
))
4242 (match-beginning 1)))
4244 (while (and (not found
)
4245 (re-search-forward org-element--object-regexp limit t
))
4246 (goto-char (match-beginning 0))
4247 (let ((result (match-string 0)))
4250 ((eq (compare-strings result nil nil
"call_" nil nil t
) t
)
4251 (and (memq 'inline-babel-call restriction
)
4252 (org-element-inline-babel-call-parser)))
4253 ((eq (compare-strings result nil nil
"src_" nil nil t
) t
)
4254 (and (memq 'inline-src-block restriction
)
4255 (org-element-inline-src-block-parser)))
4258 (?^
(and (memq 'superscript restriction
)
4259 (org-element-superscript-parser)))
4260 (?_
(or (and (memq 'subscript restriction
)
4261 (org-element-subscript-parser))
4262 (and (memq 'underline restriction
)
4263 (org-element-underline-parser))))
4264 (?
* (and (memq 'bold restriction
)
4265 (org-element-bold-parser)))
4266 (?
/ (and (memq 'italic restriction
)
4267 (org-element-italic-parser)))
4268 (?~
(and (memq 'code restriction
)
4269 (org-element-code-parser)))
4270 (?
= (and (memq 'verbatim restriction
)
4271 (org-element-verbatim-parser)))
4272 (?
+ (and (memq 'strike-through restriction
)
4273 (org-element-strike-through-parser)))
4274 (?
@ (and (memq 'export-snippet restriction
)
4275 (org-element-export-snippet-parser)))
4276 (?
{ (and (memq 'macro restriction
)
4277 (org-element-macro-parser)))
4278 (?$
(and (memq 'latex-fragment restriction
)
4279 (org-element-latex-fragment-parser)))
4281 (if (eq (aref result
1) ?
<)
4282 (or (and (memq 'radio-target restriction
)
4283 (org-element-radio-target-parser))
4284 (and (memq 'target restriction
)
4285 (org-element-target-parser)))
4286 (or (and (memq 'timestamp restriction
)
4287 (org-element-timestamp-parser))
4288 (and (memq 'link restriction
)
4289 (org-element-link-parser)))))
4290 (?
\\ (or (and (memq 'line-break restriction
)
4291 (org-element-line-break-parser))
4292 (and (memq 'entity restriction
)
4293 (org-element-entity-parser))
4294 (and (memq 'latex-fragment restriction
)
4295 (org-element-latex-fragment-parser))))
4297 (if (eq (aref result
1) ?\
[)
4298 (and (memq 'link restriction
)
4299 (org-element-link-parser))
4300 (or (and (memq 'footnote-reference restriction
)
4301 (org-element-footnote-reference-parser))
4302 (and (memq 'timestamp restriction
)
4303 (org-element-timestamp-parser))
4304 (and (memq 'statistics-cookie restriction
)
4305 (org-element-statistics-cookie-parser)))))
4306 ;; This is probably a plain link.
4307 (otherwise (and (or (memq 'link restriction
)
4308 (memq 'plain-link restriction
))
4309 (org-element-link-parser)))))))
4310 (or (eobp) (forward-char))))
4313 ((and limit
(memq 'link restriction
))
4314 (goto-char limit
) (org-element-link-parser)))))))
4316 (defun org-element--parse-objects (beg end acc restriction
)
4317 "Parse objects between BEG and END and return recursive structure.
4319 Objects are accumulated in ACC.
4321 RESTRICTION is a list of object successors which are allowed in
4322 the current object."
4325 (narrow-to-region beg end
)
4326 (goto-char (point-min))
4328 (while (and (not (eobp))
4329 (setq next-object
(org-element--object-lex restriction
)))
4330 ;; 1. Text before any object. Untabify it.
4331 (let ((obj-beg (org-element-property :begin next-object
)))
4332 (unless (= (point) obj-beg
)
4334 (org-element-adopt-elements
4336 (replace-regexp-in-string
4337 "\t" (make-string tab-width ?
)
4338 (buffer-substring-no-properties (point) obj-beg
))))))
4340 (let ((obj-end (org-element-property :end next-object
))
4341 (cont-beg (org-element-property :contents-begin next-object
)))
4342 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4343 ;; a recursive type.
4345 (memq (car next-object
) org-element-recursive-objects
))
4346 (org-element--parse-objects
4347 cont-beg
(org-element-property :contents-end next-object
)
4348 next-object
(org-element-restriction next-object
)))
4349 (setq acc
(org-element-adopt-elements acc next-object
))
4350 (goto-char obj-end
))))
4351 ;; 3. Text after last object. Untabify it.
4354 (org-element-adopt-elements
4356 (replace-regexp-in-string
4357 "\t" (make-string tab-width ?
)
4358 (buffer-substring-no-properties (point) end
)))))
4364 ;;; Towards A Bijective Process
4366 ;; The parse tree obtained with `org-element-parse-buffer' is really
4367 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4368 ;; interpreted and expanded into a string with canonical Org syntax.
4369 ;; Hence `org-element-interpret-data'.
4371 ;; The function relies internally on
4372 ;; `org-element--interpret-affiliated-keywords'.
4375 (defun org-element-interpret-data (data &optional pseudo-objects
)
4376 "Interpret DATA as Org syntax.
4378 DATA is a parse tree, an element, an object or a secondary string
4381 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4382 new types that should be treated as objects. An unknown type not
4383 belonging to this list is seen as a pseudo-element instead. Both
4384 pseudo-objects and pseudo-elements are transparent entities, i.e.
4385 only their contents are interpreted.
4387 Return Org syntax as a string."
4388 (org-element--interpret-data-1 data nil pseudo-objects
))
4390 (defun org-element--interpret-data-1 (data parent pseudo-objects
)
4391 "Interpret DATA as Org syntax.
4393 DATA is a parse tree, an element, an object or a secondary string
4394 to interpret. PARENT is used for recursive calls. It contains
4395 the element or object containing data, or nil. PSEUDO-OBJECTS
4396 are list of symbols defining new element or object types.
4397 Unknown types that don't belong to this list are treated as
4398 pseudo-elements instead.
4400 Return Org syntax as a string."
4401 (let* ((type (org-element-type data
))
4402 ;; Find interpreter for current object or element. If it
4403 ;; doesn't exist (e.g. this is a pseudo object or element),
4404 ;; return contents, if any.
4406 (let ((fun (intern (format "org-element-%s-interpreter" type
))))
4407 (if (fboundp fun
) fun
(lambda (data contents
) contents
))))
4410 ;; Secondary string.
4414 (org-element--interpret-data-1 obj parent pseudo-objects
))
4416 ;; Full Org document.
4417 ((eq type
'org-data
)
4420 (org-element--interpret-data-1 obj parent pseudo-objects
))
4421 (org-element-contents data
) ""))
4422 ;; Plain text: return it.
4423 ((stringp data
) data
)
4424 ;; Element or object without contents.
4425 ((not (org-element-contents data
)) (funcall interpret data nil
))
4426 ;; Element or object with contents.
4428 (funcall interpret data
4429 ;; Recursively interpret contents.
4432 (org-element--interpret-data-1 obj data pseudo-objects
))
4433 (org-element-contents
4434 (if (not (memq type
'(paragraph verse-block
)))
4436 ;; Fix indentation of elements containing
4437 ;; objects. We ignore `table-row' elements
4438 ;; as they are one line long anyway.
4439 (org-element-normalize-contents
4441 ;; When normalizing first paragraph of an
4442 ;; item or a footnote-definition, ignore
4443 ;; first line's indentation.
4444 (and (eq type
'paragraph
)
4445 (equal data
(car (org-element-contents parent
)))
4446 (memq (org-element-type parent
)
4447 '(footnote-definition item
))))))
4449 (if (memq type
'(org-data plain-text nil
)) results
4450 ;; Build white spaces. If no `:post-blank' property is
4451 ;; specified, assume its value is 0.
4452 (let ((post-blank (or (org-element-property :post-blank data
) 0)))
4453 (if (or (memq type org-element-all-objects
)
4454 (memq type pseudo-objects
))
4455 (concat results
(make-string post-blank ?\s
))
4457 (org-element--interpret-affiliated-keywords data
)
4458 (org-element-normalize-string results
)
4459 (make-string post-blank ?
\n)))))))
4461 (defun org-element--interpret-affiliated-keywords (element)
4462 "Return ELEMENT's affiliated keywords as Org syntax.
4463 If there is no affiliated keyword, return the empty string."
4464 (let ((keyword-to-org
4468 (when (member key org-element-dual-keywords
)
4469 (setq dual
(cdr value
) value
(car value
)))
4472 (format "[%s]" (org-element-interpret-data dual
)))
4474 (if (member key org-element-parsed-keywords
)
4475 (org-element-interpret-data value
)
4480 (let ((value (org-element-property prop element
))
4481 (keyword (upcase (substring (symbol-name prop
) 1))))
4483 (if (or (member keyword org-element-multiple-keywords
)
4484 ;; All attribute keywords can have multiple lines.
4485 (string-match "^ATTR_" keyword
))
4486 (mapconcat (lambda (line) (funcall keyword-to-org keyword line
))
4489 (funcall keyword-to-org keyword value
)))))
4490 ;; List all ELEMENT's properties matching an attribute line or an
4491 ;; affiliated keyword, but ignore translated keywords since they
4492 ;; cannot belong to the property list.
4493 (loop for prop in
(nth 1 element
) by
'cddr
4494 when
(let ((keyword (upcase (substring (symbol-name prop
) 1))))
4495 (or (string-match "^ATTR_" keyword
)
4497 (member keyword org-element-affiliated-keywords
)
4499 org-element-keyword-translation-alist
)))))
4503 ;; Because interpretation of the parse tree must return the same
4504 ;; number of blank lines between elements and the same number of white
4505 ;; space after objects, some special care must be given to white
4508 ;; The first function, `org-element-normalize-string', ensures any
4509 ;; string different from the empty string will end with a single
4510 ;; newline character.
4512 ;; The second function, `org-element-normalize-contents', removes
4513 ;; global indentation from the contents of the current element.
4515 (defun org-element-normalize-string (s)
4516 "Ensure string S ends with a single newline character.
4518 If S isn't a string return it unchanged. If S is the empty
4519 string, return it. Otherwise, return a new string with a single
4520 newline character at its end."
4522 ((not (stringp s
)) s
)
4524 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s
)
4525 (replace-match "\n" nil nil s
)))))
4527 (defun org-element-normalize-contents (element &optional ignore-first
)
4528 "Normalize plain text in ELEMENT's contents.
4530 ELEMENT must only contain plain text and objects.
4532 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4533 indentation to compute maximal common indentation.
4535 Return the normalized element that is element with global
4536 indentation removed from its contents. The function assumes that
4537 indentation is not done with TAB characters."
4538 (let* ((min-ind most-positive-fixnum
)
4539 find-min-ind
; For byte-compiler.
4542 ;; Return minimal common indentation within BLOB. This is
4543 ;; done by walking recursively BLOB and updating MIN-IND
4544 ;; along the way. FIRST-FLAG is non-nil when the first
4545 ;; string hasn't been seen yet. It is required as this
4546 ;; string is the only one whose indentation doesn't happen
4547 ;; after a newline character.
4548 (lambda (blob first-flag
)
4549 (dolist (object (org-element-contents blob
))
4550 (when (and first-flag
(stringp object
))
4551 (setq first-flag nil
)
4552 (string-match "\\`\\( *\\)" object
)
4553 (let ((len (length (match-string 1 object
))))
4554 ;; An indentation of zero means no string will be
4555 ;; modified. Quit the process.
4556 (if (zerop len
) (throw 'zero
(setq min-ind
0))
4557 (setq min-ind
(min len min-ind
)))))
4560 (dolist (line (delq "" (cdr (org-split-string object
" *\n"))))
4561 (setq min-ind
(min (org-get-indentation line
) min-ind
))))
4562 ((memq (org-element-type object
) org-element-recursive-objects
)
4563 (funcall find-min-ind object first-flag
))))))))
4564 ;; Find minimal indentation in ELEMENT.
4565 (catch 'zero
(funcall find-min-ind element
(not ignore-first
)))
4566 (if (or (zerop min-ind
) (= min-ind most-positive-fixnum
)) element
4567 ;; Build ELEMENT back, replacing each string with the same
4568 ;; string minus common indentation.
4569 (let* (build ; For byte compiler.
4572 (lambda (blob first-flag
)
4573 ;; Return BLOB with all its strings indentation
4574 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4575 ;; is non-nil when the first string hasn't been seen
4580 (when (and first-flag
(stringp object
))
4581 (setq first-flag nil
)
4583 (replace-regexp-in-string
4584 (format "\\` \\{%d\\}" min-ind
)
4588 (replace-regexp-in-string
4589 (format "\n \\{%d\\}" min-ind
) "\n" object
))
4590 ((memq (org-element-type object
)
4591 org-element-recursive-objects
)
4592 (funcall build object first-flag
))
4594 (org-element-contents blob
)))
4596 (funcall build element
(not ignore-first
))))))
4602 ;; Implement a caching mechanism for `org-element-at-point' and
4603 ;; `org-element-context', which see.
4605 ;; A single public function is provided: `org-element-cache-reset'.
4607 ;; Cache is enabled by default, but can be disabled globally with
4608 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4609 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4610 ;; can be tweaked to control caching behaviour.
4612 ;; Internally, parsed elements are stored in an AVL tree,
4613 ;; `org-element--cache'. This tree is updated lazily: whenever
4614 ;; a change happens to the buffer, a synchronization request is
4615 ;; registered in `org-element--cache-sync-requests' (see
4616 ;; `org-element--cache-submit-request'). During idle time, requests
4617 ;; are processed by `org-element--cache-sync'. Synchronization also
4618 ;; happens when an element is required from the cache. In this case,
4619 ;; the process stops as soon as the needed element is up-to-date.
4621 ;; A synchronization request can only apply on a synchronized part of
4622 ;; the cache. Therefore, the cache is updated at least to the
4623 ;; location where the new request applies. Thus, requests are ordered
4624 ;; from left to right and all elements starting before the first
4625 ;; request are correct. This property is used by functions like
4626 ;; `org-element--cache-find' to retrieve elements in the part of the
4627 ;; cache that can be trusted.
4629 ;; A request applies to every element, starting from its original
4630 ;; location (or key, see below). When a request is processed, it
4631 ;; moves forward and may collide the next one. In this case, both
4632 ;; requests are merged into a new one that starts from that element.
4633 ;; As a consequence, the whole synchronization complexity does not
4634 ;; depend on the number of pending requests, but on the number of
4635 ;; elements the very first request will be applied on.
4637 ;; Elements cannot be accessed through their beginning position, which
4638 ;; may or may not be up-to-date. Instead, each element in the tree is
4639 ;; associated to a key, obtained with `org-element--cache-key'. This
4640 ;; mechanism is robust enough to preserve total order among elements
4641 ;; even when the tree is only partially synchronized.
4643 ;; Objects contained in an element are stored in a hash table,
4644 ;; `org-element--cache-objects'.
4647 (defvar org-element-use-cache t
4648 "Non nil when Org parser should cache its results.
4649 This is mostly for debugging purpose.")
4651 (defvar org-element-cache-sync-idle-time
0.6
4652 "Length, in seconds, of idle time before syncing cache.")
4654 (defvar org-element-cache-sync-duration
(seconds-to-time 0.04)
4655 "Maximum duration, as a time value, for a cache synchronization.
4656 If the synchronization is not over after this delay, the process
4657 pauses and resumes after `org-element-cache-sync-break'
4660 (defvar org-element-cache-sync-break
(seconds-to-time 0.3)
4661 "Duration, as a time value, of the pause between synchronizations.
4662 See `org-element-cache-sync-duration' for more information.")
4667 (defvar org-element--cache nil
4668 "AVL tree used to cache elements.
4669 Each node of the tree contains an element. Comparison is done
4670 with `org-element--cache-compare'. This cache is used in
4671 `org-element-at-point'.")
4673 (defvar org-element--cache-objects nil
4674 "Hash table used as to cache objects.
4675 Key is an element, as returned by `org-element-at-point', and
4676 value is an alist where each association is:
4678 \(PARENT COMPLETEP . OBJECTS)
4680 where PARENT is an element or object, COMPLETEP is a boolean,
4681 non-nil when all direct children of parent are already cached and
4682 OBJECTS is a list of such children, as objects, from farthest to
4685 In the following example, \\alpha, bold object and \\beta are
4686 contained within a paragraph
4690 If the paragraph is completely parsed, OBJECTS-DATA will be
4692 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4693 \(BOLD-OBJECT t ENTITY-OBJECT))
4695 whereas in a partially parsed paragraph, it could be
4697 \((PARAGRAPH nil ENTITY-OBJECT))
4699 This cache is used in `org-element-context'.")
4701 (defvar org-element--cache-sync-requests nil
4702 "List of pending synchronization requests.
4704 A request is a vector with the following pattern:
4706 \[NEXT BEG END OFFSET PARENT PHASE]
4708 Processing a synchronization request consists of three phases:
4710 0. Delete modified elements,
4711 1. Fill missing area in cache,
4712 2. Shift positions and re-parent elements after the changes.
4714 During phase 0, NEXT is the key of the first element to be
4715 removed, BEG and END is buffer position delimiting the
4716 modifications. Every element starting between them (inclusive)
4717 are removed. PARENT, when non-nil, is the parent of the first
4718 element to be removed.
4720 During phase 1, NEXT is the key of the next known element in
4721 cache and BEG its beginning position. Parse buffer between that
4722 element and the one before it in order to determine the parent of
4723 the next element. Set PARENT to the element containing NEXT.
4725 During phase 2, NEXT is the key of the next element to shift in
4726 the parse tree. All elements starting from this one have their
4727 properties relatives to buffer positions shifted by integer
4728 OFFSET and, if they belong to element PARENT, are adopted by it.
4730 PHASE specifies the phase number, as an integer.")
4732 (defvar org-element--cache-sync-timer nil
4733 "Timer used for cache synchronization.")
4735 (defvar org-element--cache-sync-keys nil
4736 "Hash table used to store keys during synchronization.
4737 See `org-element--cache-key' for more information.")
4739 (defsubst org-element--cache-key
(element)
4740 "Return a unique key for ELEMENT in cache tree.
4742 Keys are used to keep a total order among elements in the cache.
4743 Comparison is done with `org-element--cache-key-less-p'.
4745 When no synchronization is taking place, a key is simply the
4746 beginning position of the element, or that position plus one in
4747 the case of an first item (respectively row) in
4748 a list (respectively a table).
4750 During a synchronization, the key is the one the element had when
4751 the cache was synchronized for the last time. Elements added to
4752 cache during the synchronization get a new key generated with
4753 `org-element--cache-generate-key'.
4755 Such keys are stored in `org-element--cache-sync-keys'. The hash
4756 table is cleared once the synchronization is complete."
4757 (or (gethash element org-element--cache-sync-keys
)
4758 (let* ((begin (org-element-property :begin element
))
4759 ;; Increase beginning position of items (respectively
4760 ;; table rows) by one, so the first item can get
4761 ;; a different key from its parent list (respectively
4763 (key (if (memq (org-element-type element
) '(item table-row
))
4766 (if org-element--cache-sync-requests
4767 (puthash element key org-element--cache-sync-keys
)
4770 (defun org-element--cache-generate-key (lower upper
)
4771 "Generate a key between LOWER and UPPER.
4773 LOWER and UPPER are integers or lists, possibly empty.
4775 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4776 a unique key, as an integer or a list of integers, according to
4777 the following rules:
4779 - LOWER and UPPER are compared level-wise until values differ.
4781 - If, at a given level, LOWER and UPPER differ from more than
4782 2, the new key shares all the levels above with LOWER and
4783 gets a new level. Its value is the mean between LOWER and
4786 \(1 2) + (1 4) --> (1 3)
4788 - If LOWER has no value to compare with, it is assumed that its
4789 value is `most-negative-fixnum'. E.g.,
4797 where m is `most-negative-fixnum'. Likewise, if UPPER is
4798 short of levels, the current value is `most-positive-fixnum'.
4800 - If they differ from only one, the new key inherits from
4801 current LOWER level and fork it at the next level. E.g.,
4809 where M is `most-positive-fixnum'.
4811 - If the key is only one level long, it is returned as an
4814 \(1 2) + (3 2) --> 2
4816 When they are not equals, the function assumes that LOWER is
4817 lesser than UPPER, per `org-element--cache-key-less-p'."
4818 (if (equal lower upper
) lower
4819 (let ((lower (if (integerp lower
) (list lower
) lower
))
4820 (upper (if (integerp upper
) (list upper
) upper
))
4824 (let ((min (or (car lower
) most-negative-fixnum
))
4825 (max (cond (skip-upper most-positive-fixnum
)
4827 (t most-positive-fixnum
))))
4828 (if (< (1+ min
) max
)
4829 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
4830 (throw 'exit
(if key
(nreverse (cons mean key
)) mean
)))
4831 (when (and (< min max
) (not skip-upper
))
4832 ;; When at a given level, LOWER and UPPER differ from
4833 ;; 1, ignore UPPER altogether. Instead create a key
4834 ;; between LOWER and the greatest key with the same
4835 ;; prefix as LOWER so far.
4836 (setq skip-upper t
))
4838 (setq lower
(cdr lower
) upper
(cdr upper
)))))))))
4840 (defsubst org-element--cache-key-less-p
(a b
)
4841 "Non-nil if key A is less than key B.
4842 A and B are either integers or lists of integers, as returned by
4843 `org-element--cache-key'."
4844 (if (integerp a
) (if (integerp b
) (< a b
) (<= a
(car b
)))
4845 (if (integerp b
) (< (car a
) b
)
4848 (cond ((car-less-than-car a b
) (throw 'exit t
))
4849 ((car-less-than-car b a
) (throw 'exit nil
))
4850 (t (setq a
(cdr a
) b
(cdr b
)))))
4851 ;; If A is empty, either keys are equal (B is also empty) and
4852 ;; we return nil, or A is lesser than B (B is longer) and we
4853 ;; return a non-nil value.
4855 ;; If A is not empty, B is necessarily empty and A is greater
4856 ;; than B (A is longer). Therefore, return nil.
4857 (and (null a
) b
)))))
4859 (defun org-element--cache-compare (a b
)
4860 "Non-nil when element A is located before element B."
4861 (org-element--cache-key-less-p (org-element--cache-key a
)
4862 (org-element--cache-key b
)))
4864 (defsubst org-element--cache-root
()
4865 "Return root value in cache.
4866 This function assumes `org-element--cache' is a valid AVL tree."
4867 (avl-tree--node-left (avl-tree--dummyroot org-element--cache
)))
4872 (defsubst org-element--cache-active-p
()
4873 "Non-nil when cache is active in current buffer."
4874 (and org-element-use-cache
4875 (or (derived-mode-p 'org-mode
) orgstruct-mode
)))
4877 (defun org-element--cache-find (pos &optional side
)
4878 "Find element in cache starting at POS or before.
4880 POS refers to a buffer position.
4882 When optional argument SIDE is non-nil, the function checks for
4883 elements starting at or past POS instead. If SIDE is `both', the
4884 function returns a cons cell where car is the first element
4885 starting at or before POS and cdr the first element starting
4888 The function can only find elements in the synchronized part of
4890 (let ((limit (and org-element--cache-sync-requests
4891 (aref (car org-element--cache-sync-requests
) 0)))
4892 (node (org-element--cache-root))
4895 (let* ((element (avl-tree--node-data node
))
4896 (begin (org-element-property :begin element
)))
4899 (not (org-element--cache-key-less-p
4900 (org-element--cache-key element
) limit
)))
4901 (setq node
(avl-tree--node-left node
)))
4904 node
(avl-tree--node-left node
)))
4907 node
(avl-tree--node-right node
)))
4908 ;; We found an element in cache starting at POS. If `side'
4909 ;; is `both' we also want the next one in order to generate
4910 ;; a key in-between.
4912 ;; If the element is the first row or item in a table or
4913 ;; a plain list, we always return the table or the plain
4916 ;; In any other case, we return the element found.
4918 (setq lower element
)
4919 (setq node
(avl-tree--node-right node
)))
4920 ((and (memq (org-element-type element
) '(item table-row
))
4921 (let ((parent (org-element-property :parent element
)))
4922 (and (= (org-element-property :begin element
)
4923 (org-element-property :contents-begin parent
))
4932 (both (cons lower upper
))
4934 (otherwise upper
))))
4936 (defun org-element--cache-put (element &optional data
)
4937 "Store ELEMENT in current buffer's cache, if allowed.
4938 When optional argument DATA is non-nil, assume is it object data
4939 relative to ELEMENT and store it in the objects cache."
4940 (cond ((not (org-element--cache-active-p)) nil
)
4942 (when org-element--cache-sync-requests
4943 ;; During synchronization, first build an appropriate key
4944 ;; for the new element so `avl-tree-enter' can insert it at
4945 ;; the right spot in the cache.
4946 (let ((keys (org-element--cache-find
4947 (org-element-property :begin element
) 'both
)))
4949 (org-element--cache-generate-key
4950 (and (car keys
) (org-element--cache-key (car keys
)))
4951 (cond ((cdr keys
) (org-element--cache-key (cdr keys
)))
4952 (org-element--cache-sync-requests
4953 (aref (car org-element--cache-sync-requests
) 0))))
4954 org-element--cache-sync-keys
)))
4955 (avl-tree-enter org-element--cache element
))
4956 ;; Headlines are not stored in cache, so objects in titles are
4957 ;; not stored either.
4958 ((eq (org-element-type element
) 'headline
) nil
)
4959 (t (puthash element data org-element--cache-objects
))))
4961 (defsubst org-element--cache-remove
(element)
4962 "Remove ELEMENT from cache.
4963 Assume ELEMENT belongs to cache and that a cache is active."
4964 (avl-tree-delete org-element--cache element
)
4965 (remhash element org-element--cache-objects
))
4968 ;;;; Synchronization
4970 (defsubst org-element--cache-set-timer
(buffer)
4971 "Set idle timer for cache synchronization in BUFFER."
4972 (when org-element--cache-sync-timer
4973 (cancel-timer org-element--cache-sync-timer
))
4974 (setq org-element--cache-sync-timer
4975 (run-with-idle-timer
4976 (let ((idle (current-idle-time)))
4977 (if idle
(time-add idle org-element-cache-sync-break
)
4978 org-element-cache-sync-idle-time
))
4980 #'org-element--cache-sync
4983 (defsubst org-element--cache-interrupt-p
(time-limit)
4984 "Non-nil when synchronization process should be interrupted.
4985 TIME-LIMIT is a time value or nil."
4987 (or (input-pending-p)
4988 (time-less-p time-limit
(current-time)))))
4990 (defsubst org-element--cache-shift-positions
(element offset
&optional props
)
4991 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4993 Properties containing buffer positions are `:begin', `:end',
4994 `:contents-begin', `:contents-end' and `:structure'. When
4995 optional argument PROPS is a list of keywords, only shift
4996 properties provided in that list.
4998 Properties are modified by side-effect."
4999 (let ((properties (nth 1 element
)))
5000 ;; Shift `:structure' property for the first plain list only: it
5001 ;; is the only one that really matters and it prevents from
5002 ;; shifting it more than once.
5003 (when (and (or (not props
) (memq :structure props
))
5004 (eq (org-element-type element
) 'plain-list
)
5005 (not (eq (org-element-type (plist-get properties
:parent
))
5007 (dolist (item (plist-get properties
:structure
))
5008 (incf (car item
) offset
)
5009 (incf (nth 6 item
) offset
)))
5010 (dolist (key '(:begin
:contents-begin
:contents-end
:end
:post-affiliated
))
5011 (let ((value (and (or (not props
) (memq key props
))
5012 (plist-get properties key
))))
5013 (and value
(plist-put properties key
(+ offset value
)))))))
5015 (defun org-element--cache-sync (buffer &optional threshold extra
)
5016 "Synchronize cache with recent modification in BUFFER.
5018 When optional argument THRESHOLD is non-nil, do the
5019 synchronization for all elements starting before or at threshold,
5020 then exit. Otherwise, synchronize cache for as long as
5021 `org-element-cache-sync-duration' or until Emacs leaves idle
5024 EXTRA, when non-nil, is an additional offset for changes not
5025 registered yet in the cache. It is used in
5026 `org-element--cache-submit-request', where cache is partially
5027 updated before current modification are actually submitted."
5028 (when (buffer-live-p buffer
)
5029 (with-current-buffer buffer
5030 (let ((inhibit-quit t
) request next
)
5031 (when org-element--cache-sync-timer
5032 (cancel-timer org-element--cache-sync-timer
))
5034 (while org-element--cache-sync-requests
5035 (setq request
(car org-element--cache-sync-requests
)
5036 next
(nth 1 org-element--cache-sync-requests
))
5037 (org-element--cache-process-request
5039 (and next
(aref next
0))
5041 (and (not threshold
)
5042 (time-add (current-time)
5043 org-element-cache-sync-duration
))
5045 ;; Request processed. Merge current and next offsets and
5046 ;; transfer phase number and ending position.
5048 (incf (aref next
3) (aref request
3))
5049 (aset next
2 (aref request
2))
5050 (aset next
5 (aref request
5)))
5051 (setq org-element--cache-sync-requests
5052 (cdr org-element--cache-sync-requests
))))
5053 ;; If more requests are awaiting, set idle timer accordingly.
5054 ;; Otherwise, reset keys.
5055 (if org-element--cache-sync-requests
5056 (org-element--cache-set-timer buffer
)
5057 (clrhash org-element--cache-sync-keys
))))))
5059 (defun org-element--cache-process-request
5060 (request next threshold time-limit extra
)
5061 "Process synchronization REQUEST for all entries before NEXT.
5063 REQUEST is a vector, built by `org-element--cache-submit-request'.
5065 NEXT is a cache key, as returned by `org-element--cache-key'.
5067 When non-nil, THRESHOLD is a buffer position. Synchronization
5068 stops as soon as a shifted element begins after it.
5070 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5071 after this time or when Emacs exits idle state.
5073 EXTRA is an additional offset taking into consideration changes
5074 not registered yet. See `org-element--cache-submit-request' for
5077 Throw `interrupt' if the process stops before completing the
5080 (when (= (aref request
5) 0)
5083 ;; Delete all elements starting after BEG, but not after buffer
5084 ;; position END or past element with key NEXT.
5086 ;; At each iteration, we start again at tree root since
5087 ;; a deletion modifies structure of the balanced tree.
5089 (let ((beg (aref request
0))
5090 (end (aref request
2)))
5092 (when (org-element--cache-interrupt-p time-limit
)
5093 (throw 'interrupt nil
))
5094 ;; Find first element in cache with key BEG or after it.
5095 (let ((node (org-element--cache-root)) data data-key
)
5097 (let* ((element (avl-tree--node-data node
))
5098 (key (org-element--cache-key element
)))
5100 ((org-element--cache-key-less-p key beg
)
5101 (setq node
(avl-tree--node-right node
)))
5102 ((org-element--cache-key-less-p beg key
)
5105 node
(avl-tree--node-left node
)))
5106 (t (setq data element
5110 (let ((pos (org-element-property :begin data
)))
5111 (if (and (<= pos end
)
5113 (org-element--cache-key-less-p data-key next
)))
5114 (org-element--cache-remove data
)
5115 (aset request
0 data-key
)
5116 (aset request
1 pos
)
5118 (throw 'end-phase nil
)))
5119 ;; No element starting after modifications left in
5120 ;; cache: further processing is futile.
5121 (throw 'quit t
)))))))
5122 (when (= (aref request
5) 1)
5125 ;; Phase 1 left a hole in the parse tree. Some elements after
5126 ;; it could have parents within. For example, in the following
5138 ;; if we remove a blank line between "item" and "Paragraph1",
5139 ;; everything down to "Paragraph2" is removed from cache. But
5140 ;; the paragraph now belongs to the list, and its `:parent'
5141 ;; property no longer is accurate.
5143 ;; Therefore we need to parse again elements in the hole, or at
5144 ;; least in its last section, so that we can re-parent
5145 ;; subsequent elements, during phase 3.
5147 ;; Note that we only need to get the parent from the first
5148 ;; element in cache after the hole.
5150 ;; Also, this part can be delayed if we don't need to retrieve
5151 ;; an element after the hole.
5153 ;; Next element will start at its beginning position plus
5154 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5155 ;; contains the real beginning position of the first element
5156 ;; to shift and re-parent.
5157 (when (equal (aref request
0) next
) (throw 'quit t
))
5158 (let ((limit (+ (aref request
1) (aref request
3) extra
)))
5159 (when (and threshold
(< threshold limit
)) (throw 'interrupt nil
))
5160 (let ((parent (org-element--parse-to limit t time-limit
)))
5161 (aset request
4 parent
)
5163 (throw 'end-phase nil
)))))
5166 ;; Shift all elements starting from key START, but before NEXT, by
5167 ;; OFFSET, and re-parent them when appropriate.
5169 ;; Elements are modified by side-effect so the tree structure
5172 ;; Once THRESHOLD, if any, is reached, or once there is an input
5173 ;; pending, exit. Before leaving, the current synchronization
5174 ;; request is updated.
5175 (let ((start (aref request
0))
5176 (offset (aref request
3))
5177 (parent (aref request
4))
5178 (node (org-element--cache-root))
5182 ;; No re-parenting nor shifting planned: request is over.
5183 (when (and (not parent
) (zerop offset
)) (throw 'quit t
))
5185 (let* ((data (avl-tree--node-data node
))
5186 (key (org-element--cache-key data
)))
5187 (if (and leftp
(avl-tree--node-left node
)
5188 (not (org-element--cache-key-less-p key start
)))
5189 (progn (push node stack
)
5190 (setq node
(avl-tree--node-left node
)))
5191 (unless (org-element--cache-key-less-p key start
)
5192 ;; We reached NEXT. Request is complete.
5193 (when (equal key next
) (throw 'quit t
))
5194 ;; Handle interruption request. Update current request.
5195 (when (or exit-flag
(org-element--cache-interrupt-p time-limit
))
5196 (aset request
0 key
)
5197 (aset request
4 parent
)
5198 (throw 'interrupt nil
))
5200 (unless (zerop offset
)
5201 (org-element--cache-shift-positions data offset
)
5202 ;; Shift associated objects data, if any.
5203 (dolist (object-data (gethash data org-element--cache-objects
))
5204 (dolist (object (cddr object-data
))
5205 (org-element--cache-shift-positions object offset
))))
5206 (let ((begin (org-element-property :begin data
)))
5209 (<= (org-element-property :end parent
) begin
))
5210 (setq parent
(org-element-property :parent parent
)))
5211 (cond (parent (org-element-put-property data
:parent parent
))
5212 ((zerop offset
) (throw 'quit t
)))
5213 ;; Cache is up-to-date past THRESHOLD. Request
5215 (when (and threshold
(> begin threshold
)) (setq exit-flag t
))))
5216 (setq node
(if (setq leftp
(avl-tree--node-right node
))
5217 (avl-tree--node-right node
)
5219 ;; We reached end of tree: synchronization complete.
5222 (defun org-element--parse-to (pos &optional syncp time-limit
)
5223 "Parse elements in current section, down to POS.
5225 Start parsing from the closest between the last known element in
5226 cache or headline above. Return the smallest element containing
5229 When optional argument SYNCP is non-nil, return the parent of the
5230 element containing POS instead. In that case, it is also
5231 possible to provide TIME-LIMIT, which is a time value specifying
5232 when the parsing should stop. The function throws `interrupt' if
5233 the process stopped before finding the expected result."
5235 (org-with-wide-buffer
5237 (let* ((cached (and (org-element--cache-active-p)
5238 (org-element--cache-find pos nil
)))
5239 (begin (org-element-property :begin cached
))
5242 ;; Nothing in cache before point: start parsing from first
5243 ;; element following headline above, or first element in
5246 (when (org-with-limited-levels (outline-previous-heading))
5248 (skip-chars-forward " \r\t\n")
5249 (beginning-of-line))
5250 ;; Cache returned exact match: return it.
5252 (throw 'exit
(if syncp
(org-element-property :parent cached
) cached
)))
5253 ;; There's a headline between cached value and POS: cached
5254 ;; value is invalid. Start parsing from first element
5255 ;; following the headline.
5256 ((re-search-backward
5257 (org-with-limited-levels org-outline-regexp-bol
) begin t
)
5259 (skip-chars-forward " \r\t\n")
5260 (beginning-of-line))
5261 ;; Check if CACHED or any of its ancestors contain point.
5263 ;; If there is such an element, we inspect it in order to know
5264 ;; if we return it or if we need to parse its contents.
5265 ;; Otherwise, we just start parsing from current location,
5266 ;; which is right after the top-most element containing
5269 ;; As a special case, if POS is at the end of the buffer, we
5270 ;; want to return the innermost element ending there.
5272 ;; Also, if we find an ancestor and discover that we need to
5273 ;; parse its contents, make sure we don't start from
5274 ;; `:contents-begin', as we would otherwise go past CACHED
5275 ;; again. Instead, in that situation, we will resume parsing
5276 ;; from NEXT, which is located after CACHED or its higher
5277 ;; ancestor not containing point.
5280 (pos (if (= (point-max) pos
) (1- pos
) pos
)))
5281 (goto-char (or (org-element-property :contents-begin cached
) begin
))
5282 (while (let ((end (org-element-property :end up
)))
5285 (setq up
(org-element-property :parent up
)))))
5287 ((eobp) (setq element up
))
5288 (t (setq element up next
(point)))))))
5289 ;; Parse successively each element until we reach POS.
5290 (let ((end (or (org-element-property :end element
)
5292 (org-with-limited-levels (outline-next-heading))
5298 (cond ((= (point) pos
) (throw 'exit parent
))
5299 ((org-element--cache-interrupt-p time-limit
)
5300 (throw 'interrupt nil
))))
5302 (setq element
(org-element--current-element
5303 end
'element special-flag
5304 (org-element-property :structure parent
)))
5305 (org-element-put-property element
:parent parent
)
5306 (org-element--cache-put element
))
5307 (let ((elem-end (org-element-property :end element
))
5308 (type (org-element-type element
)))
5310 ;; Skip any element ending before point. Also skip
5311 ;; element ending at point (unless it is also the end of
5312 ;; buffer) since we're sure that another element begins
5314 ((and (<= elem-end pos
) (/= (point-max) elem-end
))
5315 (goto-char elem-end
))
5316 ;; A non-greater element contains point: return it.
5317 ((not (memq type org-element-greater-elements
))
5318 (throw 'exit element
))
5319 ;; Otherwise, we have to decide if ELEMENT really
5320 ;; contains POS. In that case we start parsing from
5321 ;; contents' beginning.
5323 ;; If POS is at contents' beginning but it is also at
5324 ;; the beginning of the first item in a list or a table.
5325 ;; In that case, we need to create an anchor for that
5326 ;; list or table, so return it.
5328 ;; Also, if POS is at the end of the buffer, no element
5329 ;; can start after it, but more than one may end there.
5330 ;; Arbitrarily, we choose to return the innermost of
5332 ((let ((cbeg (org-element-property :contents-begin element
))
5333 (cend (org-element-property :contents-end element
)))
5338 (not (memq type
'(plain-list table
)))))
5340 (and (= cend pos
) (= (point-max) pos
)))))
5341 (goto-char (or next cbeg
))
5343 special-flag
(case type
5345 (property-drawer 'node-property
)
5349 ;; Otherwise, return ELEMENT as it is the smallest
5350 ;; element containing POS.
5351 (t (throw 'exit element
))))
5352 (setq element nil
)))))))
5355 ;;;; Staging Buffer Changes
5357 (defconst org-element--cache-sensitive-re
5359 org-outline-regexp-bol
"\\|"
5362 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5363 ;; LaTeX environments.
5364 "\\\\\\(?:begin{[A-Za-z0-9]+\\*?}\\|end{[A-Za-z0-9]+\\*?}[ \t]*$\\)" "\\|"
5368 "Regexp matching a sensitive line, structure wise.
5369 A sensitive line is a headline, inlinetask, block, drawer, or
5370 latex-environment boundary. When such a line is modified,
5371 structure changes in the document may propagate in the whole
5372 section, possibly making cache invalid.")
5374 (defvar org-element--cache-change-warning nil
5375 "Non-nil when a sensitive line is about to be changed.
5376 It is a symbol among nil, t and `headline'.")
5378 (defun org-element--cache-before-change (beg end
)
5379 "Request extension of area going to be modified if needed.
5380 BEG and END are the beginning and end of the range of changed
5381 text. See `before-change-functions' for more information."
5382 (when (org-element--cache-active-p)
5383 (org-with-wide-buffer
5386 (let ((bottom (save-excursion (goto-char end
) (line-end-position))))
5387 (setq org-element--cache-change-warning
5389 (if (and (org-with-limited-levels (org-at-heading-p))
5390 (= (line-end-position) bottom
))
5392 (let ((case-fold-search t
))
5394 org-element--cache-sensitive-re bottom t
)))))))))
5396 (defun org-element--cache-after-change (beg end pre
)
5397 "Update buffer modifications for current buffer.
5398 BEG and END are the beginning and end of the range of changed
5399 text, and the length in bytes of the pre-change text replaced by
5400 that range. See `after-change-functions' for more information."
5401 (when (org-element--cache-active-p)
5402 (org-with-wide-buffer
5407 (bottom (save-excursion (goto-char end
) (line-end-position))))
5408 ;; Determine if modified area needs to be extended, according
5409 ;; to both previous and current state. We make a special
5410 ;; case for headline editing: if a headline is modified but
5411 ;; not removed, do not extend.
5412 (when (case org-element--cache-change-warning
5415 (not (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
))))
5421 ;; Effectively extend modified area.
5422 (org-with-limited-levels
5423 (setq top
(progn (goto-char top
)
5424 (when (outline-previous-heading) (forward-line))
5426 (setq bottom
(progn (goto-char bottom
)
5427 (if (outline-next-heading) (1- (point))
5429 ;; Store synchronization request.
5430 (let ((offset (- end beg pre
)))
5431 (org-element--cache-submit-request top
(- bottom offset
) offset
)))))
5432 ;; Activate a timer to process the request during idle time.
5433 (org-element--cache-set-timer (current-buffer))))
5435 (defun org-element--cache-for-removal (beg end offset
)
5436 "Return first element to remove from cache.
5438 BEG and END are buffer positions delimiting buffer modifications.
5439 OFFSET is the size of the changes.
5441 Returned element is usually the first element in cache containing
5442 any position between BEG and END. As an exception, greater
5443 elements around the changes that are robust to contents
5444 modifications are preserved and updated according to the
5446 (let* ((elements (org-element--cache-find (1- beg
) 'both
))
5447 (before (car elements
))
5448 (after (cdr elements
)))
5449 (if (not before
) after
5451 (while (setq up
(org-element-property :parent up
))
5452 (if (and (memq (org-element-type up
)
5454 drawer dynamic-block inlinetask
5455 property-drawer quote-block special-block
))
5456 (<= (org-element-property :contents-begin up
) beg
)
5457 (> (org-element-property :contents-end up
) end
))
5458 ;; UP is a robust greater element containing changes.
5459 ;; We only need to extend its ending boundaries.
5460 (org-element--cache-shift-positions
5461 up offset
'(:contents-end
:end
))
5463 ;; We're at top level element containing ELEMENT: if it's
5464 ;; altered by buffer modifications, it is first element in
5465 ;; cache to be removed. Otherwise, that first element is the
5467 (if (< (org-element-property :end before
) beg
) after before
)))))
5469 (defun org-element--cache-submit-request (beg end offset
)
5470 "Submit a new cache synchronization request for current buffer.
5471 BEG and END are buffer positions delimiting the minimal area
5472 where cache data should be removed. OFFSET is the size of the
5473 change, as an integer."
5474 (let ((next (car org-element--cache-sync-requests
))
5475 delete-to delete-from
)
5477 (zerop (aref next
5))
5478 (> (setq delete-to
(+ (aref next
2) (aref next
3))) end
)
5479 (<= (setq delete-from
(aref next
1)) end
))
5480 ;; Current changes can be merged with first sync request: we
5481 ;; can save a partial cache synchronization.
5483 (incf (aref next
3) offset
)
5484 ;; If last change happened within area to be removed, extend
5485 ;; boundaries of robust parents, if any. Otherwise, find
5486 ;; first element to remove and update request accordingly.
5487 (if (> beg delete-from
)
5488 (let ((up (aref next
4)))
5490 (org-element--cache-shift-positions
5491 up offset
'(:contents-end
:end
))
5492 (setq up
(org-element-property :parent up
))))
5493 (let ((first (org-element--cache-for-removal beg delete-to offset
)))
5495 (aset next
0 (org-element--cache-key first
))
5496 (aset next
1 (org-element-property :begin first
))
5497 (aset next
4 (org-element-property :parent first
))))))
5498 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5499 ;; if any, is no longer a 0-phase request, thus ensuring that
5500 ;; phases are properly ordered. We need to provide OFFSET as
5501 ;; optional parameter since current modifications are not known
5502 ;; yet to the otherwise correct part of the cache (i.e, before
5503 ;; the first request).
5504 (when next
(org-element--cache-sync (current-buffer) end offset
))
5505 (let ((first (org-element--cache-for-removal beg end offset
)))
5507 ;; Changes happened before the first known element. Shift
5508 ;; the rest of the cache.
5509 ((and first
(> (org-element-property :begin first
) end
))
5510 (push (vector (org-element--cache-key first
) nil nil offset nil
2)
5511 org-element--cache-sync-requests
))
5512 ;; There is at least an element to remove. Find position
5513 ;; past every element containing END.
5515 (if (> (org-element-property :end first
) end
)
5516 (setq end
(org-element-property :end first
))
5517 (let ((element (org-element--cache-find end
)))
5518 (setq end
(org-element-property :end element
))
5520 (while (and (setq up
(org-element-property :parent up
))
5521 (>= (org-element-property :begin up
) beg
))
5522 (setq end
(org-element-property :end up
))))))
5523 (push (vector (org-element--cache-key first
)
5524 (org-element-property :begin first
)
5527 (org-element-property :parent first
)
5529 org-element--cache-sync-requests
))
5530 ;; No element to remove. No need to re-parent either.
5531 ;; Simply shift additional elements, if any, by OFFSET.
5532 (org-element--cache-sync-requests
5533 (incf (aref (car org-element--cache-sync-requests
) 3) offset
)))))))
5536 ;;;; Public Functions
5539 (defun org-element-cache-reset (&optional all
)
5540 "Reset cache in current buffer.
5541 When optional argument ALL is non-nil, reset cache in all Org
5544 (dolist (buffer (if all
(buffer-list) (list (current-buffer))))
5545 (with-current-buffer buffer
5546 (when (org-element--cache-active-p)
5547 (org-set-local 'org-element--cache
5548 (avl-tree-create #'org-element--cache-compare
))
5549 (org-set-local 'org-element--cache-objects
(make-hash-table :test
#'eq
))
5550 (org-set-local 'org-element--cache-sync-keys
5551 (make-hash-table :weakness
'key
:test
#'eq
))
5552 (org-set-local 'org-element--cache-change-warning nil
)
5553 (org-set-local 'org-element--cache-sync-requests nil
)
5554 (org-set-local 'org-element--cache-sync-timer nil
)
5555 (add-hook 'before-change-functions
5556 #'org-element--cache-before-change nil t
)
5557 (add-hook 'after-change-functions
5558 #'org-element--cache-after-change nil t
)))))
5561 (defun org-element-cache-refresh (pos)
5562 "Refresh cache at position POS."
5563 (when (org-element--cache-active-p)
5564 (org-element--cache-sync (current-buffer) pos
)
5565 (org-element--cache-submit-request pos pos
0)
5566 (org-element--cache-set-timer (current-buffer))))
5572 ;; The first move is to implement a way to obtain the smallest element
5573 ;; containing point. This is the job of `org-element-at-point'. It
5574 ;; basically jumps back to the beginning of section containing point
5575 ;; and proceed, one element after the other, with
5576 ;; `org-element--current-element' until the container is found. Note:
5577 ;; When using `org-element-at-point', secondary values are never
5578 ;; parsed since the function focuses on elements, not on objects.
5580 ;; At a deeper level, `org-element-context' lists all elements and
5581 ;; objects containing point.
5583 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5584 ;; internally by navigation and manipulation tools.
5588 (defun org-element-at-point ()
5589 "Determine closest element around point.
5591 Return value is a list like (TYPE PROPS) where TYPE is the type
5592 of the element and PROPS a plist of properties associated to the
5595 Possible types are defined in `org-element-all-elements'.
5596 Properties depend on element or object type, but always include
5597 `:begin', `:end', `:parent' and `:post-blank' properties.
5599 As a special case, if point is at the very beginning of the first
5600 item in a list or sub-list, returned element will be that list
5601 instead of the item. Likewise, if point is at the beginning of
5602 the first row of a table, returned element will be the table
5603 instead of the first row.
5605 When point is at the end of the buffer, return the innermost
5606 element ending there."
5607 (org-with-wide-buffer
5608 (let ((origin (point)))
5610 (skip-chars-backward " \r\t\n")
5612 ;; Within blank lines at the beginning of buffer, return nil.
5614 ;; Within blank lines right after a headline, return that
5616 ((org-with-limited-levels (org-at-heading-p))
5618 (org-element-headline-parser (point-max) t
))
5619 ;; Otherwise parse until we find element containing ORIGIN.
5621 (when (org-element--cache-active-p)
5622 (if (not org-element--cache
) (org-element-cache-reset)
5623 (org-element--cache-sync (current-buffer) origin
)))
5624 (org-element--parse-to origin
))))))
5627 (defun org-element-context (&optional element
)
5628 "Return smallest element or object around point.
5630 Return value is a list like (TYPE PROPS) where TYPE is the type
5631 of the element or object and PROPS a plist of properties
5634 Possible types are defined in `org-element-all-elements' and
5635 `org-element-all-objects'. Properties depend on element or
5636 object type, but always include `:begin', `:end', `:parent' and
5639 As a special case, if point is right after an object and not at
5640 the beginning of any other object, return that object.
5642 Optional argument ELEMENT, when non-nil, is the closest element
5643 containing point, as returned by `org-element-at-point'.
5644 Providing it allows for quicker computation."
5645 (catch 'objects-forbidden
5646 (org-with-wide-buffer
5647 (let* ((pos (point))
5648 (element (or element
(org-element-at-point)))
5649 (type (org-element-type element
)))
5650 ;; If point is inside an element containing objects or
5651 ;; a secondary string, narrow buffer to the container and
5652 ;; proceed with parsing. Otherwise, return ELEMENT.
5654 ;; At a parsed affiliated keyword, check if we're inside main
5656 ((let ((post (org-element-property :post-affiliated element
)))
5657 (and post
(< pos post
)))
5659 (let ((case-fold-search t
)) (looking-at org-element--affiliated-re
))
5661 ((not (member-ignore-case (match-string 1)
5662 org-element-parsed-keywords
))
5663 (throw 'objects-forbidden element
))
5664 ((< (match-end 0) pos
)
5665 (narrow-to-region (match-end 0) (line-end-position)))
5666 ((and (match-beginning 2)
5667 (>= pos
(match-beginning 2))
5668 (< pos
(match-end 2)))
5669 (narrow-to-region (match-beginning 2) (match-end 2)))
5670 (t (throw 'objects-forbidden element
)))
5671 ;; Also change type to retrieve correct restrictions.
5672 (setq type
'keyword
))
5673 ;; At an item, objects can only be located within tag, if any.
5675 (let ((tag (org-element-property :tag element
)))
5676 (if (not tag
) (throw 'objects-forbidden element
)
5678 (search-forward tag
(line-end-position))
5679 (goto-char (match-beginning 0))
5680 (if (and (>= pos
(point)) (< pos
(match-end 0)))
5681 (narrow-to-region (point) (match-end 0))
5682 (throw 'objects-forbidden element
)))))
5683 ;; At an headline or inlinetask, objects are in title.
5684 ((memq type
'(headline inlinetask
))
5685 (goto-char (org-element-property :begin element
))
5686 (skip-chars-forward "*")
5687 (if (and (> pos
(point)) (< pos
(line-end-position)))
5688 (narrow-to-region (point) (line-end-position))
5689 (throw 'objects-forbidden element
)))
5690 ;; At a paragraph, a table-row or a verse block, objects are
5691 ;; located within their contents.
5692 ((memq type
'(paragraph table-row verse-block
))
5693 (let ((cbeg (org-element-property :contents-begin element
))
5694 (cend (org-element-property :contents-end element
)))
5695 ;; CBEG is nil for table rules.
5696 (if (and cbeg cend
(>= pos cbeg
)
5697 (or (< pos cend
) (and (= pos cend
) (eobp))))
5698 (narrow-to-region cbeg cend
)
5699 (throw 'objects-forbidden element
))))
5700 ;; At a parsed keyword, objects are located within value.
5702 (if (not (member (org-element-property :key element
)
5703 org-element-document-properties
))
5704 (throw 'objects-forbidden element
)
5706 (search-forward ":")
5707 (if (and (>= pos
(point)) (< pos
(line-end-position)))
5708 (narrow-to-region (point) (line-end-position))
5709 (throw 'objects-forbidden element
))))
5710 ;; At a planning line, if point is at a timestamp, return it,
5711 ;; otherwise, return element.
5712 ((eq type
'planning
)
5713 (dolist (p '(:closed
:deadline
:scheduled
))
5714 (let ((timestamp (org-element-property p element
)))
5715 (when (and timestamp
5716 (<= (org-element-property :begin timestamp
) pos
)
5717 (> (org-element-property :end timestamp
) pos
))
5718 (throw 'objects-forbidden timestamp
))))
5719 ;; All other locations cannot contain objects: bail out.
5720 (throw 'objects-forbidden element
))
5721 (t (throw 'objects-forbidden element
)))
5722 (goto-char (point-min))
5723 (let ((restriction (org-element-restriction type
))
5725 (cache (cond ((not (org-element--cache-active-p)) nil
)
5726 (org-element--cache-objects
5727 (gethash element org-element--cache-objects
))
5728 (t (org-element-cache-reset) nil
)))
5729 next object-data last
)
5733 ;; When entering PARENT for the first time, get list
5734 ;; of objects within known so far. Store it in
5737 (let ((data (assq parent cache
)))
5738 (if data
(setq object-data data
)
5739 (push (setq object-data
(list parent nil
)) cache
))))
5740 ;; Find NEXT object for analysis.
5742 ;; If NEXT is non-nil, we already exhausted the
5743 ;; cache so we can parse buffer to find the object
5745 (if next
(setq next
(org-element--object-lex restriction
))
5746 ;; Otherwise, check if cache can help us.
5747 (let ((objects (cddr object-data
))
5748 (completep (nth 1 object-data
)))
5750 ((and (not objects
) completep
) (throw 'exit parent
))
5752 (setq next
(org-element--object-lex restriction
)))
5755 (org-element-property :end
(car objects
))))
5756 (if (>= cache-limit pos
)
5757 ;; Cache contains the information needed.
5758 (dolist (object objects
(throw 'exit parent
))
5759 (when (<= (org-element-property :begin object
)
5761 (if (>= (org-element-property :end object
)
5763 (throw 'found
(setq next object
))
5764 (throw 'exit parent
))))
5765 (goto-char cache-limit
)
5767 (org-element--object-lex restriction
))))))))
5768 ;; If we have a new object to analyze, store it in
5769 ;; cache. Otherwise record that there is nothing
5770 ;; more to parse in this element at this depth.
5772 (progn (org-element-put-property next
:parent parent
)
5773 (push next
(cddr object-data
)))
5774 (setcar (cdr object-data
) t
)))
5775 ;; Process NEXT, if any, in order to know if we need
5776 ;; to skip it, return it or move into it.
5777 (if (or (not next
) (> (org-element-property :begin next
) pos
))
5778 (throw 'exit
(or last parent
))
5779 (let ((end (org-element-property :end next
))
5780 (cbeg (org-element-property :contents-begin next
))
5781 (cend (org-element-property :contents-end next
)))
5783 ;; Skip objects ending before point. Also skip
5784 ;; objects ending at point unless it is also the
5785 ;; end of buffer, since we want to return the
5786 ;; innermost object.
5787 ((and (<= end pos
) (/= (point-max) end
))
5789 ;; For convenience, when object ends at POS,
5790 ;; without any space, store it in LAST, as we
5791 ;; will return it if no object starts here.
5792 (when (and (= end pos
)
5793 (not (memq (char-before) '(?\s ?
\t))))
5795 ;; If POS is within a container object, move
5796 ;; into that object.
5800 ;; At contents' end, if there is no
5801 ;; space before point, also move into
5802 ;; object, for consistency with
5803 ;; convenience feature above.
5805 (or (= (point-max) pos
)
5806 (not (memq (char-before pos
)
5809 (narrow-to-region (point) cend
)
5811 restriction
(org-element-restriction next
)
5814 ;; Otherwise, return NEXT.
5815 (t (throw 'exit next
)))))))
5816 ;; Store results in cache, if applicable.
5817 (org-element--cache-put element cache
)))))))
5819 (defun org-element-nested-p (elem-A elem-B
)
5820 "Non-nil when elements ELEM-A and ELEM-B are nested."
5821 (let ((beg-A (org-element-property :begin elem-A
))
5822 (beg-B (org-element-property :begin elem-B
))
5823 (end-A (org-element-property :end elem-A
))
5824 (end-B (org-element-property :end elem-B
)))
5825 (or (and (>= beg-A beg-B
) (<= end-A end-B
))
5826 (and (>= beg-B beg-A
) (<= end-B end-A
)))))
5828 (defun org-element-swap-A-B (elem-A elem-B
)
5829 "Swap elements ELEM-A and ELEM-B.
5830 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5832 (goto-char (org-element-property :begin elem-A
))
5833 ;; There are two special cases when an element doesn't start at bol:
5834 ;; the first paragraph in an item or in a footnote definition.
5835 (let ((specialp (not (bolp))))
5836 ;; Only a paragraph without any affiliated keyword can be moved at
5837 ;; ELEM-A position in such a situation. Note that the case of
5838 ;; a footnote definition is impossible: it cannot contain two
5839 ;; paragraphs in a row because it cannot contain a blank line.
5841 (or (not (eq (org-element-type elem-B
) 'paragraph
))
5842 (/= (org-element-property :begin elem-B
)
5843 (org-element-property :contents-begin elem-B
))))
5844 (error "Cannot swap elements"))
5845 ;; In a special situation, ELEM-A will have no indentation. We'll
5846 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5847 (let* ((ind-B (when specialp
5848 (goto-char (org-element-property :begin elem-B
))
5849 (org-get-indentation)))
5850 (beg-A (org-element-property :begin elem-A
))
5851 (end-A (save-excursion
5852 (goto-char (org-element-property :end elem-A
))
5853 (skip-chars-backward " \r\t\n")
5855 (beg-B (org-element-property :begin elem-B
))
5856 (end-B (save-excursion
5857 (goto-char (org-element-property :end elem-B
))
5858 (skip-chars-backward " \r\t\n")
5860 ;; Store overlays responsible for visibility status. We
5861 ;; also need to store their boundaries as they will be
5862 ;; removed from buffer.
5865 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5866 (overlays-in beg-A end-A
))
5867 (mapcar (lambda (ov) (list ov
(overlay-start ov
) (overlay-end ov
)))
5868 (overlays-in beg-B end-B
))))
5870 (body-A (buffer-substring beg-A end-A
))
5871 (body-B (delete-and-extract-region beg-B end-B
)))
5874 (setq body-B
(replace-regexp-in-string "\\`[ \t]*" "" body-B
))
5875 (org-indent-to-column ind-B
))
5877 ;; Restore ex ELEM-A overlays.
5878 (let ((offset (- beg-B beg-A
)))
5881 (car ov
) (+ (nth 1 ov
) offset
) (+ (nth 2 ov
) offset
)))
5884 (delete-region beg-A end-A
)
5886 ;; Restore ex ELEM-B overlays.
5889 (car ov
) (- (nth 1 ov
) offset
) (- (nth 2 ov
) offset
)))
5891 (goto-char (org-element-property :end elem-B
)))))
5893 (defun org-element-remove-indentation (s &optional n
)
5894 "Remove maximum common indentation in string S and return it.
5895 When optional argument N is a positive integer, remove exactly
5896 that much characters from indentation, if possible, or return
5897 S as-is otherwise. Unlike to `org-remove-indentation', this
5898 function doesn't call `untabify' on S."
5902 (goto-char (point-min))
5903 ;; Find maximum common indentation, if not specified.
5905 (let ((min-ind (point-max)))
5907 (while (re-search-forward "^[ \t]*\\S-" nil t
)
5908 (let ((ind (1- (current-column))))
5909 (if (zerop ind
) (throw 'exit s
)
5910 (setq min-ind
(min min-ind ind
))))))
5913 ;; Remove exactly N indentation, but give up if not possible.
5915 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5916 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5917 ((< ind n
) (throw 'exit s
))
5918 (t (org-indent-line-to (- ind n
))))
5924 (provide 'org-element
)
5927 ;; generated-autoload-file: "org-loaddefs.el"
5930 ;;; org-element.el ends here