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