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