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