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