Merge branch 'maint'
[org-mode.git] / lisp / org-element.el
blobb669de7335731afe512b298f044e2ee7f8d5d023
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/>.
23 ;;; Commentary:
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', `property-drawer', `node-property', `section' and
35 ;; `table-row' types), it can also accept a fixed set of keywords as
36 ;; attributes. Those are called "affiliated keywords" to distinguish
37 ;; them from other keywords, which are full-fledged elements. Almost
38 ;; all affiliated keywords are referenced in
39 ;; `org-element-affiliated-keywords'; the others are export attributes
40 ;; and start with "ATTR_" prefix.
42 ;; Element containing other elements (and only elements) are called
43 ;; greater elements. Concerned types are: `center-block', `drawer',
44 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
45 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
46 ;; and `special-block'.
48 ;; Other element types are: `babel-call', `clock', `comment',
49 ;; `comment-block', `diary-sexp', `example-block', `export-block',
50 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
51 ;; `node-property', `paragraph', `planning', `src-block', `table',
52 ;; `table-row' and `verse-block'. Among them, `paragraph' and
53 ;; `verse-block' types can contain Org objects and plain text.
55 ;; Objects are related to document's contents. Some of them are
56 ;; recursive. Associated types are of the following: `bold', `code',
57 ;; `entity', `export-snippet', `footnote-reference',
58 ;; `inline-babel-call', `inline-src-block', `italic',
59 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
60 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
61 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
63 ;; Some elements also have special properties whose value can hold
64 ;; objects themselves (e.g. an item tag or a headline name). Such
65 ;; values are called "secondary strings". Any object belongs to
66 ;; either an element or a secondary string.
68 ;; Notwithstanding affiliated keywords, each greater element, element
69 ;; and object has a fixed set of properties attached to it. Among
70 ;; them, four are shared by all types: `:begin' and `:end', which
71 ;; refer to the beginning and ending buffer positions of the
72 ;; considered element or object, `:post-blank', which holds the number
73 ;; of blank lines, or white spaces, at its end and `:parent' which
74 ;; refers to the element or object containing it. Greater elements,
75 ;; elements and objects containing objects will also have
76 ;; `:contents-begin' and `:contents-end' properties to delimit
77 ;; contents. Eventually, All elements have a `:post-affiliated'
78 ;; property referring to the buffer position after all affiliated
79 ;; keywords, if any, or to their beginning position otherwise.
81 ;; At the lowest level, a `:parent' property is also attached to any
82 ;; string, as a text property.
84 ;; Lisp-wise, an element or an object can be represented as a list.
85 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
86 ;; TYPE is a symbol describing the Org element or object.
87 ;; PROPERTIES is the property list attached to it. See docstring of
88 ;; appropriate parsing function to get an exhaustive
89 ;; list.
90 ;; CONTENTS is a list of elements, objects or raw strings contained
91 ;; in the current element or object, when applicable.
93 ;; An Org buffer is a nested list of such elements and objects, whose
94 ;; type is `org-data' and properties is nil.
96 ;; The first part of this file defines Org syntax, while the second
97 ;; one provide accessors and setters functions.
99 ;; The next part implements a parser and an interpreter for each
100 ;; element and object type in Org syntax.
102 ;; The following part creates a fully recursive buffer parser. It
103 ;; also provides a tool to map a function to elements or objects
104 ;; matching some criteria in the parse tree. Functions of interest
105 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
106 ;; extent, `org-element-parse-secondary-string'.
108 ;; The penultimate part is the cradle of an interpreter for the
109 ;; obtained parse tree: `org-element-interpret-data'.
111 ;; The library ends by furnishing `org-element-at-point' function, and
112 ;; a way to give information about document structure around point
113 ;; with `org-element-context'. A cache mechanism is also provided for
114 ;; these functions.
117 ;;; Code:
119 (eval-when-compile (require 'cl))
120 (require 'org)
121 (require 'avl-tree)
125 ;;; Definitions And Rules
127 ;; Define elements, greater elements and specify recursive objects,
128 ;; along with the affiliated keywords recognized. Also set up
129 ;; restrictions on recursive objects combinations.
131 ;; These variables really act as a control center for the parsing
132 ;; process.
134 (defconst org-element-paragraph-separate
135 (concat "^\\(?:"
136 ;; Headlines, inlinetasks.
137 org-outline-regexp "\\|"
138 ;; Footnote definitions.
139 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
140 ;; Diary sexps.
141 "%%(" "\\|"
142 "[ \t]*\\(?:"
143 ;; Empty lines.
144 "$" "\\|"
145 ;; Tables (any type).
146 "\\(?:|\\|\\+-[-+]\\)" "\\|"
147 ;; Blocks (any type), Babel calls and keywords. Note: this
148 ;; is only an indication and need some thorough check.
149 "#\\(?:[+ ]\\|$\\)" "\\|"
150 ;; Drawers (any type) and fixed-width areas. This is also
151 ;; only an indication.
152 ":" "\\|"
153 ;; Horizontal rules.
154 "-\\{5,\\}[ \t]*$" "\\|"
155 ;; LaTeX environments.
156 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
157 ;; Clock lines.
158 (regexp-quote org-clock-string) "\\|"
159 ;; Lists.
160 (let ((term (case org-plain-list-ordered-item-terminator
161 (?\) ")") (?. "\\.") (otherwise "[.)]")))
162 (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
163 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
164 "\\(?:[ \t]\\|$\\)"))
165 "\\)\\)")
166 "Regexp to separate paragraphs in an Org buffer.
167 In the case of lines starting with \"#\" and \":\", this regexp
168 is not sufficient to know if point is at a paragraph ending. See
169 `org-element-paragraph-parser' for more information.")
171 (defconst org-element-all-elements
172 '(babel-call center-block clock comment comment-block diary-sexp drawer
173 dynamic-block example-block export-block fixed-width
174 footnote-definition headline horizontal-rule inlinetask item
175 keyword latex-environment node-property paragraph plain-list
176 planning property-drawer quote-block section
177 special-block src-block table table-row verse-block)
178 "Complete list of element types.")
180 (defconst org-element-greater-elements
181 '(center-block drawer dynamic-block footnote-definition headline inlinetask
182 item plain-list property-drawer quote-block section
183 special-block table)
184 "List of recursive element types aka Greater Elements.")
186 (defconst org-element-all-objects
187 '(bold code entity export-snippet footnote-reference inline-babel-call
188 inline-src-block italic line-break latex-fragment link macro
189 radio-target statistics-cookie strike-through subscript superscript
190 table-cell target timestamp underline verbatim)
191 "Complete list of object types.")
193 (defconst org-element-recursive-objects
194 '(bold footnote-reference italic link subscript radio-target strike-through
195 superscript table-cell underline)
196 "List of recursive object types.")
198 (defvar org-element-block-name-alist
199 '(("CENTER" . org-element-center-block-parser)
200 ("COMMENT" . org-element-comment-block-parser)
201 ("EXAMPLE" . org-element-example-block-parser)
202 ("QUOTE" . org-element-quote-block-parser)
203 ("SRC" . org-element-src-block-parser)
204 ("VERSE" . org-element-verse-block-parser))
205 "Alist between block names and the associated parsing function.
206 Names must be uppercase. Any block whose name has no association
207 is parsed with `org-element-special-block-parser'.")
209 (defconst org-element-link-type-is-file
210 '("file" "file+emacs" "file+sys" "docview")
211 "List of link types equivalent to \"file\".
212 Only these types can accept search options and an explicit
213 application to open them.")
215 (defconst org-element-affiliated-keywords
216 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
217 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
218 "List of affiliated keywords as strings.
219 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
220 are affiliated keywords and need not to be in this list.")
222 (defconst org-element-keyword-translation-alist
223 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
224 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
225 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
226 "Alist of usual translations for keywords.
227 The key is the old name and the value the new one. The property
228 holding their value will be named after the translated name.")
230 (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
231 "List of affiliated keywords that can occur more than once in an element.
233 Their value will be consed into a list of strings, which will be
234 returned as the value of the property.
236 This list is checked after translations have been applied. See
237 `org-element-keyword-translation-alist'.
239 By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
240 allow multiple occurrences and need not to be in this list.")
242 (defconst org-element-parsed-keywords '("CAPTION")
243 "List of affiliated keywords whose value can be parsed.
245 Their value will be stored as a secondary string: a list of
246 strings and objects.
248 This list is checked after translations have been applied. See
249 `org-element-keyword-translation-alist'.")
251 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
252 "List of affiliated keywords which can have a secondary value.
254 In Org syntax, they can be written with optional square brackets
255 before the colons. For example, RESULTS keyword can be
256 associated to a hash value with the following:
258 #+RESULTS[hash-string]: some-source
260 This list is checked after translations have been applied. See
261 `org-element-keyword-translation-alist'.")
263 (defconst org-element-document-properties '("AUTHOR" "DATE" "TITLE")
264 "List of properties associated to the whole document.
265 Any keyword in this list will have its value parsed and stored as
266 a secondary string.")
268 (defconst org-element--affiliated-re
269 (format "[ \t]*#\\+\\(?:%s\\):\\(?: \\|$\\)"
270 (concat
271 ;; Dual affiliated keywords.
272 (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
273 (regexp-opt org-element-dual-keywords))
274 "\\|"
275 ;; Regular affiliated keywords.
276 (format "\\(?1:%s\\)"
277 (regexp-opt
278 (org-remove-if
279 #'(lambda (keyword)
280 (member keyword org-element-dual-keywords))
281 org-element-affiliated-keywords)))
282 "\\|"
283 ;; Export attributes.
284 "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
285 "Regexp matching any affiliated keyword.
287 Keyword name is put in match group 1. Moreover, if keyword
288 belongs to `org-element-dual-keywords', put the dual value in
289 match group 2.
291 Don't modify it, set `org-element-affiliated-keywords' instead.")
293 (defconst org-element-object-restrictions
294 (let* ((standard-set (remq 'table-cell org-element-all-objects))
295 (standard-set-no-line-break (remq 'line-break standard-set)))
296 `((bold ,@standard-set)
297 (footnote-reference ,@standard-set)
298 (headline ,@standard-set-no-line-break)
299 (inlinetask ,@standard-set-no-line-break)
300 (italic ,@standard-set)
301 (item ,@standard-set-no-line-break)
302 (keyword ,@standard-set)
303 ;; Ignore all links excepted plain links in a link description.
304 ;; Also ignore radio-targets and line breaks.
305 (link bold code entity export-snippet inline-babel-call inline-src-block
306 italic latex-fragment macro plain-link statistics-cookie
307 strike-through subscript superscript underline verbatim)
308 (paragraph ,@standard-set)
309 ;; Remove any variable object from radio target as it would
310 ;; prevent it from being properly recognized.
311 (radio-target bold code entity italic latex-fragment strike-through
312 subscript superscript underline superscript)
313 (strike-through ,@standard-set)
314 (subscript ,@standard-set)
315 (superscript ,@standard-set)
316 ;; Ignore inline babel call and inline src block as formulas are
317 ;; possible. Also ignore line breaks and statistics cookies.
318 (table-cell bold code entity export-snippet footnote-reference italic
319 latex-fragment link macro radio-target strike-through
320 subscript superscript target timestamp underline verbatim)
321 (table-row table-cell)
322 (underline ,@standard-set)
323 (verse-block ,@standard-set)))
324 "Alist of objects restrictions.
326 key is an element or object type containing objects and value is
327 a list of types that can be contained within an element or object
328 of such type.
330 For example, in a `radio-target' object, one can only find
331 entities, latex-fragments, subscript, superscript and text
332 markup.
334 This alist also applies to secondary string. For example, an
335 `headline' type element doesn't directly contain objects, but
336 still has an entry since one of its properties (`:title') does.")
338 (defconst org-element-secondary-value-alist
339 '((headline . :title)
340 (inlinetask . :title)
341 (item . :tag))
342 "Alist between element types and location of secondary value.")
346 ;;; Accessors and Setters
348 ;; Provide four accessors: `org-element-type', `org-element-property'
349 ;; `org-element-contents' and `org-element-restriction'.
351 ;; Setter functions allow to modify elements by side effect. There is
352 ;; `org-element-put-property', `org-element-set-contents'. These
353 ;; low-level functions are useful to build a parse tree.
355 ;; `org-element-adopt-element', `org-element-set-element',
356 ;; `org-element-extract-element' and `org-element-insert-before' are
357 ;; high-level functions useful to modify a parse tree.
359 ;; `org-element-secondary-p' is a predicate used to know if a given
360 ;; object belongs to a secondary string.
362 (defsubst org-element-type (element)
363 "Return type of ELEMENT.
365 The function returns the type of the element or object provided.
366 It can also return the following special value:
367 `plain-text' for a string
368 `org-data' for a complete document
369 nil in any other case."
370 (cond
371 ((not (consp element)) (and (stringp element) 'plain-text))
372 ((symbolp (car element)) (car element))))
374 (defsubst org-element-property (property element)
375 "Extract the value from the PROPERTY of an ELEMENT."
376 (if (stringp element) (get-text-property 0 property element)
377 (plist-get (nth 1 element) property)))
379 (defsubst org-element-contents (element)
380 "Extract contents from an ELEMENT."
381 (cond ((not (consp element)) nil)
382 ((symbolp (car element)) (nthcdr 2 element))
383 (t element)))
385 (defsubst org-element-restriction (element)
386 "Return restriction associated to ELEMENT.
387 ELEMENT can be an element, an object or a symbol representing an
388 element or object type."
389 (cdr (assq (if (symbolp element) element (org-element-type element))
390 org-element-object-restrictions)))
392 (defsubst org-element-put-property (element property value)
393 "In ELEMENT set PROPERTY to VALUE.
394 Return modified element."
395 (if (stringp element) (org-add-props element nil property value)
396 (setcar (cdr element) (plist-put (nth 1 element) property value))
397 element))
399 (defsubst org-element-set-contents (element &rest contents)
400 "Set ELEMENT contents to CONTENTS.
401 Return modified element."
402 (cond ((not element) (list contents))
403 ((not (symbolp (car element))) contents)
404 ((cdr element) (setcdr (cdr element) contents))
405 (t (nconc element contents))))
407 (defun org-element-secondary-p (object)
408 "Non-nil when OBJECT belongs to a secondary string.
409 Return value is the property name, as a keyword, or nil."
410 (let* ((parent (org-element-property :parent object))
411 (property (cdr (assq (org-element-type parent)
412 org-element-secondary-value-alist))))
413 (and property
414 (memq object (org-element-property property parent))
415 property)))
417 (defsubst org-element-adopt-elements (parent &rest children)
418 "Append elements to the contents of another element.
420 PARENT is an element or object. CHILDREN can be elements,
421 objects, or a strings.
423 The function takes care of setting `:parent' property for CHILD.
424 Return parent element."
425 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
426 ;; string: parent is the list itself.
427 (mapc (lambda (child)
428 (org-element-put-property child :parent (or parent children)))
429 children)
430 ;; Add CHILDREN at the end of PARENT contents.
431 (when parent
432 (apply 'org-element-set-contents
433 parent
434 (nconc (org-element-contents parent) children)))
435 ;; Return modified PARENT element.
436 (or parent children))
438 (defun org-element-extract-element (element)
439 "Extract ELEMENT from parse tree.
440 Remove element from the parse tree by side-effect, and return it
441 with its `:parent' property stripped out."
442 (let ((parent (org-element-property :parent element))
443 (secondary (org-element-secondary-p element)))
444 (if secondary
445 (org-element-put-property
446 parent secondary
447 (delq element (org-element-property secondary parent)))
448 (apply #'org-element-set-contents
449 parent
450 (delq element (org-element-contents parent))))
451 ;; Return ELEMENT with its :parent removed.
452 (org-element-put-property element :parent nil)))
454 (defun org-element-insert-before (element location)
455 "Insert ELEMENT before LOCATION in parse tree.
456 LOCATION is an element, object or string within the parse tree.
457 Parse tree is modified by side effect."
458 (let* ((parent (org-element-property :parent location))
459 (property (org-element-secondary-p location))
460 (siblings (if property (org-element-property property parent)
461 (org-element-contents parent)))
462 ;; Special case: LOCATION is the first element of an
463 ;; independent secondary string (e.g. :title property). Add
464 ;; ELEMENT in-place.
465 (specialp (and (not property)
466 (eq siblings parent)
467 (eq (car parent) location))))
468 ;; Install ELEMENT at the appropriate POSITION within SIBLINGS.
469 (cond (specialp)
470 ((or (null siblings) (eq (car siblings) location))
471 (push element siblings))
472 ((null location) (nconc siblings (list element)))
473 (t (let ((previous (cadr (memq location (reverse siblings)))))
474 (if (not previous)
475 (error "No location found to insert element")
476 (let ((next (memq previous siblings)))
477 (setcdr next (cons element (cdr next))))))))
478 ;; Store SIBLINGS at appropriate place in parse tree.
479 (cond
480 (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
481 (property (org-element-put-property parent property siblings))
482 (t (apply #'org-element-set-contents parent siblings)))
483 ;; Set appropriate :parent property.
484 (org-element-put-property element :parent parent)))
486 (defun org-element-set-element (old new)
487 "Replace element or object OLD with element or object NEW.
488 The function takes care of setting `:parent' property for NEW."
489 ;; Ensure OLD and NEW have the same parent.
490 (org-element-put-property new :parent (org-element-property :parent old))
491 (if (or (memq (org-element-type old) '(plain-text nil))
492 (memq (org-element-type new) '(plain-text nil)))
493 ;; We cannot replace OLD with NEW since one of them is not an
494 ;; object or element. We take the long path.
495 (progn (org-element-insert-before new old)
496 (org-element-extract-element old))
497 ;; Since OLD is going to be changed into NEW by side-effect, first
498 ;; make sure that every element or object within NEW has OLD as
499 ;; parent.
500 (dolist (blob (org-element-contents new))
501 (org-element-put-property blob :parent old))
502 ;; Transfer contents.
503 (apply #'org-element-set-contents old (org-element-contents new))
504 ;; Overwrite OLD's properties with NEW's.
505 (setcar (cdr old) (nth 1 new))
506 ;; Transfer type.
507 (setcar old (car new))))
511 ;;; Greater elements
513 ;; For each greater element type, we define a parser and an
514 ;; interpreter.
516 ;; A parser returns the element or object as the list described above.
517 ;; Most of them accepts no argument. Though, exceptions exist. Hence
518 ;; every element containing a secondary string (see
519 ;; `org-element-secondary-value-alist') will accept an optional
520 ;; argument to toggle parsing of that secondary string. Moreover,
521 ;; `item' parser requires current list's structure as its first
522 ;; element.
524 ;; An interpreter accepts two arguments: the list representation of
525 ;; the element or object, and its contents. The latter may be nil,
526 ;; depending on the element or object considered. It returns the
527 ;; appropriate Org syntax, as a string.
529 ;; Parsing functions must follow the naming convention:
530 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
531 ;; defined in `org-element-greater-elements'.
533 ;; Similarly, interpreting functions must follow the naming
534 ;; convention: org-element-TYPE-interpreter.
536 ;; With the exception of `headline' and `item' types, greater elements
537 ;; cannot contain other greater elements of their own type.
539 ;; Beside implementing a parser and an interpreter, adding a new
540 ;; greater element requires to tweak `org-element--current-element'.
541 ;; Moreover, the newly defined type must be added to both
542 ;; `org-element-all-elements' and `org-element-greater-elements'.
545 ;;;; Center Block
547 (defun org-element-center-block-parser (limit affiliated)
548 "Parse a center block.
550 LIMIT bounds the search. AFFILIATED is a list of which CAR is
551 the buffer position at the beginning of the first affiliated
552 keyword and CDR is a plist of affiliated keywords along with
553 their value.
555 Return a list whose CAR is `center-block' and CDR is a plist
556 containing `:begin', `:end', `:contents-begin', `:contents-end',
557 `:post-blank' and `:post-affiliated' keywords.
559 Assume point is at the beginning of the block."
560 (let ((case-fold-search t))
561 (if (not (save-excursion
562 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
563 ;; Incomplete block: parse it as a paragraph.
564 (org-element-paragraph-parser limit affiliated)
565 (let ((block-end-line (match-beginning 0)))
566 (let* ((begin (car affiliated))
567 (post-affiliated (point))
568 ;; Empty blocks have no contents.
569 (contents-begin (progn (forward-line)
570 (and (< (point) block-end-line)
571 (point))))
572 (contents-end (and contents-begin block-end-line))
573 (pos-before-blank (progn (goto-char block-end-line)
574 (forward-line)
575 (point)))
576 (end (save-excursion
577 (skip-chars-forward " \r\t\n" limit)
578 (if (eobp) (point) (line-beginning-position)))))
579 (list 'center-block
580 (nconc
581 (list :begin begin
582 :end end
583 :contents-begin contents-begin
584 :contents-end contents-end
585 :post-blank (count-lines pos-before-blank end)
586 :post-affiliated post-affiliated)
587 (cdr affiliated))))))))
589 (defun org-element-center-block-interpreter (center-block contents)
590 "Interpret CENTER-BLOCK element as Org syntax.
591 CONTENTS is the contents of the element."
592 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
595 ;;;; Drawer
597 (defun org-element-drawer-parser (limit affiliated)
598 "Parse a drawer.
600 LIMIT bounds the search. AFFILIATED is a list of which CAR is
601 the buffer position at the beginning of the first affiliated
602 keyword and CDR is a plist of affiliated keywords along with
603 their value.
605 Return a list whose CAR is `drawer' and CDR is a plist containing
606 `:drawer-name', `:begin', `:end', `:contents-begin',
607 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
609 Assume point is at beginning of drawer."
610 (let ((case-fold-search t))
611 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
612 ;; Incomplete drawer: parse it as a paragraph.
613 (org-element-paragraph-parser limit affiliated)
614 (save-excursion
615 (let* ((drawer-end-line (match-beginning 0))
616 (name (progn (looking-at org-drawer-regexp)
617 (org-match-string-no-properties 1)))
618 (begin (car affiliated))
619 (post-affiliated (point))
620 ;; Empty drawers have no contents.
621 (contents-begin (progn (forward-line)
622 (and (< (point) drawer-end-line)
623 (point))))
624 (contents-end (and contents-begin drawer-end-line))
625 (pos-before-blank (progn (goto-char drawer-end-line)
626 (forward-line)
627 (point)))
628 (end (progn (skip-chars-forward " \r\t\n" limit)
629 (if (eobp) (point) (line-beginning-position)))))
630 (list 'drawer
631 (nconc
632 (list :begin begin
633 :end end
634 :drawer-name name
635 :contents-begin contents-begin
636 :contents-end contents-end
637 :post-blank (count-lines pos-before-blank end)
638 :post-affiliated post-affiliated)
639 (cdr affiliated))))))))
641 (defun org-element-drawer-interpreter (drawer contents)
642 "Interpret DRAWER element as Org syntax.
643 CONTENTS is the contents of the element."
644 (format ":%s:\n%s:END:"
645 (org-element-property :drawer-name drawer)
646 contents))
649 ;;;; Dynamic Block
651 (defun org-element-dynamic-block-parser (limit affiliated)
652 "Parse a dynamic block.
654 LIMIT bounds the search. AFFILIATED is a list of which CAR is
655 the buffer position at the beginning of the first affiliated
656 keyword and CDR is a plist of affiliated keywords along with
657 their value.
659 Return a list whose CAR is `dynamic-block' and CDR is a plist
660 containing `:block-name', `:begin', `:end', `:contents-begin',
661 `:contents-end', `:arguments', `:post-blank' and
662 `:post-affiliated' keywords.
664 Assume point is at beginning of dynamic block."
665 (let ((case-fold-search t))
666 (if (not (save-excursion
667 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
668 ;; Incomplete block: parse it as a paragraph.
669 (org-element-paragraph-parser limit affiliated)
670 (let ((block-end-line (match-beginning 0)))
671 (save-excursion
672 (let* ((name (progn (looking-at org-dblock-start-re)
673 (org-match-string-no-properties 1)))
674 (arguments (org-match-string-no-properties 3))
675 (begin (car affiliated))
676 (post-affiliated (point))
677 ;; Empty blocks have no contents.
678 (contents-begin (progn (forward-line)
679 (and (< (point) block-end-line)
680 (point))))
681 (contents-end (and contents-begin block-end-line))
682 (pos-before-blank (progn (goto-char block-end-line)
683 (forward-line)
684 (point)))
685 (end (progn (skip-chars-forward " \r\t\n" limit)
686 (if (eobp) (point) (line-beginning-position)))))
687 (list 'dynamic-block
688 (nconc
689 (list :begin begin
690 :end end
691 :block-name name
692 :arguments arguments
693 :contents-begin contents-begin
694 :contents-end contents-end
695 :post-blank (count-lines pos-before-blank end)
696 :post-affiliated post-affiliated)
697 (cdr affiliated)))))))))
699 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
700 "Interpret DYNAMIC-BLOCK element as Org syntax.
701 CONTENTS is the contents of the element."
702 (format "#+BEGIN: %s%s\n%s#+END:"
703 (org-element-property :block-name dynamic-block)
704 (let ((args (org-element-property :arguments dynamic-block)))
705 (and args (concat " " args)))
706 contents))
709 ;;;; Footnote Definition
711 (defun org-element-footnote-definition-parser (limit affiliated)
712 "Parse a footnote definition.
714 LIMIT bounds the search. AFFILIATED is a list of which CAR is
715 the buffer position at the beginning of the first affiliated
716 keyword and CDR is a plist of affiliated keywords along with
717 their value.
719 Return a list whose CAR is `footnote-definition' and CDR is
720 a plist containing `:label', `:begin' `:end', `:contents-begin',
721 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
723 Assume point is at the beginning of the footnote definition."
724 (save-excursion
725 (let* ((label (progn (looking-at org-footnote-definition-re)
726 (org-match-string-no-properties 1)))
727 (begin (car affiliated))
728 (post-affiliated (point))
729 (ending (save-excursion
730 (if (progn
731 (end-of-line)
732 (re-search-forward
733 (concat org-outline-regexp-bol "\\|"
734 org-footnote-definition-re "\\|"
735 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
736 (match-beginning 0)
737 (point))))
738 (contents-begin (progn
739 (search-forward "]")
740 (skip-chars-forward " \r\t\n" ending)
741 (cond ((= (point) ending) nil)
742 ((= (line-beginning-position) begin) (point))
743 (t (line-beginning-position)))))
744 (contents-end (and contents-begin ending))
745 (end (progn (goto-char ending)
746 (skip-chars-forward " \r\t\n" limit)
747 (if (eobp) (point) (line-beginning-position)))))
748 (list 'footnote-definition
749 (nconc
750 (list :label label
751 :begin begin
752 :end end
753 :contents-begin contents-begin
754 :contents-end contents-end
755 :post-blank (count-lines ending end)
756 :post-affiliated post-affiliated)
757 (cdr affiliated))))))
759 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
760 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
761 CONTENTS is the contents of the footnote-definition."
762 (concat (format "[%s]" (org-element-property :label footnote-definition))
764 contents))
767 ;;;; Headline
769 (defun org-element--get-node-properties ()
770 "Return node properties associated to headline at point.
771 Upcase property names. It avoids confusion between properties
772 obtained through property drawer and default properties from the
773 parser (e.g. `:end' and :END:). Return value is a plist."
774 (save-excursion
775 (forward-line)
776 (when (org-looking-at-p org-planning-line-re) (forward-line))
777 (when (looking-at org-property-drawer-re)
778 (forward-line)
779 (let ((end (match-end 0)) properties)
780 (while (< (line-end-position) end)
781 (looking-at org-property-re)
782 (push (org-match-string-no-properties 3) properties)
783 (push (intern (concat ":" (upcase (match-string 2)))) properties)
784 (forward-line))
785 properties))))
787 (defun org-element--get-time-properties ()
788 "Return time properties associated to headline at point.
789 Return value is a plist."
790 (save-excursion
791 (when (progn (forward-line) (looking-at org-planning-line-re))
792 (let ((end (line-end-position)) plist)
793 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
794 (goto-char (match-end 1))
795 (skip-chars-forward " \t")
796 (let ((keyword (match-string 1))
797 (time (org-element-timestamp-parser)))
798 (cond ((equal keyword org-scheduled-string)
799 (setq plist (plist-put plist :scheduled time)))
800 ((equal keyword org-deadline-string)
801 (setq plist (plist-put plist :deadline time)))
802 (t (setq plist (plist-put plist :closed time))))))
803 plist))))
805 (defun org-element-headline-parser (limit &optional raw-secondary-p)
806 "Parse a headline.
808 Return a list whose CAR is `headline' and CDR is a plist
809 containing `:raw-value', `:title', `:alt-title', `:begin',
810 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
811 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
812 `:scheduled', `:deadline', `:closed', `:archivedp', `:commentedp'
813 `:footnote-section-p', `:post-blank' and `:post-affiliated'
814 keywords.
816 The plist also contains any property set in the property drawer,
817 with its name in upper cases and colons added at the
818 beginning (e.g., `:CUSTOM_ID').
820 LIMIT is a buffer position bounding the search.
822 When RAW-SECONDARY-P is non-nil, headline's title will not be
823 parsed as a secondary string, but as a plain string instead.
825 Assume point is at beginning of the headline."
826 (save-excursion
827 (let* ((components (org-heading-components))
828 (level (nth 1 components))
829 (todo (nth 2 components))
830 (todo-type
831 (and todo (if (member todo org-done-keywords) 'done 'todo)))
832 (tags (let ((raw-tags (nth 5 components)))
833 (and raw-tags (org-split-string raw-tags ":"))))
834 (raw-value (or (nth 4 components) ""))
835 (commentedp
836 (let ((case-fold-search nil))
837 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
838 raw-value)))
839 (archivedp (member org-archive-tag tags))
840 (footnote-section-p (and org-footnote-section
841 (string= org-footnote-section raw-value)))
842 (standard-props (org-element--get-node-properties))
843 (time-props (org-element--get-time-properties))
844 (begin (point))
845 (end (min (save-excursion (org-end-of-subtree t t)) limit))
846 (pos-after-head (progn (forward-line) (point)))
847 (contents-begin (save-excursion
848 (skip-chars-forward " \r\t\n" end)
849 (and (/= (point) end) (line-beginning-position))))
850 (contents-end (and contents-begin
851 (progn (goto-char end)
852 (skip-chars-backward " \r\t\n")
853 (forward-line)
854 (point)))))
855 ;; Clean RAW-VALUE from any comment string.
856 (when commentedp
857 (let ((case-fold-search nil))
858 (setq raw-value
859 (replace-regexp-in-string
860 (concat (regexp-quote org-comment-string) "\\(?: \\|$\\)")
862 raw-value))))
863 ;; Clean TAGS from archive tag, if any.
864 (when archivedp (setq tags (delete org-archive-tag tags)))
865 (let ((headline
866 (list 'headline
867 (nconc
868 (list :raw-value raw-value
869 :begin begin
870 :end end
871 :pre-blank
872 (if (not contents-begin) 0
873 (count-lines pos-after-head contents-begin))
874 :contents-begin contents-begin
875 :contents-end contents-end
876 :level level
877 :priority (nth 3 components)
878 :tags tags
879 :todo-keyword todo
880 :todo-type todo-type
881 :post-blank (count-lines
882 (or contents-end pos-after-head)
883 end)
884 :footnote-section-p footnote-section-p
885 :archivedp archivedp
886 :commentedp commentedp
887 :post-affiliated begin)
888 time-props
889 standard-props))))
890 (let ((alt-title (org-element-property :ALT_TITLE headline)))
891 (when alt-title
892 (org-element-put-property
893 headline :alt-title
894 (if raw-secondary-p alt-title
895 (org-element-parse-secondary-string
896 alt-title (org-element-restriction 'headline) headline)))))
897 (org-element-put-property
898 headline :title
899 (if raw-secondary-p raw-value
900 (org-element-parse-secondary-string
901 raw-value (org-element-restriction 'headline) headline)))))))
903 (defun org-element-headline-interpreter (headline contents)
904 "Interpret HEADLINE element as Org syntax.
905 CONTENTS is the contents of the element."
906 (let* ((level (org-element-property :level headline))
907 (todo (org-element-property :todo-keyword headline))
908 (priority (org-element-property :priority headline))
909 (title (org-element-interpret-data
910 (org-element-property :title headline)))
911 (tags (let ((tag-list (if (org-element-property :archivedp headline)
912 (cons org-archive-tag
913 (org-element-property :tags headline))
914 (org-element-property :tags headline))))
915 (and tag-list
916 (format ":%s:" (mapconcat #'identity tag-list ":")))))
917 (commentedp (org-element-property :commentedp headline))
918 (pre-blank (or (org-element-property :pre-blank headline) 0))
919 (heading
920 (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
922 (and todo (concat " " todo))
923 (and commentedp (concat " " org-comment-string))
924 (and priority (format " [#%s]" (char-to-string priority)))
926 (if (and org-footnote-section
927 (org-element-property :footnote-section-p headline))
928 org-footnote-section
929 title))))
930 (concat
931 heading
932 ;; Align tags.
933 (when tags
934 (cond
935 ((zerop org-tags-column) (format " %s" tags))
936 ((< org-tags-column 0)
937 (concat
938 (make-string
939 (max (- (+ org-tags-column (length heading) (length tags))) 1)
940 ?\s)
941 tags))
943 (concat
944 (make-string (max (- org-tags-column (length heading)) 1) ?\s)
945 tags))))
946 (make-string (1+ pre-blank) ?\n)
947 contents)))
950 ;;;; Inlinetask
952 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
953 "Parse an inline task.
955 Return a list whose CAR is `inlinetask' and CDR is a plist
956 containing `:title', `:begin', `:end', `:contents-begin' and
957 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
958 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
959 `:closed', `:post-blank' and `:post-affiliated' keywords.
961 The plist also contains any property set in the property drawer,
962 with its name in upper cases and colons added at the
963 beginning (e.g., `:CUSTOM_ID').
965 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
966 title will not be parsed as a secondary string, but as a plain
967 string instead.
969 Assume point is at beginning of the inline task."
970 (save-excursion
971 (let* ((begin (point))
972 (components (org-heading-components))
973 (todo (nth 2 components))
974 (todo-type (and todo
975 (if (member todo org-done-keywords) 'done 'todo)))
976 (tags (let ((raw-tags (nth 5 components)))
977 (and raw-tags (org-split-string raw-tags ":"))))
978 (raw-value (or (nth 4 components) ""))
979 (task-end (save-excursion
980 (end-of-line)
981 (and (re-search-forward org-outline-regexp-bol limit t)
982 (org-looking-at-p "END[ \t]*$")
983 (line-beginning-position))))
984 (standard-props (and task-end (org-element--get-node-properties)))
985 (time-props (and task-end (org-element--get-time-properties)))
986 (contents-begin (progn (forward-line)
987 (and task-end (< (point) task-end) (point))))
988 (contents-end (and contents-begin task-end))
989 (before-blank (if (not task-end) (point)
990 (goto-char task-end)
991 (forward-line)
992 (point)))
993 (end (progn (skip-chars-forward " \r\t\n" limit)
994 (if (eobp) (point) (line-beginning-position))))
995 (inlinetask
996 (list 'inlinetask
997 (nconc
998 (list :raw-value raw-value
999 :begin begin
1000 :end end
1001 :contents-begin contents-begin
1002 :contents-end contents-end
1003 :level (nth 1 components)
1004 :priority (nth 3 components)
1005 :tags tags
1006 :todo-keyword todo
1007 :todo-type todo-type
1008 :post-blank (count-lines before-blank end)
1009 :post-affiliated begin)
1010 time-props
1011 standard-props))))
1012 (org-element-put-property
1013 inlinetask :title
1014 (if raw-secondary-p raw-value
1015 (org-element-parse-secondary-string
1016 raw-value
1017 (org-element-restriction 'inlinetask)
1018 inlinetask))))))
1020 (defun org-element-inlinetask-interpreter (inlinetask contents)
1021 "Interpret INLINETASK element as Org syntax.
1022 CONTENTS is the contents of inlinetask."
1023 (let* ((level (org-element-property :level inlinetask))
1024 (todo (org-element-property :todo-keyword inlinetask))
1025 (priority (org-element-property :priority inlinetask))
1026 (title (org-element-interpret-data
1027 (org-element-property :title inlinetask)))
1028 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1029 (and tag-list
1030 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1031 (task (concat (make-string level ?*)
1032 (and todo (concat " " todo))
1033 (and priority
1034 (format " [#%s]" (char-to-string priority)))
1035 (and title (concat " " title)))))
1036 (concat task
1037 ;; Align tags.
1038 (when tags
1039 (cond
1040 ((zerop org-tags-column) (format " %s" tags))
1041 ((< org-tags-column 0)
1042 (concat
1043 (make-string
1044 (max (- (+ org-tags-column (length task) (length tags))) 1)
1046 tags))
1048 (concat
1049 (make-string (max (- org-tags-column (length task)) 1) ? )
1050 tags))))
1051 ;; Prefer degenerate inlinetasks when there are no
1052 ;; contents.
1053 (when contents
1054 (concat "\n"
1055 contents
1056 (make-string level ?*) " END")))))
1059 ;;;; Item
1061 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1062 "Parse an item.
1064 STRUCT is the structure of the plain list.
1066 Return a list whose CAR is `item' and CDR is a plist containing
1067 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1068 `:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
1069 `:post-affiliated' keywords.
1071 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1072 any, will not be parsed as a secondary string, but as a plain
1073 string instead.
1075 Assume point is at the beginning of the item."
1076 (save-excursion
1077 (beginning-of-line)
1078 (looking-at org-list-full-item-re)
1079 (let* ((begin (point))
1080 (bullet (org-match-string-no-properties 1))
1081 (checkbox (let ((box (org-match-string-no-properties 3)))
1082 (cond ((equal "[ ]" box) 'off)
1083 ((equal "[X]" box) 'on)
1084 ((equal "[-]" box) 'trans))))
1085 (counter (let ((c (org-match-string-no-properties 2)))
1086 (save-match-data
1087 (cond
1088 ((not c) nil)
1089 ((string-match "[A-Za-z]" c)
1090 (- (string-to-char (upcase (match-string 0 c)))
1091 64))
1092 ((string-match "[0-9]+" c)
1093 (string-to-number (match-string 0 c)))))))
1094 (end (progn (goto-char (nth 6 (assq (point) struct)))
1095 (unless (bolp) (forward-line))
1096 (point)))
1097 (contents-begin
1098 (progn (goto-char
1099 ;; Ignore tags in un-ordered lists: they are just
1100 ;; a part of item's body.
1101 (if (and (match-beginning 4)
1102 (save-match-data (string-match "[.)]" bullet)))
1103 (match-beginning 4)
1104 (match-end 0)))
1105 (skip-chars-forward " \r\t\n" limit)
1106 ;; If first line isn't empty, contents really start
1107 ;; at the text after item's meta-data.
1108 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1109 (contents-end (progn (goto-char end)
1110 (skip-chars-backward " \r\t\n")
1111 (forward-line)
1112 (point)))
1113 (item
1114 (list 'item
1115 (list :bullet bullet
1116 :begin begin
1117 :end end
1118 ;; CONTENTS-BEGIN and CONTENTS-END may be
1119 ;; mixed up in the case of an empty item
1120 ;; separated from the next by a blank line.
1121 ;; Thus ensure the former is always the
1122 ;; smallest.
1123 :contents-begin (min contents-begin contents-end)
1124 :contents-end (max contents-begin contents-end)
1125 :checkbox checkbox
1126 :counter counter
1127 :structure struct
1128 :post-blank (count-lines contents-end end)
1129 :post-affiliated begin))))
1130 (org-element-put-property
1131 item :tag
1132 (let ((raw-tag (org-list-get-tag begin struct)))
1133 (and raw-tag
1134 (if raw-secondary-p raw-tag
1135 (org-element-parse-secondary-string
1136 raw-tag (org-element-restriction 'item) item))))))))
1138 (defun org-element-item-interpreter (item contents)
1139 "Interpret ITEM element as Org syntax.
1140 CONTENTS is the contents of the element."
1141 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1142 (org-list-bullet-string
1143 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1144 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1145 (t "1.")))))
1146 (checkbox (org-element-property :checkbox item))
1147 (counter (org-element-property :counter item))
1148 (tag (let ((tag (org-element-property :tag item)))
1149 (and tag (org-element-interpret-data tag))))
1150 ;; Compute indentation.
1151 (ind (make-string (length bullet) 32))
1152 (item-starts-with-par-p
1153 (eq (org-element-type (car (org-element-contents item)))
1154 'paragraph)))
1155 ;; Indent contents.
1156 (concat
1157 bullet
1158 (and counter (format "[@%d] " counter))
1159 (case checkbox
1160 (on "[X] ")
1161 (off "[ ] ")
1162 (trans "[-] "))
1163 (and tag (format "%s :: " tag))
1164 (when contents
1165 (let ((contents (replace-regexp-in-string
1166 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1167 (if item-starts-with-par-p (org-trim contents)
1168 (concat "\n" contents)))))))
1171 ;;;; Plain List
1173 (defun org-element--list-struct (limit)
1174 ;; Return structure of list at point. Internal function. See
1175 ;; `org-list-struct' for details.
1176 (let ((case-fold-search t)
1177 (top-ind limit)
1178 (item-re (org-item-re))
1179 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1180 items struct)
1181 (save-excursion
1182 (catch 'exit
1183 (while t
1184 (cond
1185 ;; At limit: end all items.
1186 ((>= (point) limit)
1187 (throw 'exit
1188 (let ((end (progn (skip-chars-backward " \r\t\n")
1189 (forward-line)
1190 (point))))
1191 (dolist (item items (sort (nconc items struct)
1192 'car-less-than-car))
1193 (setcar (nthcdr 6 item) end)))))
1194 ;; At list end: end all items.
1195 ((looking-at org-list-end-re)
1196 (throw 'exit (dolist (item items (sort (nconc items struct)
1197 'car-less-than-car))
1198 (setcar (nthcdr 6 item) (point)))))
1199 ;; At a new item: end previous sibling.
1200 ((looking-at item-re)
1201 (let ((ind (save-excursion (skip-chars-forward " \t")
1202 (current-column))))
1203 (setq top-ind (min top-ind ind))
1204 (while (and items (<= ind (nth 1 (car items))))
1205 (let ((item (pop items)))
1206 (setcar (nthcdr 6 item) (point))
1207 (push item struct)))
1208 (push (progn (looking-at org-list-full-item-re)
1209 (let ((bullet (match-string-no-properties 1)))
1210 (list (point)
1212 bullet
1213 (match-string-no-properties 2) ; counter
1214 (match-string-no-properties 3) ; checkbox
1215 ;; Description tag.
1216 (and (save-match-data
1217 (string-match "[-+*]" bullet))
1218 (match-string-no-properties 4))
1219 ;; Ending position, unknown so far.
1220 nil)))
1221 items))
1222 (forward-line 1))
1223 ;; Skip empty lines.
1224 ((looking-at "^[ \t]*$") (forward-line))
1225 ;; Skip inline tasks and blank lines along the way.
1226 ((and inlinetask-re (looking-at inlinetask-re))
1227 (forward-line)
1228 (let ((origin (point)))
1229 (when (re-search-forward inlinetask-re limit t)
1230 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1231 (goto-char origin)))))
1232 ;; At some text line. Check if it ends any previous item.
1234 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1235 (when (<= ind top-ind)
1236 (skip-chars-backward " \r\t\n")
1237 (forward-line))
1238 (while (<= ind (nth 1 (car items)))
1239 (let ((item (pop items)))
1240 (setcar (nthcdr 6 item) (line-beginning-position))
1241 (push item struct)
1242 (unless items
1243 (throw 'exit (sort struct 'car-less-than-car))))))
1244 ;; Skip blocks (any type) and drawers contents.
1245 (cond
1246 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1247 (re-search-forward
1248 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1249 limit t)))
1250 ((and (looking-at org-drawer-regexp)
1251 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1252 (forward-line))))))))
1254 (defun org-element-plain-list-parser (limit affiliated structure)
1255 "Parse a plain list.
1257 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1258 the buffer position at the beginning of the first affiliated
1259 keyword and CDR is a plist of affiliated keywords along with
1260 their value. STRUCTURE is the structure of the plain list being
1261 parsed.
1263 Return a list whose CAR is `plain-list' and CDR is a plist
1264 containing `:type', `:begin', `:end', `:contents-begin' and
1265 `:contents-end', `:structure', `:post-blank' and
1266 `:post-affiliated' keywords.
1268 Assume point is at the beginning of the list."
1269 (save-excursion
1270 (let* ((struct (or structure (org-element--list-struct limit)))
1271 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1272 ((nth 5 (assq (point) struct)) 'descriptive)
1273 (t 'unordered)))
1274 (contents-begin (point))
1275 (begin (car affiliated))
1276 (contents-end (let* ((item (assq contents-begin struct))
1277 (ind (nth 1 item))
1278 (pos (nth 6 item)))
1279 (while (and (setq item (assq pos struct))
1280 (= (nth 1 item) ind))
1281 (setq pos (nth 6 item)))
1282 pos))
1283 (end (progn (goto-char contents-end)
1284 (skip-chars-forward " \r\t\n" limit)
1285 (if (= (point) limit) limit (line-beginning-position)))))
1286 ;; Return value.
1287 (list 'plain-list
1288 (nconc
1289 (list :type type
1290 :begin begin
1291 :end end
1292 :contents-begin contents-begin
1293 :contents-end contents-end
1294 :structure struct
1295 :post-blank (count-lines contents-end end)
1296 :post-affiliated contents-begin)
1297 (cdr affiliated))))))
1299 (defun org-element-plain-list-interpreter (plain-list contents)
1300 "Interpret PLAIN-LIST element as Org syntax.
1301 CONTENTS is the contents of the element."
1302 (with-temp-buffer
1303 (insert contents)
1304 (goto-char (point-min))
1305 (org-list-repair)
1306 (buffer-string)))
1309 ;;;; Property Drawer
1311 (defun org-element-property-drawer-parser (limit)
1312 "Parse a property drawer.
1314 LIMIT bounds the search.
1316 Return a list whose car is `property-drawer' and cdr is a plist
1317 containing `:begin', `:end', `:contents-begin', `:contents-end',
1318 `:post-blank' and `:post-affiliated' keywords.
1320 Assume point is at the beginning of the property drawer."
1321 (save-excursion
1322 (let ((case-fold-search t)
1323 (begin (point))
1324 (contents-begin (line-beginning-position 2)))
1325 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
1326 (let ((contents-end (and (> (match-beginning 0) contents-begin)
1327 (match-beginning 0)))
1328 (before-blank (progn (forward-line) (point)))
1329 (end (progn (skip-chars-forward " \r\t\n" limit)
1330 (if (eobp) (point) (line-beginning-position)))))
1331 (list 'property-drawer
1332 (list :begin begin
1333 :end end
1334 :contents-begin (and contents-end contents-begin)
1335 :contents-end contents-end
1336 :post-blank (count-lines before-blank end)
1337 :post-affiliated begin))))))
1339 (defun org-element-property-drawer-interpreter (property-drawer contents)
1340 "Interpret PROPERTY-DRAWER element as Org syntax.
1341 CONTENTS is the properties within the drawer."
1342 (format ":PROPERTIES:\n%s:END:" contents))
1345 ;;;; Quote Block
1347 (defun org-element-quote-block-parser (limit affiliated)
1348 "Parse a quote block.
1350 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1351 the buffer position at the beginning of the first affiliated
1352 keyword and CDR is a plist of affiliated keywords along with
1353 their value.
1355 Return a list whose CAR is `quote-block' and CDR is a plist
1356 containing `:begin', `:end', `:contents-begin', `:contents-end',
1357 `:post-blank' and `:post-affiliated' keywords.
1359 Assume point is at the beginning of the block."
1360 (let ((case-fold-search t))
1361 (if (not (save-excursion
1362 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1363 ;; Incomplete block: parse it as a paragraph.
1364 (org-element-paragraph-parser limit affiliated)
1365 (let ((block-end-line (match-beginning 0)))
1366 (save-excursion
1367 (let* ((begin (car affiliated))
1368 (post-affiliated (point))
1369 ;; Empty blocks have no contents.
1370 (contents-begin (progn (forward-line)
1371 (and (< (point) block-end-line)
1372 (point))))
1373 (contents-end (and contents-begin block-end-line))
1374 (pos-before-blank (progn (goto-char block-end-line)
1375 (forward-line)
1376 (point)))
1377 (end (progn (skip-chars-forward " \r\t\n" limit)
1378 (if (eobp) (point) (line-beginning-position)))))
1379 (list 'quote-block
1380 (nconc
1381 (list :begin begin
1382 :end end
1383 :contents-begin contents-begin
1384 :contents-end contents-end
1385 :post-blank (count-lines pos-before-blank end)
1386 :post-affiliated post-affiliated)
1387 (cdr affiliated)))))))))
1389 (defun org-element-quote-block-interpreter (quote-block contents)
1390 "Interpret QUOTE-BLOCK element as Org syntax.
1391 CONTENTS is the contents of the element."
1392 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1395 ;;;; Section
1397 (defun org-element-section-parser (limit)
1398 "Parse a section.
1400 LIMIT bounds the search.
1402 Return a list whose CAR is `section' and CDR is a plist
1403 containing `:begin', `:end', `:contents-begin', `contents-end',
1404 `:post-blank' and `:post-affiliated' keywords."
1405 (save-excursion
1406 ;; Beginning of section is the beginning of the first non-blank
1407 ;; line after previous headline.
1408 (let ((begin (point))
1409 (end (progn (org-with-limited-levels (outline-next-heading))
1410 (point)))
1411 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1412 (forward-line)
1413 (point))))
1414 (list 'section
1415 (list :begin begin
1416 :end end
1417 :contents-begin begin
1418 :contents-end pos-before-blank
1419 :post-blank (count-lines pos-before-blank end)
1420 :post-affiliated begin)))))
1422 (defun org-element-section-interpreter (section contents)
1423 "Interpret SECTION element as Org syntax.
1424 CONTENTS is the contents of the element."
1425 contents)
1428 ;;;; Special Block
1430 (defun org-element-special-block-parser (limit affiliated)
1431 "Parse a special block.
1433 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1434 the buffer position at the beginning of the first affiliated
1435 keyword and CDR is a plist of affiliated keywords along with
1436 their value.
1438 Return a list whose CAR is `special-block' and CDR is a plist
1439 containing `:type', `:begin', `:end', `:contents-begin',
1440 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1442 Assume point is at the beginning of the block."
1443 (let* ((case-fold-search t)
1444 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1445 (match-string-no-properties 1))))
1446 (if (not (save-excursion
1447 (re-search-forward
1448 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1449 limit t)))
1450 ;; Incomplete block: parse it as a paragraph.
1451 (org-element-paragraph-parser limit affiliated)
1452 (let ((block-end-line (match-beginning 0)))
1453 (save-excursion
1454 (let* ((begin (car affiliated))
1455 (post-affiliated (point))
1456 ;; Empty blocks have no contents.
1457 (contents-begin (progn (forward-line)
1458 (and (< (point) block-end-line)
1459 (point))))
1460 (contents-end (and contents-begin block-end-line))
1461 (pos-before-blank (progn (goto-char block-end-line)
1462 (forward-line)
1463 (point)))
1464 (end (progn (skip-chars-forward " \r\t\n" limit)
1465 (if (eobp) (point) (line-beginning-position)))))
1466 (list 'special-block
1467 (nconc
1468 (list :type type
1469 :begin begin
1470 :end end
1471 :contents-begin contents-begin
1472 :contents-end contents-end
1473 :post-blank (count-lines pos-before-blank end)
1474 :post-affiliated post-affiliated)
1475 (cdr affiliated)))))))))
1477 (defun org-element-special-block-interpreter (special-block contents)
1478 "Interpret SPECIAL-BLOCK element as Org syntax.
1479 CONTENTS is the contents of the element."
1480 (let ((block-type (org-element-property :type special-block)))
1481 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1485 ;;; Elements
1487 ;; For each element, a parser and an interpreter are also defined.
1488 ;; Both follow the same naming convention used for greater elements.
1490 ;; Also, as for greater elements, adding a new element type is done
1491 ;; through the following steps: implement a parser and an interpreter,
1492 ;; tweak `org-element--current-element' so that it recognizes the new
1493 ;; type and add that new type to `org-element-all-elements'.
1495 ;; As a special case, when the newly defined type is a block type,
1496 ;; `org-element-block-name-alist' has to be modified accordingly.
1499 ;;;; Babel Call
1501 (defun org-element-babel-call-parser (limit affiliated)
1502 "Parse a babel call.
1504 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1505 the buffer position at the beginning of the first affiliated
1506 keyword and CDR is a plist of affiliated keywords along with
1507 their value.
1509 Return a list whose CAR is `babel-call' and CDR is a plist
1510 containing `:begin', `:end', `:value', `:post-blank' and
1511 `:post-affiliated' as keywords."
1512 (save-excursion
1513 (let ((begin (car affiliated))
1514 (post-affiliated (point))
1515 (value (progn (let ((case-fold-search t))
1516 (re-search-forward "call:[ \t]*" nil t))
1517 (buffer-substring-no-properties (point)
1518 (line-end-position))))
1519 (pos-before-blank (progn (forward-line) (point)))
1520 (end (progn (skip-chars-forward " \r\t\n" limit)
1521 (if (eobp) (point) (line-beginning-position)))))
1522 (list 'babel-call
1523 (nconc
1524 (list :begin begin
1525 :end end
1526 :value value
1527 :post-blank (count-lines pos-before-blank end)
1528 :post-affiliated post-affiliated)
1529 (cdr affiliated))))))
1531 (defun org-element-babel-call-interpreter (babel-call contents)
1532 "Interpret BABEL-CALL element as Org syntax.
1533 CONTENTS is nil."
1534 (concat "#+CALL: " (org-element-property :value babel-call)))
1537 ;;;; Clock
1539 (defun org-element-clock-parser (limit)
1540 "Parse a clock.
1542 LIMIT bounds the search.
1544 Return a list whose CAR is `clock' and CDR is a plist containing
1545 `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
1546 `:post-affiliated' as keywords."
1547 (save-excursion
1548 (let* ((case-fold-search nil)
1549 (begin (point))
1550 (value (progn (search-forward org-clock-string (line-end-position) t)
1551 (skip-chars-forward " \t")
1552 (org-element-timestamp-parser)))
1553 (duration (and (search-forward " => " (line-end-position) t)
1554 (progn (skip-chars-forward " \t")
1555 (looking-at "\\(\\S-+\\)[ \t]*$"))
1556 (org-match-string-no-properties 1)))
1557 (status (if duration 'closed 'running))
1558 (post-blank (let ((before-blank (progn (forward-line) (point))))
1559 (skip-chars-forward " \r\t\n" limit)
1560 (skip-chars-backward " \t")
1561 (unless (bolp) (end-of-line))
1562 (count-lines before-blank (point))))
1563 (end (point)))
1564 (list 'clock
1565 (list :status status
1566 :value value
1567 :duration duration
1568 :begin begin
1569 :end end
1570 :post-blank post-blank
1571 :post-affiliated begin)))))
1573 (defun org-element-clock-interpreter (clock contents)
1574 "Interpret CLOCK element as Org syntax.
1575 CONTENTS is nil."
1576 (concat org-clock-string " "
1577 (org-element-timestamp-interpreter
1578 (org-element-property :value clock) nil)
1579 (let ((duration (org-element-property :duration clock)))
1580 (and duration
1581 (concat " => "
1582 (apply 'format
1583 "%2s:%02s"
1584 (org-split-string duration ":")))))))
1587 ;;;; Comment
1589 (defun org-element-comment-parser (limit affiliated)
1590 "Parse a comment.
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
1595 their value.
1597 Return a list whose CAR is `comment' and CDR is a plist
1598 containing `:begin', `:end', `:value', `:post-blank',
1599 `:post-affiliated' keywords.
1601 Assume point is at comment beginning."
1602 (save-excursion
1603 (let* ((begin (car affiliated))
1604 (post-affiliated (point))
1605 (value (prog2 (looking-at "[ \t]*# ?")
1606 (buffer-substring-no-properties
1607 (match-end 0) (line-end-position))
1608 (forward-line)))
1609 (com-end
1610 ;; Get comments ending.
1611 (progn
1612 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1613 ;; Accumulate lines without leading hash and first
1614 ;; whitespace.
1615 (setq value
1616 (concat value
1617 "\n"
1618 (buffer-substring-no-properties
1619 (match-end 0) (line-end-position))))
1620 (forward-line))
1621 (point)))
1622 (end (progn (goto-char com-end)
1623 (skip-chars-forward " \r\t\n" limit)
1624 (if (eobp) (point) (line-beginning-position)))))
1625 (list 'comment
1626 (nconc
1627 (list :begin begin
1628 :end end
1629 :value value
1630 :post-blank (count-lines com-end end)
1631 :post-affiliated post-affiliated)
1632 (cdr affiliated))))))
1634 (defun org-element-comment-interpreter (comment contents)
1635 "Interpret COMMENT element as Org syntax.
1636 CONTENTS is nil."
1637 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1640 ;;;; Comment Block
1642 (defun org-element-comment-block-parser (limit affiliated)
1643 "Parse an export block.
1645 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1646 the buffer position at the beginning of the first affiliated
1647 keyword and CDR is a plist of affiliated keywords along with
1648 their value.
1650 Return a list whose CAR is `comment-block' and CDR is a plist
1651 containing `:begin', `:end', `:value', `:post-blank' and
1652 `:post-affiliated' keywords.
1654 Assume point is at comment block beginning."
1655 (let ((case-fold-search t))
1656 (if (not (save-excursion
1657 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1658 ;; Incomplete block: parse it as a paragraph.
1659 (org-element-paragraph-parser limit affiliated)
1660 (let ((contents-end (match-beginning 0)))
1661 (save-excursion
1662 (let* ((begin (car affiliated))
1663 (post-affiliated (point))
1664 (contents-begin (progn (forward-line) (point)))
1665 (pos-before-blank (progn (goto-char contents-end)
1666 (forward-line)
1667 (point)))
1668 (end (progn (skip-chars-forward " \r\t\n" limit)
1669 (if (eobp) (point) (line-beginning-position))))
1670 (value (buffer-substring-no-properties
1671 contents-begin contents-end)))
1672 (list 'comment-block
1673 (nconc
1674 (list :begin begin
1675 :end end
1676 :value value
1677 :post-blank (count-lines pos-before-blank end)
1678 :post-affiliated post-affiliated)
1679 (cdr affiliated)))))))))
1681 (defun org-element-comment-block-interpreter (comment-block contents)
1682 "Interpret COMMENT-BLOCK element as Org syntax.
1683 CONTENTS is nil."
1684 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1685 (org-element-normalize-string
1686 (org-remove-indentation
1687 (org-element-property :value comment-block)))))
1690 ;;;; Diary Sexp
1692 (defun org-element-diary-sexp-parser (limit affiliated)
1693 "Parse a diary sexp.
1695 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1696 the buffer position at the beginning of the first affiliated
1697 keyword and CDR is a plist of affiliated keywords along with
1698 their value.
1700 Return a list whose CAR is `diary-sexp' and CDR is a plist
1701 containing `:begin', `:end', `:value', `:post-blank' and
1702 `:post-affiliated' keywords."
1703 (save-excursion
1704 (let ((begin (car affiliated))
1705 (post-affiliated (point))
1706 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1707 (org-match-string-no-properties 1)))
1708 (pos-before-blank (progn (forward-line) (point)))
1709 (end (progn (skip-chars-forward " \r\t\n" limit)
1710 (if (eobp) (point) (line-beginning-position)))))
1711 (list 'diary-sexp
1712 (nconc
1713 (list :value value
1714 :begin begin
1715 :end end
1716 :post-blank (count-lines pos-before-blank end)
1717 :post-affiliated post-affiliated)
1718 (cdr affiliated))))))
1720 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1721 "Interpret DIARY-SEXP as Org syntax.
1722 CONTENTS is nil."
1723 (org-element-property :value diary-sexp))
1726 ;;;; Example Block
1728 (defun org-element-example-block-parser (limit affiliated)
1729 "Parse an example block.
1731 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1732 the buffer position at the beginning of the first affiliated
1733 keyword and CDR is a plist of affiliated keywords along with
1734 their value.
1736 Return a list whose CAR is `example-block' and CDR is a plist
1737 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1738 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1739 `:value', `:post-blank' and `:post-affiliated' keywords."
1740 (let ((case-fold-search t))
1741 (if (not (save-excursion
1742 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1743 ;; Incomplete block: parse it as a paragraph.
1744 (org-element-paragraph-parser limit affiliated)
1745 (let ((contents-end (match-beginning 0)))
1746 (save-excursion
1747 (let* ((switches
1748 (progn
1749 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1750 (org-match-string-no-properties 1)))
1751 ;; Switches analysis
1752 (number-lines
1753 (cond ((not switches) nil)
1754 ((string-match "-n\\>" switches) 'new)
1755 ((string-match "+n\\>" switches) 'continued)))
1756 (preserve-indent
1757 (and switches (string-match "-i\\>" switches)))
1758 ;; Should labels be retained in (or stripped from) example
1759 ;; blocks?
1760 (retain-labels
1761 (or (not switches)
1762 (not (string-match "-r\\>" switches))
1763 (and number-lines (string-match "-k\\>" switches))))
1764 ;; What should code-references use - labels or
1765 ;; line-numbers?
1766 (use-labels
1767 (or (not switches)
1768 (and retain-labels
1769 (not (string-match "-k\\>" switches)))))
1770 (label-fmt
1771 (and switches
1772 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1773 (match-string 1 switches)))
1774 ;; Standard block parsing.
1775 (begin (car affiliated))
1776 (post-affiliated (point))
1777 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1778 (contents-begin (progn (forward-line) (point)))
1779 (value (org-element-remove-indentation
1780 (org-unescape-code-in-string
1781 (buffer-substring-no-properties
1782 contents-begin contents-end))
1783 block-ind))
1784 (pos-before-blank (progn (goto-char contents-end)
1785 (forward-line)
1786 (point)))
1787 (end (progn (skip-chars-forward " \r\t\n" limit)
1788 (if (eobp) (point) (line-beginning-position)))))
1789 (list 'example-block
1790 (nconc
1791 (list :begin begin
1792 :end end
1793 :value value
1794 :switches switches
1795 :number-lines number-lines
1796 :preserve-indent preserve-indent
1797 :retain-labels retain-labels
1798 :use-labels use-labels
1799 :label-fmt label-fmt
1800 :post-blank (count-lines pos-before-blank end)
1801 :post-affiliated post-affiliated)
1802 (cdr affiliated)))))))))
1804 (defun org-element-example-block-interpreter (example-block contents)
1805 "Interpret EXAMPLE-BLOCK element as Org syntax.
1806 CONTENTS is nil."
1807 (let ((switches (org-element-property :switches example-block))
1808 (value (org-element-property :value example-block)))
1809 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1810 (org-element-normalize-string
1811 (org-escape-code-in-string
1812 (if (or org-src-preserve-indentation
1813 (org-element-property :preserve-indent example-block))
1814 value
1815 (org-element-remove-indentation value))))
1816 "#+END_EXAMPLE")))
1819 ;;;; Export Block
1821 (defun org-element-export-block-parser (limit affiliated)
1822 "Parse an export block.
1824 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1825 the buffer position at the beginning of the first affiliated
1826 keyword and CDR is a plist of affiliated keywords along with
1827 their value.
1829 Return a list whose CAR is `export-block' and CDR is a plist
1830 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1831 `:post-affiliated' keywords.
1833 Assume point is at export-block beginning."
1834 (let* ((case-fold-search t)
1835 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1836 (upcase (org-match-string-no-properties 1)))))
1837 (if (not (save-excursion
1838 (re-search-forward
1839 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1840 ;; Incomplete block: parse it as a paragraph.
1841 (org-element-paragraph-parser limit affiliated)
1842 (let ((contents-end (match-beginning 0)))
1843 (save-excursion
1844 (let* ((begin (car affiliated))
1845 (post-affiliated (point))
1846 (contents-begin (progn (forward-line) (point)))
1847 (pos-before-blank (progn (goto-char contents-end)
1848 (forward-line)
1849 (point)))
1850 (end (progn (skip-chars-forward " \r\t\n" limit)
1851 (if (eobp) (point) (line-beginning-position))))
1852 (value (buffer-substring-no-properties contents-begin
1853 contents-end)))
1854 (list 'export-block
1855 (nconc
1856 (list :begin begin
1857 :end end
1858 :type type
1859 :value value
1860 :post-blank (count-lines pos-before-blank end)
1861 :post-affiliated post-affiliated)
1862 (cdr affiliated)))))))))
1864 (defun org-element-export-block-interpreter (export-block contents)
1865 "Interpret EXPORT-BLOCK element as Org syntax.
1866 CONTENTS is nil."
1867 (let ((type (org-element-property :type export-block)))
1868 (concat (format "#+BEGIN_%s\n" type)
1869 (org-element-property :value export-block)
1870 (format "#+END_%s" type))))
1873 ;;;; Fixed-width
1875 (defun org-element-fixed-width-parser (limit affiliated)
1876 "Parse a fixed-width section.
1878 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1879 the buffer position at the beginning of the first affiliated
1880 keyword and CDR is a plist of affiliated keywords along with
1881 their value.
1883 Return a list whose CAR is `fixed-width' and CDR is a plist
1884 containing `:begin', `:end', `:value', `:post-blank' and
1885 `:post-affiliated' keywords.
1887 Assume point is at the beginning of the fixed-width area."
1888 (save-excursion
1889 (let* ((begin (car affiliated))
1890 (post-affiliated (point))
1891 value
1892 (end-area
1893 (progn
1894 (while (and (< (point) limit)
1895 (looking-at "[ \t]*:\\( \\|$\\)"))
1896 ;; Accumulate text without starting colons.
1897 (setq value
1898 (concat value
1899 (buffer-substring-no-properties
1900 (match-end 0) (point-at-eol))
1901 "\n"))
1902 (forward-line))
1903 (point)))
1904 (end (progn (skip-chars-forward " \r\t\n" limit)
1905 (if (eobp) (point) (line-beginning-position)))))
1906 (list 'fixed-width
1907 (nconc
1908 (list :begin begin
1909 :end end
1910 :value value
1911 :post-blank (count-lines end-area end)
1912 :post-affiliated post-affiliated)
1913 (cdr affiliated))))))
1915 (defun org-element-fixed-width-interpreter (fixed-width contents)
1916 "Interpret FIXED-WIDTH element as Org syntax.
1917 CONTENTS is nil."
1918 (let ((value (org-element-property :value fixed-width)))
1919 (and value
1920 (replace-regexp-in-string
1921 "^" ": "
1922 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1925 ;;;; Horizontal Rule
1927 (defun org-element-horizontal-rule-parser (limit affiliated)
1928 "Parse an horizontal rule.
1930 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1931 the buffer position at the beginning of the first affiliated
1932 keyword and CDR is a plist of affiliated keywords along with
1933 their value.
1935 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1936 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1937 keywords."
1938 (save-excursion
1939 (let ((begin (car affiliated))
1940 (post-affiliated (point))
1941 (post-hr (progn (forward-line) (point)))
1942 (end (progn (skip-chars-forward " \r\t\n" limit)
1943 (if (eobp) (point) (line-beginning-position)))))
1944 (list 'horizontal-rule
1945 (nconc
1946 (list :begin begin
1947 :end end
1948 :post-blank (count-lines post-hr end)
1949 :post-affiliated post-affiliated)
1950 (cdr affiliated))))))
1952 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1953 "Interpret HORIZONTAL-RULE element as Org syntax.
1954 CONTENTS is nil."
1955 "-----")
1958 ;;;; Keyword
1960 (defun org-element-keyword-parser (limit affiliated)
1961 "Parse a keyword at point.
1963 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1964 the buffer position at the beginning of the first affiliated
1965 keyword and CDR is a plist of affiliated keywords along with
1966 their value.
1968 Return a list whose CAR is `keyword' and CDR is a plist
1969 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1970 `:post-affiliated' keywords."
1971 (save-excursion
1972 ;; An orphaned affiliated keyword is considered as a regular
1973 ;; keyword. In this case AFFILIATED is nil, so we take care of
1974 ;; this corner case.
1975 (let ((begin (or (car affiliated) (point)))
1976 (post-affiliated (point))
1977 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1978 (upcase (org-match-string-no-properties 1))))
1979 (value (org-trim (buffer-substring-no-properties
1980 (match-end 0) (point-at-eol))))
1981 (pos-before-blank (progn (forward-line) (point)))
1982 (end (progn (skip-chars-forward " \r\t\n" limit)
1983 (if (eobp) (point) (line-beginning-position)))))
1984 (list 'keyword
1985 (nconc
1986 (list :key key
1987 :value value
1988 :begin begin
1989 :end end
1990 :post-blank (count-lines pos-before-blank end)
1991 :post-affiliated post-affiliated)
1992 (cdr affiliated))))))
1994 (defun org-element-keyword-interpreter (keyword contents)
1995 "Interpret KEYWORD element as Org syntax.
1996 CONTENTS is nil."
1997 (format "#+%s: %s"
1998 (org-element-property :key keyword)
1999 (org-element-property :value keyword)))
2002 ;;;; Latex Environment
2004 (defconst org-element--latex-begin-environment
2005 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2006 "Regexp matching the beginning of a LaTeX environment.
2007 The environment is captured by the first group.
2009 See also `org-element--latex-end-environment'.")
2011 (defconst org-element--latex-end-environment
2012 "\\\\end{%s}[ \t]*$"
2013 "Format string matching the ending of a LaTeX environment.
2014 See also `org-element--latex-begin-environment'.")
2016 (defun org-element-latex-environment-parser (limit affiliated)
2017 "Parse a LaTeX environment.
2019 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2020 the buffer position at the beginning of the first affiliated
2021 keyword and CDR is a plist of affiliated keywords along with
2022 their value.
2024 Return a list whose CAR is `latex-environment' and CDR is a plist
2025 containing `:begin', `:end', `:value', `:post-blank' and
2026 `:post-affiliated' keywords.
2028 Assume point is at the beginning of the latex environment."
2029 (save-excursion
2030 (let ((case-fold-search t)
2031 (code-begin (point)))
2032 (looking-at org-element--latex-begin-environment)
2033 (if (not (re-search-forward (format org-element--latex-end-environment
2034 (regexp-quote (match-string 1)))
2035 limit t))
2036 ;; Incomplete latex environment: parse it as a paragraph.
2037 (org-element-paragraph-parser limit affiliated)
2038 (let* ((code-end (progn (forward-line) (point)))
2039 (begin (car affiliated))
2040 (value (buffer-substring-no-properties code-begin code-end))
2041 (end (progn (skip-chars-forward " \r\t\n" limit)
2042 (if (eobp) (point) (line-beginning-position)))))
2043 (list 'latex-environment
2044 (nconc
2045 (list :begin begin
2046 :end end
2047 :value value
2048 :post-blank (count-lines code-end end)
2049 :post-affiliated code-begin)
2050 (cdr affiliated))))))))
2052 (defun org-element-latex-environment-interpreter (latex-environment contents)
2053 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2054 CONTENTS is nil."
2055 (org-element-property :value latex-environment))
2058 ;;;; Node Property
2060 (defun org-element-node-property-parser (limit)
2061 "Parse a node-property at point.
2063 LIMIT bounds the search.
2065 Return a list whose CAR is `node-property' and CDR is a plist
2066 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2067 `:post-affiliated' keywords."
2068 (looking-at org-property-re)
2069 (let ((case-fold-search t)
2070 (begin (point))
2071 (key (org-match-string-no-properties 2))
2072 (value (org-match-string-no-properties 3))
2073 (end (save-excursion
2074 (end-of-line)
2075 (if (re-search-forward org-property-re limit t)
2076 (line-beginning-position)
2077 limit))))
2078 (list 'node-property
2079 (list :key key
2080 :value value
2081 :begin begin
2082 :end end
2083 :post-blank 0
2084 :post-affiliated begin))))
2086 (defun org-element-node-property-interpreter (node-property contents)
2087 "Interpret NODE-PROPERTY element as Org syntax.
2088 CONTENTS is nil."
2089 (format org-property-format
2090 (format ":%s:" (org-element-property :key node-property))
2091 (or (org-element-property :value node-property) "")))
2094 ;;;; Paragraph
2096 (defun org-element-paragraph-parser (limit affiliated)
2097 "Parse a paragraph.
2099 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2100 the buffer position at the beginning of the first affiliated
2101 keyword and CDR is a plist of affiliated keywords along with
2102 their value.
2104 Return a list whose CAR is `paragraph' and CDR is a plist
2105 containing `:begin', `:end', `:contents-begin' and
2106 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2108 Assume point is at the beginning of the paragraph."
2109 (save-excursion
2110 (let* ((begin (car affiliated))
2111 (contents-begin (point))
2112 (before-blank
2113 (let ((case-fold-search t))
2114 (end-of-line)
2115 (if (not (re-search-forward
2116 org-element-paragraph-separate limit 'm))
2117 limit
2118 ;; A matching `org-element-paragraph-separate' is not
2119 ;; necessarily the end of the paragraph. In
2120 ;; particular, lines starting with # or : as a first
2121 ;; non-space character are ambiguous. We have to
2122 ;; check if they are valid Org syntax (e.g., not an
2123 ;; incomplete keyword).
2124 (beginning-of-line)
2125 (while (not
2127 ;; There's no ambiguity for other symbols or
2128 ;; empty lines: stop here.
2129 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2130 ;; Stop at valid fixed-width areas.
2131 (looking-at "[ \t]*:\\(?: \\|$\\)")
2132 ;; Stop at drawers.
2133 (and (looking-at org-drawer-regexp)
2134 (save-excursion
2135 (re-search-forward
2136 "^[ \t]*:END:[ \t]*$" limit t)))
2137 ;; Stop at valid comments.
2138 (looking-at "[ \t]*#\\(?: \\|$\\)")
2139 ;; Stop at valid dynamic blocks.
2140 (and (looking-at org-dblock-start-re)
2141 (save-excursion
2142 (re-search-forward
2143 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2144 ;; Stop at valid blocks.
2145 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2146 (save-excursion
2147 (re-search-forward
2148 (format "^[ \t]*#\\+END_%s[ \t]*$"
2149 (regexp-quote
2150 (org-match-string-no-properties 1)))
2151 limit t)))
2152 ;; Stop at valid latex environments.
2153 (and (looking-at org-element--latex-begin-environment)
2154 (save-excursion
2155 (re-search-forward
2156 (format org-element--latex-end-environment
2157 (regexp-quote
2158 (org-match-string-no-properties 1)))
2159 limit t)))
2160 ;; Stop at valid keywords.
2161 (looking-at "[ \t]*#\\+\\S-+:")
2162 ;; Skip everything else.
2163 (not
2164 (progn
2165 (end-of-line)
2166 (re-search-forward org-element-paragraph-separate
2167 limit 'm)))))
2168 (beginning-of-line)))
2169 (if (= (point) limit) limit
2170 (goto-char (line-beginning-position)))))
2171 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2172 (forward-line)
2173 (point)))
2174 (end (progn (skip-chars-forward " \r\t\n" limit)
2175 (if (eobp) (point) (line-beginning-position)))))
2176 (list 'paragraph
2177 (nconc
2178 (list :begin begin
2179 :end end
2180 :contents-begin contents-begin
2181 :contents-end contents-end
2182 :post-blank (count-lines before-blank end)
2183 :post-affiliated contents-begin)
2184 (cdr affiliated))))))
2186 (defun org-element-paragraph-interpreter (paragraph contents)
2187 "Interpret PARAGRAPH element as Org syntax.
2188 CONTENTS is the contents of the element."
2189 contents)
2192 ;;;; Planning
2194 (defun org-element-planning-parser (limit)
2195 "Parse a planning.
2197 LIMIT bounds the search.
2199 Return a list whose CAR is `planning' and CDR is a plist
2200 containing `:closed', `:deadline', `:scheduled', `:begin',
2201 `:end', `:post-blank' and `:post-affiliated' keywords."
2202 (save-excursion
2203 (let* ((case-fold-search nil)
2204 (begin (point))
2205 (post-blank (let ((before-blank (progn (forward-line) (point))))
2206 (skip-chars-forward " \r\t\n" limit)
2207 (skip-chars-backward " \t")
2208 (unless (bolp) (end-of-line))
2209 (count-lines before-blank (point))))
2210 (end (point))
2211 closed deadline scheduled)
2212 (goto-char begin)
2213 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2214 (goto-char (match-end 1))
2215 (skip-chars-forward " \t" end)
2216 (let ((keyword (match-string 1))
2217 (time (org-element-timestamp-parser)))
2218 (cond ((equal keyword org-closed-string) (setq closed time))
2219 ((equal keyword org-deadline-string) (setq deadline time))
2220 (t (setq scheduled time)))))
2221 (list 'planning
2222 (list :closed closed
2223 :deadline deadline
2224 :scheduled scheduled
2225 :begin begin
2226 :end end
2227 :post-blank post-blank
2228 :post-affiliated begin)))))
2230 (defun org-element-planning-interpreter (planning contents)
2231 "Interpret PLANNING element as Org syntax.
2232 CONTENTS is nil."
2233 (mapconcat
2234 'identity
2235 (delq nil
2236 (list (let ((deadline (org-element-property :deadline planning)))
2237 (when deadline
2238 (concat org-deadline-string " "
2239 (org-element-timestamp-interpreter deadline nil))))
2240 (let ((scheduled (org-element-property :scheduled planning)))
2241 (when scheduled
2242 (concat org-scheduled-string " "
2243 (org-element-timestamp-interpreter scheduled nil))))
2244 (let ((closed (org-element-property :closed planning)))
2245 (when closed
2246 (concat org-closed-string " "
2247 (org-element-timestamp-interpreter closed nil))))))
2248 " "))
2251 ;;;; Src Block
2253 (defun org-element-src-block-parser (limit affiliated)
2254 "Parse a src block.
2256 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2257 the buffer position at the beginning of the first affiliated
2258 keyword and CDR is a plist of affiliated keywords along with
2259 their value.
2261 Return a list whose CAR is `src-block' and CDR is a plist
2262 containing `:language', `:switches', `:parameters', `:begin',
2263 `:end', `:number-lines', `:retain-labels', `:use-labels',
2264 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2265 `:post-affiliated' keywords.
2267 Assume point is at the beginning of the block."
2268 (let ((case-fold-search t))
2269 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2270 limit t)))
2271 ;; Incomplete block: parse it as a paragraph.
2272 (org-element-paragraph-parser limit affiliated)
2273 (let ((contents-end (match-beginning 0)))
2274 (save-excursion
2275 (let* ((begin (car affiliated))
2276 (post-affiliated (point))
2277 ;; Get language as a string.
2278 (language
2279 (progn
2280 (looking-at
2281 (concat "^[ \t]*#\\+BEGIN_SRC"
2282 "\\(?: +\\(\\S-+\\)\\)?"
2283 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2284 "\\(.*\\)[ \t]*$"))
2285 (org-match-string-no-properties 1)))
2286 ;; Get switches.
2287 (switches (org-match-string-no-properties 2))
2288 ;; Get parameters.
2289 (parameters (org-match-string-no-properties 3))
2290 ;; Switches analysis
2291 (number-lines
2292 (cond ((not switches) nil)
2293 ((string-match "-n\\>" switches) 'new)
2294 ((string-match "+n\\>" switches) 'continued)))
2295 (preserve-indent (and switches
2296 (string-match "-i\\>" switches)))
2297 (label-fmt
2298 (and switches
2299 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2300 (match-string 1 switches)))
2301 ;; Should labels be retained in (or stripped from)
2302 ;; src blocks?
2303 (retain-labels
2304 (or (not switches)
2305 (not (string-match "-r\\>" switches))
2306 (and number-lines (string-match "-k\\>" switches))))
2307 ;; What should code-references use - labels or
2308 ;; line-numbers?
2309 (use-labels
2310 (or (not switches)
2311 (and retain-labels
2312 (not (string-match "-k\\>" switches)))))
2313 ;; Indentation.
2314 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2315 ;; Retrieve code.
2316 (value (org-element-remove-indentation
2317 (org-unescape-code-in-string
2318 (buffer-substring-no-properties
2319 (progn (forward-line) (point)) contents-end))
2320 block-ind))
2321 (pos-before-blank (progn (goto-char contents-end)
2322 (forward-line)
2323 (point)))
2324 ;; Get position after ending blank lines.
2325 (end (progn (skip-chars-forward " \r\t\n" limit)
2326 (if (eobp) (point) (line-beginning-position)))))
2327 (list 'src-block
2328 (nconc
2329 (list :language language
2330 :switches (and (org-string-nw-p switches)
2331 (org-trim switches))
2332 :parameters (and (org-string-nw-p parameters)
2333 (org-trim parameters))
2334 :begin begin
2335 :end end
2336 :number-lines number-lines
2337 :preserve-indent preserve-indent
2338 :retain-labels retain-labels
2339 :use-labels use-labels
2340 :label-fmt label-fmt
2341 :value value
2342 :post-blank (count-lines pos-before-blank end)
2343 :post-affiliated post-affiliated)
2344 (cdr affiliated)))))))))
2346 (defun org-element-src-block-interpreter (src-block contents)
2347 "Interpret SRC-BLOCK element as Org syntax.
2348 CONTENTS is nil."
2349 (let ((lang (org-element-property :language src-block))
2350 (switches (org-element-property :switches src-block))
2351 (params (org-element-property :parameters src-block))
2352 (value
2353 (let ((val (org-element-property :value src-block)))
2354 (cond
2355 ((or org-src-preserve-indentation
2356 (org-element-property :preserve-indent src-block))
2357 val)
2358 ((zerop org-edit-src-content-indentation) val)
2360 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2361 (replace-regexp-in-string
2362 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2363 (concat (format "#+BEGIN_SRC%s\n"
2364 (concat (and lang (concat " " lang))
2365 (and switches (concat " " switches))
2366 (and params (concat " " params))))
2367 (org-element-normalize-string (org-escape-code-in-string value))
2368 "#+END_SRC")))
2371 ;;;; Table
2373 (defun org-element-table-parser (limit affiliated)
2374 "Parse a table at point.
2376 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2377 the buffer position at the beginning of the first affiliated
2378 keyword and CDR is a plist of affiliated keywords along with
2379 their value.
2381 Return a list whose CAR is `table' and CDR is a plist containing
2382 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2383 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2384 keywords.
2386 Assume point is at the beginning of the table."
2387 (save-excursion
2388 (let* ((case-fold-search t)
2389 (table-begin (point))
2390 (type (if (org-at-table.el-p) 'table.el 'org))
2391 (begin (car affiliated))
2392 (table-end
2393 (if (re-search-forward org-table-any-border-regexp limit 'm)
2394 (goto-char (match-beginning 0))
2395 (point)))
2396 (tblfm (let (acc)
2397 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2398 (push (org-match-string-no-properties 1) acc)
2399 (forward-line))
2400 acc))
2401 (pos-before-blank (point))
2402 (end (progn (skip-chars-forward " \r\t\n" limit)
2403 (if (eobp) (point) (line-beginning-position)))))
2404 (list 'table
2405 (nconc
2406 (list :begin begin
2407 :end end
2408 :type type
2409 :tblfm tblfm
2410 ;; Only `org' tables have contents. `table.el' tables
2411 ;; use a `:value' property to store raw table as
2412 ;; a string.
2413 :contents-begin (and (eq type 'org) table-begin)
2414 :contents-end (and (eq type 'org) table-end)
2415 :value (and (eq type 'table.el)
2416 (buffer-substring-no-properties
2417 table-begin table-end))
2418 :post-blank (count-lines pos-before-blank end)
2419 :post-affiliated table-begin)
2420 (cdr affiliated))))))
2422 (defun org-element-table-interpreter (table contents)
2423 "Interpret TABLE element as Org syntax.
2424 CONTENTS is a string, if table's type is `org', or nil."
2425 (if (eq (org-element-property :type table) 'table.el)
2426 (org-remove-indentation (org-element-property :value table))
2427 (concat (with-temp-buffer (insert contents)
2428 (org-table-align)
2429 (buffer-string))
2430 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2431 (reverse (org-element-property :tblfm table))
2432 "\n"))))
2435 ;;;; Table Row
2437 (defun org-element-table-row-parser (limit)
2438 "Parse table row at point.
2440 LIMIT bounds the search.
2442 Return a list whose CAR is `table-row' and CDR is a plist
2443 containing `:begin', `:end', `:contents-begin', `:contents-end',
2444 `:type', `:post-blank' and `:post-affiliated' keywords."
2445 (save-excursion
2446 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2447 (begin (point))
2448 ;; A table rule has no contents. In that case, ensure
2449 ;; CONTENTS-BEGIN matches CONTENTS-END.
2450 (contents-begin (and (eq type 'standard)
2451 (search-forward "|")
2452 (point)))
2453 (contents-end (and (eq type 'standard)
2454 (progn
2455 (end-of-line)
2456 (skip-chars-backward " \t")
2457 (point))))
2458 (end (progn (forward-line) (point))))
2459 (list 'table-row
2460 (list :type type
2461 :begin begin
2462 :end end
2463 :contents-begin contents-begin
2464 :contents-end contents-end
2465 :post-blank 0
2466 :post-affiliated begin)))))
2468 (defun org-element-table-row-interpreter (table-row contents)
2469 "Interpret TABLE-ROW element as Org syntax.
2470 CONTENTS is the contents of the table row."
2471 (if (eq (org-element-property :type table-row) 'rule) "|-"
2472 (concat "| " contents)))
2475 ;;;; Verse Block
2477 (defun org-element-verse-block-parser (limit affiliated)
2478 "Parse a verse block.
2480 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2481 the buffer position at the beginning of the first affiliated
2482 keyword and CDR is a plist of affiliated keywords along with
2483 their value.
2485 Return a list whose CAR is `verse-block' and CDR is a plist
2486 containing `:begin', `:end', `:contents-begin', `:contents-end',
2487 `:post-blank' and `:post-affiliated' keywords.
2489 Assume point is at beginning of the block."
2490 (let ((case-fold-search t))
2491 (if (not (save-excursion
2492 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2493 ;; Incomplete block: parse it as a paragraph.
2494 (org-element-paragraph-parser limit affiliated)
2495 (let ((contents-end (match-beginning 0)))
2496 (save-excursion
2497 (let* ((begin (car affiliated))
2498 (post-affiliated (point))
2499 (contents-begin (progn (forward-line) (point)))
2500 (pos-before-blank (progn (goto-char contents-end)
2501 (forward-line)
2502 (point)))
2503 (end (progn (skip-chars-forward " \r\t\n" limit)
2504 (if (eobp) (point) (line-beginning-position)))))
2505 (list 'verse-block
2506 (nconc
2507 (list :begin begin
2508 :end end
2509 :contents-begin contents-begin
2510 :contents-end contents-end
2511 :post-blank (count-lines pos-before-blank end)
2512 :post-affiliated post-affiliated)
2513 (cdr affiliated)))))))))
2515 (defun org-element-verse-block-interpreter (verse-block contents)
2516 "Interpret VERSE-BLOCK element as Org syntax.
2517 CONTENTS is verse block contents."
2518 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2522 ;;; Objects
2524 ;; Unlike to elements, raw text can be found between objects. Hence,
2525 ;; `org-element--object-lex' is provided to find the next object in
2526 ;; buffer.
2528 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2529 ;; object types they can contain will be specified in
2530 ;; `org-element-object-restrictions'.
2532 ;; Creating a new type of object requires to alter
2533 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2534 ;; new type in `org-element-all-objects', and possibly add
2535 ;; restrictions in `org-element-object-restrictions'.
2537 ;;;; Bold
2539 (defun org-element-bold-parser ()
2540 "Parse bold object at point, if any.
2542 When at a bold object, return a list whose car is `bold' and cdr
2543 is a plist with `:begin', `:end', `:contents-begin' and
2544 `:contents-end' and `:post-blank' keywords. Otherwise, return
2545 nil.
2547 Assume point is at the first star marker."
2548 (save-excursion
2549 (unless (bolp) (backward-char 1))
2550 (when (looking-at org-emph-re)
2551 (let ((begin (match-beginning 2))
2552 (contents-begin (match-beginning 4))
2553 (contents-end (match-end 4))
2554 (post-blank (progn (goto-char (match-end 2))
2555 (skip-chars-forward " \t")))
2556 (end (point)))
2557 (list 'bold
2558 (list :begin begin
2559 :end end
2560 :contents-begin contents-begin
2561 :contents-end contents-end
2562 :post-blank post-blank))))))
2564 (defun org-element-bold-interpreter (bold contents)
2565 "Interpret BOLD object as Org syntax.
2566 CONTENTS is the contents of the object."
2567 (format "*%s*" contents))
2570 ;;;; Code
2572 (defun org-element-code-parser ()
2573 "Parse code object at point, if any.
2575 When at a code object, return a list whose car is `code' and cdr
2576 is a plist with `:value', `:begin', `:end' and `:post-blank'
2577 keywords. Otherwise, return nil.
2579 Assume point is at the first tilde marker."
2580 (save-excursion
2581 (unless (bolp) (backward-char 1))
2582 (when (looking-at org-emph-re)
2583 (let ((begin (match-beginning 2))
2584 (value (org-match-string-no-properties 4))
2585 (post-blank (progn (goto-char (match-end 2))
2586 (skip-chars-forward " \t")))
2587 (end (point)))
2588 (list 'code
2589 (list :value value
2590 :begin begin
2591 :end end
2592 :post-blank post-blank))))))
2594 (defun org-element-code-interpreter (code contents)
2595 "Interpret CODE object as Org syntax.
2596 CONTENTS is nil."
2597 (format "~%s~" (org-element-property :value code)))
2600 ;;;; Entity
2602 (defun org-element-entity-parser ()
2603 "Parse entity at point, if any.
2605 When at an entity, return a list whose car is `entity' and cdr
2606 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2607 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2608 `:post-blank' as keywords. Otherwise, return nil.
2610 Assume point is at the beginning of the entity."
2611 (catch 'no-object
2612 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2613 (save-excursion
2614 (let* ((value (or (org-entity-get (match-string 1))
2615 (throw 'no-object nil)))
2616 (begin (match-beginning 0))
2617 (bracketsp (string= (match-string 2) "{}"))
2618 (post-blank (progn (goto-char (match-end 1))
2619 (when bracketsp (forward-char 2))
2620 (skip-chars-forward " \t")))
2621 (end (point)))
2622 (list 'entity
2623 (list :name (car value)
2624 :latex (nth 1 value)
2625 :latex-math-p (nth 2 value)
2626 :html (nth 3 value)
2627 :ascii (nth 4 value)
2628 :latin1 (nth 5 value)
2629 :utf-8 (nth 6 value)
2630 :begin begin
2631 :end end
2632 :use-brackets-p bracketsp
2633 :post-blank post-blank)))))))
2635 (defun org-element-entity-interpreter (entity contents)
2636 "Interpret ENTITY object as Org syntax.
2637 CONTENTS is nil."
2638 (concat "\\"
2639 (org-element-property :name entity)
2640 (when (org-element-property :use-brackets-p entity) "{}")))
2643 ;;;; Export Snippet
2645 (defun org-element-export-snippet-parser ()
2646 "Parse export snippet at point.
2648 When at an export snippet, return a list whose car is
2649 `export-snippet' and cdr a plist with `:begin', `:end',
2650 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2651 return nil.
2653 Assume point is at the beginning of the snippet."
2654 (save-excursion
2655 (let (contents-end)
2656 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2657 (setq contents-end
2658 (save-match-data (goto-char (match-end 0))
2659 (re-search-forward "@@" nil t)
2660 (match-beginning 0))))
2661 (let* ((begin (match-beginning 0))
2662 (back-end (org-match-string-no-properties 1))
2663 (value (buffer-substring-no-properties
2664 (match-end 0) contents-end))
2665 (post-blank (skip-chars-forward " \t"))
2666 (end (point)))
2667 (list 'export-snippet
2668 (list :back-end back-end
2669 :value value
2670 :begin begin
2671 :end end
2672 :post-blank post-blank)))))))
2674 (defun org-element-export-snippet-interpreter (export-snippet contents)
2675 "Interpret EXPORT-SNIPPET object as Org syntax.
2676 CONTENTS is nil."
2677 (format "@@%s:%s@@"
2678 (org-element-property :back-end export-snippet)
2679 (org-element-property :value export-snippet)))
2682 ;;;; Footnote Reference
2684 (defun org-element-footnote-reference-parser ()
2685 "Parse footnote reference at point, if any.
2687 When at a footnote reference, return a list whose car is
2688 `footnote-reference' and cdr a plist with `:label', `:type',
2689 `:begin', `:end', `:content-begin', `:contents-end' and
2690 `:post-blank' as keywords. Otherwise, return nil."
2691 (catch 'no-object
2692 (when (looking-at org-footnote-re)
2693 (save-excursion
2694 (let* ((begin (point))
2695 (label
2696 (or (org-match-string-no-properties 2)
2697 (org-match-string-no-properties 3)
2698 (and (match-string 1)
2699 (concat "fn:" (org-match-string-no-properties 1)))))
2700 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2701 (inner-begin (match-end 0))
2702 (inner-end
2703 (let ((count 1))
2704 (forward-char)
2705 (while (and (> count 0) (re-search-forward "[][]" nil t))
2706 (if (equal (match-string 0) "[") (incf count) (decf count)))
2707 (unless (zerop count) (throw 'no-object nil))
2708 (1- (point))))
2709 (post-blank (progn (goto-char (1+ inner-end))
2710 (skip-chars-forward " \t")))
2711 (end (point)))
2712 (list 'footnote-reference
2713 (list :label label
2714 :type type
2715 :begin begin
2716 :end end
2717 :contents-begin (and (eq type 'inline) inner-begin)
2718 :contents-end (and (eq type 'inline) inner-end)
2719 :post-blank post-blank)))))))
2721 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2722 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2723 CONTENTS is its definition, when inline, or nil."
2724 (format "[%s]"
2725 (concat (or (org-element-property :label footnote-reference) "fn:")
2726 (and contents (concat ":" contents)))))
2729 ;;;; Inline Babel Call
2731 (defun org-element-inline-babel-call-parser ()
2732 "Parse inline babel call at point, if any.
2734 When at an inline babel call, return a list whose car is
2735 `inline-babel-call' and cdr a plist with `:begin', `:end',
2736 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2738 Assume point is at the beginning of the babel call."
2739 (save-excursion
2740 (unless (bolp) (backward-char))
2741 (when (let ((case-fold-search t))
2742 (looking-at org-babel-inline-lob-one-liner-regexp))
2743 (let ((begin (match-end 1))
2744 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2745 (post-blank (progn (goto-char (match-end 0))
2746 (skip-chars-forward " \t")))
2747 (end (point)))
2748 (list 'inline-babel-call
2749 (list :begin begin
2750 :end end
2751 :value value
2752 :post-blank post-blank))))))
2754 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2755 "Interpret INLINE-BABEL-CALL object as Org syntax.
2756 CONTENTS is nil."
2757 (org-element-property :value inline-babel-call))
2760 ;;;; Inline Src Block
2762 (defun org-element-inline-src-block-parser ()
2763 "Parse inline source block at point, if any.
2765 When at an inline source block, return a list whose car is
2766 `inline-src-block' and cdr a plist with `:begin', `:end',
2767 `:language', `:value', `:parameters' and `:post-blank' as
2768 keywords. Otherwise, return nil.
2770 Assume point is at the beginning of the inline src block."
2771 (save-excursion
2772 (unless (bolp) (backward-char))
2773 (when (looking-at org-babel-inline-src-block-regexp)
2774 (let ((begin (match-beginning 1))
2775 (language (org-match-string-no-properties 2))
2776 (parameters (org-match-string-no-properties 4))
2777 (value (org-match-string-no-properties 5))
2778 (post-blank (progn (goto-char (match-end 0))
2779 (skip-chars-forward " \t")))
2780 (end (point)))
2781 (list 'inline-src-block
2782 (list :language language
2783 :value value
2784 :parameters parameters
2785 :begin begin
2786 :end end
2787 :post-blank post-blank))))))
2789 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2790 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2791 CONTENTS is nil."
2792 (let ((language (org-element-property :language inline-src-block))
2793 (arguments (org-element-property :parameters inline-src-block))
2794 (body (org-element-property :value inline-src-block)))
2795 (format "src_%s%s{%s}"
2796 language
2797 (if arguments (format "[%s]" arguments) "")
2798 body)))
2800 ;;;; Italic
2802 (defun org-element-italic-parser ()
2803 "Parse italic object at point, if any.
2805 When at an italic object, return a list whose car is `italic' and
2806 cdr is a plist with `:begin', `:end', `:contents-begin' and
2807 `:contents-end' and `:post-blank' keywords. Otherwise, return
2808 nil.
2810 Assume point is at the first slash marker."
2811 (save-excursion
2812 (unless (bolp) (backward-char 1))
2813 (when (looking-at org-emph-re)
2814 (let ((begin (match-beginning 2))
2815 (contents-begin (match-beginning 4))
2816 (contents-end (match-end 4))
2817 (post-blank (progn (goto-char (match-end 2))
2818 (skip-chars-forward " \t")))
2819 (end (point)))
2820 (list 'italic
2821 (list :begin begin
2822 :end end
2823 :contents-begin contents-begin
2824 :contents-end contents-end
2825 :post-blank post-blank))))))
2827 (defun org-element-italic-interpreter (italic contents)
2828 "Interpret ITALIC object as Org syntax.
2829 CONTENTS is the contents of the object."
2830 (format "/%s/" contents))
2833 ;;;; Latex Fragment
2835 (defun org-element-latex-fragment-parser ()
2836 "Parse LaTeX fragment at point, if any.
2838 When at a LaTeX fragment, return a list whose car is
2839 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2840 and `:post-blank' as keywords. Otherwise, return nil.
2842 Assume point is at the beginning of the LaTeX fragment."
2843 (catch 'no-object
2844 (save-excursion
2845 (let* ((begin (point))
2846 (after-fragment
2847 (if (eq (char-after) ?$)
2848 (if (eq (char-after (1+ (point))) ?$)
2849 (search-forward "$$" nil t 2)
2850 (and (not (eq (char-before) ?$))
2851 (search-forward "$" nil t 2)
2852 (not (memq (char-before (match-beginning 0))
2853 '(?\s ?\t ?\n ?, ?.)))
2854 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2855 (point)))
2856 (case (char-after (1+ (point)))
2857 (?\( (search-forward "\\)" nil t))
2858 (?\[ (search-forward "\\]" nil t))
2859 (otherwise
2860 ;; Macro.
2861 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2862 (match-end 0))))))
2863 (post-blank (if (not after-fragment) (throw 'no-object nil)
2864 (goto-char after-fragment)
2865 (skip-chars-forward " \t")))
2866 (end (point)))
2867 (list 'latex-fragment
2868 (list :value (buffer-substring-no-properties begin after-fragment)
2869 :begin begin
2870 :end end
2871 :post-blank post-blank))))))
2873 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2874 "Interpret LATEX-FRAGMENT object as Org syntax.
2875 CONTENTS is nil."
2876 (org-element-property :value latex-fragment))
2878 ;;;; Line Break
2880 (defun org-element-line-break-parser ()
2881 "Parse line break at point, if any.
2883 When at a line break, return a list whose car is `line-break',
2884 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2885 Otherwise, return nil.
2887 Assume point is at the beginning of the line break."
2888 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2889 (not (eq (char-before) ?\\)))
2890 (list 'line-break
2891 (list :begin (point)
2892 :end (progn (forward-line) (point))
2893 :post-blank 0))))
2895 (defun org-element-line-break-interpreter (line-break contents)
2896 "Interpret LINE-BREAK object as Org syntax.
2897 CONTENTS is nil."
2898 "\\\\\n")
2901 ;;;; Link
2903 (defun org-element-link-parser ()
2904 "Parse link at point, if any.
2906 When at a link, return a list whose car is `link' and cdr a plist
2907 with `:type', `:path', `:raw-link', `:application',
2908 `:search-option', `:begin', `:end', `:contents-begin',
2909 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2910 nil.
2912 Assume point is at the beginning of the link."
2913 (catch 'no-object
2914 (let ((begin (point))
2915 end contents-begin contents-end link-end post-blank path type
2916 raw-link link search-option application)
2917 (cond
2918 ;; Type 1: Text targeted from a radio target.
2919 ((and org-target-link-regexp
2920 (save-excursion (or (bolp) (backward-char))
2921 (looking-at org-target-link-regexp)))
2922 (setq type "radio"
2923 link-end (match-end 1)
2924 path (org-match-string-no-properties 1)
2925 contents-begin (match-beginning 1)
2926 contents-end (match-end 1)))
2927 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2928 ((looking-at org-bracket-link-regexp)
2929 (setq contents-begin (match-beginning 3)
2930 contents-end (match-end 3)
2931 link-end (match-end 0)
2932 ;; RAW-LINK is the original link. Expand any
2933 ;; abbreviation in it.
2934 raw-link (org-translate-link
2935 (org-link-expand-abbrev
2936 (org-match-string-no-properties 1))))
2937 ;; Determine TYPE of link and set PATH accordingly.
2938 (cond
2939 ;; File type.
2940 ((or (file-name-absolute-p raw-link)
2941 (string-match "\\`\\.\\.?/" raw-link))
2942 (setq type "file" path raw-link))
2943 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2944 ((string-match org-link-types-re raw-link)
2945 (setq type (match-string 1 raw-link)
2946 ;; According to RFC 3986, extra whitespace should be
2947 ;; ignored when a URI is extracted.
2948 path (replace-regexp-in-string
2949 "[ \t]*\n[ \t]*" "" (substring raw-link (match-end 0)))))
2950 ;; Id type: PATH is the id.
2951 ((string-match "\\`id:\\([-a-f0-9]+\\)" raw-link)
2952 (setq type "id" path (match-string 1 raw-link)))
2953 ;; Code-ref type: PATH is the name of the reference.
2954 ((string-match "\\`(\\(.*\\))\\'" raw-link)
2955 (setq type "coderef" path (match-string 1 raw-link)))
2956 ;; Custom-id type: PATH is the name of the custom id.
2957 ((= (aref raw-link 0) ?#)
2958 (setq type "custom-id" path (substring raw-link 1)))
2959 ;; Fuzzy type: Internal link either matches a target, an
2960 ;; headline name or nothing. PATH is the target or
2961 ;; headline's name.
2962 (t (setq type "fuzzy" path raw-link))))
2963 ;; Type 3: Plain link, e.g., http://orgmode.org
2964 ((looking-at org-plain-link-re)
2965 (setq raw-link (org-match-string-no-properties 0)
2966 type (org-match-string-no-properties 1)
2967 link-end (match-end 0)
2968 path (org-match-string-no-properties 2)))
2969 ;; Type 4: Angular link, e.g., <http://orgmode.org>
2970 ((looking-at org-angle-link-re)
2971 (setq raw-link (buffer-substring-no-properties
2972 (match-beginning 1) (match-end 2))
2973 type (org-match-string-no-properties 1)
2974 link-end (match-end 0)
2975 path (org-match-string-no-properties 2)))
2976 (t (throw 'no-object nil)))
2977 ;; In any case, deduce end point after trailing white space from
2978 ;; LINK-END variable.
2979 (save-excursion
2980 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2981 end (point))
2982 ;; Special "file" type link processing.
2983 (when (member type org-element-link-type-is-file)
2984 ;; Extract opening application and search option.
2985 (cond ((string-match "^file\\+\\(.*\\)$" type)
2986 (setq application (match-string 1 type)))
2987 ((not (string-match "^file" type))
2988 (setq application type)))
2989 (when (string-match "::\\(.*\\)\\'" path)
2990 (setq search-option (match-string 1 path)
2991 path (replace-match "" nil nil path)))
2992 ;; Normalize URI.
2993 (when (and (file-name-absolute-p path)
2994 (not (org-string-match-p "\\`[/~]/" path)))
2995 (setq path (concat "//" path)))
2996 ;; Make sure TYPE always reports "file".
2997 (setq type "file"))
2998 (list 'link
2999 (list :type type
3000 :path path
3001 :raw-link (or raw-link path)
3002 :application application
3003 :search-option search-option
3004 :begin begin
3005 :end end
3006 :contents-begin contents-begin
3007 :contents-end contents-end
3008 :post-blank post-blank))))))
3010 (defun org-element-link-interpreter (link contents)
3011 "Interpret LINK object as Org syntax.
3012 CONTENTS is the contents of the object, or nil."
3013 (let ((type (org-element-property :type link))
3014 (raw-link (org-element-property :raw-link link)))
3015 (if (string= type "radio") raw-link
3016 (format "[[%s]%s]"
3017 raw-link
3018 (if contents (format "[%s]" contents) "")))))
3021 ;;;; Macro
3023 (defun org-element-macro-parser ()
3024 "Parse macro at point, if any.
3026 When at a macro, return a list whose car is `macro' and cdr
3027 a plist with `:key', `:args', `:begin', `:end', `:value' and
3028 `:post-blank' as keywords. Otherwise, return nil.
3030 Assume point is at the macro."
3031 (save-excursion
3032 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3033 (let ((begin (point))
3034 (key (downcase (org-match-string-no-properties 1)))
3035 (value (org-match-string-no-properties 0))
3036 (post-blank (progn (goto-char (match-end 0))
3037 (skip-chars-forward " \t")))
3038 (end (point))
3039 (args (let ((args (org-match-string-no-properties 3)))
3040 (when args
3041 ;; Do not use `org-split-string' since empty
3042 ;; strings are meaningful here.
3043 (split-string
3044 (replace-regexp-in-string
3045 "\\(\\\\*\\)\\(,\\)"
3046 (lambda (str)
3047 (let ((len (length (match-string 1 str))))
3048 (concat (make-string (/ len 2) ?\\)
3049 (if (zerop (mod len 2)) "\000" ","))))
3050 args nil t)
3051 "\000")))))
3052 (list 'macro
3053 (list :key key
3054 :value value
3055 :args args
3056 :begin begin
3057 :end end
3058 :post-blank post-blank))))))
3060 (defun org-element-macro-interpreter (macro contents)
3061 "Interpret MACRO object as Org syntax.
3062 CONTENTS is nil."
3063 (org-element-property :value macro))
3066 ;;;; Radio-target
3068 (defun org-element-radio-target-parser ()
3069 "Parse radio target at point, if any.
3071 When at a radio target, return a list whose car is `radio-target'
3072 and cdr a plist with `:begin', `:end', `:contents-begin',
3073 `:contents-end', `:value' and `:post-blank' as keywords.
3074 Otherwise, return nil.
3076 Assume point is at the radio target."
3077 (save-excursion
3078 (when (looking-at org-radio-target-regexp)
3079 (let ((begin (point))
3080 (contents-begin (match-beginning 1))
3081 (contents-end (match-end 1))
3082 (value (org-match-string-no-properties 1))
3083 (post-blank (progn (goto-char (match-end 0))
3084 (skip-chars-forward " \t")))
3085 (end (point)))
3086 (list 'radio-target
3087 (list :begin begin
3088 :end end
3089 :contents-begin contents-begin
3090 :contents-end contents-end
3091 :post-blank post-blank
3092 :value value))))))
3094 (defun org-element-radio-target-interpreter (target contents)
3095 "Interpret TARGET object as Org syntax.
3096 CONTENTS is the contents of the object."
3097 (concat "<<<" contents ">>>"))
3100 ;;;; Statistics Cookie
3102 (defun org-element-statistics-cookie-parser ()
3103 "Parse statistics cookie at point, if any.
3105 When at a statistics cookie, return a list whose car is
3106 `statistics-cookie', and cdr a plist with `:begin', `:end',
3107 `:value' and `:post-blank' keywords. Otherwise, return nil.
3109 Assume point is at the beginning of the statistics-cookie."
3110 (save-excursion
3111 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3112 (let* ((begin (point))
3113 (value (buffer-substring-no-properties
3114 (match-beginning 0) (match-end 0)))
3115 (post-blank (progn (goto-char (match-end 0))
3116 (skip-chars-forward " \t")))
3117 (end (point)))
3118 (list 'statistics-cookie
3119 (list :begin begin
3120 :end end
3121 :value value
3122 :post-blank post-blank))))))
3124 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3125 "Interpret STATISTICS-COOKIE object as Org syntax.
3126 CONTENTS is nil."
3127 (org-element-property :value statistics-cookie))
3130 ;;;; Strike-Through
3132 (defun org-element-strike-through-parser ()
3133 "Parse strike-through object at point, if any.
3135 When at a strike-through object, return a list whose car is
3136 `strike-through' and cdr is a plist with `:begin', `:end',
3137 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3138 Otherwise, return nil.
3140 Assume point is at the first plus sign marker."
3141 (save-excursion
3142 (unless (bolp) (backward-char 1))
3143 (when (looking-at org-emph-re)
3144 (let ((begin (match-beginning 2))
3145 (contents-begin (match-beginning 4))
3146 (contents-end (match-end 4))
3147 (post-blank (progn (goto-char (match-end 2))
3148 (skip-chars-forward " \t")))
3149 (end (point)))
3150 (list 'strike-through
3151 (list :begin begin
3152 :end end
3153 :contents-begin contents-begin
3154 :contents-end contents-end
3155 :post-blank post-blank))))))
3157 (defun org-element-strike-through-interpreter (strike-through contents)
3158 "Interpret STRIKE-THROUGH object as Org syntax.
3159 CONTENTS is the contents of the object."
3160 (format "+%s+" contents))
3163 ;;;; Subscript
3165 (defun org-element-subscript-parser ()
3166 "Parse subscript at point, if any.
3168 When at a subscript object, return a list whose car is
3169 `subscript' and cdr a plist with `:begin', `:end',
3170 `:contents-begin', `:contents-end', `:use-brackets-p' and
3171 `:post-blank' as keywords. Otherwise, return nil.
3173 Assume point is at the underscore."
3174 (save-excursion
3175 (unless (bolp) (backward-char))
3176 (when (looking-at org-match-substring-regexp)
3177 (let ((bracketsp (match-beginning 4))
3178 (begin (match-beginning 2))
3179 (contents-begin (or (match-beginning 4)
3180 (match-beginning 3)))
3181 (contents-end (or (match-end 4) (match-end 3)))
3182 (post-blank (progn (goto-char (match-end 0))
3183 (skip-chars-forward " \t")))
3184 (end (point)))
3185 (list 'subscript
3186 (list :begin begin
3187 :end end
3188 :use-brackets-p bracketsp
3189 :contents-begin contents-begin
3190 :contents-end contents-end
3191 :post-blank post-blank))))))
3193 (defun org-element-subscript-interpreter (subscript contents)
3194 "Interpret SUBSCRIPT object as Org syntax.
3195 CONTENTS is the contents of the object."
3196 (format
3197 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3198 contents))
3201 ;;;; Superscript
3203 (defun org-element-superscript-parser ()
3204 "Parse superscript at point, if any.
3206 When at a superscript object, return a list whose car is
3207 `superscript' and cdr a plist with `:begin', `:end',
3208 `:contents-begin', `:contents-end', `:use-brackets-p' and
3209 `:post-blank' as keywords. Otherwise, return nil.
3211 Assume point is at the caret."
3212 (save-excursion
3213 (unless (bolp) (backward-char))
3214 (when (looking-at org-match-substring-regexp)
3215 (let ((bracketsp (match-beginning 4))
3216 (begin (match-beginning 2))
3217 (contents-begin (or (match-beginning 4)
3218 (match-beginning 3)))
3219 (contents-end (or (match-end 4) (match-end 3)))
3220 (post-blank (progn (goto-char (match-end 0))
3221 (skip-chars-forward " \t")))
3222 (end (point)))
3223 (list 'superscript
3224 (list :begin begin
3225 :end end
3226 :use-brackets-p bracketsp
3227 :contents-begin contents-begin
3228 :contents-end contents-end
3229 :post-blank post-blank))))))
3231 (defun org-element-superscript-interpreter (superscript contents)
3232 "Interpret SUPERSCRIPT object as Org syntax.
3233 CONTENTS is the contents of the object."
3234 (format
3235 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3236 contents))
3239 ;;;; Table Cell
3241 (defun org-element-table-cell-parser ()
3242 "Parse table cell at point.
3243 Return a list whose car is `table-cell' and cdr is a plist
3244 containing `:begin', `:end', `:contents-begin', `:contents-end'
3245 and `:post-blank' keywords."
3246 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3247 (let* ((begin (match-beginning 0))
3248 (end (match-end 0))
3249 (contents-begin (match-beginning 1))
3250 (contents-end (match-end 1)))
3251 (list 'table-cell
3252 (list :begin begin
3253 :end end
3254 :contents-begin contents-begin
3255 :contents-end contents-end
3256 :post-blank 0))))
3258 (defun org-element-table-cell-interpreter (table-cell contents)
3259 "Interpret TABLE-CELL element as Org syntax.
3260 CONTENTS is the contents of the cell, or nil."
3261 (concat " " contents " |"))
3264 ;;;; Target
3266 (defun org-element-target-parser ()
3267 "Parse target at point, if any.
3269 When at a target, return a list whose car is `target' and cdr
3270 a plist with `:begin', `:end', `:value' and `:post-blank' as
3271 keywords. Otherwise, return nil.
3273 Assume point is at the target."
3274 (save-excursion
3275 (when (looking-at org-target-regexp)
3276 (let ((begin (point))
3277 (value (org-match-string-no-properties 1))
3278 (post-blank (progn (goto-char (match-end 0))
3279 (skip-chars-forward " \t")))
3280 (end (point)))
3281 (list 'target
3282 (list :begin begin
3283 :end end
3284 :value value
3285 :post-blank post-blank))))))
3287 (defun org-element-target-interpreter (target contents)
3288 "Interpret TARGET object as Org syntax.
3289 CONTENTS is nil."
3290 (format "<<%s>>" (org-element-property :value target)))
3293 ;;;; Timestamp
3295 (defconst org-element--timestamp-regexp
3296 (concat org-ts-regexp-both
3297 "\\|"
3298 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3299 "\\|"
3300 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3301 "Regexp matching any timestamp type object.")
3303 (defun org-element-timestamp-parser ()
3304 "Parse time stamp at point, if any.
3306 When at a time stamp, return a list whose car is `timestamp', and
3307 cdr a plist with `:type', `:raw-value', `:year-start',
3308 `:month-start', `:day-start', `:hour-start', `:minute-start',
3309 `:year-end', `:month-end', `:day-end', `:hour-end',
3310 `:minute-end', `:repeater-type', `:repeater-value',
3311 `:repeater-unit', `:warning-type', `:warning-value',
3312 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3313 Otherwise, return nil.
3315 Assume point is at the beginning of the timestamp."
3316 (when (org-looking-at-p org-element--timestamp-regexp)
3317 (save-excursion
3318 (let* ((begin (point))
3319 (activep (eq (char-after) ?<))
3320 (raw-value
3321 (progn
3322 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3323 (match-string-no-properties 0)))
3324 (date-start (match-string-no-properties 1))
3325 (date-end (match-string 3))
3326 (diaryp (match-beginning 2))
3327 (post-blank (progn (goto-char (match-end 0))
3328 (skip-chars-forward " \t")))
3329 (end (point))
3330 (time-range
3331 (and (not diaryp)
3332 (string-match
3333 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3334 date-start)
3335 (cons (string-to-number (match-string 2 date-start))
3336 (string-to-number (match-string 3 date-start)))))
3337 (type (cond (diaryp 'diary)
3338 ((and activep (or date-end time-range)) 'active-range)
3339 (activep 'active)
3340 ((or date-end time-range) 'inactive-range)
3341 (t 'inactive)))
3342 (repeater-props
3343 (and (not diaryp)
3344 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3345 raw-value)
3346 (list
3347 :repeater-type
3348 (let ((type (match-string 1 raw-value)))
3349 (cond ((equal "++" type) 'catch-up)
3350 ((equal ".+" type) 'restart)
3351 (t 'cumulate)))
3352 :repeater-value (string-to-number (match-string 2 raw-value))
3353 :repeater-unit
3354 (case (string-to-char (match-string 3 raw-value))
3355 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3356 (warning-props
3357 (and (not diaryp)
3358 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3359 (list
3360 :warning-type (if (match-string 1 raw-value) 'first 'all)
3361 :warning-value (string-to-number (match-string 2 raw-value))
3362 :warning-unit
3363 (case (string-to-char (match-string 3 raw-value))
3364 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3365 year-start month-start day-start hour-start minute-start year-end
3366 month-end day-end hour-end minute-end)
3367 ;; Parse date-start.
3368 (unless diaryp
3369 (let ((date (org-parse-time-string date-start t)))
3370 (setq year-start (nth 5 date)
3371 month-start (nth 4 date)
3372 day-start (nth 3 date)
3373 hour-start (nth 2 date)
3374 minute-start (nth 1 date))))
3375 ;; Compute date-end. It can be provided directly in time-stamp,
3376 ;; or extracted from time range. Otherwise, it defaults to the
3377 ;; same values as date-start.
3378 (unless diaryp
3379 (let ((date (and date-end (org-parse-time-string date-end t))))
3380 (setq year-end (or (nth 5 date) year-start)
3381 month-end (or (nth 4 date) month-start)
3382 day-end (or (nth 3 date) day-start)
3383 hour-end (or (nth 2 date) (car time-range) hour-start)
3384 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3385 (list 'timestamp
3386 (nconc (list :type type
3387 :raw-value raw-value
3388 :year-start year-start
3389 :month-start month-start
3390 :day-start day-start
3391 :hour-start hour-start
3392 :minute-start minute-start
3393 :year-end year-end
3394 :month-end month-end
3395 :day-end day-end
3396 :hour-end hour-end
3397 :minute-end minute-end
3398 :begin begin
3399 :end end
3400 :post-blank post-blank)
3401 repeater-props
3402 warning-props))))))
3404 (defun org-element-timestamp-interpreter (timestamp contents)
3405 "Interpret TIMESTAMP object as Org syntax.
3406 CONTENTS is nil."
3407 (let* ((repeat-string
3408 (concat
3409 (case (org-element-property :repeater-type timestamp)
3410 (cumulate "+") (catch-up "++") (restart ".+"))
3411 (let ((val (org-element-property :repeater-value timestamp)))
3412 (and val (number-to-string val)))
3413 (case (org-element-property :repeater-unit timestamp)
3414 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3415 (warning-string
3416 (concat
3417 (case (org-element-property :warning-type timestamp)
3418 (first "--")
3419 (all "-"))
3420 (let ((val (org-element-property :warning-value timestamp)))
3421 (and val (number-to-string val)))
3422 (case (org-element-property :warning-unit timestamp)
3423 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3424 (build-ts-string
3425 ;; Build an Org timestamp string from TIME. ACTIVEP is
3426 ;; non-nil when time stamp is active. If WITH-TIME-P is
3427 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3428 ;; specify a time range in the timestamp. REPEAT-STRING is
3429 ;; the repeater string, if any.
3430 (lambda (time activep &optional with-time-p hour-end minute-end)
3431 (let ((ts (format-time-string
3432 (funcall (if with-time-p 'cdr 'car)
3433 org-time-stamp-formats)
3434 time)))
3435 (when (and hour-end minute-end)
3436 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3437 (setq ts
3438 (replace-match
3439 (format "\\&-%02d:%02d" hour-end minute-end)
3440 nil nil ts)))
3441 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3442 (dolist (s (list repeat-string warning-string))
3443 (when (org-string-nw-p s)
3444 (setq ts (concat (substring ts 0 -1)
3447 (substring ts -1)))))
3448 ;; Return value.
3449 ts)))
3450 (type (org-element-property :type timestamp)))
3451 (case type
3452 ((active inactive)
3453 (let* ((minute-start (org-element-property :minute-start timestamp))
3454 (minute-end (org-element-property :minute-end timestamp))
3455 (hour-start (org-element-property :hour-start timestamp))
3456 (hour-end (org-element-property :hour-end timestamp))
3457 (time-range-p (and hour-start hour-end minute-start minute-end
3458 (or (/= hour-start hour-end)
3459 (/= minute-start minute-end)))))
3460 (funcall
3461 build-ts-string
3462 (encode-time 0
3463 (or minute-start 0)
3464 (or hour-start 0)
3465 (org-element-property :day-start timestamp)
3466 (org-element-property :month-start timestamp)
3467 (org-element-property :year-start timestamp))
3468 (eq type 'active)
3469 (and hour-start minute-start)
3470 (and time-range-p hour-end)
3471 (and time-range-p minute-end))))
3472 ((active-range inactive-range)
3473 (let ((minute-start (org-element-property :minute-start timestamp))
3474 (minute-end (org-element-property :minute-end timestamp))
3475 (hour-start (org-element-property :hour-start timestamp))
3476 (hour-end (org-element-property :hour-end timestamp)))
3477 (concat
3478 (funcall
3479 build-ts-string (encode-time
3481 (or minute-start 0)
3482 (or hour-start 0)
3483 (org-element-property :day-start timestamp)
3484 (org-element-property :month-start timestamp)
3485 (org-element-property :year-start timestamp))
3486 (eq type 'active-range)
3487 (and hour-start minute-start))
3488 "--"
3489 (funcall build-ts-string
3490 (encode-time 0
3491 (or minute-end 0)
3492 (or hour-end 0)
3493 (org-element-property :day-end timestamp)
3494 (org-element-property :month-end timestamp)
3495 (org-element-property :year-end timestamp))
3496 (eq type 'active-range)
3497 (and hour-end minute-end))))))))
3500 ;;;; Underline
3502 (defun org-element-underline-parser ()
3503 "Parse underline object at point, if any.
3505 When at an underline object, return a list whose car is
3506 `underline' and cdr is a plist with `:begin', `:end',
3507 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3508 Otherwise, return nil.
3510 Assume point is at the first underscore marker."
3511 (save-excursion
3512 (unless (bolp) (backward-char 1))
3513 (when (looking-at org-emph-re)
3514 (let ((begin (match-beginning 2))
3515 (contents-begin (match-beginning 4))
3516 (contents-end (match-end 4))
3517 (post-blank (progn (goto-char (match-end 2))
3518 (skip-chars-forward " \t")))
3519 (end (point)))
3520 (list 'underline
3521 (list :begin begin
3522 :end end
3523 :contents-begin contents-begin
3524 :contents-end contents-end
3525 :post-blank post-blank))))))
3527 (defun org-element-underline-interpreter (underline contents)
3528 "Interpret UNDERLINE object as Org syntax.
3529 CONTENTS is the contents of the object."
3530 (format "_%s_" contents))
3533 ;;;; Verbatim
3535 (defun org-element-verbatim-parser ()
3536 "Parse verbatim object at point, if any.
3538 When at a verbatim object, return a list whose car is `verbatim'
3539 and cdr is a plist with `:value', `:begin', `:end' and
3540 `:post-blank' keywords. Otherwise, return nil.
3542 Assume point is at the first equal sign marker."
3543 (save-excursion
3544 (unless (bolp) (backward-char 1))
3545 (when (looking-at org-emph-re)
3546 (let ((begin (match-beginning 2))
3547 (value (org-match-string-no-properties 4))
3548 (post-blank (progn (goto-char (match-end 2))
3549 (skip-chars-forward " \t")))
3550 (end (point)))
3551 (list 'verbatim
3552 (list :value value
3553 :begin begin
3554 :end end
3555 :post-blank post-blank))))))
3557 (defun org-element-verbatim-interpreter (verbatim contents)
3558 "Interpret VERBATIM object as Org syntax.
3559 CONTENTS is nil."
3560 (format "=%s=" (org-element-property :value verbatim)))
3564 ;;; Parsing Element Starting At Point
3566 ;; `org-element--current-element' is the core function of this section.
3567 ;; It returns the Lisp representation of the element starting at
3568 ;; point.
3570 ;; `org-element--current-element' makes use of special modes. They
3571 ;; are activated for fixed element chaining (e.g., `plain-list' >
3572 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3573 ;; `section'). Special modes are: `first-section', `item',
3574 ;; `node-property', `section' and `table-row'.
3576 (defun org-element--current-element (limit &optional granularity mode structure)
3577 "Parse the element starting at point.
3579 Return value is a list like (TYPE PROPS) where TYPE is the type
3580 of the element and PROPS a plist of properties associated to the
3581 element.
3583 Possible types are defined in `org-element-all-elements'.
3585 LIMIT bounds the search.
3587 Optional argument GRANULARITY determines the depth of the
3588 recursion. Allowed values are `headline', `greater-element',
3589 `element', `object' or nil. When it is broader than `object' (or
3590 nil), secondary values will not be parsed, since they only
3591 contain objects.
3593 Optional argument MODE, when non-nil, can be either
3594 `first-section', `section', `planning', `item', `node-property'
3595 and `table-row'.
3597 If STRUCTURE isn't provided but MODE is set to `item', it will be
3598 computed.
3600 This function assumes point is always at the beginning of the
3601 element it has to parse."
3602 (save-excursion
3603 (let ((case-fold-search t)
3604 ;; Determine if parsing depth allows for secondary strings
3605 ;; parsing. It only applies to elements referenced in
3606 ;; `org-element-secondary-value-alist'.
3607 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3608 (cond
3609 ;; Item.
3610 ((eq mode 'item)
3611 (org-element-item-parser limit structure raw-secondary-p))
3612 ;; Table Row.
3613 ((eq mode 'table-row) (org-element-table-row-parser limit))
3614 ;; Node Property.
3615 ((eq mode 'node-property) (org-element-node-property-parser limit))
3616 ;; Headline.
3617 ((org-with-limited-levels (org-at-heading-p))
3618 (org-element-headline-parser limit raw-secondary-p))
3619 ;; Sections (must be checked after headline).
3620 ((eq mode 'section) (org-element-section-parser limit))
3621 ((eq mode 'first-section)
3622 (org-element-section-parser
3623 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3624 limit)))
3625 ;; Planning.
3626 ((and (eq mode 'planning) (looking-at org-planning-line-re))
3627 (org-element-planning-parser limit))
3628 ;; Property drawer.
3629 ((and (memq mode '(planning property-drawer))
3630 (looking-at org-property-drawer-re))
3631 (org-element-property-drawer-parser limit))
3632 ;; When not at bol, point is at the beginning of an item or
3633 ;; a footnote definition: next item is always a paragraph.
3634 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3635 ;; Clock.
3636 ((looking-at org-clock-line-re) (org-element-clock-parser limit))
3637 ;; Inlinetask.
3638 ((org-at-heading-p)
3639 (org-element-inlinetask-parser limit raw-secondary-p))
3640 ;; From there, elements can have affiliated keywords.
3641 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3642 (cond
3643 ;; Jumping over affiliated keywords put point off-limits.
3644 ;; Parse them as regular keywords.
3645 ((and (cdr affiliated) (>= (point) limit))
3646 (goto-char (car affiliated))
3647 (org-element-keyword-parser limit nil))
3648 ;; LaTeX Environment.
3649 ((looking-at org-element--latex-begin-environment)
3650 (org-element-latex-environment-parser limit affiliated))
3651 ;; Drawer and Property Drawer.
3652 ((looking-at org-drawer-regexp)
3653 (org-element-drawer-parser limit affiliated))
3654 ;; Fixed Width
3655 ((looking-at "[ \t]*:\\( \\|$\\)")
3656 (org-element-fixed-width-parser limit affiliated))
3657 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3658 ;; Keywords.
3659 ((looking-at "[ \t]*#")
3660 (goto-char (match-end 0))
3661 (cond ((looking-at "\\(?: \\|$\\)")
3662 (beginning-of-line)
3663 (org-element-comment-parser limit affiliated))
3664 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3665 (beginning-of-line)
3666 (let ((parser (assoc (upcase (match-string 1))
3667 org-element-block-name-alist)))
3668 (if parser (funcall (cdr parser) limit affiliated)
3669 (org-element-special-block-parser limit affiliated))))
3670 ((looking-at "\\+CALL:")
3671 (beginning-of-line)
3672 (org-element-babel-call-parser limit affiliated))
3673 ((looking-at "\\+BEGIN:? ")
3674 (beginning-of-line)
3675 (org-element-dynamic-block-parser limit affiliated))
3676 ((looking-at "\\+\\S-+:")
3677 (beginning-of-line)
3678 (org-element-keyword-parser limit affiliated))
3680 (beginning-of-line)
3681 (org-element-paragraph-parser limit affiliated))))
3682 ;; Footnote Definition.
3683 ((looking-at org-footnote-definition-re)
3684 (org-element-footnote-definition-parser limit affiliated))
3685 ;; Horizontal Rule.
3686 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3687 (org-element-horizontal-rule-parser limit affiliated))
3688 ;; Diary Sexp.
3689 ((looking-at "%%(")
3690 (org-element-diary-sexp-parser limit affiliated))
3691 ;; Table.
3692 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3693 ;; List.
3694 ((looking-at (org-item-re))
3695 (org-element-plain-list-parser
3696 limit affiliated
3697 (or structure (org-element--list-struct limit))))
3698 ;; Default element: Paragraph.
3699 (t (org-element-paragraph-parser limit affiliated)))))))))
3702 ;; Most elements can have affiliated keywords. When looking for an
3703 ;; element beginning, we want to move before them, as they belong to
3704 ;; that element, and, in the meantime, collect information they give
3705 ;; into appropriate properties. Hence the following function.
3707 (defun org-element--collect-affiliated-keywords (limit)
3708 "Collect affiliated keywords from point down to LIMIT.
3710 Return a list whose CAR is the position at the first of them and
3711 CDR a plist of keywords and values and move point to the
3712 beginning of the first line after them.
3714 As a special case, if element doesn't start at the beginning of
3715 the line (e.g., a paragraph starting an item), CAR is current
3716 position of point and CDR is nil."
3717 (if (not (bolp)) (list (point))
3718 (let ((case-fold-search t)
3719 (origin (point))
3720 ;; RESTRICT is the list of objects allowed in parsed
3721 ;; keywords value.
3722 (restrict (org-element-restriction 'keyword))
3723 output)
3724 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3725 (let* ((raw-kwd (upcase (match-string 1)))
3726 ;; Apply translation to RAW-KWD. From there, KWD is
3727 ;; the official keyword.
3728 (kwd (or (cdr (assoc raw-kwd
3729 org-element-keyword-translation-alist))
3730 raw-kwd))
3731 ;; Find main value for any keyword.
3732 (value
3733 (save-match-data
3734 (org-trim
3735 (buffer-substring-no-properties
3736 (match-end 0) (point-at-eol)))))
3737 ;; PARSEDP is non-nil when keyword should have its
3738 ;; value parsed.
3739 (parsedp (member kwd org-element-parsed-keywords))
3740 ;; If KWD is a dual keyword, find its secondary
3741 ;; value. Maybe parse it.
3742 (dualp (member kwd org-element-dual-keywords))
3743 (dual-value
3744 (and dualp
3745 (let ((sec (org-match-string-no-properties 2)))
3746 (if (or (not sec) (not parsedp)) sec
3747 (org-element-parse-secondary-string sec restrict)))))
3748 ;; Attribute a property name to KWD.
3749 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3750 ;; Now set final shape for VALUE.
3751 (when parsedp
3752 (setq value (org-element-parse-secondary-string value restrict)))
3753 (when dualp
3754 (setq value (and (or value dual-value) (cons value dual-value))))
3755 (when (or (member kwd org-element-multiple-keywords)
3756 ;; Attributes can always appear on multiple lines.
3757 (string-match "^ATTR_" kwd))
3758 (setq value (cons value (plist-get output kwd-sym))))
3759 ;; Eventually store the new value in OUTPUT.
3760 (setq output (plist-put output kwd-sym value))
3761 ;; Move to next keyword.
3762 (forward-line)))
3763 ;; If affiliated keywords are orphaned: move back to first one.
3764 ;; They will be parsed as a paragraph.
3765 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3766 ;; Return value.
3767 (cons origin output))))
3771 ;;; The Org Parser
3773 ;; The two major functions here are `org-element-parse-buffer', which
3774 ;; parses Org syntax inside the current buffer, taking into account
3775 ;; region, narrowing, or even visibility if specified, and
3776 ;; `org-element-parse-secondary-string', which parses objects within
3777 ;; a given string.
3779 ;; The (almost) almighty `org-element-map' allows to apply a function
3780 ;; on elements or objects matching some type, and accumulate the
3781 ;; resulting values. In an export situation, it also skips unneeded
3782 ;; parts of the parse tree.
3784 (defun org-element-parse-buffer (&optional granularity visible-only)
3785 "Recursively parse the buffer and return structure.
3786 If narrowing is in effect, only parse the visible part of the
3787 buffer.
3789 Optional argument GRANULARITY determines the depth of the
3790 recursion. It can be set to the following symbols:
3792 `headline' Only parse headlines.
3793 `greater-element' Don't recurse into greater elements excepted
3794 headlines and sections. Thus, elements
3795 parsed are the top-level ones.
3796 `element' Parse everything but objects and plain text.
3797 `object' Parse the complete buffer (default).
3799 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3800 elements.
3802 An element or an objects is represented as a list with the
3803 pattern (TYPE PROPERTIES CONTENTS), where :
3805 TYPE is a symbol describing the element or object. See
3806 `org-element-all-elements' and `org-element-all-objects' for an
3807 exhaustive list of such symbols. One can retrieve it with
3808 `org-element-type' function.
3810 PROPERTIES is the list of attributes attached to the element or
3811 object, as a plist. Although most of them are specific to the
3812 element or object type, all types share `:begin', `:end',
3813 `:post-blank' and `:parent' properties, which respectively
3814 refer to buffer position where the element or object starts,
3815 ends, the number of white spaces or blank lines after it, and
3816 the element or object containing it. Properties values can be
3817 obtained by using `org-element-property' function.
3819 CONTENTS is a list of elements, objects or raw strings
3820 contained in the current element or object, when applicable.
3821 One can access them with `org-element-contents' function.
3823 The Org buffer has `org-data' as type and nil as properties.
3824 `org-element-map' function can be used to find specific elements
3825 or objects within the parse tree.
3827 This function assumes that current major mode is `org-mode'."
3828 (save-excursion
3829 (goto-char (point-min))
3830 (org-skip-whitespace)
3831 (org-element--parse-elements
3832 (point-at-bol) (point-max)
3833 ;; Start in `first-section' mode so text before the first
3834 ;; headline belongs to a section.
3835 'first-section nil granularity visible-only (list 'org-data nil))))
3837 (defun org-element-parse-secondary-string (string restriction &optional parent)
3838 "Recursively parse objects in STRING and return structure.
3840 RESTRICTION is a symbol limiting the object types that will be
3841 looked after.
3843 Optional argument PARENT, when non-nil, is the element or object
3844 containing the secondary string. It is used to set correctly
3845 `:parent' property within the string."
3846 (let ((local-variables (buffer-local-variables)))
3847 (with-temp-buffer
3848 (dolist (v local-variables)
3849 (ignore-errors
3850 (if (symbolp v) (makunbound v)
3851 (org-set-local (car v) (cdr v)))))
3852 (insert string)
3853 (restore-buffer-modified-p nil)
3854 (let ((secondary (org-element--parse-objects
3855 (point-min) (point-max) nil restriction)))
3856 (when parent
3857 (dolist (o secondary) (org-element-put-property o :parent parent)))
3858 secondary))))
3860 (defun org-element-map
3861 (data types fun &optional info first-match no-recursion with-affiliated)
3862 "Map a function on selected elements or objects.
3864 DATA is a parse tree, an element, an object, a string, or a list
3865 of such constructs. TYPES is a symbol or list of symbols of
3866 elements or objects types (see `org-element-all-elements' and
3867 `org-element-all-objects' for a complete list of types). FUN is
3868 the function called on the matching element or object. It has to
3869 accept one argument: the element or object itself.
3871 When optional argument INFO is non-nil, it should be a plist
3872 holding export options. In that case, parts of the parse tree
3873 not exportable according to that property list will be skipped.
3875 When optional argument FIRST-MATCH is non-nil, stop at the first
3876 match for which FUN doesn't return nil, and return that value.
3878 Optional argument NO-RECURSION is a symbol or a list of symbols
3879 representing elements or objects types. `org-element-map' won't
3880 enter any recursive element or object whose type belongs to that
3881 list. Though, FUN can still be applied on them.
3883 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3884 apply to matching objects within parsed affiliated keywords (see
3885 `org-element-parsed-keywords').
3887 Nil values returned from FUN do not appear in the results.
3890 Examples:
3891 ---------
3893 Assuming TREE is a variable containing an Org buffer parse tree,
3894 the following example will return a flat list of all `src-block'
3895 and `example-block' elements in it:
3897 \(org-element-map tree '(example-block src-block) 'identity)
3899 The following snippet will find the first headline with a level
3900 of 1 and a \"phone\" tag, and will return its beginning position:
3902 \(org-element-map tree 'headline
3903 \(lambda (hl)
3904 \(and (= (org-element-property :level hl) 1)
3905 \(member \"phone\" (org-element-property :tags hl))
3906 \(org-element-property :begin hl)))
3907 nil t)
3909 The next example will return a flat list of all `plain-list' type
3910 elements in TREE that are not a sub-list themselves:
3912 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3914 Eventually, this example will return a flat list of all `bold'
3915 type objects containing a `latex-snippet' type object, even
3916 looking into captions:
3918 \(org-element-map tree 'bold
3919 \(lambda (b)
3920 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3921 nil nil nil t)"
3922 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3923 (unless (listp types) (setq types (list types)))
3924 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3925 ;; Recursion depth is determined by --CATEGORY.
3926 (let* ((--category
3927 (catch 'found
3928 (let ((category 'greater-elements))
3929 (mapc (lambda (type)
3930 (cond ((or (memq type org-element-all-objects)
3931 (eq type 'plain-text))
3932 ;; If one object is found, the function
3933 ;; has to recurse into every object.
3934 (throw 'found 'objects))
3935 ((not (memq type org-element-greater-elements))
3936 ;; If one regular element is found, the
3937 ;; function has to recurse, at least,
3938 ;; into every element it encounters.
3939 (and (not (eq category 'elements))
3940 (setq category 'elements)))))
3941 types)
3942 category)))
3943 ;; Compute properties for affiliated keywords if necessary.
3944 (--affiliated-alist
3945 (and with-affiliated
3946 (mapcar (lambda (kwd)
3947 (cons kwd (intern (concat ":" (downcase kwd)))))
3948 org-element-affiliated-keywords)))
3949 --acc
3950 --walk-tree
3951 (--walk-tree
3952 (function
3953 (lambda (--data)
3954 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3955 ;; holding contextual information.
3956 (let ((--type (org-element-type --data)))
3957 (cond
3958 ((not --data))
3959 ;; Ignored element in an export context.
3960 ((and info (memq --data (plist-get info :ignore-list))))
3961 ;; List of elements or objects.
3962 ((not --type) (mapc --walk-tree --data))
3963 ;; Unconditionally enter parse trees.
3964 ((eq --type 'org-data)
3965 (mapc --walk-tree (org-element-contents --data)))
3967 ;; Check if TYPE is matching among TYPES. If so,
3968 ;; apply FUN to --DATA and accumulate return value
3969 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3970 (when (memq --type types)
3971 (let ((result (funcall fun --data)))
3972 (cond ((not result))
3973 (first-match (throw '--map-first-match result))
3974 (t (push result --acc)))))
3975 ;; If --DATA has a secondary string that can contain
3976 ;; objects with their type among TYPES, look into it.
3977 (when (and (eq --category 'objects) (not (stringp --data)))
3978 (let ((sec-prop
3979 (assq --type org-element-secondary-value-alist)))
3980 (when sec-prop
3981 (funcall --walk-tree
3982 (org-element-property (cdr sec-prop) --data)))))
3983 ;; If --DATA has any affiliated keywords and
3984 ;; WITH-AFFILIATED is non-nil, look for objects in
3985 ;; them.
3986 (when (and with-affiliated
3987 (eq --category 'objects)
3988 (memq --type org-element-all-elements))
3989 (mapc (lambda (kwd-pair)
3990 (let ((kwd (car kwd-pair))
3991 (value (org-element-property
3992 (cdr kwd-pair) --data)))
3993 ;; Pay attention to the type of value.
3994 ;; Preserve order for multiple keywords.
3995 (cond
3996 ((not value))
3997 ((and (member kwd org-element-multiple-keywords)
3998 (member kwd org-element-dual-keywords))
3999 (mapc (lambda (line)
4000 (funcall --walk-tree (cdr line))
4001 (funcall --walk-tree (car line)))
4002 (reverse value)))
4003 ((member kwd org-element-multiple-keywords)
4004 (mapc (lambda (line) (funcall --walk-tree line))
4005 (reverse value)))
4006 ((member kwd org-element-dual-keywords)
4007 (funcall --walk-tree (cdr value))
4008 (funcall --walk-tree (car value)))
4009 (t (funcall --walk-tree value)))))
4010 --affiliated-alist))
4011 ;; Determine if a recursion into --DATA is possible.
4012 (cond
4013 ;; --TYPE is explicitly removed from recursion.
4014 ((memq --type no-recursion))
4015 ;; --DATA has no contents.
4016 ((not (org-element-contents --data)))
4017 ;; Looking for greater elements but --DATA is simply
4018 ;; an element or an object.
4019 ((and (eq --category 'greater-elements)
4020 (not (memq --type org-element-greater-elements))))
4021 ;; Looking for elements but --DATA is an object.
4022 ((and (eq --category 'elements)
4023 (memq --type org-element-all-objects)))
4024 ;; In any other case, map contents.
4025 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4026 (catch '--map-first-match
4027 (funcall --walk-tree data)
4028 ;; Return value in a proper order.
4029 (nreverse --acc))))
4030 (put 'org-element-map 'lisp-indent-function 2)
4032 ;; The following functions are internal parts of the parser.
4034 ;; The first one, `org-element--parse-elements' acts at the element's
4035 ;; level.
4037 ;; The second one, `org-element--parse-objects' applies on all objects
4038 ;; of a paragraph or a secondary string. It calls
4039 ;; `org-element--object-lex' to find the next object in the current
4040 ;; container.
4042 (defsubst org-element--next-mode (type parentp)
4043 "Return next special mode according to TYPE, or nil.
4044 TYPE is a symbol representing the type of an element or object
4045 containing next element if PARENTP is non-nil, or before it
4046 otherwise. Modes can be either `first-section', `item',
4047 `node-property', `planning', `property-drawer', `section',
4048 `table-row' or nil."
4049 (if parentp
4050 (case type
4051 (headline 'section)
4052 (plain-list 'item)
4053 (property-drawer 'node-property)
4054 (section 'planning)
4055 (table 'table-row))
4056 (case type
4057 (item 'item)
4058 (node-property 'node-property)
4059 (planning 'property-drawer)
4060 (table-row 'table-row))))
4062 (defun org-element--parse-elements
4063 (beg end mode structure granularity visible-only acc)
4064 "Parse elements between BEG and END positions.
4066 MODE prioritizes some elements over the others. It can be set to
4067 `first-section', `section', `planning', `item', `node-property'
4068 or `table-row'.
4070 When value is `item', STRUCTURE will be used as the current list
4071 structure.
4073 GRANULARITY determines the depth of the recursion. See
4074 `org-element-parse-buffer' for more information.
4076 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4077 elements.
4079 Elements are accumulated into ACC."
4080 (save-excursion
4081 (goto-char beg)
4082 ;; Visible only: skip invisible parts at the beginning of the
4083 ;; element.
4084 (when (and visible-only (org-invisible-p2))
4085 (goto-char (min (1+ (org-find-visible)) end)))
4086 ;; When parsing only headlines, skip any text before first one.
4087 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4088 (org-with-limited-levels (outline-next-heading)))
4089 ;; Main loop start.
4090 (while (< (point) end)
4091 ;; Find current element's type and parse it accordingly to
4092 ;; its category.
4093 (let* ((element (org-element--current-element
4094 end granularity mode structure))
4095 (type (org-element-type element))
4096 (cbeg (org-element-property :contents-begin element)))
4097 (goto-char (org-element-property :end element))
4098 ;; Visible only: skip invisible parts between siblings.
4099 (when (and visible-only (org-invisible-p2))
4100 (goto-char (min (1+ (org-find-visible)) end)))
4101 ;; Fill ELEMENT contents by side-effect.
4102 (cond
4103 ;; If element has no contents, don't modify it.
4104 ((not cbeg))
4105 ;; Greater element: parse it between `contents-begin' and
4106 ;; `contents-end'. Make sure GRANULARITY allows the
4107 ;; recursion, or ELEMENT is a headline, in which case going
4108 ;; inside is mandatory, in order to get sub-level headings.
4109 ((and (memq type org-element-greater-elements)
4110 (or (memq granularity '(element object nil))
4111 (and (eq granularity 'greater-element)
4112 (eq type 'section))
4113 (eq type 'headline)))
4114 (org-element--parse-elements
4115 cbeg (org-element-property :contents-end element)
4116 ;; Possibly switch to a special mode.
4117 (org-element--next-mode type t)
4118 (and (memq type '(item plain-list))
4119 (org-element-property :structure element))
4120 granularity visible-only element))
4121 ;; ELEMENT has contents. Parse objects inside, if
4122 ;; GRANULARITY allows it.
4123 ((memq granularity '(object nil))
4124 (org-element--parse-objects
4125 cbeg (org-element-property :contents-end element) element
4126 (org-element-restriction type))))
4127 (org-element-adopt-elements acc element)
4128 ;; Update mode.
4129 (setq mode (org-element--next-mode type nil))))
4130 ;; Return result.
4131 acc))
4133 (defconst org-element--object-regexp
4134 (mapconcat #'identity
4135 (let ((link-types (regexp-opt org-link-types)))
4136 (list
4137 ;; Sub/superscript.
4138 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4139 ;; Bold, code, italic, strike-through, underline and
4140 ;; verbatim.
4141 (concat "[*~=+_/]"
4142 (format "[^%s]" (nth 2 org-emphasis-regexp-components)))
4143 ;; Plain links.
4144 (concat "\\<" link-types ":")
4145 ;; Objects starting with "[": regular link, footnote
4146 ;; reference, statistics cookie, timestamp (inactive).
4147 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4148 ;; Objects starting with "@": export snippets.
4149 "@@"
4150 ;; Objects starting with "{": macro.
4151 "{{{"
4152 ;; Objects starting with "<" : timestamp (active,
4153 ;; diary), target, radio target and angular links.
4154 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
4155 ;; Objects starting with "$": latex fragment.
4156 "\\$"
4157 ;; Objects starting with "\": line break, entity,
4158 ;; latex fragment.
4159 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4160 ;; Objects starting with raw text: inline Babel
4161 ;; source block, inline Babel call.
4162 "\\(?:call\\|src\\)_"))
4163 "\\|")
4164 "Regexp possibly matching the beginning of an object.
4165 This regexp allows false positives. Dedicated parser (e.g.,
4166 `org-export-bold-parser') will take care of further filtering.
4167 Radio links are not matched by this regexp, as they are treated
4168 specially in `org-element--object-lex'.")
4170 (defun org-element--object-lex (restriction)
4171 "Return next object in current buffer or nil.
4172 RESTRICTION is a list of object types, as symbols, that should be
4173 looked after. This function assumes that the buffer is narrowed
4174 to an appropriate container (e.g., a paragraph)."
4175 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4176 (save-excursion
4177 (let ((limit (and org-target-link-regexp
4178 (save-excursion
4179 (or (bolp) (backward-char))
4180 (re-search-forward org-target-link-regexp nil t))
4181 (match-beginning 1)))
4182 found)
4183 (while (and (not found)
4184 (re-search-forward org-element--object-regexp limit t))
4185 (goto-char (match-beginning 0))
4186 (let ((result (match-string 0)))
4187 (setq found
4188 (cond
4189 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4190 (and (memq 'inline-babel-call restriction)
4191 (org-element-inline-babel-call-parser)))
4192 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4193 (and (memq 'inline-src-block restriction)
4194 (org-element-inline-src-block-parser)))
4196 (case (char-after)
4197 (?^ (and (memq 'superscript restriction)
4198 (org-element-superscript-parser)))
4199 (?_ (or (and (memq 'subscript restriction)
4200 (org-element-subscript-parser))
4201 (and (memq 'underline restriction)
4202 (org-element-underline-parser))))
4203 (?* (and (memq 'bold restriction)
4204 (org-element-bold-parser)))
4205 (?/ (and (memq 'italic restriction)
4206 (org-element-italic-parser)))
4207 (?~ (and (memq 'code restriction)
4208 (org-element-code-parser)))
4209 (?= (and (memq 'verbatim restriction)
4210 (org-element-verbatim-parser)))
4211 (?+ (and (memq 'strike-through restriction)
4212 (org-element-strike-through-parser)))
4213 (?@ (and (memq 'export-snippet restriction)
4214 (org-element-export-snippet-parser)))
4215 (?{ (and (memq 'macro restriction)
4216 (org-element-macro-parser)))
4217 (?$ (and (memq 'latex-fragment restriction)
4218 (org-element-latex-fragment-parser)))
4220 (if (eq (aref result 1) ?<)
4221 (or (and (memq 'radio-target restriction)
4222 (org-element-radio-target-parser))
4223 (and (memq 'target restriction)
4224 (org-element-target-parser)))
4225 (or (and (memq 'timestamp restriction)
4226 (org-element-timestamp-parser))
4227 (and (memq 'link restriction)
4228 (org-element-link-parser)))))
4229 (?\\
4230 (if (eq (aref result 1) ?\\)
4231 (and (memq 'line-break restriction)
4232 (org-element-line-break-parser))
4233 (or (and (memq 'entity restriction)
4234 (org-element-entity-parser))
4235 (and (memq 'latex-fragment restriction)
4236 (org-element-latex-fragment-parser)))))
4237 (?\[
4238 (if (eq (aref result 1) ?\[)
4239 (and (memq 'link restriction)
4240 (org-element-link-parser))
4241 (or (and (memq 'footnote-reference restriction)
4242 (org-element-footnote-reference-parser))
4243 (and (memq 'timestamp restriction)
4244 (org-element-timestamp-parser))
4245 (and (memq 'statistics-cookie restriction)
4246 (org-element-statistics-cookie-parser)))))
4247 ;; This is probably a plain link.
4248 (otherwise (and (or (memq 'link restriction)
4249 (memq 'plain-link restriction))
4250 (org-element-link-parser)))))))
4251 (or (eobp) (forward-char))))
4252 (cond (found)
4253 ;; Radio link.
4254 ((and limit (memq 'link restriction))
4255 (goto-char limit) (org-element-link-parser)))))))
4257 (defun org-element--parse-objects (beg end acc restriction)
4258 "Parse objects between BEG and END and return recursive structure.
4260 Objects are accumulated in ACC.
4262 RESTRICTION is a list of object successors which are allowed in
4263 the current object."
4264 (save-excursion
4265 (save-restriction
4266 (narrow-to-region beg end)
4267 (goto-char (point-min))
4268 (let (next-object)
4269 (while (and (not (eobp))
4270 (setq next-object (org-element--object-lex restriction)))
4271 ;; 1. Text before any object. Untabify it.
4272 (let ((obj-beg (org-element-property :begin next-object)))
4273 (unless (= (point) obj-beg)
4274 (setq acc
4275 (org-element-adopt-elements
4277 (replace-regexp-in-string
4278 "\t" (make-string tab-width ? )
4279 (buffer-substring-no-properties (point) obj-beg))))))
4280 ;; 2. Object...
4281 (let ((obj-end (org-element-property :end next-object))
4282 (cont-beg (org-element-property :contents-begin next-object)))
4283 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4284 ;; a recursive type.
4285 (when (and cont-beg
4286 (memq (car next-object) org-element-recursive-objects))
4287 (org-element--parse-objects
4288 cont-beg (org-element-property :contents-end next-object)
4289 next-object (org-element-restriction next-object)))
4290 (setq acc (org-element-adopt-elements acc next-object))
4291 (goto-char obj-end))))
4292 ;; 3. Text after last object. Untabify it.
4293 (unless (eobp)
4294 (setq acc
4295 (org-element-adopt-elements
4297 (replace-regexp-in-string
4298 "\t" (make-string tab-width ? )
4299 (buffer-substring-no-properties (point) end)))))
4300 ;; Result.
4301 acc)))
4305 ;;; Towards A Bijective Process
4307 ;; The parse tree obtained with `org-element-parse-buffer' is really
4308 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4309 ;; interpreted and expanded into a string with canonical Org syntax.
4310 ;; Hence `org-element-interpret-data'.
4312 ;; The function relies internally on
4313 ;; `org-element--interpret-affiliated-keywords'.
4315 ;;;###autoload
4316 (defun org-element-interpret-data (data &optional pseudo-objects)
4317 "Interpret DATA as Org syntax.
4319 DATA is a parse tree, an element, an object or a secondary string
4320 to interpret.
4322 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4323 new types that should be treated as objects. An unknown type not
4324 belonging to this list is seen as a pseudo-element instead. Both
4325 pseudo-objects and pseudo-elements are transparent entities, i.e.
4326 only their contents are interpreted.
4328 Return Org syntax as a string."
4329 (org-element--interpret-data-1 data nil pseudo-objects))
4331 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4332 "Interpret DATA as Org syntax.
4334 DATA is a parse tree, an element, an object or a secondary string
4335 to interpret. PARENT is used for recursive calls. It contains
4336 the element or object containing data, or nil. PSEUDO-OBJECTS
4337 are list of symbols defining new element or object types.
4338 Unknown types that don't belong to this list are treated as
4339 pseudo-elements instead.
4341 Return Org syntax as a string."
4342 (let* ((type (org-element-type data))
4343 ;; Find interpreter for current object or element. If it
4344 ;; doesn't exist (e.g. this is a pseudo object or element),
4345 ;; return contents, if any.
4346 (interpret
4347 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4348 (if (fboundp fun) fun (lambda (data contents) contents))))
4349 (results
4350 (cond
4351 ;; Secondary string.
4352 ((not type)
4353 (mapconcat
4354 (lambda (obj)
4355 (org-element--interpret-data-1 obj parent pseudo-objects))
4356 data ""))
4357 ;; Full Org document.
4358 ((eq type 'org-data)
4359 (mapconcat
4360 (lambda (obj)
4361 (org-element--interpret-data-1 obj parent pseudo-objects))
4362 (org-element-contents data) ""))
4363 ;; Plain text: return it.
4364 ((stringp data) data)
4365 ;; Element or object without contents.
4366 ((not (org-element-contents data)) (funcall interpret data nil))
4367 ;; Element or object with contents.
4369 (funcall interpret data
4370 ;; Recursively interpret contents.
4371 (mapconcat
4372 (lambda (obj)
4373 (org-element--interpret-data-1 obj data pseudo-objects))
4374 (org-element-contents
4375 (if (not (memq type '(paragraph verse-block)))
4376 data
4377 ;; Fix indentation of elements containing
4378 ;; objects. We ignore `table-row' elements
4379 ;; as they are one line long anyway.
4380 (org-element-normalize-contents
4381 data
4382 ;; When normalizing first paragraph of an
4383 ;; item or a footnote-definition, ignore
4384 ;; first line's indentation.
4385 (and (eq type 'paragraph)
4386 (equal data (car (org-element-contents parent)))
4387 (memq (org-element-type parent)
4388 '(footnote-definition item))))))
4389 ""))))))
4390 (if (memq type '(org-data plain-text nil)) results
4391 ;; Build white spaces. If no `:post-blank' property is
4392 ;; specified, assume its value is 0.
4393 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4394 (if (or (memq type org-element-all-objects)
4395 (memq type pseudo-objects))
4396 (concat results (make-string post-blank ?\s))
4397 (concat
4398 (org-element--interpret-affiliated-keywords data)
4399 (org-element-normalize-string results)
4400 (make-string post-blank ?\n)))))))
4402 (defun org-element--interpret-affiliated-keywords (element)
4403 "Return ELEMENT's affiliated keywords as Org syntax.
4404 If there is no affiliated keyword, return the empty string."
4405 (let ((keyword-to-org
4406 (function
4407 (lambda (key value)
4408 (let (dual)
4409 (when (member key org-element-dual-keywords)
4410 (setq dual (cdr value) value (car value)))
4411 (concat "#+" key
4412 (and dual
4413 (format "[%s]" (org-element-interpret-data dual)))
4414 ": "
4415 (if (member key org-element-parsed-keywords)
4416 (org-element-interpret-data value)
4417 value)
4418 "\n"))))))
4419 (mapconcat
4420 (lambda (prop)
4421 (let ((value (org-element-property prop element))
4422 (keyword (upcase (substring (symbol-name prop) 1))))
4423 (when value
4424 (if (or (member keyword org-element-multiple-keywords)
4425 ;; All attribute keywords can have multiple lines.
4426 (string-match "^ATTR_" keyword))
4427 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4428 (reverse value)
4430 (funcall keyword-to-org keyword value)))))
4431 ;; List all ELEMENT's properties matching an attribute line or an
4432 ;; affiliated keyword, but ignore translated keywords since they
4433 ;; cannot belong to the property list.
4434 (loop for prop in (nth 1 element) by 'cddr
4435 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4436 (or (string-match "^ATTR_" keyword)
4437 (and
4438 (member keyword org-element-affiliated-keywords)
4439 (not (assoc keyword
4440 org-element-keyword-translation-alist)))))
4441 collect prop)
4442 "")))
4444 ;; Because interpretation of the parse tree must return the same
4445 ;; number of blank lines between elements and the same number of white
4446 ;; space after objects, some special care must be given to white
4447 ;; spaces.
4449 ;; The first function, `org-element-normalize-string', ensures any
4450 ;; string different from the empty string will end with a single
4451 ;; newline character.
4453 ;; The second function, `org-element-normalize-contents', removes
4454 ;; global indentation from the contents of the current element.
4456 (defun org-element-normalize-string (s)
4457 "Ensure string S ends with a single newline character.
4459 If S isn't a string return it unchanged. If S is the empty
4460 string, return it. Otherwise, return a new string with a single
4461 newline character at its end."
4462 (cond
4463 ((not (stringp s)) s)
4464 ((string= "" s) "")
4465 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4466 (replace-match "\n" nil nil s)))))
4468 (defun org-element-normalize-contents (element &optional ignore-first)
4469 "Normalize plain text in ELEMENT's contents.
4471 ELEMENT must only contain plain text and objects.
4473 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4474 indentation to compute maximal common indentation.
4476 Return the normalized element that is element with global
4477 indentation removed from its contents. The function assumes that
4478 indentation is not done with TAB characters."
4479 (let* ((min-ind most-positive-fixnum)
4480 find-min-ind ; For byte-compiler.
4481 (find-min-ind
4482 ;; Return minimal common indentation within BLOB. This is
4483 ;; done by walking recursively BLOB and updating MIN-IND
4484 ;; along the way. FIRST-FLAG is non-nil when the first
4485 ;; string hasn't been seen yet. It is required as this
4486 ;; string is the only one whose indentation doesn't happen
4487 ;; after a newline character.
4488 (lambda (blob first-flag)
4489 (dolist (object (org-element-contents blob))
4490 (when (and first-flag (stringp object))
4491 (setq first-flag nil)
4492 (string-match "\\` *" object)
4493 (let ((len (match-end 0)))
4494 ;; An indentation of zero means no string will be
4495 ;; modified. Quit the process.
4496 (if (zerop len) (throw 'zero (setq min-ind 0))
4497 (setq min-ind (min len min-ind)))))
4498 (cond
4499 ((stringp object)
4500 (dolist (line (cdr (org-split-string object " *\n")))
4501 (unless (string= line "")
4502 (setq min-ind (min (org-get-indentation line) min-ind)))))
4503 ((memq (org-element-type object) org-element-recursive-objects)
4504 (funcall find-min-ind object first-flag)))))))
4505 ;; Find minimal indentation in ELEMENT.
4506 (catch 'zero (funcall find-min-ind element (not ignore-first)))
4507 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4508 ;; Build ELEMENT back, replacing each string with the same
4509 ;; string minus common indentation.
4510 (let* (build ; For byte compiler.
4511 (build
4512 (function
4513 (lambda (blob first-flag)
4514 ;; Return BLOB with all its strings indentation
4515 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4516 ;; is non-nil when the first string hasn't been seen
4517 ;; yet.
4518 (setcdr (cdr blob)
4519 (mapcar
4520 #'(lambda (object)
4521 (when (and first-flag (stringp object))
4522 (setq first-flag nil)
4523 (setq object
4524 (replace-regexp-in-string
4525 (format "\\` \\{%d\\}" min-ind)
4526 "" object)))
4527 (cond
4528 ((stringp object)
4529 (replace-regexp-in-string
4530 (format "\n \\{%d\\}" min-ind) "\n" object))
4531 ((memq (org-element-type object)
4532 org-element-recursive-objects)
4533 (funcall build object first-flag))
4534 (t object)))
4535 (org-element-contents blob)))
4536 blob))))
4537 (funcall build element (not ignore-first))))))
4541 ;;; Cache
4543 ;; Implement a caching mechanism for `org-element-at-point' and
4544 ;; `org-element-context', which see.
4546 ;; A single public function is provided: `org-element-cache-reset'.
4548 ;; Cache is enabled by default, but can be disabled globally with
4549 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4550 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4551 ;; can be tweaked to control caching behaviour.
4553 ;; Internally, parsed elements are stored in an AVL tree,
4554 ;; `org-element--cache'. This tree is updated lazily: whenever
4555 ;; a change happens to the buffer, a synchronization request is
4556 ;; registered in `org-element--cache-sync-requests' (see
4557 ;; `org-element--cache-submit-request'). During idle time, requests
4558 ;; are processed by `org-element--cache-sync'. Synchronization also
4559 ;; happens when an element is required from the cache. In this case,
4560 ;; the process stops as soon as the needed element is up-to-date.
4562 ;; A synchronization request can only apply on a synchronized part of
4563 ;; the cache. Therefore, the cache is updated at least to the
4564 ;; location where the new request applies. Thus, requests are ordered
4565 ;; from left to right and all elements starting before the first
4566 ;; request are correct. This property is used by functions like
4567 ;; `org-element--cache-find' to retrieve elements in the part of the
4568 ;; cache that can be trusted.
4570 ;; A request applies to every element, starting from its original
4571 ;; location (or key, see below). When a request is processed, it
4572 ;; moves forward and may collide the next one. In this case, both
4573 ;; requests are merged into a new one that starts from that element.
4574 ;; As a consequence, the whole synchronization complexity does not
4575 ;; depend on the number of pending requests, but on the number of
4576 ;; elements the very first request will be applied on.
4578 ;; Elements cannot be accessed through their beginning position, which
4579 ;; may or may not be up-to-date. Instead, each element in the tree is
4580 ;; associated to a key, obtained with `org-element--cache-key'. This
4581 ;; mechanism is robust enough to preserve total order among elements
4582 ;; even when the tree is only partially synchronized.
4584 ;; Objects contained in an element are stored in a hash table,
4585 ;; `org-element--cache-objects'.
4588 (defvar org-element-use-cache t
4589 "Non nil when Org parser should cache its results.
4590 This is mostly for debugging purpose.")
4592 (defvar org-element-cache-sync-idle-time 0.6
4593 "Length, in seconds, of idle time before syncing cache.")
4595 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4596 "Maximum duration, as a time value, for a cache synchronization.
4597 If the synchronization is not over after this delay, the process
4598 pauses and resumes after `org-element-cache-sync-break'
4599 seconds.")
4601 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4602 "Duration, as a time value, of the pause between synchronizations.
4603 See `org-element-cache-sync-duration' for more information.")
4606 ;;;; Data Structure
4608 (defvar org-element--cache nil
4609 "AVL tree used to cache elements.
4610 Each node of the tree contains an element. Comparison is done
4611 with `org-element--cache-compare'. This cache is used in
4612 `org-element-at-point'.")
4614 (defvar org-element--cache-objects nil
4615 "Hash table used as to cache objects.
4616 Key is an element, as returned by `org-element-at-point', and
4617 value is an alist where each association is:
4619 \(PARENT COMPLETEP . OBJECTS)
4621 where PARENT is an element or object, COMPLETEP is a boolean,
4622 non-nil when all direct children of parent are already cached and
4623 OBJECTS is a list of such children, as objects, from farthest to
4624 closest.
4626 In the following example, \\alpha, bold object and \\beta are
4627 contained within a paragraph
4629 \\alpha *\\beta*
4631 If the paragraph is completely parsed, OBJECTS-DATA will be
4633 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4634 \(BOLD-OBJECT t ENTITY-OBJECT))
4636 whereas in a partially parsed paragraph, it could be
4638 \((PARAGRAPH nil ENTITY-OBJECT))
4640 This cache is used in `org-element-context'.")
4642 (defvar org-element--cache-sync-requests nil
4643 "List of pending synchronization requests.
4645 A request is a vector with the following pattern:
4647 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4649 Processing a synchronization request consists of three phases:
4651 0. Delete modified elements,
4652 1. Fill missing area in cache,
4653 2. Shift positions and re-parent elements after the changes.
4655 During phase 0, NEXT is the key of the first element to be
4656 removed, BEG and END is buffer position delimiting the
4657 modifications. Elements starting between them (inclusive) are
4658 removed and so are those contained within OUTREACH. PARENT, when
4659 non-nil, is the parent of the first element to be removed.
4661 During phase 1, NEXT is the key of the next known element in
4662 cache and BEG its beginning position. Parse buffer between that
4663 element and the one before it in order to determine the parent of
4664 the next element. Set PARENT to the element containing NEXT.
4666 During phase 2, NEXT is the key of the next element to shift in
4667 the parse tree. All elements starting from this one have their
4668 properties relatives to buffer positions shifted by integer
4669 OFFSET and, if they belong to element PARENT, are adopted by it.
4671 PHASE specifies the phase number, as an integer.")
4673 (defvar org-element--cache-sync-timer nil
4674 "Timer used for cache synchronization.")
4676 (defvar org-element--cache-sync-keys nil
4677 "Hash table used to store keys during synchronization.
4678 See `org-element--cache-key' for more information.")
4680 (defsubst org-element--cache-key (element)
4681 "Return a unique key for ELEMENT in cache tree.
4683 Keys are used to keep a total order among elements in the cache.
4684 Comparison is done with `org-element--cache-key-less-p'.
4686 When no synchronization is taking place, a key is simply the
4687 beginning position of the element, or that position plus one in
4688 the case of an first item (respectively row) in
4689 a list (respectively a table).
4691 During a synchronization, the key is the one the element had when
4692 the cache was synchronized for the last time. Elements added to
4693 cache during the synchronization get a new key generated with
4694 `org-element--cache-generate-key'.
4696 Such keys are stored in `org-element--cache-sync-keys'. The hash
4697 table is cleared once the synchronization is complete."
4698 (or (gethash element org-element--cache-sync-keys)
4699 (let* ((begin (org-element-property :begin element))
4700 ;; Increase beginning position of items (respectively
4701 ;; table rows) by one, so the first item can get
4702 ;; a different key from its parent list (respectively
4703 ;; table).
4704 (key (if (memq (org-element-type element) '(item table-row))
4705 (1+ begin)
4706 begin)))
4707 (if org-element--cache-sync-requests
4708 (puthash element key org-element--cache-sync-keys)
4709 key))))
4711 (defun org-element--cache-generate-key (lower upper)
4712 "Generate a key between LOWER and UPPER.
4714 LOWER and UPPER are integers or lists, possibly empty.
4716 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4717 a unique key, as an integer or a list of integers, according to
4718 the following rules:
4720 - LOWER and UPPER are compared level-wise until values differ.
4722 - If, at a given level, LOWER and UPPER differ from more than
4723 2, the new key shares all the levels above with LOWER and
4724 gets a new level. Its value is the mean between LOWER and
4725 UPPER:
4727 \(1 2) + (1 4) --> (1 3)
4729 - If LOWER has no value to compare with, it is assumed that its
4730 value is `most-negative-fixnum'. E.g.,
4732 \(1 1) + (1 1 2)
4734 is equivalent to
4736 \(1 1 m) + (1 1 2)
4738 where m is `most-negative-fixnum'. Likewise, if UPPER is
4739 short of levels, the current value is `most-positive-fixnum'.
4741 - If they differ from only one, the new key inherits from
4742 current LOWER level and fork it at the next level. E.g.,
4744 \(2 1) + (3 3)
4746 is equivalent to
4748 \(2 1) + (2 M)
4750 where M is `most-positive-fixnum'.
4752 - If the key is only one level long, it is returned as an
4753 integer:
4755 \(1 2) + (3 2) --> 2
4757 When they are not equals, the function assumes that LOWER is
4758 lesser than UPPER, per `org-element--cache-key-less-p'."
4759 (if (equal lower upper) lower
4760 (let ((lower (if (integerp lower) (list lower) lower))
4761 (upper (if (integerp upper) (list upper) upper))
4762 skip-upper key)
4763 (catch 'exit
4764 (while t
4765 (let ((min (or (car lower) most-negative-fixnum))
4766 (max (cond (skip-upper most-positive-fixnum)
4767 ((car upper))
4768 (t most-positive-fixnum))))
4769 (if (< (1+ min) max)
4770 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4771 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4772 (when (and (< min max) (not skip-upper))
4773 ;; When at a given level, LOWER and UPPER differ from
4774 ;; 1, ignore UPPER altogether. Instead create a key
4775 ;; between LOWER and the greatest key with the same
4776 ;; prefix as LOWER so far.
4777 (setq skip-upper t))
4778 (push min key)
4779 (setq lower (cdr lower) upper (cdr upper)))))))))
4781 (defsubst org-element--cache-key-less-p (a b)
4782 "Non-nil if key A is less than key B.
4783 A and B are either integers or lists of integers, as returned by
4784 `org-element--cache-key'."
4785 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4786 (if (integerp b) (< (car a) b)
4787 (catch 'exit
4788 (while (and a b)
4789 (cond ((car-less-than-car a b) (throw 'exit t))
4790 ((car-less-than-car b a) (throw 'exit nil))
4791 (t (setq a (cdr a) b (cdr b)))))
4792 ;; If A is empty, either keys are equal (B is also empty) and
4793 ;; we return nil, or A is lesser than B (B is longer) and we
4794 ;; return a non-nil value.
4796 ;; If A is not empty, B is necessarily empty and A is greater
4797 ;; than B (A is longer). Therefore, return nil.
4798 (and (null a) b)))))
4800 (defun org-element--cache-compare (a b)
4801 "Non-nil when element A is located before element B."
4802 (org-element--cache-key-less-p (org-element--cache-key a)
4803 (org-element--cache-key b)))
4805 (defsubst org-element--cache-root ()
4806 "Return root value in cache.
4807 This function assumes `org-element--cache' is a valid AVL tree."
4808 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4811 ;;;; Tools
4813 (defsubst org-element--cache-active-p ()
4814 "Non-nil when cache is active in current buffer."
4815 (and org-element-use-cache
4816 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4818 (defun org-element--cache-find (pos &optional side)
4819 "Find element in cache starting at POS or before.
4821 POS refers to a buffer position.
4823 When optional argument SIDE is non-nil, the function checks for
4824 elements starting at or past POS instead. If SIDE is `both', the
4825 function returns a cons cell where car is the first element
4826 starting at or before POS and cdr the first element starting
4827 after POS.
4829 The function can only find elements in the synchronized part of
4830 the cache."
4831 (let ((limit (and org-element--cache-sync-requests
4832 (aref (car org-element--cache-sync-requests) 0)))
4833 (node (org-element--cache-root))
4834 lower upper)
4835 (while node
4836 (let* ((element (avl-tree--node-data node))
4837 (begin (org-element-property :begin element)))
4838 (cond
4839 ((and limit
4840 (not (org-element--cache-key-less-p
4841 (org-element--cache-key element) limit)))
4842 (setq node (avl-tree--node-left node)))
4843 ((> begin pos)
4844 (setq upper element
4845 node (avl-tree--node-left node)))
4846 ((< begin pos)
4847 (setq lower element
4848 node (avl-tree--node-right node)))
4849 ;; We found an element in cache starting at POS. If `side'
4850 ;; is `both' we also want the next one in order to generate
4851 ;; a key in-between.
4853 ;; If the element is the first row or item in a table or
4854 ;; a plain list, we always return the table or the plain
4855 ;; list.
4857 ;; In any other case, we return the element found.
4858 ((eq side 'both)
4859 (setq lower element)
4860 (setq node (avl-tree--node-right node)))
4861 ((and (memq (org-element-type element) '(item table-row))
4862 (let ((parent (org-element-property :parent element)))
4863 (and (= (org-element-property :begin element)
4864 (org-element-property :contents-begin parent))
4865 (setq node nil
4866 lower parent
4867 upper parent)))))
4869 (setq node nil
4870 lower element
4871 upper element)))))
4872 (case side
4873 (both (cons lower upper))
4874 ((nil) lower)
4875 (otherwise upper))))
4877 (defun org-element--cache-put (element &optional data)
4878 "Store ELEMENT in current buffer's cache, if allowed.
4879 When optional argument DATA is non-nil, assume is it object data
4880 relative to ELEMENT and store it in the objects cache."
4881 (cond ((not (org-element--cache-active-p)) nil)
4882 ((not data)
4883 (when org-element--cache-sync-requests
4884 ;; During synchronization, first build an appropriate key
4885 ;; for the new element so `avl-tree-enter' can insert it at
4886 ;; the right spot in the cache.
4887 (let ((keys (org-element--cache-find
4888 (org-element-property :begin element) 'both)))
4889 (puthash element
4890 (org-element--cache-generate-key
4891 (and (car keys) (org-element--cache-key (car keys)))
4892 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4893 (org-element--cache-sync-requests
4894 (aref (car org-element--cache-sync-requests) 0))))
4895 org-element--cache-sync-keys)))
4896 (avl-tree-enter org-element--cache element))
4897 ;; Headlines are not stored in cache, so objects in titles are
4898 ;; not stored either.
4899 ((eq (org-element-type element) 'headline) nil)
4900 (t (puthash element data org-element--cache-objects))))
4902 (defsubst org-element--cache-remove (element)
4903 "Remove ELEMENT from cache.
4904 Assume ELEMENT belongs to cache and that a cache is active."
4905 (avl-tree-delete org-element--cache element)
4906 (remhash element org-element--cache-objects))
4909 ;;;; Synchronization
4911 (defsubst org-element--cache-set-timer (buffer)
4912 "Set idle timer for cache synchronization in BUFFER."
4913 (when org-element--cache-sync-timer
4914 (cancel-timer org-element--cache-sync-timer))
4915 (setq org-element--cache-sync-timer
4916 (run-with-idle-timer
4917 (let ((idle (current-idle-time)))
4918 (if idle (time-add idle org-element-cache-sync-break)
4919 org-element-cache-sync-idle-time))
4921 #'org-element--cache-sync
4922 buffer)))
4924 (defsubst org-element--cache-interrupt-p (time-limit)
4925 "Non-nil when synchronization process should be interrupted.
4926 TIME-LIMIT is a time value or nil."
4927 (and time-limit
4928 (or (input-pending-p)
4929 (time-less-p time-limit (current-time)))))
4931 (defsubst org-element--cache-shift-positions (element offset &optional props)
4932 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4934 Properties containing buffer positions are `:begin', `:end',
4935 `:contents-begin', `:contents-end' and `:structure'. When
4936 optional argument PROPS is a list of keywords, only shift
4937 properties provided in that list.
4939 Properties are modified by side-effect."
4940 (let ((properties (nth 1 element)))
4941 ;; Shift `:structure' property for the first plain list only: it
4942 ;; is the only one that really matters and it prevents from
4943 ;; shifting it more than once.
4944 (when (and (or (not props) (memq :structure props))
4945 (eq (org-element-type element) 'plain-list)
4946 (not (eq (org-element-type (plist-get properties :parent))
4947 'item)))
4948 (dolist (item (plist-get properties :structure))
4949 (incf (car item) offset)
4950 (incf (nth 6 item) offset)))
4951 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
4952 (let ((value (and (or (not props) (memq key props))
4953 (plist-get properties key))))
4954 (and value (plist-put properties key (+ offset value)))))))
4956 (defun org-element--cache-sync (buffer &optional threshold future-change)
4957 "Synchronize cache with recent modification in BUFFER.
4959 When optional argument THRESHOLD is non-nil, do the
4960 synchronization for all elements starting before or at threshold,
4961 then exit. Otherwise, synchronize cache for as long as
4962 `org-element-cache-sync-duration' or until Emacs leaves idle
4963 state.
4965 FUTURE-CHANGE, when non-nil, is a buffer position where changes
4966 not registered yet in the cache are going to happen. It is used
4967 in `org-element--cache-submit-request', where cache is partially
4968 updated before current modification are actually submitted."
4969 (when (buffer-live-p buffer)
4970 (with-current-buffer buffer
4971 (let ((inhibit-quit t) request next)
4972 (when org-element--cache-sync-timer
4973 (cancel-timer org-element--cache-sync-timer))
4974 (catch 'interrupt
4975 (while org-element--cache-sync-requests
4976 (setq request (car org-element--cache-sync-requests)
4977 next (nth 1 org-element--cache-sync-requests))
4978 (org-element--cache-process-request
4979 request
4980 (and next (aref next 0))
4981 threshold
4982 (and (not threshold)
4983 (time-add (current-time)
4984 org-element-cache-sync-duration))
4985 future-change)
4986 ;; Request processed. Merge current and next offsets and
4987 ;; transfer ending position.
4988 (when next
4989 (incf (aref next 3) (aref request 3))
4990 (aset next 2 (aref request 2)))
4991 (setq org-element--cache-sync-requests
4992 (cdr org-element--cache-sync-requests))))
4993 ;; If more requests are awaiting, set idle timer accordingly.
4994 ;; Otherwise, reset keys.
4995 (if org-element--cache-sync-requests
4996 (org-element--cache-set-timer buffer)
4997 (clrhash org-element--cache-sync-keys))))))
4999 (defun org-element--cache-process-request
5000 (request next threshold time-limit future-change)
5001 "Process synchronization REQUEST for all entries before NEXT.
5003 REQUEST is a vector, built by `org-element--cache-submit-request'.
5005 NEXT is a cache key, as returned by `org-element--cache-key'.
5007 When non-nil, THRESHOLD is a buffer position. Synchronization
5008 stops as soon as a shifted element begins after it.
5010 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5011 after this time or when Emacs exits idle state.
5013 When non-nil, FUTURE-CHANGE is a buffer position where changes
5014 not registered yet in the cache are going to happen. See
5015 `org-element--cache-submit-request' for more information.
5017 Throw `interrupt' if the process stops before completing the
5018 request."
5019 (catch 'quit
5020 (when (= (aref request 6) 0)
5021 ;; Phase 0.
5023 ;; Delete all elements starting after BEG, but not after buffer
5024 ;; position END or past element with key NEXT.
5026 ;; At each iteration, we start again at tree root since
5027 ;; a deletion modifies structure of the balanced tree.
5028 (catch 'end-phase
5029 (let ((beg (aref request 0))
5030 (end (aref request 2))
5031 (outreach (aref request 4)))
5032 (while t
5033 (when (org-element--cache-interrupt-p time-limit)
5034 (throw 'interrupt nil))
5035 ;; Find first element in cache with key BEG or after it.
5036 (let ((node (org-element--cache-root)) data data-key)
5037 (while node
5038 (let* ((element (avl-tree--node-data node))
5039 (key (org-element--cache-key element)))
5040 (cond
5041 ((org-element--cache-key-less-p key beg)
5042 (setq node (avl-tree--node-right node)))
5043 ((org-element--cache-key-less-p beg key)
5044 (setq data element
5045 data-key key
5046 node (avl-tree--node-left node)))
5047 (t (setq data element
5048 data-key key
5049 node nil)))))
5050 (if data
5051 (let ((pos (org-element-property :begin data)))
5052 (if (if (or (not next)
5053 (org-element--cache-key-less-p data-key next))
5054 (<= pos end)
5055 (let ((up data))
5056 (while (and up (not (eq up outreach)))
5057 (setq up (org-element-property :parent up)))
5058 up))
5059 (org-element--cache-remove data)
5060 (aset request 0 data-key)
5061 (aset request 1 pos)
5062 (aset request 6 1)
5063 (throw 'end-phase nil)))
5064 ;; No element starting after modifications left in
5065 ;; cache: further processing is futile.
5066 (throw 'quit t)))))))
5067 (when (= (aref request 6) 1)
5068 ;; Phase 1.
5070 ;; Phase 0 left a hole in the cache. Some elements after it
5071 ;; could have parents within. For example, in the following
5072 ;; buffer:
5074 ;; - item
5077 ;; Paragraph1
5079 ;; Paragraph2
5081 ;; if we remove a blank line between "item" and "Paragraph1",
5082 ;; everything down to "Paragraph2" is removed from cache. But
5083 ;; the paragraph now belongs to the list, and its `:parent'
5084 ;; property no longer is accurate.
5086 ;; Therefore we need to parse again elements in the hole, or at
5087 ;; least in its last section, so that we can re-parent
5088 ;; subsequent elements, during phase 2.
5090 ;; Note that we only need to get the parent from the first
5091 ;; element in cache after the hole.
5093 ;; When next key is lesser or equal to the current one, delegate
5094 ;; phase 1 processing to next request in order to preserve key
5095 ;; order among requests.
5096 (let ((key (aref request 0)))
5097 (when (and next (not (org-element--cache-key-less-p key next)))
5098 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5099 (aset next-request 0 key)
5100 (aset next-request 1 (aref request 1))
5101 (aset next-request 6 1))
5102 (throw 'quit t)))
5103 ;; Next element will start at its beginning position plus
5104 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5105 ;; contains the real beginning position of the first element to
5106 ;; shift and re-parent.
5107 (let ((limit (+ (aref request 1) (aref request 3))))
5108 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5109 ((and future-change (>= limit future-change))
5110 ;; Changes are going to happen around this element and
5111 ;; they will trigger another phase 1 request. Skip the
5112 ;; current one.
5113 (aset request 6 2))
5115 (let ((parent (org-element--parse-to limit t time-limit)))
5116 (aset request 5 parent)
5117 (aset request 6 2))))))
5118 ;; Phase 2.
5120 ;; Shift all elements starting from key START, but before NEXT, by
5121 ;; OFFSET, and re-parent them when appropriate.
5123 ;; Elements are modified by side-effect so the tree structure
5124 ;; remains intact.
5126 ;; Once THRESHOLD, if any, is reached, or once there is an input
5127 ;; pending, exit. Before leaving, the current synchronization
5128 ;; request is updated.
5129 (let ((start (aref request 0))
5130 (offset (aref request 3))
5131 (parent (aref request 5))
5132 (node (org-element--cache-root))
5133 (stack (list nil))
5134 (leftp t)
5135 exit-flag)
5136 ;; No re-parenting nor shifting planned: request is over.
5137 (when (and (not parent) (zerop offset)) (throw 'quit t))
5138 (while node
5139 (let* ((data (avl-tree--node-data node))
5140 (key (org-element--cache-key data)))
5141 (if (and leftp (avl-tree--node-left node)
5142 (not (org-element--cache-key-less-p key start)))
5143 (progn (push node stack)
5144 (setq node (avl-tree--node-left node)))
5145 (unless (org-element--cache-key-less-p key start)
5146 ;; We reached NEXT. Request is complete.
5147 (when (equal key next) (throw 'quit t))
5148 ;; Handle interruption request. Update current request.
5149 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5150 (aset request 0 key)
5151 (aset request 5 parent)
5152 (throw 'interrupt nil))
5153 ;; Shift element.
5154 (unless (zerop offset)
5155 (org-element--cache-shift-positions data offset)
5156 ;; Shift associated objects data, if any.
5157 (dolist (object-data (gethash data org-element--cache-objects))
5158 (dolist (object (cddr object-data))
5159 (org-element--cache-shift-positions object offset))))
5160 (let ((begin (org-element-property :begin data)))
5161 ;; Update PARENT and re-parent DATA, only when
5162 ;; necessary. Propagate new structures for lists.
5163 (while (and parent
5164 (<= (org-element-property :end parent) begin))
5165 (setq parent (org-element-property :parent parent)))
5166 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5167 ((and parent
5168 (let ((p (org-element-property :parent data)))
5169 (or (not p)
5170 (< (org-element-property :begin p)
5171 (org-element-property :begin parent)))))
5172 (org-element-put-property data :parent parent)
5173 (let ((s (org-element-property :structure parent)))
5174 (when (and s (org-element-property :structure data))
5175 (org-element-put-property data :structure s)))))
5176 ;; Cache is up-to-date past THRESHOLD. Request
5177 ;; interruption.
5178 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5179 (setq node (if (setq leftp (avl-tree--node-right node))
5180 (avl-tree--node-right node)
5181 (pop stack))))))
5182 ;; We reached end of tree: synchronization complete.
5183 t)))
5185 (defun org-element--parse-to (pos &optional syncp time-limit)
5186 "Parse elements in current section, down to POS.
5188 Start parsing from the closest between the last known element in
5189 cache or headline above. Return the smallest element containing
5190 POS.
5192 When optional argument SYNCP is non-nil, return the parent of the
5193 element containing POS instead. In that case, it is also
5194 possible to provide TIME-LIMIT, which is a time value specifying
5195 when the parsing should stop. The function throws `interrupt' if
5196 the process stopped before finding the expected result."
5197 (catch 'exit
5198 (org-with-wide-buffer
5199 (goto-char pos)
5200 (let* ((cached (and (org-element--cache-active-p)
5201 (org-element--cache-find pos nil)))
5202 (begin (org-element-property :begin cached))
5203 element next mode)
5204 (cond
5205 ;; Nothing in cache before point: start parsing from first
5206 ;; element following headline above, or first element in
5207 ;; buffer.
5208 ((not cached)
5209 (when (org-with-limited-levels (outline-previous-heading))
5210 (setq mode 'planning)
5211 (forward-line))
5212 (skip-chars-forward " \r\t\n")
5213 (beginning-of-line))
5214 ;; Cache returned exact match: return it.
5215 ((= pos begin)
5216 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5217 ;; There's a headline between cached value and POS: cached
5218 ;; value is invalid. Start parsing from first element
5219 ;; following the headline.
5220 ((re-search-backward
5221 (org-with-limited-levels org-outline-regexp-bol) begin t)
5222 (forward-line)
5223 (skip-chars-forward " \r\t\n")
5224 (beginning-of-line)
5225 (setq mode 'planning))
5226 ;; Check if CACHED or any of its ancestors contain point.
5228 ;; If there is such an element, we inspect it in order to know
5229 ;; if we return it or if we need to parse its contents.
5230 ;; Otherwise, we just start parsing from current location,
5231 ;; which is right after the top-most element containing
5232 ;; CACHED.
5234 ;; As a special case, if POS is at the end of the buffer, we
5235 ;; want to return the innermost element ending there.
5237 ;; Also, if we find an ancestor and discover that we need to
5238 ;; parse its contents, make sure we don't start from
5239 ;; `:contents-begin', as we would otherwise go past CACHED
5240 ;; again. Instead, in that situation, we will resume parsing
5241 ;; from NEXT, which is located after CACHED or its higher
5242 ;; ancestor not containing point.
5244 (let ((up cached)
5245 (pos (if (= (point-max) pos) (1- pos) pos)))
5246 (goto-char (or (org-element-property :contents-begin cached) begin))
5247 (while (let ((end (org-element-property :end up)))
5248 (and (<= end pos)
5249 (goto-char end)
5250 (setq up (org-element-property :parent up)))))
5251 (cond ((not up))
5252 ((eobp) (setq element up))
5253 (t (setq element up next (point)))))))
5254 ;; Parse successively each element until we reach POS.
5255 (let ((end (or (org-element-property :end element)
5256 (save-excursion
5257 (org-with-limited-levels (outline-next-heading))
5258 (point))))
5259 (parent element))
5260 (while t
5261 (when syncp
5262 (cond ((= (point) pos) (throw 'exit parent))
5263 ((org-element--cache-interrupt-p time-limit)
5264 (throw 'interrupt nil))))
5265 (unless element
5266 (setq element (org-element--current-element
5267 end 'element mode
5268 (org-element-property :structure parent)))
5269 (org-element-put-property element :parent parent)
5270 (org-element--cache-put element))
5271 (let ((elem-end (org-element-property :end element))
5272 (type (org-element-type element)))
5273 (cond
5274 ;; Skip any element ending before point. Also skip
5275 ;; element ending at point (unless it is also the end of
5276 ;; buffer) since we're sure that another element begins
5277 ;; after it.
5278 ((and (<= elem-end pos) (/= (point-max) elem-end))
5279 (goto-char elem-end)
5280 (setq mode (org-element--next-mode type nil)))
5281 ;; A non-greater element contains point: return it.
5282 ((not (memq type org-element-greater-elements))
5283 (throw 'exit element))
5284 ;; Otherwise, we have to decide if ELEMENT really
5285 ;; contains POS. In that case we start parsing from
5286 ;; contents' beginning.
5288 ;; If POS is at contents' beginning but it is also at
5289 ;; the beginning of the first item in a list or a table.
5290 ;; In that case, we need to create an anchor for that
5291 ;; list or table, so return it.
5293 ;; Also, if POS is at the end of the buffer, no element
5294 ;; can start after it, but more than one may end there.
5295 ;; Arbitrarily, we choose to return the innermost of
5296 ;; such elements.
5297 ((let ((cbeg (org-element-property :contents-begin element))
5298 (cend (org-element-property :contents-end element)))
5299 (when (or syncp
5300 (and cbeg cend
5301 (or (< cbeg pos)
5302 (and (= cbeg pos)
5303 (not (memq type '(plain-list table)))))
5304 (or (> cend pos)
5305 (and (= cend pos) (= (point-max) pos)))))
5306 (goto-char (or next cbeg))
5307 (setq next nil
5308 mode (org-element--next-mode type t)
5309 parent element
5310 end cend))))
5311 ;; Otherwise, return ELEMENT as it is the smallest
5312 ;; element containing POS.
5313 (t (throw 'exit element))))
5314 (setq element nil)))))))
5317 ;;;; Staging Buffer Changes
5319 (defconst org-element--cache-sensitive-re
5320 (concat
5321 org-outline-regexp-bol "\\|"
5322 "^[ \t]*\\(?:"
5323 ;; Blocks
5324 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5325 ;; LaTeX environments.
5326 "\\\\\\(?:begin{[A-Za-z0-9*]+}\\|end{[A-Za-z0-9*]+}[ \t]*$\\)" "\\|"
5327 ;; Drawers.
5328 ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
5329 "\\)")
5330 "Regexp matching a sensitive line, structure wise.
5331 A sensitive line is a headline, inlinetask, block, drawer, or
5332 latex-environment boundary. When such a line is modified,
5333 structure changes in the document may propagate in the whole
5334 section, possibly making cache invalid.")
5336 (defvar org-element--cache-change-warning nil
5337 "Non-nil when a sensitive line is about to be changed.
5338 It is a symbol among nil, t and `headline'.")
5340 (defun org-element--cache-before-change (beg end)
5341 "Request extension of area going to be modified if needed.
5342 BEG and END are the beginning and end of the range of changed
5343 text. See `before-change-functions' for more information."
5344 (when (org-element--cache-active-p)
5345 (org-with-wide-buffer
5346 (goto-char beg)
5347 (beginning-of-line)
5348 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5349 (setq org-element--cache-change-warning
5350 (save-match-data
5351 (if (and (org-with-limited-levels (org-at-heading-p))
5352 (= (line-end-position) bottom))
5353 'headline
5354 (let ((case-fold-search t))
5355 (re-search-forward
5356 org-element--cache-sensitive-re bottom t)))))))))
5358 (defun org-element--cache-after-change (beg end pre)
5359 "Update buffer modifications for current buffer.
5360 BEG and END are the beginning and end of the range of changed
5361 text, and the length in bytes of the pre-change text replaced by
5362 that range. See `after-change-functions' for more information."
5363 (when (org-element--cache-active-p)
5364 (org-with-wide-buffer
5365 (goto-char beg)
5366 (beginning-of-line)
5367 (save-match-data
5368 (let ((top (point))
5369 (bottom (save-excursion (goto-char end) (line-end-position))))
5370 ;; Determine if modified area needs to be extended, according
5371 ;; to both previous and current state. We make a special
5372 ;; case for headline editing: if a headline is modified but
5373 ;; not removed, do not extend.
5374 (when (case org-element--cache-change-warning
5375 ((t) t)
5376 (headline
5377 (not (and (org-with-limited-levels (org-at-heading-p))
5378 (= (line-end-position) bottom))))
5379 (otherwise
5380 (let ((case-fold-search t))
5381 (re-search-forward
5382 org-element--cache-sensitive-re bottom t))))
5383 ;; Effectively extend modified area.
5384 (org-with-limited-levels
5385 (setq top (progn (goto-char top)
5386 (when (outline-previous-heading) (forward-line))
5387 (point)))
5388 (setq bottom (progn (goto-char bottom)
5389 (if (outline-next-heading) (1- (point))
5390 (point))))))
5391 ;; Store synchronization request.
5392 (let ((offset (- end beg pre)))
5393 (org-element--cache-submit-request top (- bottom offset) offset)))))
5394 ;; Activate a timer to process the request during idle time.
5395 (org-element--cache-set-timer (current-buffer))))
5397 (defun org-element--cache-for-removal (beg end offset)
5398 "Return first element to remove from cache.
5400 BEG and END are buffer positions delimiting buffer modifications.
5401 OFFSET is the size of the changes.
5403 Returned element is usually the first element in cache containing
5404 any position between BEG and END. As an exception, greater
5405 elements around the changes that are robust to contents
5406 modifications are preserved and updated according to the
5407 changes."
5408 (let* ((elements (org-element--cache-find (1- beg) 'both))
5409 (before (car elements))
5410 (after (cdr elements)))
5411 (if (not before) after
5412 (let ((up before)
5413 (robust-flag t))
5414 (while up
5415 (if (and (memq (org-element-type up)
5416 '(center-block drawer dynamic-block
5417 quote-block special-block))
5418 (let ((cbeg (org-element-property :contents-begin up)))
5419 (and cbeg
5420 (<= cbeg beg)
5421 (> (org-element-property :contents-end up) end))))
5422 ;; UP is a robust greater element containing changes.
5423 ;; We only need to extend its ending boundaries.
5424 (org-element--cache-shift-positions
5425 up offset '(:contents-end :end))
5426 (setq before up)
5427 (when robust-flag (setq robust-flag nil)))
5428 (setq up (org-element-property :parent up)))
5429 ;; We're at top level element containing ELEMENT: if it's
5430 ;; altered by buffer modifications, it is first element in
5431 ;; cache to be removed. Otherwise, that first element is the
5432 ;; following one.
5434 ;; As a special case, do not remove BEFORE if it is a robust
5435 ;; container for current changes.
5436 (if (or (< (org-element-property :end before) beg) robust-flag) after
5437 before)))))
5439 (defun org-element--cache-submit-request (beg end offset)
5440 "Submit a new cache synchronization request for current buffer.
5441 BEG and END are buffer positions delimiting the minimal area
5442 where cache data should be removed. OFFSET is the size of the
5443 change, as an integer."
5444 (let ((next (car org-element--cache-sync-requests))
5445 delete-to delete-from)
5446 (if (and next
5447 (zerop (aref next 6))
5448 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5449 (<= (setq delete-from (aref next 1)) end))
5450 ;; Current changes can be merged with first sync request: we
5451 ;; can save a partial cache synchronization.
5452 (progn
5453 (incf (aref next 3) offset)
5454 ;; If last change happened within area to be removed, extend
5455 ;; boundaries of robust parents, if any. Otherwise, find
5456 ;; first element to remove and update request accordingly.
5457 (if (> beg delete-from)
5458 (let ((up (aref next 5)))
5459 (while up
5460 (org-element--cache-shift-positions
5461 up offset '(:contents-end :end))
5462 (setq up (org-element-property :parent up))))
5463 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5464 (when first
5465 (aset next 0 (org-element--cache-key first))
5466 (aset next 1 (org-element-property :begin first))
5467 (aset next 5 (org-element-property :parent first))))))
5468 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5469 ;; if any, is no longer a 0-phase request, thus ensuring that
5470 ;; phases are properly ordered. We need to provide OFFSET as
5471 ;; optional parameter since current modifications are not known
5472 ;; yet to the otherwise correct part of the cache (i.e, before
5473 ;; the first request).
5474 (when next (org-element--cache-sync (current-buffer) end beg))
5475 (let ((first (org-element--cache-for-removal beg end offset)))
5476 (if first
5477 (push (let ((beg (org-element-property :begin first))
5478 (key (org-element--cache-key first)))
5479 (cond
5480 ;; When changes happen before the first known
5481 ;; element, re-parent and shift the rest of the
5482 ;; cache.
5483 ((> beg end) (vector key beg nil offset nil nil 1))
5484 ;; Otherwise, we find the first non robust
5485 ;; element containing END. All elements between
5486 ;; FIRST and this one are to be removed.
5488 ;; Among them, some could be located outside the
5489 ;; synchronized part of the cache, in which case
5490 ;; comparing buffer positions to find them is
5491 ;; useless. Instead, we store the element
5492 ;; containing them in the request itself. All
5493 ;; its children will be removed.
5494 ((let ((first-end (org-element-property :end first)))
5495 (and (> first-end end)
5496 (vector key beg first-end offset first
5497 (org-element-property :parent first) 0))))
5499 (let* ((element (org-element--cache-find end))
5500 (end (org-element-property :end element))
5501 (up element))
5502 (while (and (setq up (org-element-property :parent up))
5503 (>= (org-element-property :begin up) beg))
5504 (setq end (org-element-property :end up)
5505 element up))
5506 (vector key beg end offset element
5507 (org-element-property :parent first) 0)))))
5508 org-element--cache-sync-requests)
5509 ;; No element to remove. No need to re-parent either.
5510 ;; Simply shift additional elements, if any, by OFFSET.
5511 (when org-element--cache-sync-requests
5512 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5515 ;;;; Public Functions
5517 ;;;###autoload
5518 (defun org-element-cache-reset (&optional all)
5519 "Reset cache in current buffer.
5520 When optional argument ALL is non-nil, reset cache in all Org
5521 buffers."
5522 (interactive "P")
5523 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5524 (with-current-buffer buffer
5525 (when (org-element--cache-active-p)
5526 (org-set-local 'org-element--cache
5527 (avl-tree-create #'org-element--cache-compare))
5528 (org-set-local 'org-element--cache-objects (make-hash-table :test #'eq))
5529 (org-set-local 'org-element--cache-sync-keys
5530 (make-hash-table :weakness 'key :test #'eq))
5531 (org-set-local 'org-element--cache-change-warning nil)
5532 (org-set-local 'org-element--cache-sync-requests nil)
5533 (org-set-local 'org-element--cache-sync-timer nil)
5534 (add-hook 'before-change-functions
5535 #'org-element--cache-before-change nil t)
5536 (add-hook 'after-change-functions
5537 #'org-element--cache-after-change nil t)))))
5539 ;;;###autoload
5540 (defun org-element-cache-refresh (pos)
5541 "Refresh cache at position POS."
5542 (when (org-element--cache-active-p)
5543 (org-element--cache-sync (current-buffer) pos)
5544 (org-element--cache-submit-request pos pos 0)
5545 (org-element--cache-set-timer (current-buffer))))
5549 ;;; The Toolbox
5551 ;; The first move is to implement a way to obtain the smallest element
5552 ;; containing point. This is the job of `org-element-at-point'. It
5553 ;; basically jumps back to the beginning of section containing point
5554 ;; and proceed, one element after the other, with
5555 ;; `org-element--current-element' until the container is found. Note:
5556 ;; When using `org-element-at-point', secondary values are never
5557 ;; parsed since the function focuses on elements, not on objects.
5559 ;; At a deeper level, `org-element-context' lists all elements and
5560 ;; objects containing point.
5562 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5563 ;; internally by navigation and manipulation tools.
5566 ;;;###autoload
5567 (defun org-element-at-point ()
5568 "Determine closest element around point.
5570 Return value is a list like (TYPE PROPS) where TYPE is the type
5571 of the element and PROPS a plist of properties associated to the
5572 element.
5574 Possible types are defined in `org-element-all-elements'.
5575 Properties depend on element or object type, but always include
5576 `:begin', `:end', `:parent' and `:post-blank' properties.
5578 As a special case, if point is at the very beginning of the first
5579 item in a list or sub-list, returned element will be that list
5580 instead of the item. Likewise, if point is at the beginning of
5581 the first row of a table, returned element will be the table
5582 instead of the first row.
5584 When point is at the end of the buffer, return the innermost
5585 element ending there."
5586 (org-with-wide-buffer
5587 (let ((origin (point)))
5588 (end-of-line)
5589 (skip-chars-backward " \r\t\n")
5590 (cond
5591 ;; Within blank lines at the beginning of buffer, return nil.
5592 ((bobp) nil)
5593 ;; Within blank lines right after a headline, return that
5594 ;; headline.
5595 ((org-with-limited-levels (org-at-heading-p))
5596 (beginning-of-line)
5597 (org-element-headline-parser (point-max) t))
5598 ;; Otherwise parse until we find element containing ORIGIN.
5600 (when (org-element--cache-active-p)
5601 (if (not org-element--cache) (org-element-cache-reset)
5602 (org-element--cache-sync (current-buffer) origin)))
5603 (org-element--parse-to origin))))))
5605 ;;;###autoload
5606 (defun org-element-context (&optional element)
5607 "Return smallest element or object around point.
5609 Return value is a list like (TYPE PROPS) where TYPE is the type
5610 of the element or object and PROPS a plist of properties
5611 associated to it.
5613 Possible types are defined in `org-element-all-elements' and
5614 `org-element-all-objects'. Properties depend on element or
5615 object type, but always include `:begin', `:end', `:parent' and
5616 `:post-blank'.
5618 As a special case, if point is right after an object and not at
5619 the beginning of any other object, return that object.
5621 Optional argument ELEMENT, when non-nil, is the closest element
5622 containing point, as returned by `org-element-at-point'.
5623 Providing it allows for quicker computation."
5624 (catch 'objects-forbidden
5625 (org-with-wide-buffer
5626 (let* ((pos (point))
5627 (element (or element (org-element-at-point)))
5628 (type (org-element-type element)))
5629 ;; If point is inside an element containing objects or
5630 ;; a secondary string, narrow buffer to the container and
5631 ;; proceed with parsing. Otherwise, return ELEMENT.
5632 (cond
5633 ;; At a parsed affiliated keyword, check if we're inside main
5634 ;; or dual value.
5635 ((let ((post (org-element-property :post-affiliated element)))
5636 (and post (< pos post)))
5637 (beginning-of-line)
5638 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5639 (cond
5640 ((not (member-ignore-case (match-string 1)
5641 org-element-parsed-keywords))
5642 (throw 'objects-forbidden element))
5643 ((< (match-end 0) pos)
5644 (narrow-to-region (match-end 0) (line-end-position)))
5645 ((and (match-beginning 2)
5646 (>= pos (match-beginning 2))
5647 (< pos (match-end 2)))
5648 (narrow-to-region (match-beginning 2) (match-end 2)))
5649 (t (throw 'objects-forbidden element)))
5650 ;; Also change type to retrieve correct restrictions.
5651 (setq type 'keyword))
5652 ;; At an item, objects can only be located within tag, if any.
5653 ((eq type 'item)
5654 (let ((tag (org-element-property :tag element)))
5655 (if (not tag) (throw 'objects-forbidden element)
5656 (beginning-of-line)
5657 (search-forward tag (line-end-position))
5658 (goto-char (match-beginning 0))
5659 (if (and (>= pos (point)) (< pos (match-end 0)))
5660 (narrow-to-region (point) (match-end 0))
5661 (throw 'objects-forbidden element)))))
5662 ;; At an headline or inlinetask, objects are in title.
5663 ((memq type '(headline inlinetask))
5664 (goto-char (org-element-property :begin element))
5665 (skip-chars-forward "*")
5666 (if (and (> pos (point)) (< pos (line-end-position)))
5667 (narrow-to-region (point) (line-end-position))
5668 (throw 'objects-forbidden element)))
5669 ;; At a paragraph, a table-row or a verse block, objects are
5670 ;; located within their contents.
5671 ((memq type '(paragraph table-row verse-block))
5672 (let ((cbeg (org-element-property :contents-begin element))
5673 (cend (org-element-property :contents-end element)))
5674 ;; CBEG is nil for table rules.
5675 (if (and cbeg cend (>= pos cbeg)
5676 (or (< pos cend) (and (= pos cend) (eobp))))
5677 (narrow-to-region cbeg cend)
5678 (throw 'objects-forbidden element))))
5679 ;; At a parsed keyword, objects are located within value.
5680 ((eq type 'keyword)
5681 (if (not (member (org-element-property :key element)
5682 org-element-document-properties))
5683 (throw 'objects-forbidden element)
5684 (beginning-of-line)
5685 (search-forward ":")
5686 (if (and (>= pos (point)) (< pos (line-end-position)))
5687 (narrow-to-region (point) (line-end-position))
5688 (throw 'objects-forbidden element))))
5689 ;; At a planning line, if point is at a timestamp, return it,
5690 ;; otherwise, return element.
5691 ((eq type 'planning)
5692 (dolist (p '(:closed :deadline :scheduled))
5693 (let ((timestamp (org-element-property p element)))
5694 (when (and timestamp
5695 (<= (org-element-property :begin timestamp) pos)
5696 (> (org-element-property :end timestamp) pos))
5697 (throw 'objects-forbidden timestamp))))
5698 ;; All other locations cannot contain objects: bail out.
5699 (throw 'objects-forbidden element))
5700 (t (throw 'objects-forbidden element)))
5701 (goto-char (point-min))
5702 (let ((restriction (org-element-restriction type))
5703 (parent element)
5704 (cache (cond ((not (org-element--cache-active-p)) nil)
5705 (org-element--cache-objects
5706 (gethash element org-element--cache-objects))
5707 (t (org-element-cache-reset) nil)))
5708 next object-data last)
5709 (prog1
5710 (catch 'exit
5711 (while t
5712 ;; When entering PARENT for the first time, get list
5713 ;; of objects within known so far. Store it in
5714 ;; OBJECT-DATA.
5715 (unless next
5716 (let ((data (assq parent cache)))
5717 (if data (setq object-data data)
5718 (push (setq object-data (list parent nil)) cache))))
5719 ;; Find NEXT object for analysis.
5720 (catch 'found
5721 ;; If NEXT is non-nil, we already exhausted the
5722 ;; cache so we can parse buffer to find the object
5723 ;; after it.
5724 (if next (setq next (org-element--object-lex restriction))
5725 ;; Otherwise, check if cache can help us.
5726 (let ((objects (cddr object-data))
5727 (completep (nth 1 object-data)))
5728 (cond
5729 ((and (not objects) completep) (throw 'exit parent))
5730 ((not objects)
5731 (setq next (org-element--object-lex restriction)))
5733 (let ((cache-limit
5734 (org-element-property :end (car objects))))
5735 (if (>= cache-limit pos)
5736 ;; Cache contains the information needed.
5737 (dolist (object objects (throw 'exit parent))
5738 (when (<= (org-element-property :begin object)
5739 pos)
5740 (if (>= (org-element-property :end object)
5741 pos)
5742 (throw 'found (setq next object))
5743 (throw 'exit parent))))
5744 (goto-char cache-limit)
5745 (setq next
5746 (org-element--object-lex restriction))))))))
5747 ;; If we have a new object to analyze, store it in
5748 ;; cache. Otherwise record that there is nothing
5749 ;; more to parse in this element at this depth.
5750 (if next
5751 (progn (org-element-put-property next :parent parent)
5752 (push next (cddr object-data)))
5753 (setcar (cdr object-data) t)))
5754 ;; Process NEXT, if any, in order to know if we need
5755 ;; to skip it, return it or move into it.
5756 (if (or (not next) (> (org-element-property :begin next) pos))
5757 (throw 'exit (or last parent))
5758 (let ((end (org-element-property :end next))
5759 (cbeg (org-element-property :contents-begin next))
5760 (cend (org-element-property :contents-end next)))
5761 (cond
5762 ;; Skip objects ending before point. Also skip
5763 ;; objects ending at point unless it is also the
5764 ;; end of buffer, since we want to return the
5765 ;; innermost object.
5766 ((and (<= end pos) (/= (point-max) end))
5767 (goto-char end)
5768 ;; For convenience, when object ends at POS,
5769 ;; without any space, store it in LAST, as we
5770 ;; will return it if no object starts here.
5771 (when (and (= end pos)
5772 (not (memq (char-before) '(?\s ?\t))))
5773 (setq last next)))
5774 ;; If POS is within a container object, move
5775 ;; into that object.
5776 ((and cbeg cend
5777 (>= pos cbeg)
5778 (or (< pos cend)
5779 ;; At contents' end, if there is no
5780 ;; space before point, also move into
5781 ;; object, for consistency with
5782 ;; convenience feature above.
5783 (and (= pos cend)
5784 (or (= (point-max) pos)
5785 (not (memq (char-before pos)
5786 '(?\s ?\t)))))))
5787 (goto-char cbeg)
5788 (narrow-to-region (point) cend)
5789 (setq parent next
5790 restriction (org-element-restriction next)
5791 next nil
5792 object-data nil))
5793 ;; Otherwise, return NEXT.
5794 (t (throw 'exit next)))))))
5795 ;; Store results in cache, if applicable.
5796 (org-element--cache-put element cache)))))))
5798 (defun org-element-nested-p (elem-A elem-B)
5799 "Non-nil when elements ELEM-A and ELEM-B are nested."
5800 (let ((beg-A (org-element-property :begin elem-A))
5801 (beg-B (org-element-property :begin elem-B))
5802 (end-A (org-element-property :end elem-A))
5803 (end-B (org-element-property :end elem-B)))
5804 (or (and (>= beg-A beg-B) (<= end-A end-B))
5805 (and (>= beg-B beg-A) (<= end-B end-A)))))
5807 (defun org-element-swap-A-B (elem-A elem-B)
5808 "Swap elements ELEM-A and ELEM-B.
5809 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5810 end of ELEM-A."
5811 (goto-char (org-element-property :begin elem-A))
5812 ;; There are two special cases when an element doesn't start at bol:
5813 ;; the first paragraph in an item or in a footnote definition.
5814 (let ((specialp (not (bolp))))
5815 ;; Only a paragraph without any affiliated keyword can be moved at
5816 ;; ELEM-A position in such a situation. Note that the case of
5817 ;; a footnote definition is impossible: it cannot contain two
5818 ;; paragraphs in a row because it cannot contain a blank line.
5819 (if (and specialp
5820 (or (not (eq (org-element-type elem-B) 'paragraph))
5821 (/= (org-element-property :begin elem-B)
5822 (org-element-property :contents-begin elem-B))))
5823 (error "Cannot swap elements"))
5824 ;; In a special situation, ELEM-A will have no indentation. We'll
5825 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5826 (let* ((ind-B (when specialp
5827 (goto-char (org-element-property :begin elem-B))
5828 (org-get-indentation)))
5829 (beg-A (org-element-property :begin elem-A))
5830 (end-A (save-excursion
5831 (goto-char (org-element-property :end elem-A))
5832 (skip-chars-backward " \r\t\n")
5833 (point-at-eol)))
5834 (beg-B (org-element-property :begin elem-B))
5835 (end-B (save-excursion
5836 (goto-char (org-element-property :end elem-B))
5837 (skip-chars-backward " \r\t\n")
5838 (point-at-eol)))
5839 ;; Store overlays responsible for visibility status. We
5840 ;; also need to store their boundaries as they will be
5841 ;; removed from buffer.
5842 (overlays
5843 (cons
5844 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5845 (overlays-in beg-A end-A))
5846 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5847 (overlays-in beg-B end-B))))
5848 ;; Get contents.
5849 (body-A (buffer-substring beg-A end-A))
5850 (body-B (delete-and-extract-region beg-B end-B)))
5851 (goto-char beg-B)
5852 (when specialp
5853 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5854 (org-indent-to-column ind-B))
5855 (insert body-A)
5856 ;; Restore ex ELEM-A overlays.
5857 (let ((offset (- beg-B beg-A)))
5858 (mapc (lambda (ov)
5859 (move-overlay
5860 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5861 (car overlays))
5862 (goto-char beg-A)
5863 (delete-region beg-A end-A)
5864 (insert body-B)
5865 ;; Restore ex ELEM-B overlays.
5866 (mapc (lambda (ov)
5867 (move-overlay
5868 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5869 (cdr overlays)))
5870 (goto-char (org-element-property :end elem-B)))))
5872 (defun org-element-remove-indentation (s &optional n)
5873 "Remove maximum common indentation in string S and return it.
5874 When optional argument N is a positive integer, remove exactly
5875 that much characters from indentation, if possible, or return
5876 S as-is otherwise. Unlike to `org-remove-indentation', this
5877 function doesn't call `untabify' on S."
5878 (catch 'exit
5879 (with-temp-buffer
5880 (insert s)
5881 (goto-char (point-min))
5882 ;; Find maximum common indentation, if not specified.
5883 (setq n (or n
5884 (let ((min-ind (point-max)))
5885 (save-excursion
5886 (while (re-search-forward "^[ \t]*\\S-" nil t)
5887 (let ((ind (1- (current-column))))
5888 (if (zerop ind) (throw 'exit s)
5889 (setq min-ind (min min-ind ind))))))
5890 min-ind)))
5891 (if (zerop n) s
5892 ;; Remove exactly N indentation, but give up if not possible.
5893 (while (not (eobp))
5894 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5895 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5896 ((< ind n) (throw 'exit s))
5897 (t (org-indent-line-to (- ind n))))
5898 (forward-line)))
5899 (buffer-string)))))
5903 (provide 'org-element)
5905 ;; Local variables:
5906 ;; generated-autoload-file: "org-loaddefs.el"
5907 ;; End:
5909 ;;; org-element.el ends here