Merge branch 'maint'
[org-mode.git] / lisp / org-element.el
blob7ffa7fca468b87a9ee785539d0cdd8bc00057b60
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 When RAW-SECONDARY-P is non-nil, headline's title will not be
793 parsed as a secondary string, but as a plain string instead.
795 Assume point is at beginning of the headline."
796 (save-excursion
797 (let* ((components (org-heading-components))
798 (level (nth 1 components))
799 (todo (nth 2 components))
800 (todo-type
801 (and todo (if (member todo org-done-keywords) 'done 'todo)))
802 (tags (let ((raw-tags (nth 5 components)))
803 (and raw-tags (org-split-string raw-tags ":"))))
804 (raw-value (or (nth 4 components) ""))
805 (commentedp
806 (let ((case-fold-search nil))
807 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
808 raw-value)))
809 (archivedp (member org-archive-tag tags))
810 (footnote-section-p (and org-footnote-section
811 (string= org-footnote-section raw-value)))
812 ;; Upcase property names. It avoids confusion between
813 ;; properties obtained through property drawer and default
814 ;; properties from the parser (e.g. `:end' and :END:)
815 (standard-props
816 (let (plist)
817 (mapc
818 (lambda (p)
819 (setq plist
820 (plist-put plist
821 (intern (concat ":" (upcase (car p))))
822 (cdr p))))
823 (org-entry-properties nil 'standard))
824 plist))
825 (time-props
826 ;; Read time properties on the line below the headline.
827 (save-excursion
828 (when (progn (forward-line)
829 (looking-at org-planning-or-clock-line-re))
830 (let ((end (line-end-position)) plist)
831 (while (re-search-forward
832 org-keyword-time-not-clock-regexp end t)
833 (goto-char (match-end 1))
834 (skip-chars-forward " \t")
835 (let ((keyword (match-string 1))
836 (time (org-element-timestamp-parser)))
837 (cond ((equal keyword org-scheduled-string)
838 (setq plist (plist-put plist :scheduled time)))
839 ((equal keyword org-deadline-string)
840 (setq plist (plist-put plist :deadline time)))
841 (t (setq plist (plist-put plist :closed time))))))
842 plist))))
843 (begin (point))
844 (end (save-excursion (goto-char (org-end-of-subtree t t))))
845 (pos-after-head (progn (forward-line) (point)))
846 (contents-begin (save-excursion
847 (skip-chars-forward " \r\t\n" end)
848 (and (/= (point) end) (line-beginning-position))))
849 (contents-end (and contents-begin
850 (progn (goto-char end)
851 (skip-chars-backward " \r\t\n")
852 (forward-line)
853 (point)))))
854 ;; Clean RAW-VALUE from any comment string.
855 (when commentedp
856 (let ((case-fold-search nil))
857 (setq raw-value
858 (replace-regexp-in-string
859 (concat (regexp-quote org-comment-string) "\\(?: \\|$\\)")
861 raw-value))))
862 ;; Clean TAGS from archive tag, if any.
863 (when archivedp (setq tags (delete org-archive-tag tags)))
864 (let ((headline
865 (list 'headline
866 (nconc
867 (list :raw-value raw-value
868 :begin begin
869 :end end
870 :pre-blank
871 (if (not contents-begin) 0
872 (count-lines pos-after-head contents-begin))
873 :contents-begin contents-begin
874 :contents-end contents-end
875 :level level
876 :priority (nth 3 components)
877 :tags tags
878 :todo-keyword todo
879 :todo-type todo-type
880 :post-blank (count-lines
881 (if (not contents-end) pos-after-head
882 (goto-char contents-end)
883 (forward-line)
884 (point))
885 end)
886 :footnote-section-p footnote-section-p
887 :archivedp archivedp
888 :commentedp commentedp)
889 time-props
890 standard-props))))
891 (let ((alt-title (org-element-property :ALT_TITLE headline)))
892 (when alt-title
893 (org-element-put-property
894 headline :alt-title
895 (if raw-secondary-p alt-title
896 (org-element-parse-secondary-string
897 alt-title (org-element-restriction 'headline) headline)))))
898 (org-element-put-property
899 headline :title
900 (if raw-secondary-p raw-value
901 (org-element-parse-secondary-string
902 raw-value (org-element-restriction 'headline) headline)))))))
904 (defun org-element-headline-interpreter (headline contents)
905 "Interpret HEADLINE element as Org syntax.
906 CONTENTS is the contents of the element."
907 (let* ((level (org-element-property :level headline))
908 (todo (org-element-property :todo-keyword headline))
909 (priority (org-element-property :priority headline))
910 (title (org-element-interpret-data
911 (org-element-property :title headline)))
912 (tags (let ((tag-list (if (org-element-property :archivedp headline)
913 (cons org-archive-tag
914 (org-element-property :tags headline))
915 (org-element-property :tags headline))))
916 (and tag-list
917 (format ":%s:" (mapconcat 'identity tag-list ":")))))
918 (commentedp (org-element-property :commentedp headline))
919 (pre-blank (or (org-element-property :pre-blank headline) 0))
920 (heading (concat (make-string (org-reduced-level level) ?*)
921 (and todo (concat " " todo))
922 (and commentedp (concat " " org-comment-string))
923 (and priority
924 (format " [#%s]" (char-to-string priority)))
925 (cond ((and org-footnote-section
926 (org-element-property
927 :footnote-section-p headline))
928 (concat " " org-footnote-section))
929 (title (concat " " title))))))
930 (concat heading
931 ;; Align tags.
932 (when tags
933 (cond
934 ((zerop org-tags-column) (format " %s" tags))
935 ((< org-tags-column 0)
936 (concat
937 (make-string
938 (max (- (+ org-tags-column (length heading) (length tags))) 1)
940 tags))
942 (concat
943 (make-string (max (- org-tags-column (length heading)) 1) ? )
944 tags))))
945 (make-string (1+ pre-blank) 10)
946 contents)))
949 ;;;; Inlinetask
951 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
952 "Parse an inline task.
954 Return a list whose CAR is `inlinetask' and CDR is a plist
955 containing `:title', `:begin', `:end', `:contents-begin' and
956 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
957 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
958 `:closed' and `:post-blank' keywords.
960 The plist also contains any property set in the property drawer,
961 with its name in upper cases and colons added at the
962 beginning (e.g., `:CUSTOM_ID').
964 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
965 title will not be parsed as a secondary string, but as a plain
966 string instead.
968 Assume point is at beginning of the inline task."
969 (save-excursion
970 (let* ((begin (point))
971 (components (org-heading-components))
972 (todo (nth 2 components))
973 (todo-type (and todo
974 (if (member todo org-done-keywords) 'done 'todo)))
975 (tags (let ((raw-tags (nth 5 components)))
976 (and raw-tags (org-split-string raw-tags ":"))))
977 (raw-value (or (nth 4 components) ""))
978 ;; Upcase property names. It avoids confusion between
979 ;; properties obtained through property drawer and default
980 ;; properties from the parser (e.g. `:end' and :END:)
981 (standard-props
982 (let (plist)
983 (mapc
984 (lambda (p)
985 (setq plist
986 (plist-put plist
987 (intern (concat ":" (upcase (car p))))
988 (cdr p))))
989 (org-entry-properties nil 'standard))
990 plist))
991 (time-props
992 ;; Read time properties on the line below the inlinetask
993 ;; opening string.
994 (save-excursion
995 (when (progn (forward-line)
996 (looking-at org-planning-or-clock-line-re))
997 (let ((end (line-end-position)) plist)
998 (while (re-search-forward
999 org-keyword-time-not-clock-regexp end t)
1000 (goto-char (match-end 1))
1001 (skip-chars-forward " \t")
1002 (let ((keyword (match-string 1))
1003 (time (org-element-timestamp-parser)))
1004 (cond ((equal keyword org-scheduled-string)
1005 (setq plist (plist-put plist :scheduled time)))
1006 ((equal keyword org-deadline-string)
1007 (setq plist (plist-put plist :deadline time)))
1008 (t (setq plist (plist-put plist :closed time))))))
1009 plist))))
1010 (task-end (save-excursion
1011 (end-of-line)
1012 (and (re-search-forward org-outline-regexp-bol limit t)
1013 (org-looking-at-p "END[ \t]*$")
1014 (line-beginning-position))))
1015 (contents-begin (progn (forward-line)
1016 (and task-end (< (point) task-end) (point))))
1017 (contents-end (and contents-begin task-end))
1018 (before-blank (if (not task-end) (point)
1019 (goto-char task-end)
1020 (forward-line)
1021 (point)))
1022 (end (progn (skip-chars-forward " \r\t\n" limit)
1023 (if (eobp) (point) (line-beginning-position))))
1024 (inlinetask
1025 (list 'inlinetask
1026 (nconc
1027 (list :raw-value raw-value
1028 :begin begin
1029 :end end
1030 :contents-begin contents-begin
1031 :contents-end contents-end
1032 :level (nth 1 components)
1033 :priority (nth 3 components)
1034 :tags tags
1035 :todo-keyword todo
1036 :todo-type todo-type
1037 :post-blank (count-lines before-blank end))
1038 time-props
1039 standard-props))))
1040 (org-element-put-property
1041 inlinetask :title
1042 (if raw-secondary-p raw-value
1043 (org-element-parse-secondary-string
1044 raw-value
1045 (org-element-restriction 'inlinetask)
1046 inlinetask))))))
1048 (defun org-element-inlinetask-interpreter (inlinetask contents)
1049 "Interpret INLINETASK element as Org syntax.
1050 CONTENTS is the contents of inlinetask."
1051 (let* ((level (org-element-property :level inlinetask))
1052 (todo (org-element-property :todo-keyword inlinetask))
1053 (priority (org-element-property :priority inlinetask))
1054 (title (org-element-interpret-data
1055 (org-element-property :title inlinetask)))
1056 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1057 (and tag-list
1058 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1059 (task (concat (make-string level ?*)
1060 (and todo (concat " " todo))
1061 (and priority
1062 (format " [#%s]" (char-to-string priority)))
1063 (and title (concat " " title)))))
1064 (concat task
1065 ;; Align tags.
1066 (when tags
1067 (cond
1068 ((zerop org-tags-column) (format " %s" tags))
1069 ((< org-tags-column 0)
1070 (concat
1071 (make-string
1072 (max (- (+ org-tags-column (length task) (length tags))) 1)
1074 tags))
1076 (concat
1077 (make-string (max (- org-tags-column (length task)) 1) ? )
1078 tags))))
1079 ;; Prefer degenerate inlinetasks when there are no
1080 ;; contents.
1081 (when contents
1082 (concat "\n"
1083 contents
1084 (make-string level ?*) " END")))))
1087 ;;;; Item
1089 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1090 "Parse an item.
1092 STRUCT is the structure of the plain list.
1094 Return a list whose CAR is `item' and CDR is a plist containing
1095 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1096 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1097 keywords.
1099 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1100 any, will not be parsed as a secondary string, but as a plain
1101 string instead.
1103 Assume point is at the beginning of the item."
1104 (save-excursion
1105 (beginning-of-line)
1106 (looking-at org-list-full-item-re)
1107 (let* ((begin (point))
1108 (bullet (org-match-string-no-properties 1))
1109 (checkbox (let ((box (org-match-string-no-properties 3)))
1110 (cond ((equal "[ ]" box) 'off)
1111 ((equal "[X]" box) 'on)
1112 ((equal "[-]" box) 'trans))))
1113 (counter (let ((c (org-match-string-no-properties 2)))
1114 (save-match-data
1115 (cond
1116 ((not c) nil)
1117 ((string-match "[A-Za-z]" c)
1118 (- (string-to-char (upcase (match-string 0 c)))
1119 64))
1120 ((string-match "[0-9]+" c)
1121 (string-to-number (match-string 0 c)))))))
1122 (end (progn (goto-char (nth 6 (assq (point) struct)))
1123 (unless (bolp) (forward-line))
1124 (point)))
1125 (contents-begin
1126 (progn (goto-char
1127 ;; Ignore tags in un-ordered lists: they are just
1128 ;; a part of item's body.
1129 (if (and (match-beginning 4)
1130 (save-match-data (string-match "[.)]" bullet)))
1131 (match-beginning 4)
1132 (match-end 0)))
1133 (skip-chars-forward " \r\t\n" limit)
1134 ;; If first line isn't empty, contents really start
1135 ;; at the text after item's meta-data.
1136 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1137 (contents-end (progn (goto-char end)
1138 (skip-chars-backward " \r\t\n")
1139 (forward-line)
1140 (point)))
1141 (item
1142 (list 'item
1143 (list :bullet bullet
1144 :begin begin
1145 :end end
1146 ;; CONTENTS-BEGIN and CONTENTS-END may be
1147 ;; mixed up in the case of an empty item
1148 ;; separated from the next by a blank line.
1149 ;; Thus ensure the former is always the
1150 ;; smallest.
1151 :contents-begin (min contents-begin contents-end)
1152 :contents-end (max contents-begin contents-end)
1153 :checkbox checkbox
1154 :counter counter
1155 :structure struct
1156 :post-blank (count-lines contents-end end)))))
1157 (org-element-put-property
1158 item :tag
1159 (let ((raw-tag (org-list-get-tag begin struct)))
1160 (and raw-tag
1161 (if raw-secondary-p raw-tag
1162 (org-element-parse-secondary-string
1163 raw-tag (org-element-restriction 'item) item))))))))
1165 (defun org-element-item-interpreter (item contents)
1166 "Interpret ITEM element as Org syntax.
1167 CONTENTS is the contents of the element."
1168 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1169 (org-list-bullet-string
1170 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1171 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1172 (t "1.")))))
1173 (checkbox (org-element-property :checkbox item))
1174 (counter (org-element-property :counter item))
1175 (tag (let ((tag (org-element-property :tag item)))
1176 (and tag (org-element-interpret-data tag))))
1177 ;; Compute indentation.
1178 (ind (make-string (length bullet) 32))
1179 (item-starts-with-par-p
1180 (eq (org-element-type (car (org-element-contents item)))
1181 'paragraph)))
1182 ;; Indent contents.
1183 (concat
1184 bullet
1185 (and counter (format "[@%d] " counter))
1186 (case checkbox
1187 (on "[X] ")
1188 (off "[ ] ")
1189 (trans "[-] "))
1190 (and tag (format "%s :: " tag))
1191 (when contents
1192 (let ((contents (replace-regexp-in-string
1193 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1194 (if item-starts-with-par-p (org-trim contents)
1195 (concat "\n" contents)))))))
1198 ;;;; Plain List
1200 (defun org-element--list-struct (limit)
1201 ;; Return structure of list at point. Internal function. See
1202 ;; `org-list-struct' for details.
1203 (let ((case-fold-search t)
1204 (top-ind limit)
1205 (item-re (org-item-re))
1206 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1207 items struct)
1208 (save-excursion
1209 (catch 'exit
1210 (while t
1211 (cond
1212 ;; At limit: end all items.
1213 ((>= (point) limit)
1214 (throw 'exit
1215 (let ((end (progn (skip-chars-backward " \r\t\n")
1216 (forward-line)
1217 (point))))
1218 (dolist (item items (sort (nconc items struct)
1219 'car-less-than-car))
1220 (setcar (nthcdr 6 item) end)))))
1221 ;; At list end: end all items.
1222 ((looking-at org-list-end-re)
1223 (throw 'exit (dolist (item items (sort (nconc items struct)
1224 'car-less-than-car))
1225 (setcar (nthcdr 6 item) (point)))))
1226 ;; At a new item: end previous sibling.
1227 ((looking-at item-re)
1228 (let ((ind (save-excursion (skip-chars-forward " \t")
1229 (current-column))))
1230 (setq top-ind (min top-ind ind))
1231 (while (and items (<= ind (nth 1 (car items))))
1232 (let ((item (pop items)))
1233 (setcar (nthcdr 6 item) (point))
1234 (push item struct)))
1235 (push (progn (looking-at org-list-full-item-re)
1236 (let ((bullet (match-string-no-properties 1)))
1237 (list (point)
1239 bullet
1240 (match-string-no-properties 2) ; counter
1241 (match-string-no-properties 3) ; checkbox
1242 ;; Description tag.
1243 (and (save-match-data
1244 (string-match "[-+*]" bullet))
1245 (match-string-no-properties 4))
1246 ;; Ending position, unknown so far.
1247 nil)))
1248 items))
1249 (forward-line 1))
1250 ;; Skip empty lines.
1251 ((looking-at "^[ \t]*$") (forward-line))
1252 ;; Skip inline tasks and blank lines along the way.
1253 ((and inlinetask-re (looking-at inlinetask-re))
1254 (forward-line)
1255 (let ((origin (point)))
1256 (when (re-search-forward inlinetask-re limit t)
1257 (if (org-looking-at-p "END[ \t]*$") (forward-line)
1258 (goto-char origin)))))
1259 ;; At some text line. Check if it ends any previous item.
1261 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1262 (when (<= ind top-ind)
1263 (skip-chars-backward " \r\t\n")
1264 (forward-line))
1265 (while (<= ind (nth 1 (car items)))
1266 (let ((item (pop items)))
1267 (setcar (nthcdr 6 item) (line-beginning-position))
1268 (push item struct)
1269 (unless items
1270 (throw 'exit (sort struct 'car-less-than-car))))))
1271 ;; Skip blocks (any type) and drawers contents.
1272 (cond
1273 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1274 (re-search-forward
1275 (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
1276 limit t)))
1277 ((and (looking-at org-drawer-regexp)
1278 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1279 (forward-line))))))))
1281 (defun org-element-plain-list-parser (limit affiliated structure)
1282 "Parse a plain list.
1284 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1285 the buffer position at the beginning of the first affiliated
1286 keyword and CDR is a plist of affiliated keywords along with
1287 their value. STRUCTURE is the structure of the plain list being
1288 parsed.
1290 Return a list whose CAR is `plain-list' and CDR is a plist
1291 containing `:type', `:begin', `:end', `:contents-begin' and
1292 `:contents-end', `:structure', `:post-blank' and
1293 `:post-affiliated' keywords.
1295 Assume point is at the beginning of the list."
1296 (save-excursion
1297 (let* ((struct (or structure (org-element--list-struct limit)))
1298 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1299 ((nth 5 (assq (point) struct)) 'descriptive)
1300 (t 'unordered)))
1301 (contents-begin (point))
1302 (begin (car affiliated))
1303 (contents-end (let* ((item (assq contents-begin struct))
1304 (ind (nth 1 item))
1305 (pos (nth 6 item)))
1306 (while (and (setq item (assq pos struct))
1307 (= (nth 1 item) ind))
1308 (setq pos (nth 6 item)))
1309 pos))
1310 (end (progn (goto-char contents-end)
1311 (skip-chars-forward " \r\t\n" limit)
1312 (if (= (point) limit) limit (line-beginning-position)))))
1313 ;; Return value.
1314 (list 'plain-list
1315 (nconc
1316 (list :type type
1317 :begin begin
1318 :end end
1319 :contents-begin contents-begin
1320 :contents-end contents-end
1321 :structure struct
1322 :post-blank (count-lines contents-end end)
1323 :post-affiliated contents-begin)
1324 (cdr affiliated))))))
1326 (defun org-element-plain-list-interpreter (plain-list contents)
1327 "Interpret PLAIN-LIST element as Org syntax.
1328 CONTENTS is the contents of the element."
1329 (with-temp-buffer
1330 (insert contents)
1331 (goto-char (point-min))
1332 (org-list-repair)
1333 (buffer-string)))
1336 ;;;; Property Drawer
1338 (defun org-element-property-drawer-parser (limit affiliated)
1339 "Parse a property drawer.
1341 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1342 the buffer position at the beginning of the first affiliated
1343 keyword and CDR is a plist of affiliated keywords along with
1344 their value.
1346 Return a list whose CAR is `property-drawer' and CDR is a plist
1347 containing `:begin', `:end', `:contents-begin', `:contents-end',
1348 `:post-blank' and `:post-affiliated' keywords.
1350 Assume point is at the beginning of the property drawer."
1351 (save-excursion
1352 (let ((case-fold-search t))
1353 (if (not (save-excursion
1354 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1355 ;; Incomplete drawer: parse it as a paragraph.
1356 (org-element-paragraph-parser limit affiliated)
1357 (save-excursion
1358 (let* ((drawer-end-line (match-beginning 0))
1359 (begin (car affiliated))
1360 (post-affiliated (point))
1361 (contents-begin (progn (forward-line)
1362 (and (< (point) drawer-end-line)
1363 (point))))
1364 (contents-end (and contents-begin drawer-end-line))
1365 (pos-before-blank (progn (goto-char drawer-end-line)
1366 (forward-line)
1367 (point)))
1368 (end (progn (skip-chars-forward " \r\t\n" limit)
1369 (if (eobp) (point) (line-beginning-position)))))
1370 (list 'property-drawer
1371 (nconc
1372 (list :begin begin
1373 :end end
1374 :contents-begin contents-begin
1375 :contents-end contents-end
1376 :post-blank (count-lines pos-before-blank end)
1377 :post-affiliated post-affiliated)
1378 (cdr affiliated)))))))))
1380 (defun org-element-property-drawer-interpreter (property-drawer contents)
1381 "Interpret PROPERTY-DRAWER element as Org syntax.
1382 CONTENTS is the properties within the drawer."
1383 (format ":PROPERTIES:\n%s:END:" contents))
1386 ;;;; Quote Block
1388 (defun org-element-quote-block-parser (limit affiliated)
1389 "Parse a quote block.
1391 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1392 the buffer position at the beginning of the first affiliated
1393 keyword and CDR is a plist of affiliated keywords along with
1394 their value.
1396 Return a list whose CAR is `quote-block' and CDR is a plist
1397 containing `:begin', `:end', `:contents-begin', `:contents-end',
1398 `:post-blank' and `:post-affiliated' keywords.
1400 Assume point is at the beginning of the block."
1401 (let ((case-fold-search t))
1402 (if (not (save-excursion
1403 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1404 ;; Incomplete block: parse it as a paragraph.
1405 (org-element-paragraph-parser limit affiliated)
1406 (let ((block-end-line (match-beginning 0)))
1407 (save-excursion
1408 (let* ((begin (car affiliated))
1409 (post-affiliated (point))
1410 ;; Empty blocks have no contents.
1411 (contents-begin (progn (forward-line)
1412 (and (< (point) block-end-line)
1413 (point))))
1414 (contents-end (and contents-begin block-end-line))
1415 (pos-before-blank (progn (goto-char block-end-line)
1416 (forward-line)
1417 (point)))
1418 (end (progn (skip-chars-forward " \r\t\n" limit)
1419 (if (eobp) (point) (line-beginning-position)))))
1420 (list 'quote-block
1421 (nconc
1422 (list :begin begin
1423 :end end
1424 :contents-begin contents-begin
1425 :contents-end contents-end
1426 :post-blank (count-lines pos-before-blank end)
1427 :post-affiliated post-affiliated)
1428 (cdr affiliated)))))))))
1430 (defun org-element-quote-block-interpreter (quote-block contents)
1431 "Interpret QUOTE-BLOCK element as Org syntax.
1432 CONTENTS is the contents of the element."
1433 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1436 ;;;; Section
1438 (defun org-element-section-parser (limit)
1439 "Parse a section.
1441 LIMIT bounds the search.
1443 Return a list whose CAR is `section' and CDR is a plist
1444 containing `:begin', `:end', `:contents-begin', `contents-end'
1445 and `:post-blank' keywords."
1446 (save-excursion
1447 ;; Beginning of section is the beginning of the first non-blank
1448 ;; line after previous headline.
1449 (let ((begin (point))
1450 (end (progn (org-with-limited-levels (outline-next-heading))
1451 (point)))
1452 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1453 (forward-line)
1454 (point))))
1455 (list 'section
1456 (list :begin begin
1457 :end end
1458 :contents-begin begin
1459 :contents-end pos-before-blank
1460 :post-blank (count-lines pos-before-blank end))))))
1462 (defun org-element-section-interpreter (section contents)
1463 "Interpret SECTION element as Org syntax.
1464 CONTENTS is the contents of the element."
1465 contents)
1468 ;;;; Special Block
1470 (defun org-element-special-block-parser (limit affiliated)
1471 "Parse a special block.
1473 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1474 the buffer position at the beginning of the first affiliated
1475 keyword and CDR is a plist of affiliated keywords along with
1476 their value.
1478 Return a list whose CAR is `special-block' and CDR is a plist
1479 containing `:type', `:begin', `:end', `:contents-begin',
1480 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1482 Assume point is at the beginning of the block."
1483 (let* ((case-fold-search t)
1484 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1485 (upcase (match-string-no-properties 1)))))
1486 (if (not (save-excursion
1487 (re-search-forward
1488 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1489 limit t)))
1490 ;; Incomplete block: parse it as a paragraph.
1491 (org-element-paragraph-parser limit affiliated)
1492 (let ((block-end-line (match-beginning 0)))
1493 (save-excursion
1494 (let* ((begin (car affiliated))
1495 (post-affiliated (point))
1496 ;; Empty blocks have no contents.
1497 (contents-begin (progn (forward-line)
1498 (and (< (point) block-end-line)
1499 (point))))
1500 (contents-end (and contents-begin block-end-line))
1501 (pos-before-blank (progn (goto-char block-end-line)
1502 (forward-line)
1503 (point)))
1504 (end (progn (skip-chars-forward " \r\t\n" limit)
1505 (if (eobp) (point) (line-beginning-position)))))
1506 (list 'special-block
1507 (nconc
1508 (list :type type
1509 :begin begin
1510 :end end
1511 :contents-begin contents-begin
1512 :contents-end contents-end
1513 :post-blank (count-lines pos-before-blank end)
1514 :post-affiliated post-affiliated)
1515 (cdr affiliated)))))))))
1517 (defun org-element-special-block-interpreter (special-block contents)
1518 "Interpret SPECIAL-BLOCK element as Org syntax.
1519 CONTENTS is the contents of the element."
1520 (let ((block-type (org-element-property :type special-block)))
1521 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1525 ;;; Elements
1527 ;; For each element, a parser and an interpreter are also defined.
1528 ;; Both follow the same naming convention used for greater elements.
1530 ;; Also, as for greater elements, adding a new element type is done
1531 ;; through the following steps: implement a parser and an interpreter,
1532 ;; tweak `org-element--current-element' so that it recognizes the new
1533 ;; type and add that new type to `org-element-all-elements'.
1535 ;; As a special case, when the newly defined type is a block type,
1536 ;; `org-element-block-name-alist' has to be modified accordingly.
1539 ;;;; Babel Call
1541 (defun org-element-babel-call-parser (limit affiliated)
1542 "Parse a babel call.
1544 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1545 the buffer position at the beginning of the first affiliated
1546 keyword and CDR is a plist of affiliated keywords along with
1547 their value.
1549 Return a list whose CAR is `babel-call' and CDR is a plist
1550 containing `:begin', `:end', `:value', `:post-blank' and
1551 `:post-affiliated' as keywords."
1552 (save-excursion
1553 (let ((begin (car affiliated))
1554 (post-affiliated (point))
1555 (value (progn (let ((case-fold-search t))
1556 (re-search-forward "call:[ \t]*" nil t))
1557 (buffer-substring-no-properties (point)
1558 (line-end-position))))
1559 (pos-before-blank (progn (forward-line) (point)))
1560 (end (progn (skip-chars-forward " \r\t\n" limit)
1561 (if (eobp) (point) (line-beginning-position)))))
1562 (list 'babel-call
1563 (nconc
1564 (list :begin begin
1565 :end end
1566 :value value
1567 :post-blank (count-lines pos-before-blank end)
1568 :post-affiliated post-affiliated)
1569 (cdr affiliated))))))
1571 (defun org-element-babel-call-interpreter (babel-call contents)
1572 "Interpret BABEL-CALL element as Org syntax.
1573 CONTENTS is nil."
1574 (concat "#+CALL: " (org-element-property :value babel-call)))
1577 ;;;; Clock
1579 (defun org-element-clock-parser (limit)
1580 "Parse a clock.
1582 LIMIT bounds the search.
1584 Return a list whose CAR is `clock' and CDR is a plist containing
1585 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1586 as keywords."
1587 (save-excursion
1588 (let* ((case-fold-search nil)
1589 (begin (point))
1590 (value (progn (search-forward org-clock-string (line-end-position) t)
1591 (skip-chars-forward " \t")
1592 (org-element-timestamp-parser)))
1593 (duration (and (search-forward " => " (line-end-position) t)
1594 (progn (skip-chars-forward " \t")
1595 (looking-at "\\(\\S-+\\)[ \t]*$"))
1596 (org-match-string-no-properties 1)))
1597 (status (if duration 'closed 'running))
1598 (post-blank (let ((before-blank (progn (forward-line) (point))))
1599 (skip-chars-forward " \r\t\n" limit)
1600 (skip-chars-backward " \t")
1601 (unless (bolp) (end-of-line))
1602 (count-lines before-blank (point))))
1603 (end (point)))
1604 (list 'clock
1605 (list :status status
1606 :value value
1607 :duration duration
1608 :begin begin
1609 :end end
1610 :post-blank post-blank)))))
1612 (defun org-element-clock-interpreter (clock contents)
1613 "Interpret CLOCK element as Org syntax.
1614 CONTENTS is nil."
1615 (concat org-clock-string " "
1616 (org-element-timestamp-interpreter
1617 (org-element-property :value clock) nil)
1618 (let ((duration (org-element-property :duration clock)))
1619 (and duration
1620 (concat " => "
1621 (apply 'format
1622 "%2s:%02s"
1623 (org-split-string duration ":")))))))
1626 ;;;; Comment
1628 (defun org-element-comment-parser (limit affiliated)
1629 "Parse a comment.
1631 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1632 the buffer position at the beginning of the first affiliated
1633 keyword and CDR is a plist of affiliated keywords along with
1634 their value.
1636 Return a list whose CAR is `comment' and CDR is a plist
1637 containing `:begin', `:end', `:value', `:post-blank',
1638 `:post-affiliated' keywords.
1640 Assume point is at comment beginning."
1641 (save-excursion
1642 (let* ((begin (car affiliated))
1643 (post-affiliated (point))
1644 (value (prog2 (looking-at "[ \t]*# ?")
1645 (buffer-substring-no-properties
1646 (match-end 0) (line-end-position))
1647 (forward-line)))
1648 (com-end
1649 ;; Get comments ending.
1650 (progn
1651 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1652 ;; Accumulate lines without leading hash and first
1653 ;; whitespace.
1654 (setq value
1655 (concat value
1656 "\n"
1657 (buffer-substring-no-properties
1658 (match-end 0) (line-end-position))))
1659 (forward-line))
1660 (point)))
1661 (end (progn (goto-char com-end)
1662 (skip-chars-forward " \r\t\n" limit)
1663 (if (eobp) (point) (line-beginning-position)))))
1664 (list 'comment
1665 (nconc
1666 (list :begin begin
1667 :end end
1668 :value value
1669 :post-blank (count-lines com-end end)
1670 :post-affiliated post-affiliated)
1671 (cdr affiliated))))))
1673 (defun org-element-comment-interpreter (comment contents)
1674 "Interpret COMMENT element as Org syntax.
1675 CONTENTS is nil."
1676 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1679 ;;;; Comment Block
1681 (defun org-element-comment-block-parser (limit affiliated)
1682 "Parse an export block.
1684 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1685 the buffer position at the beginning of the first affiliated
1686 keyword and CDR is a plist of affiliated keywords along with
1687 their value.
1689 Return a list whose CAR is `comment-block' and CDR is a plist
1690 containing `:begin', `:end', `:value', `:post-blank' and
1691 `:post-affiliated' keywords.
1693 Assume point is at comment block beginning."
1694 (let ((case-fold-search t))
1695 (if (not (save-excursion
1696 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1697 ;; Incomplete block: parse it as a paragraph.
1698 (org-element-paragraph-parser limit affiliated)
1699 (let ((contents-end (match-beginning 0)))
1700 (save-excursion
1701 (let* ((begin (car affiliated))
1702 (post-affiliated (point))
1703 (contents-begin (progn (forward-line) (point)))
1704 (pos-before-blank (progn (goto-char contents-end)
1705 (forward-line)
1706 (point)))
1707 (end (progn (skip-chars-forward " \r\t\n" limit)
1708 (if (eobp) (point) (line-beginning-position))))
1709 (value (buffer-substring-no-properties
1710 contents-begin contents-end)))
1711 (list 'comment-block
1712 (nconc
1713 (list :begin begin
1714 :end end
1715 :value value
1716 :post-blank (count-lines pos-before-blank end)
1717 :post-affiliated post-affiliated)
1718 (cdr affiliated)))))))))
1720 (defun org-element-comment-block-interpreter (comment-block contents)
1721 "Interpret COMMENT-BLOCK element as Org syntax.
1722 CONTENTS is nil."
1723 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1724 (org-remove-indentation (org-element-property :value comment-block))))
1727 ;;;; Diary Sexp
1729 (defun org-element-diary-sexp-parser (limit affiliated)
1730 "Parse a diary sexp.
1732 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1733 the buffer position at the beginning of the first affiliated
1734 keyword and CDR is a plist of affiliated keywords along with
1735 their value.
1737 Return a list whose CAR is `diary-sexp' and CDR is a plist
1738 containing `:begin', `:end', `:value', `:post-blank' and
1739 `:post-affiliated' keywords."
1740 (save-excursion
1741 (let ((begin (car affiliated))
1742 (post-affiliated (point))
1743 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1744 (org-match-string-no-properties 1)))
1745 (pos-before-blank (progn (forward-line) (point)))
1746 (end (progn (skip-chars-forward " \r\t\n" limit)
1747 (if (eobp) (point) (line-beginning-position)))))
1748 (list 'diary-sexp
1749 (nconc
1750 (list :value value
1751 :begin begin
1752 :end end
1753 :post-blank (count-lines pos-before-blank end)
1754 :post-affiliated post-affiliated)
1755 (cdr affiliated))))))
1757 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1758 "Interpret DIARY-SEXP as Org syntax.
1759 CONTENTS is nil."
1760 (org-element-property :value diary-sexp))
1763 ;;;; Example Block
1765 (defun org-element-example-block-parser (limit affiliated)
1766 "Parse an example block.
1768 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1769 the buffer position at the beginning of the first affiliated
1770 keyword and CDR is a plist of affiliated keywords along with
1771 their value.
1773 Return a list whose CAR is `example-block' and CDR is a plist
1774 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1775 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1776 `:value', `:post-blank' and `:post-affiliated' keywords."
1777 (let ((case-fold-search t))
1778 (if (not (save-excursion
1779 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1780 ;; Incomplete block: parse it as a paragraph.
1781 (org-element-paragraph-parser limit affiliated)
1782 (let ((contents-end (match-beginning 0)))
1783 (save-excursion
1784 (let* ((switches
1785 (progn
1786 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1787 (org-match-string-no-properties 1)))
1788 ;; Switches analysis
1789 (number-lines
1790 (cond ((not switches) nil)
1791 ((string-match "-n\\>" switches) 'new)
1792 ((string-match "+n\\>" switches) 'continued)))
1793 (preserve-indent
1794 (and switches (string-match "-i\\>" switches)))
1795 ;; Should labels be retained in (or stripped from) example
1796 ;; blocks?
1797 (retain-labels
1798 (or (not switches)
1799 (not (string-match "-r\\>" switches))
1800 (and number-lines (string-match "-k\\>" switches))))
1801 ;; What should code-references use - labels or
1802 ;; line-numbers?
1803 (use-labels
1804 (or (not switches)
1805 (and retain-labels
1806 (not (string-match "-k\\>" switches)))))
1807 (label-fmt
1808 (and switches
1809 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1810 (match-string 1 switches)))
1811 ;; Standard block parsing.
1812 (begin (car affiliated))
1813 (post-affiliated (point))
1814 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1815 (contents-begin (progn (forward-line) (point)))
1816 (value (org-element-remove-indentation
1817 (org-unescape-code-in-string
1818 (buffer-substring-no-properties
1819 contents-begin contents-end))
1820 block-ind))
1821 (pos-before-blank (progn (goto-char contents-end)
1822 (forward-line)
1823 (point)))
1824 (end (progn (skip-chars-forward " \r\t\n" limit)
1825 (if (eobp) (point) (line-beginning-position)))))
1826 (list 'example-block
1827 (nconc
1828 (list :begin begin
1829 :end end
1830 :value value
1831 :switches switches
1832 :number-lines number-lines
1833 :preserve-indent preserve-indent
1834 :retain-labels retain-labels
1835 :use-labels use-labels
1836 :label-fmt label-fmt
1837 :post-blank (count-lines pos-before-blank end)
1838 :post-affiliated post-affiliated)
1839 (cdr affiliated)))))))))
1841 (defun org-element-example-block-interpreter (example-block contents)
1842 "Interpret EXAMPLE-BLOCK element as Org syntax.
1843 CONTENTS is nil."
1844 (let ((switches (org-element-property :switches example-block))
1845 (value (org-element-property :value example-block)))
1846 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1847 (org-escape-code-in-string
1848 (if (or org-src-preserve-indentation
1849 (org-element-property :preserve-indent example-block))
1850 value
1851 (org-element-remove-indentation value)))
1852 "#+END_EXAMPLE")))
1855 ;;;; Export Block
1857 (defun org-element-export-block-parser (limit affiliated)
1858 "Parse an export block.
1860 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1861 the buffer position at the beginning of the first affiliated
1862 keyword and CDR is a plist of affiliated keywords along with
1863 their value.
1865 Return a list whose CAR is `export-block' and CDR is a plist
1866 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1867 `:post-affiliated' keywords.
1869 Assume point is at export-block beginning."
1870 (let* ((case-fold-search t)
1871 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1872 (upcase (org-match-string-no-properties 1)))))
1873 (if (not (save-excursion
1874 (re-search-forward
1875 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1876 ;; Incomplete block: parse it as a paragraph.
1877 (org-element-paragraph-parser limit affiliated)
1878 (let ((contents-end (match-beginning 0)))
1879 (save-excursion
1880 (let* ((begin (car affiliated))
1881 (post-affiliated (point))
1882 (contents-begin (progn (forward-line) (point)))
1883 (pos-before-blank (progn (goto-char contents-end)
1884 (forward-line)
1885 (point)))
1886 (end (progn (skip-chars-forward " \r\t\n" limit)
1887 (if (eobp) (point) (line-beginning-position))))
1888 (value (buffer-substring-no-properties contents-begin
1889 contents-end)))
1890 (list 'export-block
1891 (nconc
1892 (list :begin begin
1893 :end end
1894 :type type
1895 :value value
1896 :post-blank (count-lines pos-before-blank end)
1897 :post-affiliated post-affiliated)
1898 (cdr affiliated)))))))))
1900 (defun org-element-export-block-interpreter (export-block contents)
1901 "Interpret EXPORT-BLOCK element as Org syntax.
1902 CONTENTS is nil."
1903 (let ((type (org-element-property :type export-block)))
1904 (concat (format "#+BEGIN_%s\n" type)
1905 (org-element-property :value export-block)
1906 (format "#+END_%s" type))))
1909 ;;;; Fixed-width
1911 (defun org-element-fixed-width-parser (limit affiliated)
1912 "Parse a fixed-width section.
1914 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1915 the buffer position at the beginning of the first affiliated
1916 keyword and CDR is a plist of affiliated keywords along with
1917 their value.
1919 Return a list whose CAR is `fixed-width' and CDR is a plist
1920 containing `:begin', `:end', `:value', `:post-blank' and
1921 `:post-affiliated' keywords.
1923 Assume point is at the beginning of the fixed-width area."
1924 (save-excursion
1925 (let* ((begin (car affiliated))
1926 (post-affiliated (point))
1927 value
1928 (end-area
1929 (progn
1930 (while (and (< (point) limit)
1931 (looking-at "[ \t]*:\\( \\|$\\)"))
1932 ;; Accumulate text without starting colons.
1933 (setq value
1934 (concat value
1935 (buffer-substring-no-properties
1936 (match-end 0) (point-at-eol))
1937 "\n"))
1938 (forward-line))
1939 (point)))
1940 (end (progn (skip-chars-forward " \r\t\n" limit)
1941 (if (eobp) (point) (line-beginning-position)))))
1942 (list 'fixed-width
1943 (nconc
1944 (list :begin begin
1945 :end end
1946 :value value
1947 :post-blank (count-lines end-area end)
1948 :post-affiliated post-affiliated)
1949 (cdr affiliated))))))
1951 (defun org-element-fixed-width-interpreter (fixed-width contents)
1952 "Interpret FIXED-WIDTH element as Org syntax.
1953 CONTENTS is nil."
1954 (let ((value (org-element-property :value fixed-width)))
1955 (and value
1956 (replace-regexp-in-string
1957 "^" ": "
1958 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1961 ;;;; Horizontal Rule
1963 (defun org-element-horizontal-rule-parser (limit affiliated)
1964 "Parse an horizontal rule.
1966 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1967 the buffer position at the beginning of the first affiliated
1968 keyword and CDR is a plist of affiliated keywords along with
1969 their value.
1971 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1972 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1973 keywords."
1974 (save-excursion
1975 (let ((begin (car affiliated))
1976 (post-affiliated (point))
1977 (post-hr (progn (forward-line) (point)))
1978 (end (progn (skip-chars-forward " \r\t\n" limit)
1979 (if (eobp) (point) (line-beginning-position)))))
1980 (list 'horizontal-rule
1981 (nconc
1982 (list :begin begin
1983 :end end
1984 :post-blank (count-lines post-hr end)
1985 :post-affiliated post-affiliated)
1986 (cdr affiliated))))))
1988 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1989 "Interpret HORIZONTAL-RULE element as Org syntax.
1990 CONTENTS is nil."
1991 "-----")
1994 ;;;; Keyword
1996 (defun org-element-keyword-parser (limit affiliated)
1997 "Parse a keyword at point.
1999 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2000 the buffer position at the beginning of the first affiliated
2001 keyword and CDR is a plist of affiliated keywords along with
2002 their value.
2004 Return a list whose CAR is `keyword' and CDR is a plist
2005 containing `:key', `:value', `:begin', `:end', `:post-blank' and
2006 `:post-affiliated' keywords."
2007 (save-excursion
2008 ;; An orphaned affiliated keyword is considered as a regular
2009 ;; keyword. In this case AFFILIATED is nil, so we take care of
2010 ;; this corner case.
2011 (let ((begin (or (car affiliated) (point)))
2012 (post-affiliated (point))
2013 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
2014 (upcase (org-match-string-no-properties 1))))
2015 (value (org-trim (buffer-substring-no-properties
2016 (match-end 0) (point-at-eol))))
2017 (pos-before-blank (progn (forward-line) (point)))
2018 (end (progn (skip-chars-forward " \r\t\n" limit)
2019 (if (eobp) (point) (line-beginning-position)))))
2020 (list 'keyword
2021 (nconc
2022 (list :key key
2023 :value value
2024 :begin begin
2025 :end end
2026 :post-blank (count-lines pos-before-blank end)
2027 :post-affiliated post-affiliated)
2028 (cdr affiliated))))))
2030 (defun org-element-keyword-interpreter (keyword contents)
2031 "Interpret KEYWORD element as Org syntax.
2032 CONTENTS is nil."
2033 (format "#+%s: %s"
2034 (org-element-property :key keyword)
2035 (org-element-property :value keyword)))
2038 ;;;; Latex Environment
2040 (defun org-element-latex-environment-parser (limit affiliated)
2041 "Parse a LaTeX environment.
2043 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2044 the buffer position at the beginning of the first affiliated
2045 keyword and CDR is a plist of affiliated keywords along with
2046 their value.
2048 Return a list whose CAR is `latex-environment' and CDR is a plist
2049 containing `:begin', `:end', `:value', `:post-blank' and
2050 `:post-affiliated' keywords.
2052 Assume point is at the beginning of the latex environment."
2053 (save-excursion
2054 (let ((case-fold-search t)
2055 (code-begin (point)))
2056 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2057 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2058 (regexp-quote (match-string 1)))
2059 limit t))
2060 ;; Incomplete latex environment: parse it as a paragraph.
2061 (org-element-paragraph-parser limit affiliated)
2062 (let* ((code-end (progn (forward-line) (point)))
2063 (begin (car affiliated))
2064 (value (buffer-substring-no-properties code-begin code-end))
2065 (end (progn (skip-chars-forward " \r\t\n" limit)
2066 (if (eobp) (point) (line-beginning-position)))))
2067 (list 'latex-environment
2068 (nconc
2069 (list :begin begin
2070 :end end
2071 :value value
2072 :post-blank (count-lines code-end end)
2073 :post-affiliated code-begin)
2074 (cdr affiliated))))))))
2076 (defun org-element-latex-environment-interpreter (latex-environment contents)
2077 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2078 CONTENTS is nil."
2079 (org-element-property :value latex-environment))
2082 ;;;; Node Property
2084 (defun org-element-node-property-parser (limit)
2085 "Parse a node-property at point.
2087 LIMIT bounds the search.
2089 Return a list whose CAR is `node-property' and CDR is a plist
2090 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2091 keywords."
2092 (save-excursion
2093 (looking-at org-property-re)
2094 (let ((case-fold-search t)
2095 (begin (point))
2096 (key (org-match-string-no-properties 2))
2097 (value (org-match-string-no-properties 3))
2098 (pos-before-blank (progn (forward-line) (point)))
2099 (end (progn (skip-chars-forward " \r\t\n" limit)
2100 (if (eobp) (point) (point-at-bol)))))
2101 (list 'node-property
2102 (list :key key
2103 :value value
2104 :begin begin
2105 :end end
2106 :post-blank (count-lines pos-before-blank end))))))
2108 (defun org-element-node-property-interpreter (node-property contents)
2109 "Interpret NODE-PROPERTY element as Org syntax.
2110 CONTENTS is nil."
2111 (format org-property-format
2112 (format ":%s:" (org-element-property :key node-property))
2113 (org-element-property :value node-property)))
2116 ;;;; Paragraph
2118 (defun org-element-paragraph-parser (limit affiliated)
2119 "Parse a paragraph.
2121 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2122 the buffer position at the beginning of the first affiliated
2123 keyword and CDR is a plist of affiliated keywords along with
2124 their value.
2126 Return a list whose CAR is `paragraph' and CDR is a plist
2127 containing `:begin', `:end', `:contents-begin' and
2128 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2130 Assume point is at the beginning of the paragraph."
2131 (save-excursion
2132 (let* ((begin (car affiliated))
2133 (contents-begin (point))
2134 (before-blank
2135 (let ((case-fold-search t))
2136 (end-of-line)
2137 (if (not (re-search-forward
2138 org-element-paragraph-separate limit 'm))
2139 limit
2140 ;; A matching `org-element-paragraph-separate' is not
2141 ;; necessarily the end of the paragraph. In
2142 ;; particular, lines starting with # or : as a first
2143 ;; non-space character are ambiguous. We have to
2144 ;; check if they are valid Org syntax (e.g., not an
2145 ;; incomplete keyword).
2146 (beginning-of-line)
2147 (while (not
2149 ;; There's no ambiguity for other symbols or
2150 ;; empty lines: stop here.
2151 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2152 ;; Stop at valid fixed-width areas.
2153 (looking-at "[ \t]*:\\(?: \\|$\\)")
2154 ;; Stop at drawers.
2155 (and (looking-at org-drawer-regexp)
2156 (save-excursion
2157 (re-search-forward
2158 "^[ \t]*:END:[ \t]*$" limit t)))
2159 ;; Stop at valid comments.
2160 (looking-at "[ \t]*#\\(?: \\|$\\)")
2161 ;; Stop at valid dynamic blocks.
2162 (and (looking-at org-dblock-start-re)
2163 (save-excursion
2164 (re-search-forward
2165 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2166 ;; Stop at valid blocks.
2167 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2168 (save-excursion
2169 (re-search-forward
2170 (format "^[ \t]*#\\+END_%s[ \t]*$"
2171 (regexp-quote
2172 (org-match-string-no-properties 1)))
2173 limit t)))
2174 ;; Stop at valid latex environments.
2175 (and (looking-at
2176 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2177 (save-excursion
2178 (re-search-forward
2179 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2180 (regexp-quote
2181 (org-match-string-no-properties 1)))
2182 limit t)))
2183 ;; Stop at valid keywords.
2184 (looking-at "[ \t]*#\\+\\S-+:")
2185 ;; Skip everything else.
2186 (not
2187 (progn
2188 (end-of-line)
2189 (re-search-forward org-element-paragraph-separate
2190 limit 'm)))))
2191 (beginning-of-line)))
2192 (if (= (point) limit) limit
2193 (goto-char (line-beginning-position)))))
2194 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2195 (forward-line)
2196 (point)))
2197 (end (progn (skip-chars-forward " \r\t\n" limit)
2198 (if (eobp) (point) (line-beginning-position)))))
2199 (list 'paragraph
2200 (nconc
2201 (list :begin begin
2202 :end end
2203 :contents-begin contents-begin
2204 :contents-end contents-end
2205 :post-blank (count-lines before-blank end)
2206 :post-affiliated contents-begin)
2207 (cdr affiliated))))))
2209 (defun org-element-paragraph-interpreter (paragraph contents)
2210 "Interpret PARAGRAPH element as Org syntax.
2211 CONTENTS is the contents of the element."
2212 contents)
2215 ;;;; Planning
2217 (defun org-element-planning-parser (limit)
2218 "Parse a planning.
2220 LIMIT bounds the search.
2222 Return a list whose CAR is `planning' and CDR is a plist
2223 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2224 and `:post-blank' keywords."
2225 (save-excursion
2226 (let* ((case-fold-search nil)
2227 (begin (point))
2228 (post-blank (let ((before-blank (progn (forward-line) (point))))
2229 (skip-chars-forward " \r\t\n" limit)
2230 (skip-chars-backward " \t")
2231 (unless (bolp) (end-of-line))
2232 (count-lines before-blank (point))))
2233 (end (point))
2234 closed deadline scheduled)
2235 (goto-char begin)
2236 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2237 (goto-char (match-end 1))
2238 (skip-chars-forward " \t" end)
2239 (let ((keyword (match-string 1))
2240 (time (org-element-timestamp-parser)))
2241 (cond ((equal keyword org-closed-string) (setq closed time))
2242 ((equal keyword org-deadline-string) (setq deadline time))
2243 (t (setq scheduled time)))))
2244 (list 'planning
2245 (list :closed closed
2246 :deadline deadline
2247 :scheduled scheduled
2248 :begin begin
2249 :end end
2250 :post-blank post-blank)))))
2252 (defun org-element-planning-interpreter (planning contents)
2253 "Interpret PLANNING element as Org syntax.
2254 CONTENTS is nil."
2255 (mapconcat
2256 'identity
2257 (delq nil
2258 (list (let ((deadline (org-element-property :deadline planning)))
2259 (when deadline
2260 (concat org-deadline-string " "
2261 (org-element-timestamp-interpreter deadline nil))))
2262 (let ((scheduled (org-element-property :scheduled planning)))
2263 (when scheduled
2264 (concat org-scheduled-string " "
2265 (org-element-timestamp-interpreter scheduled nil))))
2266 (let ((closed (org-element-property :closed planning)))
2267 (when closed
2268 (concat org-closed-string " "
2269 (org-element-timestamp-interpreter closed nil))))))
2270 " "))
2273 ;;;; Src Block
2275 (defun org-element-src-block-parser (limit affiliated)
2276 "Parse a src block.
2278 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2279 the buffer position at the beginning of the first affiliated
2280 keyword and CDR is a plist of affiliated keywords along with
2281 their value.
2283 Return a list whose CAR is `src-block' and CDR is a plist
2284 containing `:language', `:switches', `:parameters', `:begin',
2285 `:end', `:number-lines', `:retain-labels', `:use-labels',
2286 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2287 `:post-affiliated' keywords.
2289 Assume point is at the beginning of the block."
2290 (let ((case-fold-search t))
2291 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2292 limit t)))
2293 ;; Incomplete block: parse it as a paragraph.
2294 (org-element-paragraph-parser limit affiliated)
2295 (let ((contents-end (match-beginning 0)))
2296 (save-excursion
2297 (let* ((begin (car affiliated))
2298 (post-affiliated (point))
2299 ;; Get language as a string.
2300 (language
2301 (progn
2302 (looking-at
2303 (concat "^[ \t]*#\\+BEGIN_SRC"
2304 "\\(?: +\\(\\S-+\\)\\)?"
2305 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2306 "\\(.*\\)[ \t]*$"))
2307 (org-match-string-no-properties 1)))
2308 ;; Get switches.
2309 (switches (org-match-string-no-properties 2))
2310 ;; Get parameters.
2311 (parameters (org-match-string-no-properties 3))
2312 ;; Switches analysis
2313 (number-lines
2314 (cond ((not switches) nil)
2315 ((string-match "-n\\>" switches) 'new)
2316 ((string-match "+n\\>" switches) 'continued)))
2317 (preserve-indent (and switches
2318 (string-match "-i\\>" switches)))
2319 (label-fmt
2320 (and switches
2321 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2322 (match-string 1 switches)))
2323 ;; Should labels be retained in (or stripped from)
2324 ;; src blocks?
2325 (retain-labels
2326 (or (not switches)
2327 (not (string-match "-r\\>" switches))
2328 (and number-lines (string-match "-k\\>" switches))))
2329 ;; What should code-references use - labels or
2330 ;; line-numbers?
2331 (use-labels
2332 (or (not switches)
2333 (and retain-labels
2334 (not (string-match "-k\\>" switches)))))
2335 ;; Indentation.
2336 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2337 ;; Retrieve code.
2338 (value (org-element-remove-indentation
2339 (org-unescape-code-in-string
2340 (buffer-substring-no-properties
2341 (progn (forward-line) (point)) contents-end))
2342 block-ind))
2343 (pos-before-blank (progn (goto-char contents-end)
2344 (forward-line)
2345 (point)))
2346 ;; Get position after ending blank lines.
2347 (end (progn (skip-chars-forward " \r\t\n" limit)
2348 (if (eobp) (point) (line-beginning-position)))))
2349 (list 'src-block
2350 (nconc
2351 (list :language language
2352 :switches (and (org-string-nw-p switches)
2353 (org-trim switches))
2354 :parameters (and (org-string-nw-p parameters)
2355 (org-trim parameters))
2356 :begin begin
2357 :end end
2358 :number-lines number-lines
2359 :preserve-indent preserve-indent
2360 :retain-labels retain-labels
2361 :use-labels use-labels
2362 :label-fmt label-fmt
2363 :value value
2364 :post-blank (count-lines pos-before-blank end)
2365 :post-affiliated post-affiliated)
2366 (cdr affiliated)))))))))
2368 (defun org-element-src-block-interpreter (src-block contents)
2369 "Interpret SRC-BLOCK element as Org syntax.
2370 CONTENTS is nil."
2371 (let ((lang (org-element-property :language src-block))
2372 (switches (org-element-property :switches src-block))
2373 (params (org-element-property :parameters src-block))
2374 (value
2375 (let ((val (org-element-property :value src-block)))
2376 (cond
2377 ((or org-src-preserve-indentation
2378 (org-element-property :preserve-indent src-block))
2379 val)
2380 ((zerop org-edit-src-content-indentation) val)
2382 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2383 (replace-regexp-in-string
2384 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2385 (concat (format "#+BEGIN_SRC%s\n"
2386 (concat (and lang (concat " " lang))
2387 (and switches (concat " " switches))
2388 (and params (concat " " params))))
2389 (org-escape-code-in-string value)
2390 "#+END_SRC")))
2393 ;;;; Table
2395 (defun org-element-table-parser (limit affiliated)
2396 "Parse a table at point.
2398 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2399 the buffer position at the beginning of the first affiliated
2400 keyword and CDR is a plist of affiliated keywords along with
2401 their value.
2403 Return a list whose CAR is `table' and CDR is a plist containing
2404 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2405 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2406 keywords.
2408 Assume point is at the beginning of the table."
2409 (save-excursion
2410 (let* ((case-fold-search t)
2411 (table-begin (point))
2412 (type (if (org-at-table.el-p) 'table.el 'org))
2413 (begin (car affiliated))
2414 (table-end
2415 (if (re-search-forward org-table-any-border-regexp limit 'm)
2416 (goto-char (match-beginning 0))
2417 (point)))
2418 (tblfm (let (acc)
2419 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2420 (push (org-match-string-no-properties 1) acc)
2421 (forward-line))
2422 acc))
2423 (pos-before-blank (point))
2424 (end (progn (skip-chars-forward " \r\t\n" limit)
2425 (if (eobp) (point) (line-beginning-position)))))
2426 (list 'table
2427 (nconc
2428 (list :begin begin
2429 :end end
2430 :type type
2431 :tblfm tblfm
2432 ;; Only `org' tables have contents. `table.el' tables
2433 ;; use a `:value' property to store raw table as
2434 ;; a string.
2435 :contents-begin (and (eq type 'org) table-begin)
2436 :contents-end (and (eq type 'org) table-end)
2437 :value (and (eq type 'table.el)
2438 (buffer-substring-no-properties
2439 table-begin table-end))
2440 :post-blank (count-lines pos-before-blank end)
2441 :post-affiliated table-begin)
2442 (cdr affiliated))))))
2444 (defun org-element-table-interpreter (table contents)
2445 "Interpret TABLE element as Org syntax.
2446 CONTENTS is nil."
2447 (if (eq (org-element-property :type table) 'table.el)
2448 (org-remove-indentation (org-element-property :value table))
2449 (concat (with-temp-buffer (insert contents)
2450 (org-table-align)
2451 (buffer-string))
2452 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2453 (reverse (org-element-property :tblfm table))
2454 "\n"))))
2457 ;;;; Table Row
2459 (defun org-element-table-row-parser (limit)
2460 "Parse table row at point.
2462 LIMIT bounds the search.
2464 Return a list whose CAR is `table-row' and CDR is a plist
2465 containing `:begin', `:end', `:contents-begin', `:contents-end',
2466 `:type' and `:post-blank' keywords."
2467 (save-excursion
2468 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2469 (begin (point))
2470 ;; A table rule has no contents. In that case, ensure
2471 ;; CONTENTS-BEGIN matches CONTENTS-END.
2472 (contents-begin (and (eq type 'standard)
2473 (search-forward "|")
2474 (point)))
2475 (contents-end (and (eq type 'standard)
2476 (progn
2477 (end-of-line)
2478 (skip-chars-backward " \t")
2479 (point))))
2480 (end (progn (forward-line) (point))))
2481 (list 'table-row
2482 (list :type type
2483 :begin begin
2484 :end end
2485 :contents-begin contents-begin
2486 :contents-end contents-end
2487 :post-blank 0)))))
2489 (defun org-element-table-row-interpreter (table-row contents)
2490 "Interpret TABLE-ROW element as Org syntax.
2491 CONTENTS is the contents of the table row."
2492 (if (eq (org-element-property :type table-row) 'rule) "|-"
2493 (concat "| " contents)))
2496 ;;;; Verse Block
2498 (defun org-element-verse-block-parser (limit affiliated)
2499 "Parse a verse block.
2501 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2502 the buffer position at the beginning of the first affiliated
2503 keyword and CDR is a plist of affiliated keywords along with
2504 their value.
2506 Return a list whose CAR is `verse-block' and CDR is a plist
2507 containing `:begin', `:end', `:contents-begin', `:contents-end',
2508 `:post-blank' and `:post-affiliated' keywords.
2510 Assume point is at beginning of the block."
2511 (let ((case-fold-search t))
2512 (if (not (save-excursion
2513 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2514 ;; Incomplete block: parse it as a paragraph.
2515 (org-element-paragraph-parser limit affiliated)
2516 (let ((contents-end (match-beginning 0)))
2517 (save-excursion
2518 (let* ((begin (car affiliated))
2519 (post-affiliated (point))
2520 (contents-begin (progn (forward-line) (point)))
2521 (pos-before-blank (progn (goto-char contents-end)
2522 (forward-line)
2523 (point)))
2524 (end (progn (skip-chars-forward " \r\t\n" limit)
2525 (if (eobp) (point) (line-beginning-position)))))
2526 (list 'verse-block
2527 (nconc
2528 (list :begin begin
2529 :end end
2530 :contents-begin contents-begin
2531 :contents-end contents-end
2532 :post-blank (count-lines pos-before-blank end)
2533 :post-affiliated post-affiliated)
2534 (cdr affiliated)))))))))
2536 (defun org-element-verse-block-interpreter (verse-block contents)
2537 "Interpret VERSE-BLOCK element as Org syntax.
2538 CONTENTS is verse block contents."
2539 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2543 ;;; Objects
2545 ;; Unlike to elements, raw text can be found between objects. Hence,
2546 ;; `org-element--object-lex' is provided to find the next object in
2547 ;; buffer.
2549 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2550 ;; object types they can contain will be specified in
2551 ;; `org-element-object-restrictions'.
2553 ;; Creating a new type of object requires to alter
2554 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2555 ;; new type in `org-element-all-objects', and possibly add
2556 ;; restrictions in `org-element-object-restrictions'.
2558 ;;;; Bold
2560 (defun org-element-bold-parser ()
2561 "Parse bold object at point, if any.
2563 When at a bold object, return a list whose car is `bold' and cdr
2564 is a plist with `:begin', `:end', `:contents-begin' and
2565 `:contents-end' and `:post-blank' keywords. Otherwise, return
2566 nil.
2568 Assume point is at the first star marker."
2569 (save-excursion
2570 (unless (bolp) (backward-char 1))
2571 (when (looking-at org-emph-re)
2572 (let ((begin (match-beginning 2))
2573 (contents-begin (match-beginning 4))
2574 (contents-end (match-end 4))
2575 (post-blank (progn (goto-char (match-end 2))
2576 (skip-chars-forward " \t")))
2577 (end (point)))
2578 (list 'bold
2579 (list :begin begin
2580 :end end
2581 :contents-begin contents-begin
2582 :contents-end contents-end
2583 :post-blank post-blank))))))
2585 (defun org-element-bold-interpreter (bold contents)
2586 "Interpret BOLD object as Org syntax.
2587 CONTENTS is the contents of the object."
2588 (format "*%s*" contents))
2591 ;;;; Code
2593 (defun org-element-code-parser ()
2594 "Parse code object at point, if any.
2596 When at a code object, return a list whose car is `code' and cdr
2597 is a plist with `:value', `:begin', `:end' and `:post-blank'
2598 keywords. Otherwise, return nil.
2600 Assume point is at the first tilde marker."
2601 (save-excursion
2602 (unless (bolp) (backward-char 1))
2603 (when (looking-at org-emph-re)
2604 (let ((begin (match-beginning 2))
2605 (value (org-match-string-no-properties 4))
2606 (post-blank (progn (goto-char (match-end 2))
2607 (skip-chars-forward " \t")))
2608 (end (point)))
2609 (list 'code
2610 (list :value value
2611 :begin begin
2612 :end end
2613 :post-blank post-blank))))))
2615 (defun org-element-code-interpreter (code contents)
2616 "Interpret CODE object as Org syntax.
2617 CONTENTS is nil."
2618 (format "~%s~" (org-element-property :value code)))
2621 ;;;; Entity
2623 (defun org-element-entity-parser ()
2624 "Parse entity at point, if any.
2626 When at an entity, return a list whose car is `entity' and cdr
2627 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2628 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2629 `:post-blank' as keywords. Otherwise, return nil.
2631 Assume point is at the beginning of the entity."
2632 (catch 'no-object
2633 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2634 (save-excursion
2635 (let* ((value (or (org-entity-get (match-string 1))
2636 (throw 'no-object nil)))
2637 (begin (match-beginning 0))
2638 (bracketsp (string= (match-string 2) "{}"))
2639 (post-blank (progn (goto-char (match-end 1))
2640 (when bracketsp (forward-char 2))
2641 (skip-chars-forward " \t")))
2642 (end (point)))
2643 (list 'entity
2644 (list :name (car value)
2645 :latex (nth 1 value)
2646 :latex-math-p (nth 2 value)
2647 :html (nth 3 value)
2648 :ascii (nth 4 value)
2649 :latin1 (nth 5 value)
2650 :utf-8 (nth 6 value)
2651 :begin begin
2652 :end end
2653 :use-brackets-p bracketsp
2654 :post-blank post-blank)))))))
2656 (defun org-element-entity-interpreter (entity contents)
2657 "Interpret ENTITY object as Org syntax.
2658 CONTENTS is nil."
2659 (concat "\\"
2660 (org-element-property :name entity)
2661 (when (org-element-property :use-brackets-p entity) "{}")))
2664 ;;;; Export Snippet
2666 (defun org-element-export-snippet-parser ()
2667 "Parse export snippet at point.
2669 When at an export snippet, return a list whose car is
2670 `export-snippet' and cdr a plist with `:begin', `:end',
2671 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2672 return nil.
2674 Assume point is at the beginning of the snippet."
2675 (save-excursion
2676 (let (contents-end)
2677 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2678 (setq contents-end
2679 (save-match-data (goto-char (match-end 0))
2680 (re-search-forward "@@" nil t)
2681 (match-beginning 0))))
2682 (let* ((begin (match-beginning 0))
2683 (back-end (org-match-string-no-properties 1))
2684 (value (buffer-substring-no-properties
2685 (match-end 0) contents-end))
2686 (post-blank (skip-chars-forward " \t"))
2687 (end (point)))
2688 (list 'export-snippet
2689 (list :back-end back-end
2690 :value value
2691 :begin begin
2692 :end end
2693 :post-blank post-blank)))))))
2695 (defun org-element-export-snippet-interpreter (export-snippet contents)
2696 "Interpret EXPORT-SNIPPET object as Org syntax.
2697 CONTENTS is nil."
2698 (format "@@%s:%s@@"
2699 (org-element-property :back-end export-snippet)
2700 (org-element-property :value export-snippet)))
2703 ;;;; Footnote Reference
2705 (defun org-element-footnote-reference-parser ()
2706 "Parse footnote reference at point, if any.
2708 When at a footnote reference, return a list whose car is
2709 `footnote-reference' and cdr a plist with `:label', `:type',
2710 `:inline-definition', `:begin', `:end' and `:post-blank' as
2711 keywords. Otherwise, return nil."
2712 (catch 'no-object
2713 (when (looking-at org-footnote-re)
2714 (save-excursion
2715 (let* ((begin (point))
2716 (label (or (org-match-string-no-properties 2)
2717 (org-match-string-no-properties 3)
2718 (and (match-string 1)
2719 (concat "fn:" (org-match-string-no-properties 1)))))
2720 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2721 (inner-begin (match-end 0))
2722 (inner-end
2723 (let ((count 1))
2724 (forward-char)
2725 (while (and (> count 0) (re-search-forward "[][]" nil t))
2726 (if (equal (match-string 0) "[") (incf count) (decf count)))
2727 (unless (zerop count) (throw 'no-object nil))
2728 (1- (point))))
2729 (post-blank (progn (goto-char (1+ inner-end))
2730 (skip-chars-forward " \t")))
2731 (end (point))
2732 (footnote-reference
2733 (list 'footnote-reference
2734 (list :label label
2735 :type type
2736 :begin begin
2737 :end end
2738 :post-blank post-blank))))
2739 (org-element-put-property
2740 footnote-reference :inline-definition
2741 (and (eq type 'inline)
2742 (org-element-parse-secondary-string
2743 (buffer-substring inner-begin inner-end)
2744 (org-element-restriction 'footnote-reference)
2745 footnote-reference))))))))
2747 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2748 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2749 CONTENTS is nil."
2750 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2751 (def
2752 (let ((inline-def
2753 (org-element-property :inline-definition footnote-reference)))
2754 (if (not inline-def) ""
2755 (concat ":" (org-element-interpret-data inline-def))))))
2756 (format "[%s]" (concat label def))))
2759 ;;;; Inline Babel Call
2761 (defun org-element-inline-babel-call-parser ()
2762 "Parse inline babel call at point, if any.
2764 When at an inline babel call, return a list whose car is
2765 `inline-babel-call' and cdr a plist with `:begin', `:end',
2766 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2768 Assume point is at the beginning of the babel call."
2769 (save-excursion
2770 (unless (bolp) (backward-char))
2771 (when (let ((case-fold-search t))
2772 (looking-at org-babel-inline-lob-one-liner-regexp))
2773 (let ((begin (match-end 1))
2774 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2775 (post-blank (progn (goto-char (match-end 0))
2776 (skip-chars-forward " \t")))
2777 (end (point)))
2778 (list 'inline-babel-call
2779 (list :begin begin
2780 :end end
2781 :value value
2782 :post-blank post-blank))))))
2784 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2785 "Interpret INLINE-BABEL-CALL object as Org syntax.
2786 CONTENTS is nil."
2787 (org-element-property :value inline-babel-call))
2790 ;;;; Inline Src Block
2792 (defun org-element-inline-src-block-parser ()
2793 "Parse inline source block at point, if any.
2795 When at an inline source block, return a list whose car is
2796 `inline-src-block' and cdr a plist with `:begin', `:end',
2797 `:language', `:value', `:parameters' and `:post-blank' as
2798 keywords. Otherwise, return nil.
2800 Assume point is at the beginning of the inline src block."
2801 (save-excursion
2802 (unless (bolp) (backward-char))
2803 (when (looking-at org-babel-inline-src-block-regexp)
2804 (let ((begin (match-beginning 1))
2805 (language (org-match-string-no-properties 2))
2806 (parameters (org-match-string-no-properties 4))
2807 (value (org-match-string-no-properties 5))
2808 (post-blank (progn (goto-char (match-end 0))
2809 (skip-chars-forward " \t")))
2810 (end (point)))
2811 (list 'inline-src-block
2812 (list :language language
2813 :value value
2814 :parameters parameters
2815 :begin begin
2816 :end end
2817 :post-blank post-blank))))))
2819 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2820 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2821 CONTENTS is nil."
2822 (let ((language (org-element-property :language inline-src-block))
2823 (arguments (org-element-property :parameters inline-src-block))
2824 (body (org-element-property :value inline-src-block)))
2825 (format "src_%s%s{%s}"
2826 language
2827 (if arguments (format "[%s]" arguments) "")
2828 body)))
2830 ;;;; Italic
2832 (defun org-element-italic-parser ()
2833 "Parse italic object at point, if any.
2835 When at an italic object, return a list whose car is `italic' and
2836 cdr is a plist with `:begin', `:end', `:contents-begin' and
2837 `:contents-end' and `:post-blank' keywords. Otherwise, return
2838 nil.
2840 Assume point is at the first slash marker."
2841 (save-excursion
2842 (unless (bolp) (backward-char 1))
2843 (when (looking-at org-emph-re)
2844 (let ((begin (match-beginning 2))
2845 (contents-begin (match-beginning 4))
2846 (contents-end (match-end 4))
2847 (post-blank (progn (goto-char (match-end 2))
2848 (skip-chars-forward " \t")))
2849 (end (point)))
2850 (list 'italic
2851 (list :begin begin
2852 :end end
2853 :contents-begin contents-begin
2854 :contents-end contents-end
2855 :post-blank post-blank))))))
2857 (defun org-element-italic-interpreter (italic contents)
2858 "Interpret ITALIC object as Org syntax.
2859 CONTENTS is the contents of the object."
2860 (format "/%s/" contents))
2863 ;;;; Latex Fragment
2865 (defun org-element-latex-fragment-parser ()
2866 "Parse LaTeX fragment at point, if any.
2868 When at a LaTeX fragment, return a list whose car is
2869 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2870 and `:post-blank' as keywords. Otherwise, return nil.
2872 Assume point is at the beginning of the LaTeX fragment."
2873 (catch 'no-object
2874 (save-excursion
2875 (let* ((begin (point))
2876 (substring-match
2877 (or (catch 'exit
2878 (dolist (e (cdr org-latex-regexps))
2879 (let ((latex-regexp (nth 1 e)))
2880 (when (or (looking-at latex-regexp)
2881 (and (not (bobp))
2882 (save-excursion
2883 (backward-char)
2884 (looking-at latex-regexp))))
2885 (throw 'exit (nth 2 e))))))
2886 ;; Macro.
2887 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2889 ;; No fragment found.
2890 (throw 'no-object nil)))
2891 (value (org-match-string-no-properties substring-match))
2892 (post-blank (progn (goto-char (match-end substring-match))
2893 (skip-chars-forward " \t")))
2894 (end (point)))
2895 (list 'latex-fragment
2896 (list :value value
2897 :begin begin
2898 :end end
2899 :post-blank post-blank))))))
2901 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2902 "Interpret LATEX-FRAGMENT object as Org syntax.
2903 CONTENTS is nil."
2904 (org-element-property :value latex-fragment))
2906 ;;;; Line Break
2908 (defun org-element-line-break-parser ()
2909 "Parse line break at point, if any.
2911 When at a line break, return a list whose car is `line-break',
2912 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2913 Otherwise, return nil.
2915 Assume point is at the beginning of the line break."
2916 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2917 (not (eq (char-before) ?\\)))
2918 (list 'line-break
2919 (list :begin (point)
2920 :end (progn (forward-line) (point))
2921 :post-blank 0))))
2923 (defun org-element-line-break-interpreter (line-break contents)
2924 "Interpret LINE-BREAK object as Org syntax.
2925 CONTENTS is nil."
2926 "\\\\\n")
2929 ;;;; Link
2931 (defun org-element-link-parser ()
2932 "Parse link at point, if any.
2934 When at a link, return a list whose car is `link' and cdr a plist
2935 with `:type', `:path', `:raw-link', `:application',
2936 `:search-option', `:begin', `:end', `:contents-begin',
2937 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2938 nil.
2940 Assume point is at the beginning of the link."
2941 (catch 'no-object
2942 (let ((begin (point))
2943 end contents-begin contents-end link-end post-blank path type
2944 raw-link link search-option application)
2945 (cond
2946 ;; Type 1: Text targeted from a radio target.
2947 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2948 (setq type "radio"
2949 link-end (match-end 0)
2950 path (org-match-string-no-properties 0)
2951 contents-begin (match-beginning 0)
2952 contents-end (match-end 0)))
2953 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2954 ((looking-at org-bracket-link-regexp)
2955 (setq contents-begin (match-beginning 3)
2956 contents-end (match-end 3)
2957 link-end (match-end 0)
2958 ;; RAW-LINK is the original link. Expand any
2959 ;; abbreviation in it.
2960 raw-link (org-translate-link
2961 (org-link-expand-abbrev
2962 (org-match-string-no-properties 1))))
2963 ;; Determine TYPE of link and set PATH accordingly.
2964 (cond
2965 ;; File type.
2966 ((or (file-name-absolute-p raw-link)
2967 (string-match "^\\.\\.?/" raw-link))
2968 (setq type "file" path raw-link))
2969 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2970 ((string-match org-link-re-with-space3 raw-link)
2971 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
2972 ;; Id type: PATH is the id.
2973 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
2974 (setq type "id" path (match-string 1 raw-link)))
2975 ;; Code-ref type: PATH is the name of the reference.
2976 ((string-match "^(\\(.*\\))$" raw-link)
2977 (setq type "coderef" path (match-string 1 raw-link)))
2978 ;; Custom-id type: PATH is the name of the custom id.
2979 ((= (aref raw-link 0) ?#)
2980 (setq type "custom-id" path (substring raw-link 1)))
2981 ;; Fuzzy type: Internal link either matches a target, an
2982 ;; headline name or nothing. PATH is the target or
2983 ;; headline's name.
2984 (t (setq type "fuzzy" path raw-link))))
2985 ;; Type 3: Plain link, e.g., http://orgmode.org
2986 ((looking-at org-plain-link-re)
2987 (setq raw-link (org-match-string-no-properties 0)
2988 type (org-match-string-no-properties 1)
2989 link-end (match-end 0)
2990 path (org-match-string-no-properties 2)))
2991 ;; Type 4: Angular link, e.g., <http://orgmode.org>
2992 ((looking-at org-angle-link-re)
2993 (setq raw-link (buffer-substring-no-properties
2994 (match-beginning 1) (match-end 2))
2995 type (org-match-string-no-properties 1)
2996 link-end (match-end 0)
2997 path (org-match-string-no-properties 2)))
2998 (t (throw 'no-object nil)))
2999 ;; In any case, deduce end point after trailing white space from
3000 ;; LINK-END variable.
3001 (save-excursion
3002 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3003 end (point))
3004 ;; Extract search option and opening application out of
3005 ;; "file"-type links.
3006 (when (member type org-element-link-type-is-file)
3007 ;; Application.
3008 (cond ((string-match "^file\\+\\(.*\\)$" type)
3009 (setq application (match-string 1 type)))
3010 ((not (string-match "^file" type))
3011 (setq application type)))
3012 ;; Extract search option from PATH.
3013 (when (string-match "::\\(.*\\)$" path)
3014 (setq search-option (match-string 1 path)
3015 path (replace-match "" nil nil path)))
3016 ;; Make sure TYPE always reports "file".
3017 (setq type "file"))
3018 (list 'link
3019 (list :type type
3020 :path path
3021 :raw-link (or raw-link path)
3022 :application application
3023 :search-option search-option
3024 :begin begin
3025 :end end
3026 :contents-begin contents-begin
3027 :contents-end contents-end
3028 :post-blank post-blank))))))
3030 (defun org-element-link-interpreter (link contents)
3031 "Interpret LINK object as Org syntax.
3032 CONTENTS is the contents of the object, or nil."
3033 (let ((type (org-element-property :type link))
3034 (raw-link (org-element-property :raw-link link)))
3035 (if (string= type "radio") raw-link
3036 (format "[[%s]%s]"
3037 raw-link
3038 (if contents (format "[%s]" contents) "")))))
3041 ;;;; Macro
3043 (defun org-element-macro-parser ()
3044 "Parse macro at point, if any.
3046 When at a macro, return a list whose car is `macro' and cdr
3047 a plist with `:key', `:args', `:begin', `:end', `:value' and
3048 `:post-blank' as keywords. Otherwise, return nil.
3050 Assume point is at the macro."
3051 (save-excursion
3052 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3053 (let ((begin (point))
3054 (key (downcase (org-match-string-no-properties 1)))
3055 (value (org-match-string-no-properties 0))
3056 (post-blank (progn (goto-char (match-end 0))
3057 (skip-chars-forward " \t")))
3058 (end (point))
3059 (args (let ((args (org-match-string-no-properties 3)))
3060 (when args
3061 ;; Do not use `org-split-string' since empty
3062 ;; strings are meaningful here.
3063 (split-string
3064 (replace-regexp-in-string
3065 "\\(\\\\*\\)\\(,\\)"
3066 (lambda (str)
3067 (let ((len (length (match-string 1 str))))
3068 (concat (make-string (/ len 2) ?\\)
3069 (if (zerop (mod len 2)) "\000" ","))))
3070 args nil t)
3071 "\000")))))
3072 (list 'macro
3073 (list :key key
3074 :value value
3075 :args args
3076 :begin begin
3077 :end end
3078 :post-blank post-blank))))))
3080 (defun org-element-macro-interpreter (macro contents)
3081 "Interpret MACRO object as Org syntax.
3082 CONTENTS is nil."
3083 (org-element-property :value macro))
3086 ;;;; Radio-target
3088 (defun org-element-radio-target-parser ()
3089 "Parse radio target at point, if any.
3091 When at a radio target, return a list whose car is `radio-target'
3092 and cdr a plist with `:begin', `:end', `:contents-begin',
3093 `:contents-end', `:value' and `:post-blank' as keywords.
3094 Otherwise, return nil.
3096 Assume point is at the radio target."
3097 (save-excursion
3098 (when (looking-at org-radio-target-regexp)
3099 (let ((begin (point))
3100 (contents-begin (match-beginning 1))
3101 (contents-end (match-end 1))
3102 (value (org-match-string-no-properties 1))
3103 (post-blank (progn (goto-char (match-end 0))
3104 (skip-chars-forward " \t")))
3105 (end (point)))
3106 (list 'radio-target
3107 (list :begin begin
3108 :end end
3109 :contents-begin contents-begin
3110 :contents-end contents-end
3111 :post-blank post-blank
3112 :value value))))))
3114 (defun org-element-radio-target-interpreter (target contents)
3115 "Interpret TARGET object as Org syntax.
3116 CONTENTS is the contents of the object."
3117 (concat "<<<" contents ">>>"))
3120 ;;;; Statistics Cookie
3122 (defun org-element-statistics-cookie-parser ()
3123 "Parse statistics cookie at point, if any.
3125 When at a statistics cookie, return a list whose car is
3126 `statistics-cookie', and cdr a plist with `:begin', `:end',
3127 `:value' and `:post-blank' keywords. Otherwise, return nil.
3129 Assume point is at the beginning of the statistics-cookie."
3130 (save-excursion
3131 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3132 (let* ((begin (point))
3133 (value (buffer-substring-no-properties
3134 (match-beginning 0) (match-end 0)))
3135 (post-blank (progn (goto-char (match-end 0))
3136 (skip-chars-forward " \t")))
3137 (end (point)))
3138 (list 'statistics-cookie
3139 (list :begin begin
3140 :end end
3141 :value value
3142 :post-blank post-blank))))))
3144 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3145 "Interpret STATISTICS-COOKIE object as Org syntax.
3146 CONTENTS is nil."
3147 (org-element-property :value statistics-cookie))
3150 ;;;; Strike-Through
3152 (defun org-element-strike-through-parser ()
3153 "Parse strike-through object at point, if any.
3155 When at a strike-through object, return a list whose car is
3156 `strike-through' and cdr is a plist with `:begin', `:end',
3157 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3158 Otherwise, return nil.
3160 Assume point is at the first plus sign marker."
3161 (save-excursion
3162 (unless (bolp) (backward-char 1))
3163 (when (looking-at org-emph-re)
3164 (let ((begin (match-beginning 2))
3165 (contents-begin (match-beginning 4))
3166 (contents-end (match-end 4))
3167 (post-blank (progn (goto-char (match-end 2))
3168 (skip-chars-forward " \t")))
3169 (end (point)))
3170 (list 'strike-through
3171 (list :begin begin
3172 :end end
3173 :contents-begin contents-begin
3174 :contents-end contents-end
3175 :post-blank post-blank))))))
3177 (defun org-element-strike-through-interpreter (strike-through contents)
3178 "Interpret STRIKE-THROUGH object as Org syntax.
3179 CONTENTS is the contents of the object."
3180 (format "+%s+" contents))
3183 ;;;; Subscript
3185 (defun org-element-subscript-parser ()
3186 "Parse subscript at point, if any.
3188 When at a subscript object, return a list whose car is
3189 `subscript' and cdr a plist with `:begin', `:end',
3190 `:contents-begin', `:contents-end', `:use-brackets-p' and
3191 `:post-blank' as keywords. Otherwise, return nil.
3193 Assume point is at the underscore."
3194 (save-excursion
3195 (unless (bolp) (backward-char))
3196 (when (looking-at org-match-substring-regexp)
3197 (let ((bracketsp (match-beginning 4))
3198 (begin (match-beginning 2))
3199 (contents-begin (or (match-beginning 4)
3200 (match-beginning 3)))
3201 (contents-end (or (match-end 4) (match-end 3)))
3202 (post-blank (progn (goto-char (match-end 0))
3203 (skip-chars-forward " \t")))
3204 (end (point)))
3205 (list 'subscript
3206 (list :begin begin
3207 :end end
3208 :use-brackets-p bracketsp
3209 :contents-begin contents-begin
3210 :contents-end contents-end
3211 :post-blank post-blank))))))
3213 (defun org-element-subscript-interpreter (subscript contents)
3214 "Interpret SUBSCRIPT object as Org syntax.
3215 CONTENTS is the contents of the object."
3216 (format
3217 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3218 contents))
3221 ;;;; Superscript
3223 (defun org-element-superscript-parser ()
3224 "Parse superscript at point, if any.
3226 When at a superscript object, return a list whose car is
3227 `superscript' and cdr a plist with `:begin', `:end',
3228 `:contents-begin', `:contents-end', `:use-brackets-p' and
3229 `:post-blank' as keywords. Otherwise, return nil.
3231 Assume point is at the caret."
3232 (save-excursion
3233 (unless (bolp) (backward-char))
3234 (when (looking-at org-match-substring-regexp)
3235 (let ((bracketsp (match-beginning 4))
3236 (begin (match-beginning 2))
3237 (contents-begin (or (match-beginning 4)
3238 (match-beginning 3)))
3239 (contents-end (or (match-end 4) (match-end 3)))
3240 (post-blank (progn (goto-char (match-end 0))
3241 (skip-chars-forward " \t")))
3242 (end (point)))
3243 (list 'superscript
3244 (list :begin begin
3245 :end end
3246 :use-brackets-p bracketsp
3247 :contents-begin contents-begin
3248 :contents-end contents-end
3249 :post-blank post-blank))))))
3251 (defun org-element-superscript-interpreter (superscript contents)
3252 "Interpret SUPERSCRIPT object as Org syntax.
3253 CONTENTS is the contents of the object."
3254 (format
3255 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3256 contents))
3259 ;;;; Table Cell
3261 (defun org-element-table-cell-parser ()
3262 "Parse table cell at point.
3263 Return a list whose car is `table-cell' and cdr is a plist
3264 containing `:begin', `:end', `:contents-begin', `:contents-end'
3265 and `:post-blank' keywords."
3266 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3267 (let* ((begin (match-beginning 0))
3268 (end (match-end 0))
3269 (contents-begin (match-beginning 1))
3270 (contents-end (match-end 1)))
3271 (list 'table-cell
3272 (list :begin begin
3273 :end end
3274 :contents-begin contents-begin
3275 :contents-end contents-end
3276 :post-blank 0))))
3278 (defun org-element-table-cell-interpreter (table-cell contents)
3279 "Interpret TABLE-CELL element as Org syntax.
3280 CONTENTS is the contents of the cell, or nil."
3281 (concat " " contents " |"))
3284 ;;;; Target
3286 (defun org-element-target-parser ()
3287 "Parse target at point, if any.
3289 When at a target, return a list whose car is `target' and cdr
3290 a plist with `:begin', `:end', `:value' and `:post-blank' as
3291 keywords. Otherwise, return nil.
3293 Assume point is at the target."
3294 (save-excursion
3295 (when (looking-at org-target-regexp)
3296 (let ((begin (point))
3297 (value (org-match-string-no-properties 1))
3298 (post-blank (progn (goto-char (match-end 0))
3299 (skip-chars-forward " \t")))
3300 (end (point)))
3301 (list 'target
3302 (list :begin begin
3303 :end end
3304 :value value
3305 :post-blank post-blank))))))
3307 (defun org-element-target-interpreter (target contents)
3308 "Interpret TARGET object as Org syntax.
3309 CONTENTS is nil."
3310 (format "<<%s>>" (org-element-property :value target)))
3313 ;;;; Timestamp
3315 (defconst org-element--timestamp-regexp
3316 (concat org-ts-regexp-both
3317 "\\|"
3318 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3319 "\\|"
3320 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3321 "Regexp matching any timestamp type object.")
3323 (defun org-element-timestamp-parser ()
3324 "Parse time stamp at point, if any.
3326 When at a time stamp, return a list whose car is `timestamp', and
3327 cdr a plist with `:type', `:raw-value', `:year-start',
3328 `:month-start', `:day-start', `:hour-start', `:minute-start',
3329 `:year-end', `:month-end', `:day-end', `:hour-end',
3330 `:minute-end', `:repeater-type', `:repeater-value',
3331 `:repeater-unit', `:warning-type', `:warning-value',
3332 `:warning-unit', `:begin', `:end', `:value' and `:post-blank'
3333 keywords. Otherwise, return nil.
3335 Assume point is at the beginning of the timestamp."
3336 (when (org-looking-at-p org-element--timestamp-regexp)
3337 (save-excursion
3338 (let* ((begin (point))
3339 (activep (eq (char-after) ?<))
3340 (raw-value
3341 (progn
3342 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3343 (match-string-no-properties 0)))
3344 (date-start (match-string-no-properties 1))
3345 (date-end (match-string 3))
3346 (diaryp (match-beginning 2))
3347 (post-blank (progn (goto-char (match-end 0))
3348 (skip-chars-forward " \t")))
3349 (end (point))
3350 (time-range
3351 (and (not diaryp)
3352 (string-match
3353 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3354 date-start)
3355 (cons (string-to-number (match-string 2 date-start))
3356 (string-to-number (match-string 3 date-start)))))
3357 (type (cond (diaryp 'diary)
3358 ((and activep (or date-end time-range)) 'active-range)
3359 (activep 'active)
3360 ((or date-end time-range) 'inactive-range)
3361 (t 'inactive)))
3362 (repeater-props
3363 (and (not diaryp)
3364 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3365 raw-value)
3366 (list
3367 :repeater-type
3368 (let ((type (match-string 1 raw-value)))
3369 (cond ((equal "++" type) 'catch-up)
3370 ((equal ".+" type) 'restart)
3371 (t 'cumulate)))
3372 :repeater-value (string-to-number (match-string 2 raw-value))
3373 :repeater-unit
3374 (case (string-to-char (match-string 3 raw-value))
3375 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3376 (warning-props
3377 (and (not diaryp)
3378 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3379 (list
3380 :warning-type (if (match-string 1 raw-value) 'first 'all)
3381 :warning-value (string-to-number (match-string 2 raw-value))
3382 :warning-unit
3383 (case (string-to-char (match-string 3 raw-value))
3384 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3385 year-start month-start day-start hour-start minute-start year-end
3386 month-end day-end hour-end minute-end)
3387 ;; Parse date-start.
3388 (unless diaryp
3389 (let ((date (org-parse-time-string date-start t)))
3390 (setq year-start (nth 5 date)
3391 month-start (nth 4 date)
3392 day-start (nth 3 date)
3393 hour-start (nth 2 date)
3394 minute-start (nth 1 date))))
3395 ;; Compute date-end. It can be provided directly in time-stamp,
3396 ;; or extracted from time range. Otherwise, it defaults to the
3397 ;; same values as date-start.
3398 (unless diaryp
3399 (let ((date (and date-end (org-parse-time-string date-end t))))
3400 (setq year-end (or (nth 5 date) year-start)
3401 month-end (or (nth 4 date) month-start)
3402 day-end (or (nth 3 date) day-start)
3403 hour-end (or (nth 2 date) (car time-range) hour-start)
3404 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3405 (list 'timestamp
3406 (nconc (list :type type
3407 :raw-value raw-value
3408 :year-start year-start
3409 :month-start month-start
3410 :day-start day-start
3411 :hour-start hour-start
3412 :minute-start minute-start
3413 :year-end year-end
3414 :month-end month-end
3415 :day-end day-end
3416 :hour-end hour-end
3417 :minute-end minute-end
3418 :begin begin
3419 :end end
3420 :post-blank post-blank)
3421 repeater-props
3422 warning-props))))))
3424 (defun org-element-timestamp-interpreter (timestamp contents)
3425 "Interpret TIMESTAMP object as Org syntax.
3426 CONTENTS is nil."
3427 (let* ((repeat-string
3428 (concat
3429 (case (org-element-property :repeater-type timestamp)
3430 (cumulate "+") (catch-up "++") (restart ".+"))
3431 (let ((val (org-element-property :repeater-value timestamp)))
3432 (and val (number-to-string val)))
3433 (case (org-element-property :repeater-unit timestamp)
3434 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3435 (warning-string
3436 (concat
3437 (case (org-element-property :warning-type timestamp)
3438 (first "--")
3439 (all "-"))
3440 (let ((val (org-element-property :warning-value timestamp)))
3441 (and val (number-to-string val)))
3442 (case (org-element-property :warning-unit timestamp)
3443 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3444 (build-ts-string
3445 ;; Build an Org timestamp string from TIME. ACTIVEP is
3446 ;; non-nil when time stamp is active. If WITH-TIME-P is
3447 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3448 ;; specify a time range in the timestamp. REPEAT-STRING is
3449 ;; the repeater string, if any.
3450 (lambda (time activep &optional with-time-p hour-end minute-end)
3451 (let ((ts (format-time-string
3452 (funcall (if with-time-p 'cdr 'car)
3453 org-time-stamp-formats)
3454 time)))
3455 (when (and hour-end minute-end)
3456 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3457 (setq ts
3458 (replace-match
3459 (format "\\&-%02d:%02d" hour-end minute-end)
3460 nil nil ts)))
3461 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3462 (dolist (s (list repeat-string warning-string))
3463 (when (org-string-nw-p s)
3464 (setq ts (concat (substring ts 0 -1)
3467 (substring ts -1)))))
3468 ;; Return value.
3469 ts)))
3470 (type (org-element-property :type timestamp)))
3471 (case type
3472 ((active inactive)
3473 (let* ((minute-start (org-element-property :minute-start timestamp))
3474 (minute-end (org-element-property :minute-end timestamp))
3475 (hour-start (org-element-property :hour-start timestamp))
3476 (hour-end (org-element-property :hour-end timestamp))
3477 (time-range-p (and hour-start hour-end minute-start minute-end
3478 (or (/= hour-start hour-end)
3479 (/= minute-start minute-end)))))
3480 (funcall
3481 build-ts-string
3482 (encode-time 0
3483 (or minute-start 0)
3484 (or hour-start 0)
3485 (org-element-property :day-start timestamp)
3486 (org-element-property :month-start timestamp)
3487 (org-element-property :year-start timestamp))
3488 (eq type 'active)
3489 (and hour-start minute-start)
3490 (and time-range-p hour-end)
3491 (and time-range-p minute-end))))
3492 ((active-range inactive-range)
3493 (let ((minute-start (org-element-property :minute-start timestamp))
3494 (minute-end (org-element-property :minute-end timestamp))
3495 (hour-start (org-element-property :hour-start timestamp))
3496 (hour-end (org-element-property :hour-end timestamp)))
3497 (concat
3498 (funcall
3499 build-ts-string (encode-time
3501 (or minute-start 0)
3502 (or hour-start 0)
3503 (org-element-property :day-start timestamp)
3504 (org-element-property :month-start timestamp)
3505 (org-element-property :year-start timestamp))
3506 (eq type 'active-range)
3507 (and hour-start minute-start))
3508 "--"
3509 (funcall build-ts-string
3510 (encode-time 0
3511 (or minute-end 0)
3512 (or hour-end 0)
3513 (org-element-property :day-end timestamp)
3514 (org-element-property :month-end timestamp)
3515 (org-element-property :year-end timestamp))
3516 (eq type 'active-range)
3517 (and hour-end minute-end))))))))
3520 ;;;; Underline
3522 (defun org-element-underline-parser ()
3523 "Parse underline object at point, if any.
3525 When at an underline object, return a list whose car is
3526 `underline' and cdr is a plist with `:begin', `:end',
3527 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3528 Otherwise, return nil.
3530 Assume point is at the first underscore marker."
3531 (save-excursion
3532 (unless (bolp) (backward-char 1))
3533 (when (looking-at org-emph-re)
3534 (let ((begin (match-beginning 2))
3535 (contents-begin (match-beginning 4))
3536 (contents-end (match-end 4))
3537 (post-blank (progn (goto-char (match-end 2))
3538 (skip-chars-forward " \t")))
3539 (end (point)))
3540 (list 'underline
3541 (list :begin begin
3542 :end end
3543 :contents-begin contents-begin
3544 :contents-end contents-end
3545 :post-blank post-blank))))))
3547 (defun org-element-underline-interpreter (underline contents)
3548 "Interpret UNDERLINE object as Org syntax.
3549 CONTENTS is the contents of the object."
3550 (format "_%s_" contents))
3553 ;;;; Verbatim
3555 (defun org-element-verbatim-parser ()
3556 "Parse verbatim object at point, if any.
3558 When at a verbatim object, return a list whose car is `verbatim'
3559 and cdr is a plist with `:value', `:begin', `:end' and
3560 `:post-blank' keywords. Otherwise, return nil.
3562 Assume point is at the first equal sign marker."
3563 (save-excursion
3564 (unless (bolp) (backward-char 1))
3565 (when (looking-at org-emph-re)
3566 (let ((begin (match-beginning 2))
3567 (value (org-match-string-no-properties 4))
3568 (post-blank (progn (goto-char (match-end 2))
3569 (skip-chars-forward " \t")))
3570 (end (point)))
3571 (list 'verbatim
3572 (list :value value
3573 :begin begin
3574 :end end
3575 :post-blank post-blank))))))
3577 (defun org-element-verbatim-interpreter (verbatim contents)
3578 "Interpret VERBATIM object as Org syntax.
3579 CONTENTS is nil."
3580 (format "=%s=" (org-element-property :value verbatim)))
3584 ;;; Parsing Element Starting At Point
3586 ;; `org-element--current-element' is the core function of this section.
3587 ;; It returns the Lisp representation of the element starting at
3588 ;; point.
3590 ;; `org-element--current-element' makes use of special modes. They
3591 ;; are activated for fixed element chaining (e.g., `plain-list' >
3592 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3593 ;; `section'). Special modes are: `first-section', `item',
3594 ;; `node-property', `section' and `table-row'.
3596 (defun org-element--current-element
3597 (limit &optional granularity special structure)
3598 "Parse the element starting at point.
3600 Return value is a list like (TYPE PROPS) where TYPE is the type
3601 of the element and PROPS a plist of properties associated to the
3602 element.
3604 Possible types are defined in `org-element-all-elements'.
3606 LIMIT bounds the search.
3608 Optional argument GRANULARITY determines the depth of the
3609 recursion. Allowed values are `headline', `greater-element',
3610 `element', `object' or nil. When it is broader than `object' (or
3611 nil), secondary values will not be parsed, since they only
3612 contain objects.
3614 Optional argument SPECIAL, when non-nil, can be either
3615 `first-section', `item', `node-property', `section', and
3616 `table-row'.
3618 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3619 be computed.
3621 This function assumes point is always at the beginning of the
3622 element it has to parse."
3623 (save-excursion
3624 (let ((case-fold-search t)
3625 ;; Determine if parsing depth allows for secondary strings
3626 ;; parsing. It only applies to elements referenced in
3627 ;; `org-element-secondary-value-alist'.
3628 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3629 (cond
3630 ;; Item.
3631 ((eq special 'item)
3632 (org-element-item-parser limit structure raw-secondary-p))
3633 ;; Table Row.
3634 ((eq special 'table-row) (org-element-table-row-parser limit))
3635 ;; Node Property.
3636 ((eq special 'node-property) (org-element-node-property-parser limit))
3637 ;; Headline.
3638 ((org-with-limited-levels (org-at-heading-p))
3639 (org-element-headline-parser limit raw-secondary-p))
3640 ;; Sections (must be checked after headline).
3641 ((eq special 'section) (org-element-section-parser limit))
3642 ((eq special 'first-section)
3643 (org-element-section-parser
3644 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3645 limit)))
3646 ;; When not at bol, point is at the beginning of an item or
3647 ;; a footnote definition: next item is always a paragraph.
3648 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3649 ;; Planning and Clock.
3650 ((looking-at org-planning-or-clock-line-re)
3651 (if (equal (match-string 1) org-clock-string)
3652 (org-element-clock-parser limit)
3653 (org-element-planning-parser limit)))
3654 ;; Inlinetask.
3655 ((org-at-heading-p)
3656 (org-element-inlinetask-parser limit raw-secondary-p))
3657 ;; From there, elements can have affiliated keywords.
3658 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3659 (cond
3660 ;; Jumping over affiliated keywords put point off-limits.
3661 ;; Parse them as regular keywords.
3662 ((and (cdr affiliated) (>= (point) limit))
3663 (goto-char (car affiliated))
3664 (org-element-keyword-parser limit nil))
3665 ;; LaTeX Environment.
3666 ((looking-at
3667 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3668 (org-element-latex-environment-parser limit affiliated))
3669 ;; Drawer and Property Drawer.
3670 ((looking-at org-drawer-regexp)
3671 (if (equal (match-string 1) "PROPERTIES")
3672 (org-element-property-drawer-parser limit affiliated)
3673 (org-element-drawer-parser limit affiliated)))
3674 ;; Fixed Width
3675 ((looking-at "[ \t]*:\\( \\|$\\)")
3676 (org-element-fixed-width-parser limit affiliated))
3677 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3678 ;; Keywords.
3679 ((looking-at "[ \t]*#")
3680 (goto-char (match-end 0))
3681 (cond ((looking-at "\\(?: \\|$\\)")
3682 (beginning-of-line)
3683 (org-element-comment-parser limit affiliated))
3684 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3685 (beginning-of-line)
3686 (let ((parser (assoc (upcase (match-string 1))
3687 org-element-block-name-alist)))
3688 (if parser (funcall (cdr parser) limit affiliated)
3689 (org-element-special-block-parser limit affiliated))))
3690 ((looking-at "\\+CALL:")
3691 (beginning-of-line)
3692 (org-element-babel-call-parser limit affiliated))
3693 ((looking-at "\\+BEGIN:? ")
3694 (beginning-of-line)
3695 (org-element-dynamic-block-parser limit affiliated))
3696 ((looking-at "\\+\\S-+:")
3697 (beginning-of-line)
3698 (org-element-keyword-parser limit affiliated))
3700 (beginning-of-line)
3701 (org-element-paragraph-parser limit affiliated))))
3702 ;; Footnote Definition.
3703 ((looking-at org-footnote-definition-re)
3704 (org-element-footnote-definition-parser limit affiliated))
3705 ;; Horizontal Rule.
3706 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3707 (org-element-horizontal-rule-parser limit affiliated))
3708 ;; Diary Sexp.
3709 ((looking-at "%%(")
3710 (org-element-diary-sexp-parser limit affiliated))
3711 ;; Table.
3712 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3713 ;; List.
3714 ((looking-at (org-item-re))
3715 (org-element-plain-list-parser
3716 limit affiliated
3717 (or structure (org-element--list-struct limit))))
3718 ;; Default element: Paragraph.
3719 (t (org-element-paragraph-parser limit affiliated)))))))))
3722 ;; Most elements can have affiliated keywords. When looking for an
3723 ;; element beginning, we want to move before them, as they belong to
3724 ;; that element, and, in the meantime, collect information they give
3725 ;; into appropriate properties. Hence the following function.
3727 (defun org-element--collect-affiliated-keywords (limit)
3728 "Collect affiliated keywords from point down to LIMIT.
3730 Return a list whose CAR is the position at the first of them and
3731 CDR a plist of keywords and values and move point to the
3732 beginning of the first line after them.
3734 As a special case, if element doesn't start at the beginning of
3735 the line (e.g., a paragraph starting an item), CAR is current
3736 position of point and CDR is nil."
3737 (if (not (bolp)) (list (point))
3738 (let ((case-fold-search t)
3739 (origin (point))
3740 ;; RESTRICT is the list of objects allowed in parsed
3741 ;; keywords value.
3742 (restrict (org-element-restriction 'keyword))
3743 output)
3744 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3745 (let* ((raw-kwd (upcase (match-string 1)))
3746 ;; Apply translation to RAW-KWD. From there, KWD is
3747 ;; the official keyword.
3748 (kwd (or (cdr (assoc raw-kwd
3749 org-element-keyword-translation-alist))
3750 raw-kwd))
3751 ;; Find main value for any keyword.
3752 (value
3753 (save-match-data
3754 (org-trim
3755 (buffer-substring-no-properties
3756 (match-end 0) (point-at-eol)))))
3757 ;; PARSEDP is non-nil when keyword should have its
3758 ;; value parsed.
3759 (parsedp (member kwd org-element-parsed-keywords))
3760 ;; If KWD is a dual keyword, find its secondary
3761 ;; value. Maybe parse it.
3762 (dualp (member kwd org-element-dual-keywords))
3763 (dual-value
3764 (and dualp
3765 (let ((sec (org-match-string-no-properties 2)))
3766 (if (or (not sec) (not parsedp)) sec
3767 (org-element-parse-secondary-string sec restrict)))))
3768 ;; Attribute a property name to KWD.
3769 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3770 ;; Now set final shape for VALUE.
3771 (when parsedp
3772 (setq value (org-element-parse-secondary-string value restrict)))
3773 (when dualp
3774 (setq value (and (or value dual-value) (cons value dual-value))))
3775 (when (or (member kwd org-element-multiple-keywords)
3776 ;; Attributes can always appear on multiple lines.
3777 (string-match "^ATTR_" kwd))
3778 (setq value (cons value (plist-get output kwd-sym))))
3779 ;; Eventually store the new value in OUTPUT.
3780 (setq output (plist-put output kwd-sym value))
3781 ;; Move to next keyword.
3782 (forward-line)))
3783 ;; If affiliated keywords are orphaned: move back to first one.
3784 ;; They will be parsed as a paragraph.
3785 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3786 ;; Return value.
3787 (cons origin output))))
3791 ;;; The Org Parser
3793 ;; The two major functions here are `org-element-parse-buffer', which
3794 ;; parses Org syntax inside the current buffer, taking into account
3795 ;; region, narrowing, or even visibility if specified, and
3796 ;; `org-element-parse-secondary-string', which parses objects within
3797 ;; a given string.
3799 ;; The (almost) almighty `org-element-map' allows to apply a function
3800 ;; on elements or objects matching some type, and accumulate the
3801 ;; resulting values. In an export situation, it also skips unneeded
3802 ;; parts of the parse tree.
3804 (defun org-element-parse-buffer (&optional granularity visible-only)
3805 "Recursively parse the buffer and return structure.
3806 If narrowing is in effect, only parse the visible part of the
3807 buffer.
3809 Optional argument GRANULARITY determines the depth of the
3810 recursion. It can be set to the following symbols:
3812 `headline' Only parse headlines.
3813 `greater-element' Don't recurse into greater elements excepted
3814 headlines and sections. Thus, elements
3815 parsed are the top-level ones.
3816 `element' Parse everything but objects and plain text.
3817 `object' Parse the complete buffer (default).
3819 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3820 elements.
3822 An element or an objects is represented as a list with the
3823 pattern (TYPE PROPERTIES CONTENTS), where :
3825 TYPE is a symbol describing the element or object. See
3826 `org-element-all-elements' and `org-element-all-objects' for an
3827 exhaustive list of such symbols. One can retrieve it with
3828 `org-element-type' function.
3830 PROPERTIES is the list of attributes attached to the element or
3831 object, as a plist. Although most of them are specific to the
3832 element or object type, all types share `:begin', `:end',
3833 `:post-blank' and `:parent' properties, which respectively
3834 refer to buffer position where the element or object starts,
3835 ends, the number of white spaces or blank lines after it, and
3836 the element or object containing it. Properties values can be
3837 obtained by using `org-element-property' function.
3839 CONTENTS is a list of elements, objects or raw strings
3840 contained in the current element or object, when applicable.
3841 One can access them with `org-element-contents' function.
3843 The Org buffer has `org-data' as type and nil as properties.
3844 `org-element-map' function can be used to find specific elements
3845 or objects within the parse tree.
3847 This function assumes that current major mode is `org-mode'."
3848 (save-excursion
3849 (goto-char (point-min))
3850 (org-skip-whitespace)
3851 (org-element--parse-elements
3852 (point-at-bol) (point-max)
3853 ;; Start in `first-section' mode so text before the first
3854 ;; headline belongs to a section.
3855 'first-section nil granularity visible-only (list 'org-data nil))))
3857 (defun org-element-parse-secondary-string (string restriction &optional parent)
3858 "Recursively parse objects in STRING and return structure.
3860 RESTRICTION is a symbol limiting the object types that will be
3861 looked after.
3863 Optional argument PARENT, when non-nil, is the element or object
3864 containing the secondary string. It is used to set correctly
3865 `:parent' property within the string."
3866 ;; Copy buffer-local variables listed in
3867 ;; `org-element-object-variables' into temporary buffer. This is
3868 ;; required since object parsing is dependent on these variables.
3869 (let ((pairs (delq nil (mapcar (lambda (var)
3870 (when (boundp var)
3871 (cons var (symbol-value var))))
3872 org-element-object-variables))))
3873 (with-temp-buffer
3874 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
3875 (insert string)
3876 (let ((secondary (org-element--parse-objects
3877 (point-min) (point-max) nil restriction)))
3878 (when parent
3879 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
3880 secondary))
3881 secondary))))
3883 (defun org-element-map
3884 (data types fun &optional info first-match no-recursion with-affiliated)
3885 "Map a function on selected elements or objects.
3887 DATA is a parse tree, an element, an object, a string, or a list
3888 of such constructs. TYPES is a symbol or list of symbols of
3889 elements or objects types (see `org-element-all-elements' and
3890 `org-element-all-objects' for a complete list of types). FUN is
3891 the function called on the matching element or object. It has to
3892 accept one argument: the element or object itself.
3894 When optional argument INFO is non-nil, it should be a plist
3895 holding export options. In that case, parts of the parse tree
3896 not exportable according to that property list will be skipped.
3898 When optional argument FIRST-MATCH is non-nil, stop at the first
3899 match for which FUN doesn't return nil, and return that value.
3901 Optional argument NO-RECURSION is a symbol or a list of symbols
3902 representing elements or objects types. `org-element-map' won't
3903 enter any recursive element or object whose type belongs to that
3904 list. Though, FUN can still be applied on them.
3906 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3907 apply to matching objects within parsed affiliated keywords (see
3908 `org-element-parsed-keywords').
3910 Nil values returned from FUN do not appear in the results.
3913 Examples:
3914 ---------
3916 Assuming TREE is a variable containing an Org buffer parse tree,
3917 the following example will return a flat list of all `src-block'
3918 and `example-block' elements in it:
3920 \(org-element-map tree '(example-block src-block) 'identity)
3922 The following snippet will find the first headline with a level
3923 of 1 and a \"phone\" tag, and will return its beginning position:
3925 \(org-element-map tree 'headline
3926 \(lambda (hl)
3927 \(and (= (org-element-property :level hl) 1)
3928 \(member \"phone\" (org-element-property :tags hl))
3929 \(org-element-property :begin hl)))
3930 nil t)
3932 The next example will return a flat list of all `plain-list' type
3933 elements in TREE that are not a sub-list themselves:
3935 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3937 Eventually, this example will return a flat list of all `bold'
3938 type objects containing a `latex-snippet' type object, even
3939 looking into captions:
3941 \(org-element-map tree 'bold
3942 \(lambda (b)
3943 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3944 nil nil nil t)"
3945 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3946 (unless (listp types) (setq types (list types)))
3947 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3948 ;; Recursion depth is determined by --CATEGORY.
3949 (let* ((--category
3950 (catch 'found
3951 (let ((category 'greater-elements))
3952 (mapc (lambda (type)
3953 (cond ((or (memq type org-element-all-objects)
3954 (eq type 'plain-text))
3955 ;; If one object is found, the function
3956 ;; has to recurse into every object.
3957 (throw 'found 'objects))
3958 ((not (memq type org-element-greater-elements))
3959 ;; If one regular element is found, the
3960 ;; function has to recurse, at least,
3961 ;; into every element it encounters.
3962 (and (not (eq category 'elements))
3963 (setq category 'elements)))))
3964 types)
3965 category)))
3966 ;; Compute properties for affiliated keywords if necessary.
3967 (--affiliated-alist
3968 (and with-affiliated
3969 (mapcar (lambda (kwd)
3970 (cons kwd (intern (concat ":" (downcase kwd)))))
3971 org-element-affiliated-keywords)))
3972 --acc
3973 --walk-tree
3974 (--walk-tree
3975 (function
3976 (lambda (--data)
3977 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3978 ;; holding contextual information.
3979 (let ((--type (org-element-type --data)))
3980 (cond
3981 ((not --data))
3982 ;; Ignored element in an export context.
3983 ((and info (memq --data (plist-get info :ignore-list))))
3984 ;; List of elements or objects.
3985 ((not --type) (mapc --walk-tree --data))
3986 ;; Unconditionally enter parse trees.
3987 ((eq --type 'org-data)
3988 (mapc --walk-tree (org-element-contents --data)))
3990 ;; Check if TYPE is matching among TYPES. If so,
3991 ;; apply FUN to --DATA and accumulate return value
3992 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3993 (when (memq --type types)
3994 (let ((result (funcall fun --data)))
3995 (cond ((not result))
3996 (first-match (throw '--map-first-match result))
3997 (t (push result --acc)))))
3998 ;; If --DATA has a secondary string that can contain
3999 ;; objects with their type among TYPES, look into it.
4000 (when (and (eq --category 'objects) (not (stringp --data)))
4001 (let ((sec-prop
4002 (assq --type org-element-secondary-value-alist)))
4003 (when sec-prop
4004 (funcall --walk-tree
4005 (org-element-property (cdr sec-prop) --data)))))
4006 ;; If --DATA has any affiliated keywords and
4007 ;; WITH-AFFILIATED is non-nil, look for objects in
4008 ;; them.
4009 (when (and with-affiliated
4010 (eq --category 'objects)
4011 (memq --type org-element-all-elements))
4012 (mapc (lambda (kwd-pair)
4013 (let ((kwd (car kwd-pair))
4014 (value (org-element-property
4015 (cdr kwd-pair) --data)))
4016 ;; Pay attention to the type of value.
4017 ;; Preserve order for multiple keywords.
4018 (cond
4019 ((not value))
4020 ((and (member kwd org-element-multiple-keywords)
4021 (member kwd org-element-dual-keywords))
4022 (mapc (lambda (line)
4023 (funcall --walk-tree (cdr line))
4024 (funcall --walk-tree (car line)))
4025 (reverse value)))
4026 ((member kwd org-element-multiple-keywords)
4027 (mapc (lambda (line) (funcall --walk-tree line))
4028 (reverse value)))
4029 ((member kwd org-element-dual-keywords)
4030 (funcall --walk-tree (cdr value))
4031 (funcall --walk-tree (car value)))
4032 (t (funcall --walk-tree value)))))
4033 --affiliated-alist))
4034 ;; Determine if a recursion into --DATA is possible.
4035 (cond
4036 ;; --TYPE is explicitly removed from recursion.
4037 ((memq --type no-recursion))
4038 ;; --DATA has no contents.
4039 ((not (org-element-contents --data)))
4040 ;; Looking for greater elements but --DATA is simply
4041 ;; an element or an object.
4042 ((and (eq --category 'greater-elements)
4043 (not (memq --type org-element-greater-elements))))
4044 ;; Looking for elements but --DATA is an object.
4045 ((and (eq --category 'elements)
4046 (memq --type org-element-all-objects)))
4047 ;; In any other case, map contents.
4048 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4049 (catch '--map-first-match
4050 (funcall --walk-tree data)
4051 ;; Return value in a proper order.
4052 (nreverse --acc))))
4053 (put 'org-element-map 'lisp-indent-function 2)
4055 ;; The following functions are internal parts of the parser.
4057 ;; The first one, `org-element--parse-elements' acts at the element's
4058 ;; level.
4060 ;; The second one, `org-element--parse-objects' applies on all objects
4061 ;; of a paragraph or a secondary string.
4063 ;; More precisely, that function looks for every allowed object type
4064 ;; first. Then, it discards failed searches, keeps further matches,
4065 ;; and searches again types matched behind point, for subsequent
4066 ;; calls. Thus, searching for a given type fails only once, and every
4067 ;; object is searched only once at top level (but sometimes more for
4068 ;; nested types).
4070 (defun org-element--parse-elements
4071 (beg end special structure granularity visible-only acc)
4072 "Parse elements between BEG and END positions.
4074 SPECIAL prioritize some elements over the others. It can be set
4075 to `first-section', `section' `item' or `table-row'.
4077 When value is `item', STRUCTURE will be used as the current list
4078 structure.
4080 GRANULARITY determines the depth of the recursion. See
4081 `org-element-parse-buffer' for more information.
4083 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4084 elements.
4086 Elements are accumulated into ACC."
4087 (save-excursion
4088 (goto-char beg)
4089 ;; Visible only: skip invisible parts at the beginning of the
4090 ;; element.
4091 (when (and visible-only (org-invisible-p2))
4092 (goto-char (min (1+ (org-find-visible)) end)))
4093 ;; When parsing only headlines, skip any text before first one.
4094 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4095 (org-with-limited-levels (outline-next-heading)))
4096 ;; Main loop start.
4097 (while (< (point) end)
4098 ;; Find current element's type and parse it accordingly to
4099 ;; its category.
4100 (let* ((element (org-element--current-element
4101 end granularity special structure))
4102 (type (org-element-type element))
4103 (cbeg (org-element-property :contents-begin element)))
4104 (goto-char (org-element-property :end element))
4105 ;; Visible only: skip invisible parts between siblings.
4106 (when (and visible-only (org-invisible-p2))
4107 (goto-char (min (1+ (org-find-visible)) end)))
4108 ;; Fill ELEMENT contents by side-effect.
4109 (cond
4110 ;; If element has no contents, don't modify it.
4111 ((not cbeg))
4112 ;; Greater element: parse it between `contents-begin' and
4113 ;; `contents-end'. Make sure GRANULARITY allows the
4114 ;; recursion, or ELEMENT is a headline, in which case going
4115 ;; inside is mandatory, in order to get sub-level headings.
4116 ((and (memq type org-element-greater-elements)
4117 (or (memq granularity '(element object nil))
4118 (and (eq granularity 'greater-element)
4119 (eq type 'section))
4120 (eq type 'headline)))
4121 (org-element--parse-elements
4122 cbeg (org-element-property :contents-end element)
4123 ;; Possibly switch to a special mode.
4124 (case type
4125 (headline 'section)
4126 (plain-list 'item)
4127 (property-drawer 'node-property)
4128 (table 'table-row))
4129 (and (memq type '(item plain-list))
4130 (org-element-property :structure element))
4131 granularity visible-only element))
4132 ;; ELEMENT has contents. Parse objects inside, if
4133 ;; GRANULARITY allows it.
4134 ((memq granularity '(object nil))
4135 (org-element--parse-objects
4136 cbeg (org-element-property :contents-end element) element
4137 (org-element-restriction type))))
4138 (org-element-adopt-elements acc element)))
4139 ;; Return result.
4140 acc))
4142 (defconst org-element--object-regexp
4143 (mapconcat #'identity
4144 (let ((link-types (regexp-opt org-link-types)))
4145 (list
4146 ;; Sub/superscript.
4147 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4148 ;; Bold, code, italic, strike-through, underline and
4149 ;; verbatim.
4150 (concat "[*~=+_/]"
4151 (format "[^%s]" (nth 2 org-emphasis-regexp-components)))
4152 ;; Plain links.
4153 (concat "\\<" link-types ":")
4154 ;; Objects starting with "[": regular link, footnote
4155 ;; reference, statistics cookie, timestamp (inactive).
4156 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4157 ;; Objects starting with "@": export snippets.
4158 "@@"
4159 ;; Objects starting with "{": macro.
4160 "{{{"
4161 ;; Objects starting with "<" : timestamp (active,
4162 ;; diary), target, radio target and angular links.
4163 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
4164 ;; Objects starting with "$": latex fragment.
4165 "\\$"
4166 ;; Objects starting with "\": line break, entity,
4167 ;; latex fragment.
4168 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4169 ;; Objects starting with raw text: inline Babel
4170 ;; source block, inline Babel call.
4171 "\\(?:call\\|src\\)_"))
4172 "\\|")
4173 "Regexp possibly matching the beginning of an object.
4174 This regexp allows false positives. Dedicated parser (e.g.,
4175 `org-export-bold-parser') will take care of further filtering.
4176 Radio links are not matched by this regexp, as they are treated
4177 specially in `org-element--object-lex'.")
4179 (defun org-element--object-lex (restriction)
4180 "Return next object in current buffer or nil.
4181 RESTRICTION is a list of object types, as symbols, that should be
4182 looked after. This function assumes that the buffer is narrowed
4183 to an appropriate container (e.g., a paragraph)."
4184 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4185 (save-excursion
4186 (let ((limit (and org-target-link-regexp
4187 (save-excursion
4188 (re-search-forward org-target-link-regexp nil t))
4189 (match-beginning 0)))
4190 found)
4191 (while (and (not found)
4192 (re-search-forward org-element--object-regexp limit t))
4193 (goto-char (match-beginning 0))
4194 (let ((result (match-string 0)))
4195 (setq found
4196 (cond
4197 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4198 (and (memq 'inline-babel-call restriction)
4199 (org-element-inline-babel-call-parser)))
4200 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4201 (and (memq 'inline-src-block restriction)
4202 (org-element-inline-src-block-parser)))
4204 (case (char-after)
4205 (?^ (and (memq 'superscript restriction)
4206 (org-element-superscript-parser)))
4207 (?_ (or (and (memq 'subscript restriction)
4208 (org-element-subscript-parser))
4209 (and (memq 'underline restriction)
4210 (org-element-underline-parser))))
4211 (?* (and (memq 'bold restriction)
4212 (org-element-bold-parser)))
4213 (?/ (and (memq 'italic restriction)
4214 (org-element-italic-parser)))
4215 (?~ (and (memq 'code restriction)
4216 (org-element-code-parser)))
4217 (?= (and (memq 'verbatim restriction)
4218 (org-element-verbatim-parser)))
4219 (?+ (and (memq 'strike-through restriction)
4220 (org-element-strike-through-parser)))
4221 (?@ (and (memq 'export-snippet restriction)
4222 (org-element-export-snippet-parser)))
4223 (?{ (and (memq 'macro restriction)
4224 (org-element-macro-parser)))
4225 (?$ (and (memq 'latex-fragment restriction)
4226 (org-element-latex-fragment-parser)))
4228 (if (eq (aref result 1) ?<)
4229 (or (and (memq 'radio-target restriction)
4230 (org-element-radio-target-parser))
4231 (and (memq 'target restriction)
4232 (org-element-target-parser)))
4233 (or (and (memq 'timestamp restriction)
4234 (org-element-timestamp-parser))
4235 (and (memq 'link restriction)
4236 (org-element-link-parser)))))
4237 (?\\ (or (and (memq 'line-break restriction)
4238 (org-element-line-break-parser))
4239 (and (memq 'entity restriction)
4240 (org-element-entity-parser))
4241 (and (memq 'latex-fragment restriction)
4242 (org-element-latex-fragment-parser))))
4243 (?\[
4244 (if (eq (aref result 1) ?\[)
4245 (and (memq 'link restriction)
4246 (org-element-link-parser))
4247 (or (and (memq 'footnote-reference restriction)
4248 (org-element-footnote-reference-parser))
4249 (and (memq 'timestamp restriction)
4250 (org-element-timestamp-parser))
4251 (and (memq 'statistics-cookie restriction)
4252 (org-element-statistics-cookie-parser)))))
4253 ;; This is probably a plain link.
4254 (otherwise (and (or (memq 'link restriction)
4255 (memq 'plain-link restriction))
4256 (org-element-link-parser)))))))
4257 (or (eobp) (forward-char))))
4258 (cond (found)
4259 ;; Radio link.
4260 ((and limit (memq 'link restriction))
4261 (goto-char limit) (org-element-link-parser)))))))
4263 (defun org-element--parse-objects (beg end acc restriction)
4264 "Parse objects between BEG and END and return recursive structure.
4266 Objects are accumulated in ACC.
4268 RESTRICTION is a list of object successors which are allowed in
4269 the current object."
4270 (save-excursion
4271 (save-restriction
4272 (narrow-to-region beg end)
4273 (goto-char (point-min))
4274 (let (next-object)
4275 (while (and (not (eobp))
4276 (setq next-object (org-element--object-lex restriction)))
4277 ;; 1. Text before any object. Untabify it.
4278 (let ((obj-beg (org-element-property :begin next-object)))
4279 (unless (= (point) obj-beg)
4280 (setq acc
4281 (org-element-adopt-elements
4283 (replace-regexp-in-string
4284 "\t" (make-string tab-width ? )
4285 (buffer-substring-no-properties (point) obj-beg))))))
4286 ;; 2. Object...
4287 (let ((obj-end (org-element-property :end next-object))
4288 (cont-beg (org-element-property :contents-begin next-object)))
4289 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4290 ;; a recursive type.
4291 (when (and cont-beg
4292 (memq (car next-object) org-element-recursive-objects))
4293 (org-element--parse-objects
4294 cont-beg (org-element-property :contents-end next-object)
4295 next-object (org-element-restriction next-object)))
4296 (setq acc (org-element-adopt-elements acc next-object))
4297 (goto-char obj-end))))
4298 ;; 3. Text after last object. Untabify it.
4299 (unless (eobp)
4300 (setq acc
4301 (org-element-adopt-elements
4303 (replace-regexp-in-string
4304 "\t" (make-string tab-width ? )
4305 (buffer-substring-no-properties (point) end)))))
4306 ;; Result.
4307 acc)))
4311 ;;; Towards A Bijective Process
4313 ;; The parse tree obtained with `org-element-parse-buffer' is really
4314 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4315 ;; interpreted and expanded into a string with canonical Org syntax.
4316 ;; Hence `org-element-interpret-data'.
4318 ;; The function relies internally on
4319 ;; `org-element--interpret-affiliated-keywords'.
4321 ;;;###autoload
4322 (defun org-element-interpret-data (data &optional pseudo-objects)
4323 "Interpret DATA as Org syntax.
4325 DATA is a parse tree, an element, an object or a secondary string
4326 to interpret.
4328 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4329 new types that should be treated as objects. An unknown type not
4330 belonging to this list is seen as a pseudo-element instead. Both
4331 pseudo-objects and pseudo-elements are transparent entities, i.e.
4332 only their contents are interpreted.
4334 Return Org syntax as a string."
4335 (org-element--interpret-data-1 data nil pseudo-objects))
4337 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4338 "Interpret DATA as Org syntax.
4340 DATA is a parse tree, an element, an object or a secondary string
4341 to interpret. PARENT is used for recursive calls. It contains
4342 the element or object containing data, or nil. PSEUDO-OBJECTS
4343 are list of symbols defining new element or object types.
4344 Unknown types that don't belong to this list are treated as
4345 pseudo-elements instead.
4347 Return Org syntax as a string."
4348 (let* ((type (org-element-type data))
4349 ;; Find interpreter for current object or element. If it
4350 ;; doesn't exist (e.g. this is a pseudo object or element),
4351 ;; return contents, if any.
4352 (interpret
4353 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4354 (if (fboundp fun) fun (lambda (data contents) contents))))
4355 (results
4356 (cond
4357 ;; Secondary string.
4358 ((not type)
4359 (mapconcat
4360 (lambda (obj)
4361 (org-element--interpret-data-1 obj parent pseudo-objects))
4362 data ""))
4363 ;; Full Org document.
4364 ((eq type 'org-data)
4365 (mapconcat
4366 (lambda (obj)
4367 (org-element--interpret-data-1 obj parent pseudo-objects))
4368 (org-element-contents data) ""))
4369 ;; Plain text: return it.
4370 ((stringp data) data)
4371 ;; Element or object without contents.
4372 ((not (org-element-contents data)) (funcall interpret data nil))
4373 ;; Element or object with contents.
4375 (funcall interpret data
4376 ;; Recursively interpret contents.
4377 (mapconcat
4378 (lambda (obj)
4379 (org-element--interpret-data-1 obj data pseudo-objects))
4380 (org-element-contents
4381 (if (not (memq type '(paragraph verse-block)))
4382 data
4383 ;; Fix indentation of elements containing
4384 ;; objects. We ignore `table-row' elements
4385 ;; as they are one line long anyway.
4386 (org-element-normalize-contents
4387 data
4388 ;; When normalizing first paragraph of an
4389 ;; item or a footnote-definition, ignore
4390 ;; first line's indentation.
4391 (and (eq type 'paragraph)
4392 (equal data (car (org-element-contents parent)))
4393 (memq (org-element-type parent)
4394 '(footnote-definition item))))))
4395 ""))))))
4396 (if (memq type '(org-data plain-text nil)) results
4397 ;; Build white spaces. If no `:post-blank' property is
4398 ;; specified, assume its value is 0.
4399 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4400 (if (or (memq type org-element-all-objects)
4401 (memq type pseudo-objects))
4402 (concat results (make-string post-blank ?\s))
4403 (concat
4404 (org-element--interpret-affiliated-keywords data)
4405 (org-element-normalize-string results)
4406 (make-string post-blank ?\n)))))))
4408 (defun org-element--interpret-affiliated-keywords (element)
4409 "Return ELEMENT's affiliated keywords as Org syntax.
4410 If there is no affiliated keyword, return the empty string."
4411 (let ((keyword-to-org
4412 (function
4413 (lambda (key value)
4414 (let (dual)
4415 (when (member key org-element-dual-keywords)
4416 (setq dual (cdr value) value (car value)))
4417 (concat "#+" key
4418 (and dual
4419 (format "[%s]" (org-element-interpret-data dual)))
4420 ": "
4421 (if (member key org-element-parsed-keywords)
4422 (org-element-interpret-data value)
4423 value)
4424 "\n"))))))
4425 (mapconcat
4426 (lambda (prop)
4427 (let ((value (org-element-property prop element))
4428 (keyword (upcase (substring (symbol-name prop) 1))))
4429 (when value
4430 (if (or (member keyword org-element-multiple-keywords)
4431 ;; All attribute keywords can have multiple lines.
4432 (string-match "^ATTR_" keyword))
4433 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4434 (reverse value)
4436 (funcall keyword-to-org keyword value)))))
4437 ;; List all ELEMENT's properties matching an attribute line or an
4438 ;; affiliated keyword, but ignore translated keywords since they
4439 ;; cannot belong to the property list.
4440 (loop for prop in (nth 1 element) by 'cddr
4441 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4442 (or (string-match "^ATTR_" keyword)
4443 (and
4444 (member keyword org-element-affiliated-keywords)
4445 (not (assoc keyword
4446 org-element-keyword-translation-alist)))))
4447 collect prop)
4448 "")))
4450 ;; Because interpretation of the parse tree must return the same
4451 ;; number of blank lines between elements and the same number of white
4452 ;; space after objects, some special care must be given to white
4453 ;; spaces.
4455 ;; The first function, `org-element-normalize-string', ensures any
4456 ;; string different from the empty string will end with a single
4457 ;; newline character.
4459 ;; The second function, `org-element-normalize-contents', removes
4460 ;; global indentation from the contents of the current element.
4462 (defun org-element-normalize-string (s)
4463 "Ensure string S ends with a single newline character.
4465 If S isn't a string return it unchanged. If S is the empty
4466 string, return it. Otherwise, return a new string with a single
4467 newline character at its end."
4468 (cond
4469 ((not (stringp s)) s)
4470 ((string= "" s) "")
4471 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4472 (replace-match "\n" nil nil s)))))
4474 (defun org-element-normalize-contents (element &optional ignore-first)
4475 "Normalize plain text in ELEMENT's contents.
4477 ELEMENT must only contain plain text and objects.
4479 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4480 indentation to compute maximal common indentation.
4482 Return the normalized element that is element with global
4483 indentation removed from its contents. The function assumes that
4484 indentation is not done with TAB characters."
4485 (let* ((min-ind most-positive-fixnum)
4486 find-min-ind ; For byte-compiler.
4487 (find-min-ind
4488 (function
4489 ;; Return minimal common indentation within BLOB. This is
4490 ;; done by walking recursively BLOB and updating MIN-IND
4491 ;; along the way. FIRST-FLAG is non-nil when the first
4492 ;; string hasn't been seen yet. It is required as this
4493 ;; string is the only one whose indentation doesn't happen
4494 ;; after a newline character.
4495 (lambda (blob first-flag)
4496 (dolist (object (org-element-contents blob))
4497 (when (and first-flag (stringp object))
4498 (setq first-flag nil)
4499 (string-match "\\`\\( *\\)" object)
4500 (let ((len (length (match-string 1 object))))
4501 ;; An indentation of zero means no string will be
4502 ;; modified. Quit the process.
4503 (if (zerop len) (throw 'zero (setq min-ind 0))
4504 (setq min-ind (min len min-ind)))))
4505 (cond
4506 ((stringp object)
4507 (dolist (line (delq "" (cdr (org-split-string object " *\n"))))
4508 (setq min-ind (min (org-get-indentation line) min-ind))))
4509 ((memq (org-element-type object) org-element-recursive-objects)
4510 (funcall find-min-ind object first-flag))))))))
4511 ;; Find minimal indentation in ELEMENT.
4512 (catch 'zero (funcall find-min-ind element (not ignore-first)))
4513 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4514 ;; Build ELEMENT back, replacing each string with the same
4515 ;; string minus common indentation.
4516 (let* (build ; For byte compiler.
4517 (build
4518 (function
4519 (lambda (blob first-flag)
4520 ;; Return BLOB with all its strings indentation
4521 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4522 ;; is non-nil when the first string hasn't been seen
4523 ;; yet.
4524 (setcdr (cdr blob)
4525 (mapcar
4526 #'(lambda (object)
4527 (when (and first-flag (stringp object))
4528 (setq first-flag nil)
4529 (setq object
4530 (replace-regexp-in-string
4531 (format "\\` \\{%d\\}" min-ind)
4532 "" object)))
4533 (cond
4534 ((stringp object)
4535 (replace-regexp-in-string
4536 (format "\n \\{%d\\}" min-ind) "\n" object))
4537 ((memq (org-element-type object)
4538 org-element-recursive-objects)
4539 (funcall build object first-flag))
4540 (t object)))
4541 (org-element-contents blob)))
4542 blob))))
4543 (funcall build element (not ignore-first))))))
4547 ;;; Cache
4549 ;; Implement a caching mechanism for `org-element-at-point' and
4550 ;; `org-element-context', which see.
4552 ;; A single public function is provided: `org-element-cache-reset'.
4554 ;; Cache is enabled by default, but can be disabled globally with
4555 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4556 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4557 ;; can be tweaked to control caching behaviour.
4559 ;; Internally, parsed elements are stored in an AVL tree,
4560 ;; `org-element--cache'. This tree is updated lazily: whenever
4561 ;; a change happens to the buffer, a synchronization request is
4562 ;; registered in `org-element--cache-sync-requests' (see
4563 ;; `org-element--cache-submit-request'). During idle time, requests
4564 ;; are processed by `org-element--cache-sync'. Synchronization also
4565 ;; happens when an element is required from the cache. In this case,
4566 ;; the process stops as soon as the needed element is up-to-date.
4568 ;; A synchronization request can only apply on a synchronized part of
4569 ;; the cache. Therefore, the cache is updated at least to the
4570 ;; location where the new request applies. Thus, requests are ordered
4571 ;; from left to right and all elements starting before the first
4572 ;; request are correct. This property is used by functions like
4573 ;; `org-element--cache-find' to retrieve elements in the part of the
4574 ;; cache that can be trusted.
4576 ;; A request applies to every element, starting from its original
4577 ;; location (or key, see below). When a request is processed, it
4578 ;; moves forward and may collide the next one. In this case, both
4579 ;; requests are merged into a new one that starts from that element.
4580 ;; As a consequence, the whole synchronization complexity does not
4581 ;; depend on the number of pending requests, but on the number of
4582 ;; elements the very first request will be applied on.
4584 ;; Elements cannot be accessed through their beginning position, which
4585 ;; may or may not be up-to-date. Instead, each element in the tree is
4586 ;; associated to a key, obtained with `org-element--cache-key'. This
4587 ;; mechanism is robust enough to preserve total order among elements
4588 ;; even when the tree is only partially synchronized.
4590 ;; Objects contained in an element are stored in a hash table,
4591 ;; `org-element--cache-objects'.
4594 (defvar org-element-use-cache t
4595 "Non nil when Org parser should cache its results.
4596 This is mostly for debugging purpose.")
4598 (defvar org-element-cache-sync-idle-time 0.4
4599 "Length, in seconds, of idle time before syncing cache.")
4601 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4602 "Maximum duration, as a time value, for a cache synchronization.
4603 If the synchronization is not over after this delay, the process
4604 pauses and resumes after `org-element-cache-sync-break'
4605 seconds.")
4607 (defvar org-element-cache-sync-break (seconds-to-time 0.2)
4608 "Duration, as a time value, of the pause between synchronizations.
4609 See `org-element-cache-sync-duration' for more information.")
4612 ;;;; Data Structure
4614 (defvar org-element--cache nil
4615 "AVL tree used to cache elements.
4616 Each node of the tree contains an element. Comparison is done
4617 with `org-element--cache-compare'. This cache is used in
4618 `org-element-at-point'.")
4620 (defvar org-element--cache-objects nil
4621 "Hash table used as to cache objects.
4622 Key is an element, as returned by `org-element-at-point', and
4623 value is an alist where each association is:
4625 \(PARENT COMPLETEP . OBJECTS)
4627 where PARENT is an element or object, COMPLETEP is a boolean,
4628 non-nil when all direct children of parent are already cached and
4629 OBJECTS is a list of such children, as objects, from farthest to
4630 closest.
4632 In the following example, \\alpha, bold object and \\beta are
4633 contained within a paragraph
4635 \\alpha *\\beta*
4637 If the paragraph is completely parsed, OBJECTS-DATA will be
4639 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4640 \(BOLD-OBJECT t ENTITY-OBJECT))
4642 whereas in a partially parsed paragraph, it could be
4644 \((PARAGRAPH nil ENTITY-OBJECT))
4646 This cache is used in `org-element-context'.")
4648 (defvar org-element--cache-sync-requests nil
4649 "List of pending synchronization requests.
4651 A request is a vector with the following pattern:
4653 \[NEXT END OFFSET PARENT PHASE]
4655 Processing a synchronization request consists in three phases:
4657 0. Delete modified elements,
4658 1. Fill missing area in cache,
4659 2. Shift positions and re-parent elements after the changes.
4661 During phase 0, NEXT is the key of the first element to be
4662 removed and END is buffer position delimiting the modifications.
4663 Every element starting between these are removed. PARENT is an
4664 element to be removed. Every element contained in it will also
4665 be removed.
4667 During phase 1, NEXT is the key of the next known element in
4668 cache. Parse buffer between that element and the one before it
4669 in order to determine the parent of the next element. Set PARENT
4670 to the element containing NEXT.
4672 During phase 2, NEXT is the key of the next element to shift in
4673 the parse tree. All elements starting from this one have their
4674 properties relatives to buffer positions shifted by integer
4675 OFFSET and, if they belong to element PARENT, are adopted by it.
4677 PHASE specifies the phase number, as an integer.")
4679 (defvar org-element--cache-sync-timer nil
4680 "Timer used for cache synchronization.")
4682 (defvar org-element--cache-sync-keys nil
4683 "Hash table used to store keys during synchronization.
4684 See `org-element--cache-key' for more information.")
4686 (defsubst org-element--cache-key (element)
4687 "Return a unique key for ELEMENT in cache tree.
4689 Keys are used to keep a total order among elements in the cache.
4690 Comparison is done with `org-element--cache-key-less-p'.
4692 When no synchronization is taking place, a key is simply the
4693 beginning position of the element, or that position plus one in
4694 the case of an first item (respectively row) in
4695 a list (respectively a table).
4697 During a synchronization, the key is the one the element had when
4698 the cache was synchronized for the last time. Elements added to
4699 cache during the synchronization get a new key generated with
4700 `org-element--cache-generate-key'.
4702 Such keys are stored in `org-element--cache-sync-keys'. The hash
4703 table is cleared once the synchronization is complete."
4704 (or (gethash element org-element--cache-sync-keys)
4705 (let* ((begin (org-element-property :begin element))
4706 ;; Increase beginning position of items (respectively
4707 ;; table rows) by one, so the first item can get
4708 ;; a different key from its parent list (respectively
4709 ;; table).
4710 (key (if (memq (org-element-type element) '(item table-row))
4711 (1+ begin)
4712 begin)))
4713 (if org-element--cache-sync-requests
4714 (puthash element key org-element--cache-sync-keys)
4715 key))))
4717 (defconst org-element--cache-default-key (ash most-positive-fixnum -1)
4718 "Default value for a new key level.
4719 See `org-element--cache-generate-key' for more information.")
4721 (defun org-element--cache-generate-key (lower upper)
4722 "Generate a key between LOWER and UPPER.
4724 LOWER and UPPER are integers or lists, possibly empty.
4726 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4727 a unique key, as an integer or a list of integers, according to
4728 the following rules:
4730 - LOWER and UPPER are compared level-wise until values differ.
4732 - If, at a given level, LOWER and UPPER differ from more than
4733 2, the new key shares all the levels above with LOWER and
4734 gets a new level. Its value is the mean between LOWER and
4735 UPPER.
4737 \(1 2) + (1 4) --> (1 3)
4739 - If LOWER has no value to compare with, it is assumed that its
4740 value is 0:
4742 \(1 1) + (1 1 2) --> (1 1 1)
4744 Likewise, if UPPER is short of levels, the current value is
4745 `most-positive-fixnum'.
4747 - If they differ from only one, the new key inherits from
4748 current LOWER lever and has a new level at the value
4749 `org-element--cache-default-key'.
4751 \(1 2) + (1 3) --> (1 2 org-element--cache-default-key)
4753 - If the key is only one level long, it is returned as an
4754 integer.
4756 \(1 2) + (3 2) --> 2"
4757 (if (equal lower upper) lower
4758 (let ((lower (if (integerp lower) (list lower) lower))
4759 (upper (if (integerp upper) (list upper) upper))
4760 key)
4761 (catch 'exit
4762 (while (and lower upper)
4763 (let ((lower-level (car lower))
4764 (upper-level (car upper)))
4765 (cond
4766 ((= lower-level upper-level)
4767 (push lower-level key)
4768 (setq lower (cdr lower) upper (cdr upper)))
4769 ((= (- upper-level lower-level) 1)
4770 (push lower-level key)
4771 (setq lower (cdr lower))
4772 (while (and lower (= (car lower) most-positive-fixnum))
4773 (push most-positive-fixnum key)
4774 (setq lower (cdr lower)))
4775 (push (if lower
4776 (let ((n (car lower)))
4777 (+ (ash (if (zerop (mod n 2)) n (1+ n)) -1)
4778 org-element--cache-default-key))
4779 org-element--cache-default-key)
4780 key)
4781 (throw 'exit t))
4783 (push (let ((n (car lower)))
4784 (+ (ash (if (zerop (mod n 2)) n (1+ n)) -1)
4785 (ash (car upper) -1)))
4786 key)
4787 (throw 'exit t)))))
4788 (cond
4789 ((not lower)
4790 (while (and upper (zerop (car upper)))
4791 (push 0 key)
4792 (setq upper (cdr upper)))
4793 ;; (n) is equivalent to (n 0 0 0 0 ...) so we want to avoid
4794 ;; ending on a sequence of 0.
4795 (if (= (car upper) 1)
4796 (progn (push 0 key)
4797 (push org-element--cache-default-key key))
4798 (push (if upper (ash (car upper) -1) org-element--cache-default-key)
4799 key)))
4800 ((not upper)
4801 (while (and lower (= (car lower) most-positive-fixnum))
4802 (push most-positive-fixnum key)
4803 (setq lower (cdr lower)))
4804 (push (if lower
4805 (let ((n (car lower)))
4806 (+ (ash (if (zerop (mod n 2)) n (1+ n)) -1)
4807 org-element--cache-default-key))
4808 org-element--cache-default-key)
4809 key))))
4810 ;; Ensure we don't return a list with a single element.
4811 (if (cdr key) (nreverse key) (car key)))))
4813 (defsubst org-element--cache-key-less-p (a b)
4814 "Non-nil if key A is less than key B.
4815 A and B are either integers or lists of integers, as returned by
4816 `org-element--cache-key'."
4817 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4818 (if (integerp b) (< (car a) b)
4819 (catch 'exit
4820 (while (and a b)
4821 (cond ((car-less-than-car a b) (throw 'exit t))
4822 ((car-less-than-car b a) (throw 'exit nil))
4823 (t (setq a (cdr a) b (cdr b)))))
4824 ;; If A is empty, either keys are equal (B is also empty) or
4825 ;; B is less than A (B is longer). Therefore return nil.
4827 ;; If A is not empty, B is necessarily empty and A is less
4828 ;; than B (A is longer). Therefore, return a non-nil value.
4829 a))))
4831 (defun org-element--cache-compare (a b)
4832 "Non-nil when element A is located before element B."
4833 (org-element--cache-key-less-p (org-element--cache-key a)
4834 (org-element--cache-key b)))
4836 (defsubst org-element--cache-root ()
4837 "Return root value in cache.
4838 This function assumes `org-element--cache' is a valid AVL tree."
4839 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4842 ;;;; Tools
4844 (defsubst org-element--cache-active-p ()
4845 "Non-nil when cache is active in current buffer."
4846 (and org-element-use-cache
4847 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4849 (defun org-element--cache-find (pos &optional side)
4850 "Find element in cache starting at POS or before.
4852 POS refers to a buffer position.
4854 When optional argument SIDE is non-nil, the function checks for
4855 elements starting at or past POS instead. If SIDE is `both', the
4856 function returns a cons cell where car is the first element
4857 starting at or before POS and cdr the first element starting
4858 after POS.
4860 The function can only find elements in the synchronized part of
4861 the cache."
4862 (let ((limit (and org-element--cache-sync-requests
4863 (aref (car org-element--cache-sync-requests) 0)))
4864 (node (org-element--cache-root))
4865 lower upper)
4866 (while node
4867 (let* ((element (avl-tree--node-data node))
4868 (begin (org-element-property :begin element)))
4869 (cond
4870 ((and limit
4871 (not (org-element--cache-key-less-p
4872 (org-element--cache-key element) limit)))
4873 (setq node (avl-tree--node-left node)))
4874 ((> begin pos)
4875 (setq upper element
4876 node (avl-tree--node-left node)))
4877 ((< begin pos)
4878 (setq lower element
4879 node (avl-tree--node-right node)))
4880 ;; We found an element in cache starting at POS. If `side'
4881 ;; is `both' we also want the next one in order to generate
4882 ;; a key in-between.
4884 ;; If the element is the first row or item in a table or
4885 ;; a plain list, we always return the table or the plain
4886 ;; list.
4888 ;; In any other case, we return the element found.
4889 ((eq side 'both)
4890 (setq lower element)
4891 (setq node (avl-tree--node-right node)))
4892 ((and (memq (org-element-type element) '(item table-row))
4893 (let ((parent (org-element-property :parent element)))
4894 (and (= (org-element-property :begin element)
4895 (org-element-property :contents-begin parent))
4896 (setq node nil
4897 lower parent
4898 upper parent)))))
4900 (setq node nil
4901 lower element
4902 upper element)))))
4903 (case side
4904 (both (cons lower upper))
4905 ((nil) lower)
4906 (otherwise upper))))
4908 (defun org-element--cache-put (element &optional data)
4909 "Store ELEMENT in current buffer's cache, if allowed.
4910 When optional argument DATA is non-nil, assume is it object data
4911 relative to ELEMENT and store it in the objects cache."
4912 (cond ((not (org-element--cache-active-p)) nil)
4913 ((not data)
4914 (when org-element--cache-sync-requests
4915 ;; During synchronization, first build an appropriate key
4916 ;; for the new element so `avl-tree-enter' can insert it at
4917 ;; the right spot in the cache.
4918 (let ((keys (org-element--cache-find
4919 (org-element-property :begin element) 'both)))
4920 (puthash element
4921 (org-element--cache-generate-key
4922 (and (car keys) (org-element--cache-key (car keys)))
4923 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4924 (org-element--cache-sync-requests
4925 (aref (car org-element--cache-sync-requests) 0))))
4926 org-element--cache-sync-keys)))
4927 (avl-tree-enter org-element--cache element))
4928 ;; Headlines are not stored in cache, so objects in titles are
4929 ;; not stored either.
4930 ((eq (org-element-type element) 'headline) nil)
4931 (t (puthash element data org-element--cache-objects))))
4934 ;;;; Synchronization
4936 (defsubst org-element--cache-set-timer (buffer)
4937 "Set idle timer for cache synchronization in BUFFER."
4938 (when org-element--cache-sync-timer
4939 (cancel-timer org-element--cache-sync-timer))
4940 (setq org-element--cache-sync-timer
4941 (run-with-idle-timer
4942 (let ((idle (current-idle-time)))
4943 (if idle (time-add idle org-element-cache-sync-break)
4944 org-element-cache-sync-idle-time))
4946 #'org-element--cache-sync
4947 buffer)))
4949 (defsubst org-element--cache-interrupt-p (time-limit)
4950 "Non-nil when synchronization process should be interrupted.
4951 TIME-LIMIT is a time value or nil."
4952 (and time-limit
4953 (or (input-pending-p)
4954 (time-less-p time-limit (current-time)))))
4956 (defsubst org-element--cache-shift-positions (element offset &optional props)
4957 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4959 Properties containing buffer positions are `:begin', `:end',
4960 `:contents-begin', `:contents-end' and `:structure'. When
4961 optional argument PROPS is a list of keywords, only shift
4962 properties provided in that list.
4964 Properties are modified by side-effect."
4965 (let ((properties (nth 1 element)))
4966 ;; Shift `:structure' property for the first plain list only: it
4967 ;; is the only one that really matters and it prevents from
4968 ;; shifting it more than once.
4969 (when (and (or (not props) (memq :structure props))
4970 (eq (org-element-type element) 'plain-list)
4971 (not (eq (org-element-type (plist-get properties :parent))
4972 'item)))
4973 (dolist (item (plist-get properties :structure))
4974 (incf (car item) offset)
4975 (incf (nth 6 item) offset)))
4976 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
4977 (let ((value (and (or (not props) (memq key props))
4978 (plist-get properties key))))
4979 (and value (plist-put properties key (+ offset value)))))))
4981 (defun org-element--cache-sync (buffer &optional threshold)
4982 "Synchronize cache with recent modification in BUFFER.
4983 When optional argument THRESHOLD is non-nil, do the
4984 synchronization for all elements starting before or at threshold,
4985 then exit. Otherwise, synchronize cache for as long as
4986 `org-element-cache-sync-duration' or until Emacs leaves idle
4987 state."
4988 (when (buffer-live-p buffer)
4989 (with-current-buffer buffer
4990 (let ((inhibit-quit t) request next)
4991 (when org-element--cache-sync-timer
4992 (cancel-timer org-element--cache-sync-timer))
4993 (catch 'interrupt
4994 (while org-element--cache-sync-requests
4995 (setq request (car org-element--cache-sync-requests)
4996 next (nth 1 org-element--cache-sync-requests))
4997 (or (org-element--cache-process-request
4998 request
4999 (and next (aref next 0))
5000 threshold
5001 (and (not threshold)
5002 (time-add (current-time)
5003 org-element-cache-sync-duration)))
5004 (throw 'interrupt t))
5005 ;; Request processed. Merge current and next offsets and
5006 ;; transfer phase number and ending position.
5007 (when next
5008 (incf (aref next 2) (aref request 2))
5009 (aset next 1 (aref request 1))
5010 (aset next 4 (aref request 4)))
5011 (setq org-element--cache-sync-requests
5012 (cdr org-element--cache-sync-requests))))
5013 ;; If more requests are awaiting, set idle timer accordingly.
5014 ;; Otherwise, reset keys.
5015 (if org-element--cache-sync-requests
5016 (org-element--cache-set-timer buffer)
5017 (clrhash org-element--cache-sync-keys))))))
5019 (defun org-element--cache-process-request (request next threshold time-limit)
5020 "Process synchronization REQUEST for all entries before NEXT.
5022 REQUEST is a vector, built by `org-element--cache-submit-request'.
5024 NEXT is a cache key, as returned by `org-element--cache-key'.
5026 When non-nil, THRESHOLD is a buffer position. Synchronization
5027 stops as soon as a shifted element begins after it.
5029 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5030 after this time or when Emacs exits idle state.
5032 Return nil if the process stops before completing the request,
5033 t otherwise."
5034 (catch 'quit
5035 (when (= (aref request 4) 0)
5036 ;; Phase 1.
5038 ;; Delete all elements starting after BEG, but not after buffer
5039 ;; position END or past element with key NEXT.
5041 ;; As an exception, also delete elements starting after
5042 ;; modifications but included in an element altered by
5043 ;; modifications (orphans).
5045 ;; At each iteration, we start again at tree root since
5046 ;; a deletion modifies structure of the balanced tree.
5047 (catch 'end-phase
5048 (let ((beg (aref request 0))
5049 (end (aref request 1))
5050 (deleted-parent (aref request 3)))
5051 (while t
5052 (when (org-element--cache-interrupt-p time-limit)
5053 (aset request 3 deleted-parent)
5054 (throw 'quit nil))
5055 ;; Find first element in cache with key BEG or after it.
5056 ;; We don't use `org-element--cache-find' because it
5057 ;; couldn't reach orphaned elements past NEXT. Moreover,
5058 ;; BEG is a key, not a buffer position.
5059 (let ((node (org-element--cache-root)) data data-key)
5060 (while node
5061 (let* ((element (avl-tree--node-data node))
5062 (key (org-element--cache-key element)))
5063 (cond
5064 ((org-element--cache-key-less-p key beg)
5065 (setq node (avl-tree--node-right node)))
5066 ((org-element--cache-key-less-p beg key)
5067 (setq data element
5068 data-key key
5069 node (avl-tree--node-left node)))
5070 (t (setq data element
5071 data-key key
5072 node nil)))))
5073 (if (not data) (throw 'quit t)
5074 (let ((pos (org-element-property :begin data)))
5075 (cond
5076 ;; Remove orphaned elements.
5077 ((and deleted-parent
5078 (let ((up data))
5079 (while (and
5080 (setq up (org-element-property :parent up))
5081 (not (eq up deleted-parent))))
5082 up))
5083 (avl-tree-delete org-element--cache data))
5084 ((or (and next
5085 (not (org-element--cache-key-less-p data-key
5086 next)))
5087 (> pos end))
5088 (aset request 0 data-key)
5089 (aset request 1 pos)
5090 (aset request 4 1)
5091 (throw 'end-phase nil))
5092 (t (avl-tree-delete org-element--cache data)
5093 (when (= (org-element-property :end data) end)
5094 (setq deleted-parent data)))))))))))
5095 (when (= (aref request 4) 1)
5096 ;; Phase 2.
5098 ;; Phase 1 left a hole in the parse tree. Some elements after
5099 ;; it could have parents within. For example, in the following
5100 ;; buffer:
5103 ;; - item
5106 ;; Paragraph1
5108 ;; Paragraph2
5111 ;; if we remove a blank line between "item" and "Paragraph1",
5112 ;; everything down to "Paragraph2" is removed from cache. But
5113 ;; the paragraph now belongs to the list, and its `:parent'
5114 ;; property no longer is accurate.
5116 ;; Therefore we need to parse again elements in the hole, or at
5117 ;; least in its last section, so that we can re-parent
5118 ;; subsequent elements, during phase 3.
5120 ;; Note that we only need to get the parent from the first
5121 ;; element in cache after the hole.
5123 ;; Also, this part can be delayed if we don't need to retrieve
5124 ;; an element after the hole.
5125 (catch 'end-phase
5126 ;; Next element will start at its beginning position plus
5127 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5128 ;; contains the real beginning position of the first element
5129 ;; to shift and re-parent.
5130 (when (equal (aref request 0) next) (throw 'quit t))
5131 (let ((limit (+ (aref request 1) (aref request 2))))
5132 (when (and threshold (< threshold limit)) (throw 'quit nil))
5133 (let ((parent (org-element--parse-to limit t time-limit)))
5134 (if (eq parent 'interrupted) (throw 'quit nil)
5135 (aset request 3 parent)
5136 (aset request 4 2)
5137 (throw 'end-phase nil))))))
5138 ;; Phase 3.
5140 ;; Shift all elements starting from key START, but before NEXT, by
5141 ;; OFFSET, and re-parent them when appropriate.
5143 ;; Elements are modified by side-effect so the tree structure
5144 ;; remains intact.
5146 ;; Once THRESHOLD, if any, is reached, or once there is an input
5147 ;; pending, exit. Before leaving, the current synchronization
5148 ;; request is updated.
5149 (let ((start (aref request 0))
5150 (offset (aref request 2))
5151 (parent (aref request 3))
5152 (node (org-element--cache-root))
5153 (stack (list nil))
5154 (leftp t)
5155 exit-flag)
5156 ;; No re-parenting nor shifting planned: request is over.
5157 (when (and (not parent) (zerop offset)) (throw 'quit t))
5158 (while node
5159 (let* ((data (avl-tree--node-data node))
5160 (key (org-element--cache-key data)))
5161 (if (and leftp (avl-tree--node-left node)
5162 (not (org-element--cache-key-less-p key start)))
5163 (progn (push node stack)
5164 (setq node (avl-tree--node-left node)))
5165 (unless (org-element--cache-key-less-p key start)
5166 ;; We reached NEXT. Request is complete.
5167 (when (equal key next) (throw 'quit t))
5168 ;; Handle interruption request. Update current request.
5169 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5170 (aset request 0 key)
5171 (aset request 3 parent)
5172 (throw 'quit nil))
5173 ;; Shift element.
5174 (unless (zerop offset)
5175 (org-element--cache-shift-positions data offset)
5176 ;; Shift associated objects data, if any.
5177 (dolist (object-data (gethash data org-element--cache-objects))
5178 (dolist (object (cddr object-data))
5179 (org-element--cache-shift-positions object offset))))
5180 (let ((begin (org-element-property :begin data)))
5181 ;; Re-parent it.
5182 (while (and parent
5183 (<= (org-element-property :end parent) begin))
5184 (setq parent (org-element-property :parent parent)))
5185 (cond (parent (org-element-put-property data :parent parent))
5186 ((zerop offset) (throw 'quit t)))
5187 ;; Cache is up-to-date past THRESHOLD. Request
5188 ;; interruption.
5189 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5190 (setq node (if (setq leftp (avl-tree--node-right node))
5191 (avl-tree--node-right node)
5192 (pop stack))))))
5193 ;; We reached end of tree: synchronization complete.
5194 t)))
5196 (defun org-element--parse-to (pos &optional syncp time-limit)
5197 "Parse elements in current section, down to POS.
5199 Start parsing from the closest between the last known element in
5200 cache or headline above. Return the smallest element containing
5201 POS.
5203 When optional argument SYNCP is non-nil, return the parent of the
5204 element containing POS instead. In that case, it is also
5205 possible to provide TIME-LIMIT, which is a time value specifying
5206 when the parsing should stop. The function returns `interrupted'
5207 if the process stopped before finding the expected result."
5208 (catch 'exit
5209 (org-with-wide-buffer
5210 (goto-char pos)
5211 (let* ((cached (and (org-element--cache-active-p)
5212 (org-element--cache-find pos nil)))
5213 (begin (org-element-property :begin cached))
5214 element next)
5215 (cond
5216 ;; Nothing in cache before point: start parsing from first
5217 ;; element following headline above, or first element in
5218 ;; buffer.
5219 ((not cached)
5220 (when (org-with-limited-levels (outline-previous-heading))
5221 (forward-line))
5222 (skip-chars-forward " \r\t\n")
5223 (beginning-of-line))
5224 ;; Cache returned exact match: return it.
5225 ((= pos begin)
5226 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5227 ;; There's a headline between cached value and POS: cached
5228 ;; value is invalid. Start parsing from first element
5229 ;; following the headline.
5230 ((re-search-backward
5231 (org-with-limited-levels org-outline-regexp-bol) begin t)
5232 (forward-line)
5233 (skip-chars-forward " \r\t\n")
5234 (beginning-of-line))
5235 ;; Check if CACHED or any of its ancestors contain point.
5237 ;; If there is such an element, we inspect it in order to know
5238 ;; if we return it or if we need to parse its contents.
5239 ;; Otherwise, we just start parsing from current location,
5240 ;; which is right after the top-most element containing
5241 ;; CACHED.
5243 ;; As a special case, if POS is at the end of the buffer, we
5244 ;; want to return the innermost element ending there.
5246 ;; Also, if we find an ancestor and discover that we need to
5247 ;; parse its contents, make sure we don't start from
5248 ;; `:contents-begin', as we would otherwise go past CACHED
5249 ;; again. Instead, in that situation, we will resume parsing
5250 ;; from NEXT, which is located after CACHED or its higher
5251 ;; ancestor not containing point.
5253 (let ((up cached)
5254 (pos (if (= (point-max) pos) (1- pos) pos)))
5255 (goto-char (or (org-element-property :contents-begin cached) begin))
5256 (while (let ((end (org-element-property :end up)))
5257 (and (<= end pos)
5258 (goto-char end)
5259 (setq up (org-element-property :parent up)))))
5260 (cond ((not up))
5261 ((eobp) (setq element up))
5262 (t (setq element up next (point)))))))
5263 ;; Parse successively each element until we reach POS.
5264 (let ((end (or (org-element-property :end element)
5265 (save-excursion
5266 (org-with-limited-levels (outline-next-heading))
5267 (point))))
5268 (parent element)
5269 special-flag)
5270 (while t
5271 (when syncp
5272 (cond ((= (point) pos) (throw 'exit parent))
5273 ((org-element--cache-interrupt-p time-limit)
5274 (throw 'exit 'interrupted))))
5275 (unless element
5276 (setq element (org-element--current-element
5277 end 'element special-flag
5278 (org-element-property :structure parent)))
5279 (org-element-put-property element :parent parent)
5280 (org-element--cache-put element))
5281 (let ((elem-end (org-element-property :end element))
5282 (type (org-element-type element)))
5283 (cond
5284 ;; Skip any element ending before point. Also skip
5285 ;; element ending at point (unless it is also the end of
5286 ;; buffer) since we're sure that another element begins
5287 ;; after it.
5288 ((and (<= elem-end pos) (/= (point-max) elem-end))
5289 (goto-char elem-end))
5290 ;; A non-greater element contains point: return it.
5291 ((not (memq type org-element-greater-elements))
5292 (throw 'exit element))
5293 ;; Otherwise, we have to decide if ELEMENT really
5294 ;; contains POS. In that case we start parsing from
5295 ;; contents' beginning.
5297 ;; If POS is at contents' beginning but it is also at
5298 ;; the beginning of the first item in a list or a table.
5299 ;; In that case, we need to create an anchor for that
5300 ;; list or table, so return it.
5302 ;; Also, if POS is at the end of the buffer, no element
5303 ;; can start after it, but more than one may end there.
5304 ;; Arbitrarily, we choose to return the innermost of
5305 ;; such elements.
5306 ((let ((cbeg (org-element-property :contents-begin element))
5307 (cend (org-element-property :contents-end element)))
5308 (when (or syncp
5309 (and cbeg cend
5310 (or (< cbeg pos)
5311 (and (= cbeg pos)
5312 (not (memq type '(plain-list table)))))
5313 (or (> cend pos)
5314 (and (= cend pos) (= (point-max) pos)))))
5315 (goto-char (or next cbeg))
5316 (setq next nil
5317 special-flag (case type
5318 (plain-list 'item)
5319 (property-drawer 'node-property)
5320 (table 'table-row))
5321 parent element
5322 end cend))))
5323 ;; Otherwise, return ELEMENT as it is the smallest
5324 ;; element containing POS.
5325 (t (throw 'exit element))))
5326 (setq element nil)))))))
5329 ;;;; Staging Buffer Changes
5331 (defconst org-element--cache-opening-line
5332 (concat "^[ \t]*\\(?:"
5333 "#\\+BEGIN[:_]" "\\|"
5334 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
5335 ":\\S-+:[ \t]*$"
5336 "\\)")
5337 "Regexp matching an element opening line.
5338 When such a line is modified, modifications may propagate after
5339 modified area. In that situation, every element between that
5340 area and next section is removed from cache.")
5342 (defconst org-element--cache-closing-line
5343 (concat "^[ \t]*\\(?:"
5344 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
5345 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
5346 ":END:[ \t]*$"
5347 "\\)")
5348 "Regexp matching an element closing line.
5349 When such a line is modified, modifications may propagate before
5350 modified area. In that situation, every element between that
5351 area and previous section is removed from cache.")
5353 (defvar org-element--cache-change-warning nil
5354 "Non-nil when a sensitive line is about to be changed.
5355 It is a symbol among nil, t and `headline'.")
5357 (defun org-element--cache-before-change (beg end)
5358 "Request extension of area going to be modified if needed.
5359 BEG and END are the beginning and end of the range of changed
5360 text. See `before-change-functions' for more information."
5361 (let ((inhibit-quit t))
5362 ;; Make sure buffer positions in cache are correct until END.
5363 (save-match-data
5364 (org-element--cache-sync (current-buffer) end)
5365 (org-with-wide-buffer
5366 (goto-char beg)
5367 (beginning-of-line)
5368 (let ((top (point))
5369 (bottom (save-excursion (goto-char end) (line-end-position)))
5370 (sensitive-re
5371 ;; A sensitive line is a headline or a block (or drawer,
5372 ;; or latex-environment) boundary. Inserting one can
5373 ;; modify buffer drastically both above and below that
5374 ;; line, possibly making cache invalid. Therefore, we
5375 ;; need to pay attention to changes happening to them.
5376 (concat
5377 "\\(" (org-with-limited-levels org-outline-regexp-bol) "\\)" "\\|"
5378 org-element--cache-closing-line "\\|"
5379 org-element--cache-opening-line)))
5380 (setq org-element--cache-change-warning
5381 (cond ((not (re-search-forward sensitive-re bottom t)) nil)
5382 ((and (match-beginning 1)
5383 (progn (goto-char bottom)
5384 (or (not (re-search-backward sensitive-re
5385 (match-end 1) t))
5386 (match-beginning 1))))
5387 'headline)
5388 (t))))))))
5390 (defun org-element--cache-after-change (beg end pre)
5391 "Update buffer modifications for current buffer.
5392 BEG and END are the beginning and end of the range of changed
5393 text, and the length in bytes of the pre-change text replaced by
5394 that range. See `after-change-functions' for more information."
5395 (let ((inhibit-quit t))
5396 (when (org-element--cache-active-p)
5397 (org-with-wide-buffer
5398 (goto-char beg)
5399 (beginning-of-line)
5400 (let ((top (point))
5401 (bottom (save-excursion (goto-char end) (line-end-position))))
5402 (org-with-limited-levels
5403 (save-match-data
5404 ;; Determine if modified area needs to be extended,
5405 ;; according to both previous and current state. We make
5406 ;; a special case for headline editing: if a headline is
5407 ;; modified but not removed, do not extend.
5408 (when (let ((previous-state org-element--cache-change-warning)
5409 (sensitive-re
5410 (concat "\\(" org-outline-regexp-bol "\\)" "\\|"
5411 org-element--cache-closing-line "\\|"
5412 org-element--cache-opening-line))
5413 (case-fold-search t))
5414 (cond ((eq previous-state t))
5415 ((not (re-search-forward sensitive-re bottom t))
5416 (eq previous-state 'headline))
5417 ((match-beginning 1)
5418 (or (not (eq previous-state 'headline))
5419 (and (progn (goto-char bottom)
5420 (re-search-backward
5421 sensitive-re (match-end 1) t))
5422 (not (match-beginning 1)))))
5423 (t)))
5424 ;; Effectively extend modified area.
5425 (setq top (progn (goto-char top)
5426 (when (outline-previous-heading) (forward-line))
5427 (point)))
5428 (setq bottom (progn (goto-char bottom)
5429 (if (outline-next-heading) (1- (point))
5430 (point)))))))
5431 ;; Store synchronization request.
5432 (let ((offset (- end beg pre)))
5433 (org-element--cache-submit-request top (- bottom offset) offset))))
5434 ;; Activate a timer to process the request during idle time.
5435 (org-element--cache-set-timer (current-buffer)))))
5437 (defun org-element--cache-submit-request (beg end offset)
5438 "Submit a new cache synchronization request for current buffer.
5439 BEG and END are buffer positions delimiting the minimal area
5440 where cache data should be removed. OFFSET is the size of the
5441 change, as an integer."
5442 (let ((first-element
5443 ;; Find the position of the first element in cache to remove.
5445 ;; Partially modified elements will be removed during request
5446 ;; processing. As an exception, greater elements around the
5447 ;; changes that are robust to contents modifications are
5448 ;; preserved.
5450 ;; We look just before BEG because an element ending at BEG
5451 ;; needs to be removed too.
5452 (let* ((elements (org-element--cache-find (1- beg) 'both))
5453 (before (car elements))
5454 (after (cdr elements)))
5455 (if (not before) after
5456 (let ((up before))
5457 (while (setq up (org-element-property :parent up))
5458 (if (and (memq (org-element-type up)
5459 '(center-block
5460 drawer dynamic-block inlinetask
5461 property-drawer quote-block special-block))
5462 (<= (org-element-property :contents-begin up) beg)
5463 (> (org-element-property :contents-end up) end))
5464 ;; UP is a greater element that is wrapped around
5465 ;; the changes. We only need to extend its
5466 ;; ending boundaries and those of all its
5467 ;; parents.
5468 (while up
5469 (org-element--cache-shift-positions
5470 up offset '(:contents-end :end))
5471 (setq up (org-element-property :parent up)))
5472 (setq before up)))
5473 ;; We're at top level element containing ELEMENT: if
5474 ;; it's altered by buffer modifications, it is first
5475 ;; element in cache to be removed. Otherwise, that
5476 ;; first element is the following one.
5477 (if (< (org-element-property :end before) beg) after before))))))
5478 (cond
5479 ;; Changes happened before the first known element. Shift the
5480 ;; rest of the cache.
5481 ((and first-element (> (org-element-property :begin first-element) end))
5482 (push (vector (org-element--cache-key first-element) nil offset nil 2)
5483 org-element--cache-sync-requests))
5484 ;; There is at least an element to remove. Find position past
5485 ;; every element containing END.
5486 (first-element
5487 (if (> (org-element-property :end first-element) end)
5488 (setq end (org-element-property :end first-element))
5489 (let ((element (org-element--cache-find end)))
5490 (setq end (org-element-property :end element))
5491 (let ((up element))
5492 (while (and (setq up (org-element-property :parent up))
5493 (>= (org-element-property :begin up) beg))
5494 (setq end (org-element-property :end up))))))
5495 (push (vector (org-element--cache-key first-element) end offset nil 0)
5496 org-element--cache-sync-requests))
5497 ;; No element to remove. No need to re-parent either. Simply
5498 ;; shift additional elements, if any, by OFFSET.
5499 (org-element--cache-sync-requests
5500 (incf (aref (car org-element--cache-sync-requests) 2) offset)))))
5503 ;;;; Public Functions
5505 ;;;###autoload
5506 (defun org-element-cache-reset (&optional all)
5507 "Reset cache in current buffer.
5508 When optional argument ALL is non-nil, reset cache in all Org
5509 buffers. This function will do nothing if
5510 `org-element-use-cache' is nil."
5511 (interactive "P")
5512 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5513 (with-current-buffer buffer
5514 (when (org-element--cache-active-p)
5515 (org-set-local 'org-element--cache
5516 (avl-tree-create #'org-element--cache-compare))
5517 (org-set-local 'org-element--cache-objects
5518 (make-hash-table :weakness 'key :test #'eq))
5519 (org-set-local 'org-element--cache-sync-keys
5520 (make-hash-table :weakness 'key :test #'eq))
5521 (org-set-local 'org-element--cache-change-warning nil)
5522 (org-set-local 'org-element--cache-sync-requests nil)
5523 (org-set-local 'org-element--cache-sync-timer nil)
5524 (add-hook 'before-change-functions
5525 #'org-element--cache-before-change nil t)
5526 (add-hook 'after-change-functions
5527 #'org-element--cache-after-change nil t)))))
5531 ;;; The Toolbox
5533 ;; The first move is to implement a way to obtain the smallest element
5534 ;; containing point. This is the job of `org-element-at-point'. It
5535 ;; basically jumps back to the beginning of section containing point
5536 ;; and proceed, one element after the other, with
5537 ;; `org-element--current-element' until the container is found. Note:
5538 ;; When using `org-element-at-point', secondary values are never
5539 ;; parsed since the function focuses on elements, not on objects.
5541 ;; At a deeper level, `org-element-context' lists all elements and
5542 ;; objects containing point.
5544 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5545 ;; internally by navigation and manipulation tools.
5548 ;;;###autoload
5549 (defun org-element-at-point ()
5550 "Determine closest element around point.
5552 Return value is a list like (TYPE PROPS) where TYPE is the type
5553 of the element and PROPS a plist of properties associated to the
5554 element.
5556 Possible types are defined in `org-element-all-elements'.
5557 Properties depend on element or object type, but always include
5558 `:begin', `:end', `:parent' and `:post-blank' properties.
5560 As a special case, if point is at the very beginning of the first
5561 item in a list or sub-list, returned element will be that list
5562 instead of the item. Likewise, if point is at the beginning of
5563 the first row of a table, returned element will be the table
5564 instead of the first row.
5566 When point is at the end of the buffer, return the innermost
5567 element ending there."
5568 (org-with-wide-buffer
5569 (let ((origin (point)))
5570 (end-of-line)
5571 (skip-chars-backward " \r\t\n")
5572 (cond
5573 ;; Within blank lines at the beginning of buffer, return nil.
5574 ((bobp) nil)
5575 ;; Within blank lines right after a headline, return that
5576 ;; headline.
5577 ((org-with-limited-levels (org-at-heading-p))
5578 (beginning-of-line)
5579 (org-element-headline-parser (point-max) t))
5580 ;; Otherwise parse until we find element containing ORIGIN.
5582 (when (org-element--cache-active-p)
5583 (if (not org-element--cache) (org-element-cache-reset)
5584 (org-element--cache-sync (current-buffer) origin)))
5585 (org-element--parse-to origin))))))
5587 ;;;###autoload
5588 (defun org-element-context (&optional element)
5589 "Return smallest element or object around point.
5591 Return value is a list like (TYPE PROPS) where TYPE is the type
5592 of the element or object and PROPS a plist of properties
5593 associated to it.
5595 Possible types are defined in `org-element-all-elements' and
5596 `org-element-all-objects'. Properties depend on element or
5597 object type, but always include `:begin', `:end', `:parent' and
5598 `:post-blank'.
5600 As a special case, if point is right after an object and not at
5601 the beginning of any other object, return that object.
5603 Optional argument ELEMENT, when non-nil, is the closest element
5604 containing point, as returned by `org-element-at-point'.
5605 Providing it allows for quicker computation."
5606 (catch 'objects-forbidden
5607 (org-with-wide-buffer
5608 (let* ((pos (point))
5609 (element (or element (org-element-at-point)))
5610 (type (org-element-type element)))
5611 ;; If point is inside an element containing objects or
5612 ;; a secondary string, narrow buffer to the container and
5613 ;; proceed with parsing. Otherwise, return ELEMENT.
5614 (cond
5615 ;; At a parsed affiliated keyword, check if we're inside main
5616 ;; or dual value.
5617 ((let ((post (org-element-property :post-affiliated element)))
5618 (and post (< pos post)))
5619 (beginning-of-line)
5620 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5621 (cond
5622 ((not (member-ignore-case (match-string 1)
5623 org-element-parsed-keywords))
5624 (throw 'objects-forbidden element))
5625 ((< (match-end 0) pos)
5626 (narrow-to-region (match-end 0) (line-end-position)))
5627 ((and (match-beginning 2)
5628 (>= pos (match-beginning 2))
5629 (< pos (match-end 2)))
5630 (narrow-to-region (match-beginning 2) (match-end 2)))
5631 (t (throw 'objects-forbidden element)))
5632 ;; Also change type to retrieve correct restrictions.
5633 (setq type 'keyword))
5634 ;; At an item, objects can only be located within tag, if any.
5635 ((eq type 'item)
5636 (let ((tag (org-element-property :tag element)))
5637 (if (not tag) (throw 'objects-forbidden element)
5638 (beginning-of-line)
5639 (search-forward tag (line-end-position))
5640 (goto-char (match-beginning 0))
5641 (if (and (>= pos (point)) (< pos (match-end 0)))
5642 (narrow-to-region (point) (match-end 0))
5643 (throw 'objects-forbidden element)))))
5644 ;; At an headline or inlinetask, objects are in title.
5645 ((memq type '(headline inlinetask))
5646 (goto-char (org-element-property :begin element))
5647 (skip-chars-forward "*")
5648 (if (and (> pos (point)) (< pos (line-end-position)))
5649 (narrow-to-region (point) (line-end-position))
5650 (throw 'objects-forbidden element)))
5651 ;; At a paragraph, a table-row or a verse block, objects are
5652 ;; located within their contents.
5653 ((memq type '(paragraph table-row verse-block))
5654 (let ((cbeg (org-element-property :contents-begin element))
5655 (cend (org-element-property :contents-end element)))
5656 ;; CBEG is nil for table rules.
5657 (if (and cbeg cend (>= pos cbeg)
5658 (or (< pos cend) (and (= pos cend) (eobp))))
5659 (narrow-to-region cbeg cend)
5660 (throw 'objects-forbidden element))))
5661 ;; At a parsed keyword, objects are located within value.
5662 ((eq type 'keyword)
5663 (if (not (member (org-element-property :key element)
5664 org-element-document-properties))
5665 (throw 'objects-forbidden element)
5666 (beginning-of-line)
5667 (search-forward ":")
5668 (if (and (>= pos (point)) (< pos (line-end-position)))
5669 (narrow-to-region (point) (line-end-position))
5670 (throw 'objects-forbidden element))))
5671 ;; At a planning line, if point is at a timestamp, return it,
5672 ;; otherwise, return element.
5673 ((eq type 'planning)
5674 (dolist (p '(:closed :deadline :scheduled))
5675 (let ((timestamp (org-element-property p element)))
5676 (when (and timestamp
5677 (<= (org-element-property :begin timestamp) pos)
5678 (> (org-element-property :end timestamp) pos))
5679 (throw 'objects-forbidden timestamp))))
5680 ;; All other locations cannot contain objects: bail out.
5681 (throw 'objects-forbidden element))
5682 (t (throw 'objects-forbidden element)))
5683 (goto-char (point-min))
5684 (let ((restriction (org-element-restriction type))
5685 (parent element)
5686 (cache (cond ((not (org-element--cache-active-p)) nil)
5687 (org-element--cache-objects
5688 (gethash element org-element--cache-objects))
5689 (t (org-element-cache-reset) nil)))
5690 next object-data last)
5691 (prog1
5692 (catch 'exit
5693 (while t
5694 ;; When entering PARENT for the first time, get list
5695 ;; of objects within known so far. Store it in
5696 ;; OBJECT-DATA.
5697 (unless next
5698 (let ((data (assq parent cache)))
5699 (if data (setq object-data data)
5700 (push (setq object-data (list parent nil)) cache))))
5701 ;; Find NEXT object for analysis.
5702 (catch 'found
5703 ;; If NEXT is non-nil, we already exhausted the
5704 ;; cache so we can parse buffer to find the object
5705 ;; after it.
5706 (if next (setq next (org-element--object-lex restriction))
5707 ;; Otherwise, check if cache can help us.
5708 (let ((objects (cddr object-data))
5709 (completep (nth 1 object-data)))
5710 (cond
5711 ((and (not objects) completep) (throw 'exit parent))
5712 ((not objects)
5713 (setq next (org-element--object-lex restriction)))
5715 (let ((cache-limit
5716 (org-element-property :end (car objects))))
5717 (if (>= cache-limit pos)
5718 ;; Cache contains the information needed.
5719 (dolist (object objects (throw 'exit parent))
5720 (when (<= (org-element-property :begin object)
5721 pos)
5722 (if (>= (org-element-property :end object)
5723 pos)
5724 (throw 'found (setq next object))
5725 (throw 'exit parent))))
5726 (goto-char cache-limit)
5727 (setq next
5728 (org-element--object-lex restriction))))))))
5729 ;; If we have a new object to analyze, store it in
5730 ;; cache. Otherwise record that there is nothing
5731 ;; more to parse in this element at this depth.
5732 (if next
5733 (progn (org-element-put-property next :parent parent)
5734 (push next (cddr object-data)))
5735 (setcar (cdr object-data) t)))
5736 ;; Process NEXT, if any, in order to know if we need
5737 ;; to skip it, return it or move into it.
5738 (if (or (not next) (> (org-element-property :begin next) pos))
5739 (throw 'exit (or last parent))
5740 (let ((end (org-element-property :end next))
5741 (cbeg (org-element-property :contents-begin next))
5742 (cend (org-element-property :contents-end next)))
5743 (cond
5744 ;; Skip objects ending before or at POS.
5745 ((<= end pos)
5746 (goto-char end)
5747 ;; For convenience, when object ends at POS,
5748 ;; without any space, store it in LAST, as we
5749 ;; will return it if no object starts here.
5750 (when (and (= end pos)
5751 (not (memq (char-before) '(?\s ?\t))))
5752 (setq last next)))
5753 ;; If POS is within a container object, move
5754 ;; into that object.
5755 ((and cbeg cend
5756 (>= pos cbeg)
5757 (or (< pos cend)
5758 ;; At contents' end, if there is no
5759 ;; space before point, also move into
5760 ;; object, for consistency with
5761 ;; convenience feature above.
5762 (and (= pos cend)
5763 (not (memq (char-before pos) '(?\s ?\t))))))
5764 (goto-char cbeg)
5765 (narrow-to-region (point) cend)
5766 (setq parent next
5767 restriction (org-element-restriction next)
5768 next nil
5769 object-data nil))
5770 ;; Otherwise, return NEXT.
5771 (t (throw 'exit next)))))))
5772 ;; Store results in cache, if applicable.
5773 (org-element--cache-put element cache)))))))
5775 (defun org-element-nested-p (elem-A elem-B)
5776 "Non-nil when elements ELEM-A and ELEM-B are nested."
5777 (let ((beg-A (org-element-property :begin elem-A))
5778 (beg-B (org-element-property :begin elem-B))
5779 (end-A (org-element-property :end elem-A))
5780 (end-B (org-element-property :end elem-B)))
5781 (or (and (>= beg-A beg-B) (<= end-A end-B))
5782 (and (>= beg-B beg-A) (<= end-B end-A)))))
5784 (defun org-element-swap-A-B (elem-A elem-B)
5785 "Swap elements ELEM-A and ELEM-B.
5786 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5787 end of ELEM-A."
5788 (goto-char (org-element-property :begin elem-A))
5789 ;; There are two special cases when an element doesn't start at bol:
5790 ;; the first paragraph in an item or in a footnote definition.
5791 (let ((specialp (not (bolp))))
5792 ;; Only a paragraph without any affiliated keyword can be moved at
5793 ;; ELEM-A position in such a situation. Note that the case of
5794 ;; a footnote definition is impossible: it cannot contain two
5795 ;; paragraphs in a row because it cannot contain a blank line.
5796 (if (and specialp
5797 (or (not (eq (org-element-type elem-B) 'paragraph))
5798 (/= (org-element-property :begin elem-B)
5799 (org-element-property :contents-begin elem-B))))
5800 (error "Cannot swap elements"))
5801 ;; In a special situation, ELEM-A will have no indentation. We'll
5802 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5803 (let* ((ind-B (when specialp
5804 (goto-char (org-element-property :begin elem-B))
5805 (org-get-indentation)))
5806 (beg-A (org-element-property :begin elem-A))
5807 (end-A (save-excursion
5808 (goto-char (org-element-property :end elem-A))
5809 (skip-chars-backward " \r\t\n")
5810 (point-at-eol)))
5811 (beg-B (org-element-property :begin elem-B))
5812 (end-B (save-excursion
5813 (goto-char (org-element-property :end elem-B))
5814 (skip-chars-backward " \r\t\n")
5815 (point-at-eol)))
5816 ;; Store overlays responsible for visibility status. We
5817 ;; also need to store their boundaries as they will be
5818 ;; removed from buffer.
5819 (overlays
5820 (cons
5821 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5822 (overlays-in beg-A end-A))
5823 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5824 (overlays-in beg-B end-B))))
5825 ;; Get contents.
5826 (body-A (buffer-substring beg-A end-A))
5827 (body-B (delete-and-extract-region beg-B end-B)))
5828 (goto-char beg-B)
5829 (when specialp
5830 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5831 (org-indent-to-column ind-B))
5832 (insert body-A)
5833 ;; Restore ex ELEM-A overlays.
5834 (let ((offset (- beg-B beg-A)))
5835 (mapc (lambda (ov)
5836 (move-overlay
5837 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5838 (car overlays))
5839 (goto-char beg-A)
5840 (delete-region beg-A end-A)
5841 (insert body-B)
5842 ;; Restore ex ELEM-B overlays.
5843 (mapc (lambda (ov)
5844 (move-overlay
5845 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5846 (cdr overlays)))
5847 (goto-char (org-element-property :end elem-B)))))
5849 (defun org-element-remove-indentation (s &optional n)
5850 "Remove maximum common indentation in string S and return it.
5851 When optional argument N is a positive integer, remove exactly
5852 that much characters from indentation, if possible, or return
5853 S as-is otherwise. Unlike to `org-remove-indentation', this
5854 function doesn't call `untabify' on S."
5855 (catch 'exit
5856 (with-temp-buffer
5857 (insert s)
5858 (goto-char (point-min))
5859 ;; Find maximum common indentation, if not specified.
5860 (setq n (or n
5861 (let ((min-ind (point-max)))
5862 (save-excursion
5863 (while (re-search-forward "^[ \t]*\\S-" nil t)
5864 (let ((ind (1- (current-column))))
5865 (if (zerop ind) (throw 'exit s)
5866 (setq min-ind (min min-ind ind))))))
5867 min-ind)))
5868 (if (zerop n) s
5869 ;; Remove exactly N indentation, but give up if not possible.
5870 (while (not (eobp))
5871 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5872 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5873 ((< ind n) (throw 'exit s))
5874 (t (org-indent-line-to (- ind n))))
5875 (forward-line)))
5876 (buffer-string)))))
5880 (provide 'org-element)
5882 ;; Local variables:
5883 ;; generated-autoload-file: "org-loaddefs.el"
5884 ;; End:
5886 ;;; org-element.el ends here