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