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