Merge branch 'maint'
[org-mode.git] / lisp / org-element.el
blob352482ef825fa495fd4e0daa7f6f236a442d2b01
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 (defconst org-element--latex-begin-environment
2088 "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
2089 "Regexp matching the beginning of a LaTeX environment.
2090 The environment is captured by the first group.
2092 See also `org-element--latex-end-environment'.")
2094 (defconst org-element--latex-end-environment
2095 "\\\\end{%s}[ \t]*$"
2096 "Format string matching the ending of a LaTeX environment.
2097 See also `org-element--latex-begin-environment'.")
2099 (defun org-element-latex-environment-parser (limit affiliated)
2100 "Parse a LaTeX environment.
2102 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2103 the buffer position at the beginning of the first affiliated
2104 keyword and CDR is a plist of affiliated keywords along with
2105 their value.
2107 Return a list whose CAR is `latex-environment' and CDR is a plist
2108 containing `:begin', `:end', `:value', `:post-blank' and
2109 `:post-affiliated' keywords.
2111 Assume point is at the beginning of the latex environment."
2112 (save-excursion
2113 (let ((case-fold-search t)
2114 (code-begin (point)))
2115 (looking-at org-element--latex-begin-environment)
2116 (if (not (re-search-forward (format org-element--latex-end-environment
2117 (regexp-quote (match-string 1)))
2118 limit t))
2119 ;; Incomplete latex environment: parse it as a paragraph.
2120 (org-element-paragraph-parser limit affiliated)
2121 (let* ((code-end (progn (forward-line) (point)))
2122 (begin (car affiliated))
2123 (value (buffer-substring-no-properties code-begin code-end))
2124 (end (progn (skip-chars-forward " \r\t\n" limit)
2125 (if (eobp) (point) (line-beginning-position)))))
2126 (list 'latex-environment
2127 (nconc
2128 (list :begin begin
2129 :end end
2130 :value value
2131 :post-blank (count-lines code-end end)
2132 :post-affiliated code-begin)
2133 (cdr affiliated))))))))
2135 (defun org-element-latex-environment-interpreter (latex-environment contents)
2136 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2137 CONTENTS is nil."
2138 (org-element-property :value latex-environment))
2141 ;;;; Node Property
2143 (defun org-element-node-property-parser (limit)
2144 "Parse a node-property at point.
2146 LIMIT bounds the search.
2148 Return a list whose CAR is `node-property' and CDR is a plist
2149 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2150 keywords."
2151 (save-excursion
2152 (looking-at org-property-re)
2153 (let ((case-fold-search t)
2154 (begin (point))
2155 (key (org-match-string-no-properties 2))
2156 (value (org-match-string-no-properties 3))
2157 (pos-before-blank (progn (forward-line) (point)))
2158 (end (progn (skip-chars-forward " \r\t\n" limit)
2159 (if (eobp) (point) (point-at-bol)))))
2160 (list 'node-property
2161 (list :key key
2162 :value value
2163 :begin begin
2164 :end end
2165 :post-blank (count-lines pos-before-blank end))))))
2167 (defun org-element-node-property-interpreter (node-property contents)
2168 "Interpret NODE-PROPERTY element as Org syntax.
2169 CONTENTS is nil."
2170 (format org-property-format
2171 (format ":%s:" (org-element-property :key node-property))
2172 (org-element-property :value node-property)))
2175 ;;;; Paragraph
2177 (defun org-element-paragraph-parser (limit affiliated)
2178 "Parse a paragraph.
2180 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2181 the buffer position at the beginning of the first affiliated
2182 keyword and CDR is a plist of affiliated keywords along with
2183 their value.
2185 Return a list whose CAR is `paragraph' and CDR is a plist
2186 containing `:begin', `:end', `:contents-begin' and
2187 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2189 Assume point is at the beginning of the paragraph."
2190 (save-excursion
2191 (let* ((begin (car affiliated))
2192 (contents-begin (point))
2193 (before-blank
2194 (let ((case-fold-search t))
2195 (end-of-line)
2196 (if (not (re-search-forward
2197 org-element-paragraph-separate limit 'm))
2198 limit
2199 ;; A matching `org-element-paragraph-separate' is not
2200 ;; necessarily the end of the paragraph. In
2201 ;; particular, lines starting with # or : as a first
2202 ;; non-space character are ambiguous. We have to
2203 ;; check if they are valid Org syntax (e.g., not an
2204 ;; incomplete keyword).
2205 (beginning-of-line)
2206 (while (not
2208 ;; There's no ambiguity for other symbols or
2209 ;; empty lines: stop here.
2210 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2211 ;; Stop at valid fixed-width areas.
2212 (looking-at "[ \t]*:\\(?: \\|$\\)")
2213 ;; Stop at drawers.
2214 (and (looking-at org-drawer-regexp)
2215 (save-excursion
2216 (re-search-forward
2217 "^[ \t]*:END:[ \t]*$" limit t)))
2218 ;; Stop at valid comments.
2219 (looking-at "[ \t]*#\\(?: \\|$\\)")
2220 ;; Stop at valid dynamic blocks.
2221 (and (looking-at org-dblock-start-re)
2222 (save-excursion
2223 (re-search-forward
2224 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2225 ;; Stop at valid blocks.
2226 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2227 (save-excursion
2228 (re-search-forward
2229 (format "^[ \t]*#\\+END_%s[ \t]*$"
2230 (regexp-quote
2231 (org-match-string-no-properties 1)))
2232 limit t)))
2233 ;; Stop at valid latex environments.
2234 (and (looking-at org-element--latex-begin-environment)
2235 (save-excursion
2236 (re-search-forward
2237 (format org-element--latex-end-environment
2238 (regexp-quote
2239 (org-match-string-no-properties 1)))
2240 limit t)))
2241 ;; Stop at valid keywords.
2242 (looking-at "[ \t]*#\\+\\S-+:")
2243 ;; Skip everything else.
2244 (not
2245 (progn
2246 (end-of-line)
2247 (re-search-forward org-element-paragraph-separate
2248 limit 'm)))))
2249 (beginning-of-line)))
2250 (if (= (point) limit) limit
2251 (goto-char (line-beginning-position)))))
2252 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2253 (forward-line)
2254 (point)))
2255 (end (progn (skip-chars-forward " \r\t\n" limit)
2256 (if (eobp) (point) (line-beginning-position)))))
2257 (list 'paragraph
2258 (nconc
2259 (list :begin begin
2260 :end end
2261 :contents-begin contents-begin
2262 :contents-end contents-end
2263 :post-blank (count-lines before-blank end)
2264 :post-affiliated contents-begin)
2265 (cdr affiliated))))))
2267 (defun org-element-paragraph-interpreter (paragraph contents)
2268 "Interpret PARAGRAPH element as Org syntax.
2269 CONTENTS is the contents of the element."
2270 contents)
2273 ;;;; Planning
2275 (defun org-element-planning-parser (limit)
2276 "Parse a planning.
2278 LIMIT bounds the search.
2280 Return a list whose CAR is `planning' and CDR is a plist
2281 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2282 and `:post-blank' keywords."
2283 (save-excursion
2284 (let* ((case-fold-search nil)
2285 (begin (point))
2286 (post-blank (let ((before-blank (progn (forward-line) (point))))
2287 (skip-chars-forward " \r\t\n" limit)
2288 (skip-chars-backward " \t")
2289 (unless (bolp) (end-of-line))
2290 (count-lines before-blank (point))))
2291 (end (point))
2292 closed deadline scheduled)
2293 (goto-char begin)
2294 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2295 (goto-char (match-end 1))
2296 (skip-chars-forward " \t" end)
2297 (let ((keyword (match-string 1))
2298 (time (org-element-timestamp-parser)))
2299 (cond ((equal keyword org-closed-string) (setq closed time))
2300 ((equal keyword org-deadline-string) (setq deadline time))
2301 (t (setq scheduled time)))))
2302 (list 'planning
2303 (list :closed closed
2304 :deadline deadline
2305 :scheduled scheduled
2306 :begin begin
2307 :end end
2308 :post-blank post-blank)))))
2310 (defun org-element-planning-interpreter (planning contents)
2311 "Interpret PLANNING element as Org syntax.
2312 CONTENTS is nil."
2313 (mapconcat
2314 'identity
2315 (delq nil
2316 (list (let ((deadline (org-element-property :deadline planning)))
2317 (when deadline
2318 (concat org-deadline-string " "
2319 (org-element-timestamp-interpreter deadline nil))))
2320 (let ((scheduled (org-element-property :scheduled planning)))
2321 (when scheduled
2322 (concat org-scheduled-string " "
2323 (org-element-timestamp-interpreter scheduled nil))))
2324 (let ((closed (org-element-property :closed planning)))
2325 (when closed
2326 (concat org-closed-string " "
2327 (org-element-timestamp-interpreter closed nil))))))
2328 " "))
2331 ;;;; Src Block
2333 (defun org-element-src-block-parser (limit affiliated)
2334 "Parse a src block.
2336 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2337 the buffer position at the beginning of the first affiliated
2338 keyword and CDR is a plist of affiliated keywords along with
2339 their value.
2341 Return a list whose CAR is `src-block' and CDR is a plist
2342 containing `:language', `:switches', `:parameters', `:begin',
2343 `:end', `:number-lines', `:retain-labels', `:use-labels',
2344 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2345 `:post-affiliated' keywords.
2347 Assume point is at the beginning of the block."
2348 (let ((case-fold-search t))
2349 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2350 limit t)))
2351 ;; Incomplete block: parse it as a paragraph.
2352 (org-element-paragraph-parser limit affiliated)
2353 (let ((contents-end (match-beginning 0)))
2354 (save-excursion
2355 (let* ((begin (car affiliated))
2356 (post-affiliated (point))
2357 ;; Get language as a string.
2358 (language
2359 (progn
2360 (looking-at
2361 (concat "^[ \t]*#\\+BEGIN_SRC"
2362 "\\(?: +\\(\\S-+\\)\\)?"
2363 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2364 "\\(.*\\)[ \t]*$"))
2365 (org-match-string-no-properties 1)))
2366 ;; Get switches.
2367 (switches (org-match-string-no-properties 2))
2368 ;; Get parameters.
2369 (parameters (org-match-string-no-properties 3))
2370 ;; Switches analysis
2371 (number-lines
2372 (cond ((not switches) nil)
2373 ((string-match "-n\\>" switches) 'new)
2374 ((string-match "+n\\>" switches) 'continued)))
2375 (preserve-indent (and switches
2376 (string-match "-i\\>" switches)))
2377 (label-fmt
2378 (and switches
2379 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2380 (match-string 1 switches)))
2381 ;; Should labels be retained in (or stripped from)
2382 ;; src blocks?
2383 (retain-labels
2384 (or (not switches)
2385 (not (string-match "-r\\>" switches))
2386 (and number-lines (string-match "-k\\>" switches))))
2387 ;; What should code-references use - labels or
2388 ;; line-numbers?
2389 (use-labels
2390 (or (not switches)
2391 (and retain-labels
2392 (not (string-match "-k\\>" switches)))))
2393 ;; Indentation.
2394 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2395 ;; Retrieve code.
2396 (value (org-element-remove-indentation
2397 (org-unescape-code-in-string
2398 (buffer-substring-no-properties
2399 (progn (forward-line) (point)) contents-end))
2400 block-ind))
2401 (pos-before-blank (progn (goto-char contents-end)
2402 (forward-line)
2403 (point)))
2404 ;; Get position after ending blank lines.
2405 (end (progn (skip-chars-forward " \r\t\n" limit)
2406 (if (eobp) (point) (line-beginning-position)))))
2407 (list 'src-block
2408 (nconc
2409 (list :language language
2410 :switches (and (org-string-nw-p switches)
2411 (org-trim switches))
2412 :parameters (and (org-string-nw-p parameters)
2413 (org-trim parameters))
2414 :begin begin
2415 :end end
2416 :number-lines number-lines
2417 :preserve-indent preserve-indent
2418 :retain-labels retain-labels
2419 :use-labels use-labels
2420 :label-fmt label-fmt
2421 :value value
2422 :post-blank (count-lines pos-before-blank end)
2423 :post-affiliated post-affiliated)
2424 (cdr affiliated)))))))))
2426 (defun org-element-src-block-interpreter (src-block contents)
2427 "Interpret SRC-BLOCK element as Org syntax.
2428 CONTENTS is nil."
2429 (let ((lang (org-element-property :language src-block))
2430 (switches (org-element-property :switches src-block))
2431 (params (org-element-property :parameters src-block))
2432 (value
2433 (let ((val (org-element-property :value src-block)))
2434 (cond
2435 ((or org-src-preserve-indentation
2436 (org-element-property :preserve-indent src-block))
2437 val)
2438 ((zerop org-edit-src-content-indentation) val)
2440 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2441 (replace-regexp-in-string
2442 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2443 (concat (format "#+BEGIN_SRC%s\n"
2444 (concat (and lang (concat " " lang))
2445 (and switches (concat " " switches))
2446 (and params (concat " " params))))
2447 (org-escape-code-in-string value)
2448 "#+END_SRC")))
2451 ;;;; Table
2453 (defun org-element-table-parser (limit affiliated)
2454 "Parse a table at point.
2456 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2457 the buffer position at the beginning of the first affiliated
2458 keyword and CDR is a plist of affiliated keywords along with
2459 their value.
2461 Return a list whose CAR is `table' and CDR is a plist containing
2462 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2463 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2464 keywords.
2466 Assume point is at the beginning of the table."
2467 (save-excursion
2468 (let* ((case-fold-search t)
2469 (table-begin (point))
2470 (type (if (org-at-table.el-p) 'table.el 'org))
2471 (begin (car affiliated))
2472 (table-end
2473 (if (re-search-forward org-table-any-border-regexp limit 'm)
2474 (goto-char (match-beginning 0))
2475 (point)))
2476 (tblfm (let (acc)
2477 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2478 (push (org-match-string-no-properties 1) acc)
2479 (forward-line))
2480 acc))
2481 (pos-before-blank (point))
2482 (end (progn (skip-chars-forward " \r\t\n" limit)
2483 (if (eobp) (point) (line-beginning-position)))))
2484 (list 'table
2485 (nconc
2486 (list :begin begin
2487 :end end
2488 :type type
2489 :tblfm tblfm
2490 ;; Only `org' tables have contents. `table.el' tables
2491 ;; use a `:value' property to store raw table as
2492 ;; a string.
2493 :contents-begin (and (eq type 'org) table-begin)
2494 :contents-end (and (eq type 'org) table-end)
2495 :value (and (eq type 'table.el)
2496 (buffer-substring-no-properties
2497 table-begin table-end))
2498 :post-blank (count-lines pos-before-blank end)
2499 :post-affiliated table-begin)
2500 (cdr affiliated))))))
2502 (defun org-element-table-interpreter (table contents)
2503 "Interpret TABLE element as Org syntax.
2504 CONTENTS is nil."
2505 (if (eq (org-element-property :type table) 'table.el)
2506 (org-remove-indentation (org-element-property :value table))
2507 (concat (with-temp-buffer (insert contents)
2508 (org-table-align)
2509 (buffer-string))
2510 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2511 (reverse (org-element-property :tblfm table))
2512 "\n"))))
2515 ;;;; Table Row
2517 (defun org-element-table-row-parser (limit)
2518 "Parse table row at point.
2520 LIMIT bounds the search.
2522 Return a list whose CAR is `table-row' and CDR is a plist
2523 containing `:begin', `:end', `:contents-begin', `:contents-end',
2524 `:type' and `:post-blank' keywords."
2525 (save-excursion
2526 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2527 (begin (point))
2528 ;; A table rule has no contents. In that case, ensure
2529 ;; CONTENTS-BEGIN matches CONTENTS-END.
2530 (contents-begin (and (eq type 'standard)
2531 (search-forward "|")
2532 (point)))
2533 (contents-end (and (eq type 'standard)
2534 (progn
2535 (end-of-line)
2536 (skip-chars-backward " \t")
2537 (point))))
2538 (end (progn (forward-line) (point))))
2539 (list 'table-row
2540 (list :type type
2541 :begin begin
2542 :end end
2543 :contents-begin contents-begin
2544 :contents-end contents-end
2545 :post-blank 0)))))
2547 (defun org-element-table-row-interpreter (table-row contents)
2548 "Interpret TABLE-ROW element as Org syntax.
2549 CONTENTS is the contents of the table row."
2550 (if (eq (org-element-property :type table-row) 'rule) "|-"
2551 (concat "| " contents)))
2554 ;;;; Verse Block
2556 (defun org-element-verse-block-parser (limit affiliated)
2557 "Parse a verse block.
2559 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2560 the buffer position at the beginning of the first affiliated
2561 keyword and CDR is a plist of affiliated keywords along with
2562 their value.
2564 Return a list whose CAR is `verse-block' and CDR is a plist
2565 containing `:begin', `:end', `:contents-begin', `:contents-end',
2566 `:post-blank' and `:post-affiliated' keywords.
2568 Assume point is at beginning of the block."
2569 (let ((case-fold-search t))
2570 (if (not (save-excursion
2571 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2572 ;; Incomplete block: parse it as a paragraph.
2573 (org-element-paragraph-parser limit affiliated)
2574 (let ((contents-end (match-beginning 0)))
2575 (save-excursion
2576 (let* ((begin (car affiliated))
2577 (post-affiliated (point))
2578 (contents-begin (progn (forward-line) (point)))
2579 (pos-before-blank (progn (goto-char contents-end)
2580 (forward-line)
2581 (point)))
2582 (end (progn (skip-chars-forward " \r\t\n" limit)
2583 (if (eobp) (point) (line-beginning-position)))))
2584 (list 'verse-block
2585 (nconc
2586 (list :begin begin
2587 :end end
2588 :contents-begin contents-begin
2589 :contents-end contents-end
2590 :post-blank (count-lines pos-before-blank end)
2591 :post-affiliated post-affiliated)
2592 (cdr affiliated)))))))))
2594 (defun org-element-verse-block-interpreter (verse-block contents)
2595 "Interpret VERSE-BLOCK element as Org syntax.
2596 CONTENTS is verse block contents."
2597 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2601 ;;; Objects
2603 ;; Unlike to elements, raw text can be found between objects. Hence,
2604 ;; `org-element--object-lex' is provided to find the next object in
2605 ;; buffer.
2607 ;; Some object types (e.g., `italic') are recursive. Restrictions on
2608 ;; object types they can contain will be specified in
2609 ;; `org-element-object-restrictions'.
2611 ;; Creating a new type of object requires to alter
2612 ;; `org-element--object-regexp' and `org-element--object-lex', add the
2613 ;; new type in `org-element-all-objects', and possibly add
2614 ;; restrictions in `org-element-object-restrictions'.
2616 ;;;; Bold
2618 (defun org-element-bold-parser ()
2619 "Parse bold object at point, if any.
2621 When at a bold object, return a list whose car is `bold' and cdr
2622 is a plist with `:begin', `:end', `:contents-begin' and
2623 `:contents-end' and `:post-blank' keywords. Otherwise, return
2624 nil.
2626 Assume point is at the first star marker."
2627 (save-excursion
2628 (unless (bolp) (backward-char 1))
2629 (when (looking-at org-emph-re)
2630 (let ((begin (match-beginning 2))
2631 (contents-begin (match-beginning 4))
2632 (contents-end (match-end 4))
2633 (post-blank (progn (goto-char (match-end 2))
2634 (skip-chars-forward " \t")))
2635 (end (point)))
2636 (list 'bold
2637 (list :begin begin
2638 :end end
2639 :contents-begin contents-begin
2640 :contents-end contents-end
2641 :post-blank post-blank))))))
2643 (defun org-element-bold-interpreter (bold contents)
2644 "Interpret BOLD object as Org syntax.
2645 CONTENTS is the contents of the object."
2646 (format "*%s*" contents))
2649 ;;;; Code
2651 (defun org-element-code-parser ()
2652 "Parse code object at point, if any.
2654 When at a code object, return a list whose car is `code' and cdr
2655 is a plist with `:value', `:begin', `:end' and `:post-blank'
2656 keywords. Otherwise, return nil.
2658 Assume point is at the first tilde marker."
2659 (save-excursion
2660 (unless (bolp) (backward-char 1))
2661 (when (looking-at org-emph-re)
2662 (let ((begin (match-beginning 2))
2663 (value (org-match-string-no-properties 4))
2664 (post-blank (progn (goto-char (match-end 2))
2665 (skip-chars-forward " \t")))
2666 (end (point)))
2667 (list 'code
2668 (list :value value
2669 :begin begin
2670 :end end
2671 :post-blank post-blank))))))
2673 (defun org-element-code-interpreter (code contents)
2674 "Interpret CODE object as Org syntax.
2675 CONTENTS is nil."
2676 (format "~%s~" (org-element-property :value code)))
2679 ;;;; Entity
2681 (defun org-element-entity-parser ()
2682 "Parse entity at point, if any.
2684 When at an entity, return a list whose car is `entity' and cdr
2685 a plist with `:begin', `:end', `:latex', `:latex-math-p',
2686 `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
2687 `:post-blank' as keywords. Otherwise, return nil.
2689 Assume point is at the beginning of the entity."
2690 (catch 'no-object
2691 (when (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2692 (save-excursion
2693 (let* ((value (or (org-entity-get (match-string 1))
2694 (throw 'no-object nil)))
2695 (begin (match-beginning 0))
2696 (bracketsp (string= (match-string 2) "{}"))
2697 (post-blank (progn (goto-char (match-end 1))
2698 (when bracketsp (forward-char 2))
2699 (skip-chars-forward " \t")))
2700 (end (point)))
2701 (list 'entity
2702 (list :name (car value)
2703 :latex (nth 1 value)
2704 :latex-math-p (nth 2 value)
2705 :html (nth 3 value)
2706 :ascii (nth 4 value)
2707 :latin1 (nth 5 value)
2708 :utf-8 (nth 6 value)
2709 :begin begin
2710 :end end
2711 :use-brackets-p bracketsp
2712 :post-blank post-blank)))))))
2714 (defun org-element-entity-interpreter (entity contents)
2715 "Interpret ENTITY object as Org syntax.
2716 CONTENTS is nil."
2717 (concat "\\"
2718 (org-element-property :name entity)
2719 (when (org-element-property :use-brackets-p entity) "{}")))
2722 ;;;; Export Snippet
2724 (defun org-element-export-snippet-parser ()
2725 "Parse export snippet at point.
2727 When at an export snippet, return a list whose car is
2728 `export-snippet' and cdr a plist with `:begin', `:end',
2729 `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
2730 return nil.
2732 Assume point is at the beginning of the snippet."
2733 (save-excursion
2734 (let (contents-end)
2735 (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
2736 (setq contents-end
2737 (save-match-data (goto-char (match-end 0))
2738 (re-search-forward "@@" nil t)
2739 (match-beginning 0))))
2740 (let* ((begin (match-beginning 0))
2741 (back-end (org-match-string-no-properties 1))
2742 (value (buffer-substring-no-properties
2743 (match-end 0) contents-end))
2744 (post-blank (skip-chars-forward " \t"))
2745 (end (point)))
2746 (list 'export-snippet
2747 (list :back-end back-end
2748 :value value
2749 :begin begin
2750 :end end
2751 :post-blank post-blank)))))))
2753 (defun org-element-export-snippet-interpreter (export-snippet contents)
2754 "Interpret EXPORT-SNIPPET object as Org syntax.
2755 CONTENTS is nil."
2756 (format "@@%s:%s@@"
2757 (org-element-property :back-end export-snippet)
2758 (org-element-property :value export-snippet)))
2761 ;;;; Footnote Reference
2763 (defun org-element-footnote-reference-parser ()
2764 "Parse footnote reference at point, if any.
2766 When at a footnote reference, return a list whose car is
2767 `footnote-reference' and cdr a plist with `:label', `:type',
2768 `:begin', `:end', `:content-begin', `:contents-end' and
2769 `:post-blank' as keywords. Otherwise, return nil."
2770 (catch 'no-object
2771 (when (looking-at org-footnote-re)
2772 (save-excursion
2773 (let* ((begin (point))
2774 (label
2775 (or (org-match-string-no-properties 2)
2776 (org-match-string-no-properties 3)
2777 (and (match-string 1)
2778 (concat "fn:" (org-match-string-no-properties 1)))))
2779 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2780 (inner-begin (match-end 0))
2781 (inner-end
2782 (let ((count 1))
2783 (forward-char)
2784 (while (and (> count 0) (re-search-forward "[][]" nil t))
2785 (if (equal (match-string 0) "[") (incf count) (decf count)))
2786 (unless (zerop count) (throw 'no-object nil))
2787 (1- (point))))
2788 (post-blank (progn (goto-char (1+ inner-end))
2789 (skip-chars-forward " \t")))
2790 (end (point)))
2791 (list 'footnote-reference
2792 (list :label label
2793 :type type
2794 :begin begin
2795 :end end
2796 :contents-begin (and (eq type 'inline) inner-begin)
2797 :contents-end (and (eq type 'inline) inner-end)
2798 :post-blank post-blank)))))))
2800 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2801 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2802 CONTENTS is its definition, when inline, or nil."
2803 (format "[%s]"
2804 (concat (or (org-element-property :label footnote-reference) "fn:")
2805 (and contents (concat ":" contents)))))
2808 ;;;; Inline Babel Call
2810 (defun org-element-inline-babel-call-parser ()
2811 "Parse inline babel call at point, if any.
2813 When at an inline babel call, return a list whose car is
2814 `inline-babel-call' and cdr a plist with `:begin', `:end',
2815 `:value' and `:post-blank' as keywords. Otherwise, return nil.
2817 Assume point is at the beginning of the babel call."
2818 (save-excursion
2819 (unless (bolp) (backward-char))
2820 (when (let ((case-fold-search t))
2821 (looking-at org-babel-inline-lob-one-liner-regexp))
2822 (let ((begin (match-end 1))
2823 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2824 (post-blank (progn (goto-char (match-end 0))
2825 (skip-chars-forward " \t")))
2826 (end (point)))
2827 (list 'inline-babel-call
2828 (list :begin begin
2829 :end end
2830 :value value
2831 :post-blank post-blank))))))
2833 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2834 "Interpret INLINE-BABEL-CALL object as Org syntax.
2835 CONTENTS is nil."
2836 (org-element-property :value inline-babel-call))
2839 ;;;; Inline Src Block
2841 (defun org-element-inline-src-block-parser ()
2842 "Parse inline source block at point, if any.
2844 When at an inline source block, return a list whose car is
2845 `inline-src-block' and cdr a plist with `:begin', `:end',
2846 `:language', `:value', `:parameters' and `:post-blank' as
2847 keywords. Otherwise, return nil.
2849 Assume point is at the beginning of the inline src block."
2850 (save-excursion
2851 (unless (bolp) (backward-char))
2852 (when (looking-at org-babel-inline-src-block-regexp)
2853 (let ((begin (match-beginning 1))
2854 (language (org-match-string-no-properties 2))
2855 (parameters (org-match-string-no-properties 4))
2856 (value (org-match-string-no-properties 5))
2857 (post-blank (progn (goto-char (match-end 0))
2858 (skip-chars-forward " \t")))
2859 (end (point)))
2860 (list 'inline-src-block
2861 (list :language language
2862 :value value
2863 :parameters parameters
2864 :begin begin
2865 :end end
2866 :post-blank post-blank))))))
2868 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2869 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2870 CONTENTS is nil."
2871 (let ((language (org-element-property :language inline-src-block))
2872 (arguments (org-element-property :parameters inline-src-block))
2873 (body (org-element-property :value inline-src-block)))
2874 (format "src_%s%s{%s}"
2875 language
2876 (if arguments (format "[%s]" arguments) "")
2877 body)))
2879 ;;;; Italic
2881 (defun org-element-italic-parser ()
2882 "Parse italic object at point, if any.
2884 When at an italic object, return a list whose car is `italic' and
2885 cdr is a plist with `:begin', `:end', `:contents-begin' and
2886 `:contents-end' and `:post-blank' keywords. Otherwise, return
2887 nil.
2889 Assume point is at the first slash marker."
2890 (save-excursion
2891 (unless (bolp) (backward-char 1))
2892 (when (looking-at org-emph-re)
2893 (let ((begin (match-beginning 2))
2894 (contents-begin (match-beginning 4))
2895 (contents-end (match-end 4))
2896 (post-blank (progn (goto-char (match-end 2))
2897 (skip-chars-forward " \t")))
2898 (end (point)))
2899 (list 'italic
2900 (list :begin begin
2901 :end end
2902 :contents-begin contents-begin
2903 :contents-end contents-end
2904 :post-blank post-blank))))))
2906 (defun org-element-italic-interpreter (italic contents)
2907 "Interpret ITALIC object as Org syntax.
2908 CONTENTS is the contents of the object."
2909 (format "/%s/" contents))
2912 ;;;; Latex Fragment
2914 (defun org-element-latex-fragment-parser ()
2915 "Parse LaTeX fragment at point, if any.
2917 When at a LaTeX fragment, return a list whose car is
2918 `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
2919 and `:post-blank' as keywords. Otherwise, return nil.
2921 Assume point is at the beginning of the LaTeX fragment."
2922 (catch 'no-object
2923 (save-excursion
2924 (let* ((begin (point))
2925 (after-fragment
2926 (if (eq (char-after) ?$)
2927 (if (eq (char-after (1+ (point))) ?$)
2928 (search-forward "$$" nil t 2)
2929 (and (not (eq (char-before) ?$))
2930 (search-forward "$" nil t 2)
2931 (not (memq (char-before (match-beginning 0))
2932 '(?\s ?\t ?\n ?, ?.)))
2933 (looking-at "\\([- \t.,?;:'\"]\\|$\\)")
2934 (point)))
2935 (case (char-after (1+ (point)))
2936 (?\( (search-forward "\\)" nil t))
2937 (?\[ (search-forward "\\]" nil t))
2938 (otherwise
2939 ;; Macro.
2940 (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2941 (match-end 0))))))
2942 (post-blank (if (not after-fragment) (throw 'no-object nil)
2943 (goto-char after-fragment)
2944 (skip-chars-forward " \t")))
2945 (end (point)))
2946 (list 'latex-fragment
2947 (list :value (buffer-substring-no-properties begin after-fragment)
2948 :begin begin
2949 :end end
2950 :post-blank post-blank))))))
2952 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2953 "Interpret LATEX-FRAGMENT object as Org syntax.
2954 CONTENTS is nil."
2955 (org-element-property :value latex-fragment))
2957 ;;;; Line Break
2959 (defun org-element-line-break-parser ()
2960 "Parse line break at point, if any.
2962 When at a line break, return a list whose car is `line-break',
2963 and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
2964 Otherwise, return nil.
2966 Assume point is at the beginning of the line break."
2967 (when (and (org-looking-at-p "\\\\\\\\[ \t]*$")
2968 (not (eq (char-before) ?\\)))
2969 (list 'line-break
2970 (list :begin (point)
2971 :end (progn (forward-line) (point))
2972 :post-blank 0))))
2974 (defun org-element-line-break-interpreter (line-break contents)
2975 "Interpret LINE-BREAK object as Org syntax.
2976 CONTENTS is nil."
2977 "\\\\\n")
2980 ;;;; Link
2982 (defun org-element-link-parser ()
2983 "Parse link at point, if any.
2985 When at a link, return a list whose car is `link' and cdr a plist
2986 with `:type', `:path', `:raw-link', `:application',
2987 `:search-option', `:begin', `:end', `:contents-begin',
2988 `:contents-end' and `:post-blank' as keywords. Otherwise, return
2989 nil.
2991 Assume point is at the beginning of the link."
2992 (catch 'no-object
2993 (let ((begin (point))
2994 end contents-begin contents-end link-end post-blank path type
2995 raw-link link search-option application)
2996 (cond
2997 ;; Type 1: Text targeted from a radio target.
2998 ((and org-target-link-regexp
2999 (save-excursion (or (bolp) (backward-char))
3000 (looking-at org-target-link-regexp)))
3001 (setq type "radio"
3002 link-end (match-end 1)
3003 path (org-match-string-no-properties 1)
3004 contents-begin (match-beginning 1)
3005 contents-end (match-end 1)))
3006 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3007 ((looking-at org-bracket-link-regexp)
3008 (setq contents-begin (match-beginning 3)
3009 contents-end (match-end 3)
3010 link-end (match-end 0)
3011 ;; RAW-LINK is the original link. Expand any
3012 ;; abbreviation in it.
3013 raw-link (org-translate-link
3014 (org-link-expand-abbrev
3015 (org-match-string-no-properties 1))))
3016 ;; Determine TYPE of link and set PATH accordingly.
3017 (cond
3018 ;; File type.
3019 ((or (file-name-absolute-p raw-link)
3020 (string-match "^\\.\\.?/" raw-link))
3021 (setq type "file" path raw-link))
3022 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3023 ((string-match org-link-re-with-space3 raw-link)
3024 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3025 ;; Id type: PATH is the id.
3026 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3027 (setq type "id" path (match-string 1 raw-link)))
3028 ;; Code-ref type: PATH is the name of the reference.
3029 ((string-match "^(\\(.*\\))$" raw-link)
3030 (setq type "coderef" path (match-string 1 raw-link)))
3031 ;; Custom-id type: PATH is the name of the custom id.
3032 ((= (aref raw-link 0) ?#)
3033 (setq type "custom-id" path (substring raw-link 1)))
3034 ;; Fuzzy type: Internal link either matches a target, an
3035 ;; headline name or nothing. PATH is the target or
3036 ;; headline's name.
3037 (t (setq type "fuzzy" path raw-link))))
3038 ;; Type 3: Plain link, e.g., http://orgmode.org
3039 ((looking-at org-plain-link-re)
3040 (setq raw-link (org-match-string-no-properties 0)
3041 type (org-match-string-no-properties 1)
3042 link-end (match-end 0)
3043 path (org-match-string-no-properties 2)))
3044 ;; Type 4: Angular link, e.g., <http://orgmode.org>
3045 ((looking-at org-angle-link-re)
3046 (setq raw-link (buffer-substring-no-properties
3047 (match-beginning 1) (match-end 2))
3048 type (org-match-string-no-properties 1)
3049 link-end (match-end 0)
3050 path (org-match-string-no-properties 2)))
3051 (t (throw 'no-object nil)))
3052 ;; In any case, deduce end point after trailing white space from
3053 ;; LINK-END variable.
3054 (save-excursion
3055 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3056 end (point))
3057 ;; Special "file" type link processing.
3058 (when (member type org-element-link-type-is-file)
3059 ;; Extract opening application and search option.
3060 (cond ((string-match "^file\\+\\(.*\\)$" type)
3061 (setq application (match-string 1 type)))
3062 ((not (string-match "^file" type))
3063 (setq application type)))
3064 (when (string-match "::\\(.*\\)\\'" path)
3065 (setq search-option (match-string 1 path)
3066 path (replace-match "" nil nil path)))
3067 ;; Normalize URI.
3068 (when (and (file-name-absolute-p path)
3069 (not (org-string-match-p "\\`[/~]/" path)))
3070 (setq path (concat "//" path)))
3071 ;; Make sure TYPE always reports "file".
3072 (setq type "file"))
3073 (list 'link
3074 (list :type type
3075 :path path
3076 :raw-link (or raw-link path)
3077 :application application
3078 :search-option search-option
3079 :begin begin
3080 :end end
3081 :contents-begin contents-begin
3082 :contents-end contents-end
3083 :post-blank post-blank))))))
3085 (defun org-element-link-interpreter (link contents)
3086 "Interpret LINK object as Org syntax.
3087 CONTENTS is the contents of the object, or nil."
3088 (let ((type (org-element-property :type link))
3089 (raw-link (org-element-property :raw-link link)))
3090 (if (string= type "radio") raw-link
3091 (format "[[%s]%s]"
3092 raw-link
3093 (if contents (format "[%s]" contents) "")))))
3096 ;;;; Macro
3098 (defun org-element-macro-parser ()
3099 "Parse macro at point, if any.
3101 When at a macro, return a list whose car is `macro' and cdr
3102 a plist with `:key', `:args', `:begin', `:end', `:value' and
3103 `:post-blank' as keywords. Otherwise, return nil.
3105 Assume point is at the macro."
3106 (save-excursion
3107 (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3108 (let ((begin (point))
3109 (key (downcase (org-match-string-no-properties 1)))
3110 (value (org-match-string-no-properties 0))
3111 (post-blank (progn (goto-char (match-end 0))
3112 (skip-chars-forward " \t")))
3113 (end (point))
3114 (args (let ((args (org-match-string-no-properties 3)))
3115 (when args
3116 ;; Do not use `org-split-string' since empty
3117 ;; strings are meaningful here.
3118 (split-string
3119 (replace-regexp-in-string
3120 "\\(\\\\*\\)\\(,\\)"
3121 (lambda (str)
3122 (let ((len (length (match-string 1 str))))
3123 (concat (make-string (/ len 2) ?\\)
3124 (if (zerop (mod len 2)) "\000" ","))))
3125 args nil t)
3126 "\000")))))
3127 (list 'macro
3128 (list :key key
3129 :value value
3130 :args args
3131 :begin begin
3132 :end end
3133 :post-blank post-blank))))))
3135 (defun org-element-macro-interpreter (macro contents)
3136 "Interpret MACRO object as Org syntax.
3137 CONTENTS is nil."
3138 (org-element-property :value macro))
3141 ;;;; Radio-target
3143 (defun org-element-radio-target-parser ()
3144 "Parse radio target at point, if any.
3146 When at a radio target, return a list whose car is `radio-target'
3147 and cdr a plist with `:begin', `:end', `:contents-begin',
3148 `:contents-end', `:value' and `:post-blank' as keywords.
3149 Otherwise, return nil.
3151 Assume point is at the radio target."
3152 (save-excursion
3153 (when (looking-at org-radio-target-regexp)
3154 (let ((begin (point))
3155 (contents-begin (match-beginning 1))
3156 (contents-end (match-end 1))
3157 (value (org-match-string-no-properties 1))
3158 (post-blank (progn (goto-char (match-end 0))
3159 (skip-chars-forward " \t")))
3160 (end (point)))
3161 (list 'radio-target
3162 (list :begin begin
3163 :end end
3164 :contents-begin contents-begin
3165 :contents-end contents-end
3166 :post-blank post-blank
3167 :value value))))))
3169 (defun org-element-radio-target-interpreter (target contents)
3170 "Interpret TARGET object as Org syntax.
3171 CONTENTS is the contents of the object."
3172 (concat "<<<" contents ">>>"))
3175 ;;;; Statistics Cookie
3177 (defun org-element-statistics-cookie-parser ()
3178 "Parse statistics cookie at point, if any.
3180 When at a statistics cookie, return a list whose car is
3181 `statistics-cookie', and cdr a plist with `:begin', `:end',
3182 `:value' and `:post-blank' keywords. Otherwise, return nil.
3184 Assume point is at the beginning of the statistics-cookie."
3185 (save-excursion
3186 (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3187 (let* ((begin (point))
3188 (value (buffer-substring-no-properties
3189 (match-beginning 0) (match-end 0)))
3190 (post-blank (progn (goto-char (match-end 0))
3191 (skip-chars-forward " \t")))
3192 (end (point)))
3193 (list 'statistics-cookie
3194 (list :begin begin
3195 :end end
3196 :value value
3197 :post-blank post-blank))))))
3199 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3200 "Interpret STATISTICS-COOKIE object as Org syntax.
3201 CONTENTS is nil."
3202 (org-element-property :value statistics-cookie))
3205 ;;;; Strike-Through
3207 (defun org-element-strike-through-parser ()
3208 "Parse strike-through object at point, if any.
3210 When at a strike-through object, return a list whose car is
3211 `strike-through' and cdr is a plist with `:begin', `:end',
3212 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3213 Otherwise, return nil.
3215 Assume point is at the first plus sign marker."
3216 (save-excursion
3217 (unless (bolp) (backward-char 1))
3218 (when (looking-at org-emph-re)
3219 (let ((begin (match-beginning 2))
3220 (contents-begin (match-beginning 4))
3221 (contents-end (match-end 4))
3222 (post-blank (progn (goto-char (match-end 2))
3223 (skip-chars-forward " \t")))
3224 (end (point)))
3225 (list 'strike-through
3226 (list :begin begin
3227 :end end
3228 :contents-begin contents-begin
3229 :contents-end contents-end
3230 :post-blank post-blank))))))
3232 (defun org-element-strike-through-interpreter (strike-through contents)
3233 "Interpret STRIKE-THROUGH object as Org syntax.
3234 CONTENTS is the contents of the object."
3235 (format "+%s+" contents))
3238 ;;;; Subscript
3240 (defun org-element-subscript-parser ()
3241 "Parse subscript at point, if any.
3243 When at a subscript object, return a list whose car is
3244 `subscript' and cdr a plist with `:begin', `:end',
3245 `:contents-begin', `:contents-end', `:use-brackets-p' and
3246 `:post-blank' as keywords. Otherwise, return nil.
3248 Assume point is at the underscore."
3249 (save-excursion
3250 (unless (bolp) (backward-char))
3251 (when (looking-at org-match-substring-regexp)
3252 (let ((bracketsp (match-beginning 4))
3253 (begin (match-beginning 2))
3254 (contents-begin (or (match-beginning 4)
3255 (match-beginning 3)))
3256 (contents-end (or (match-end 4) (match-end 3)))
3257 (post-blank (progn (goto-char (match-end 0))
3258 (skip-chars-forward " \t")))
3259 (end (point)))
3260 (list 'subscript
3261 (list :begin begin
3262 :end end
3263 :use-brackets-p bracketsp
3264 :contents-begin contents-begin
3265 :contents-end contents-end
3266 :post-blank post-blank))))))
3268 (defun org-element-subscript-interpreter (subscript contents)
3269 "Interpret SUBSCRIPT object as Org syntax.
3270 CONTENTS is the contents of the object."
3271 (format
3272 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3273 contents))
3276 ;;;; Superscript
3278 (defun org-element-superscript-parser ()
3279 "Parse superscript at point, if any.
3281 When at a superscript object, return a list whose car is
3282 `superscript' and cdr a plist with `:begin', `:end',
3283 `:contents-begin', `:contents-end', `:use-brackets-p' and
3284 `:post-blank' as keywords. Otherwise, return nil.
3286 Assume point is at the caret."
3287 (save-excursion
3288 (unless (bolp) (backward-char))
3289 (when (looking-at org-match-substring-regexp)
3290 (let ((bracketsp (match-beginning 4))
3291 (begin (match-beginning 2))
3292 (contents-begin (or (match-beginning 4)
3293 (match-beginning 3)))
3294 (contents-end (or (match-end 4) (match-end 3)))
3295 (post-blank (progn (goto-char (match-end 0))
3296 (skip-chars-forward " \t")))
3297 (end (point)))
3298 (list 'superscript
3299 (list :begin begin
3300 :end end
3301 :use-brackets-p bracketsp
3302 :contents-begin contents-begin
3303 :contents-end contents-end
3304 :post-blank post-blank))))))
3306 (defun org-element-superscript-interpreter (superscript contents)
3307 "Interpret SUPERSCRIPT object as Org syntax.
3308 CONTENTS is the contents of the object."
3309 (format
3310 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3311 contents))
3314 ;;;; Table Cell
3316 (defun org-element-table-cell-parser ()
3317 "Parse table cell at point.
3318 Return a list whose car is `table-cell' and cdr is a plist
3319 containing `:begin', `:end', `:contents-begin', `:contents-end'
3320 and `:post-blank' keywords."
3321 (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
3322 (let* ((begin (match-beginning 0))
3323 (end (match-end 0))
3324 (contents-begin (match-beginning 1))
3325 (contents-end (match-end 1)))
3326 (list 'table-cell
3327 (list :begin begin
3328 :end end
3329 :contents-begin contents-begin
3330 :contents-end contents-end
3331 :post-blank 0))))
3333 (defun org-element-table-cell-interpreter (table-cell contents)
3334 "Interpret TABLE-CELL element as Org syntax.
3335 CONTENTS is the contents of the cell, or nil."
3336 (concat " " contents " |"))
3339 ;;;; Target
3341 (defun org-element-target-parser ()
3342 "Parse target at point, if any.
3344 When at a target, return a list whose car is `target' and cdr
3345 a plist with `:begin', `:end', `:value' and `:post-blank' as
3346 keywords. Otherwise, return nil.
3348 Assume point is at the target."
3349 (save-excursion
3350 (when (looking-at org-target-regexp)
3351 (let ((begin (point))
3352 (value (org-match-string-no-properties 1))
3353 (post-blank (progn (goto-char (match-end 0))
3354 (skip-chars-forward " \t")))
3355 (end (point)))
3356 (list 'target
3357 (list :begin begin
3358 :end end
3359 :value value
3360 :post-blank post-blank))))))
3362 (defun org-element-target-interpreter (target contents)
3363 "Interpret TARGET object as Org syntax.
3364 CONTENTS is nil."
3365 (format "<<%s>>" (org-element-property :value target)))
3368 ;;;; Timestamp
3370 (defconst org-element--timestamp-regexp
3371 (concat org-ts-regexp-both
3372 "\\|"
3373 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3374 "\\|"
3375 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3376 "Regexp matching any timestamp type object.")
3378 (defun org-element-timestamp-parser ()
3379 "Parse time stamp at point, if any.
3381 When at a time stamp, return a list whose car is `timestamp', and
3382 cdr a plist with `:type', `:raw-value', `:year-start',
3383 `:month-start', `:day-start', `:hour-start', `:minute-start',
3384 `:year-end', `:month-end', `:day-end', `:hour-end',
3385 `:minute-end', `:repeater-type', `:repeater-value',
3386 `:repeater-unit', `:warning-type', `:warning-value',
3387 `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
3388 Otherwise, return nil.
3390 Assume point is at the beginning of the timestamp."
3391 (when (org-looking-at-p org-element--timestamp-regexp)
3392 (save-excursion
3393 (let* ((begin (point))
3394 (activep (eq (char-after) ?<))
3395 (raw-value
3396 (progn
3397 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3398 (match-string-no-properties 0)))
3399 (date-start (match-string-no-properties 1))
3400 (date-end (match-string 3))
3401 (diaryp (match-beginning 2))
3402 (post-blank (progn (goto-char (match-end 0))
3403 (skip-chars-forward " \t")))
3404 (end (point))
3405 (time-range
3406 (and (not diaryp)
3407 (string-match
3408 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3409 date-start)
3410 (cons (string-to-number (match-string 2 date-start))
3411 (string-to-number (match-string 3 date-start)))))
3412 (type (cond (diaryp 'diary)
3413 ((and activep (or date-end time-range)) 'active-range)
3414 (activep 'active)
3415 ((or date-end time-range) 'inactive-range)
3416 (t 'inactive)))
3417 (repeater-props
3418 (and (not diaryp)
3419 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3420 raw-value)
3421 (list
3422 :repeater-type
3423 (let ((type (match-string 1 raw-value)))
3424 (cond ((equal "++" type) 'catch-up)
3425 ((equal ".+" type) 'restart)
3426 (t 'cumulate)))
3427 :repeater-value (string-to-number (match-string 2 raw-value))
3428 :repeater-unit
3429 (case (string-to-char (match-string 3 raw-value))
3430 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3431 (warning-props
3432 (and (not diaryp)
3433 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3434 (list
3435 :warning-type (if (match-string 1 raw-value) 'first 'all)
3436 :warning-value (string-to-number (match-string 2 raw-value))
3437 :warning-unit
3438 (case (string-to-char (match-string 3 raw-value))
3439 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3440 year-start month-start day-start hour-start minute-start year-end
3441 month-end day-end hour-end minute-end)
3442 ;; Parse date-start.
3443 (unless diaryp
3444 (let ((date (org-parse-time-string date-start t)))
3445 (setq year-start (nth 5 date)
3446 month-start (nth 4 date)
3447 day-start (nth 3 date)
3448 hour-start (nth 2 date)
3449 minute-start (nth 1 date))))
3450 ;; Compute date-end. It can be provided directly in time-stamp,
3451 ;; or extracted from time range. Otherwise, it defaults to the
3452 ;; same values as date-start.
3453 (unless diaryp
3454 (let ((date (and date-end (org-parse-time-string date-end t))))
3455 (setq year-end (or (nth 5 date) year-start)
3456 month-end (or (nth 4 date) month-start)
3457 day-end (or (nth 3 date) day-start)
3458 hour-end (or (nth 2 date) (car time-range) hour-start)
3459 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3460 (list 'timestamp
3461 (nconc (list :type type
3462 :raw-value raw-value
3463 :year-start year-start
3464 :month-start month-start
3465 :day-start day-start
3466 :hour-start hour-start
3467 :minute-start minute-start
3468 :year-end year-end
3469 :month-end month-end
3470 :day-end day-end
3471 :hour-end hour-end
3472 :minute-end minute-end
3473 :begin begin
3474 :end end
3475 :post-blank post-blank)
3476 repeater-props
3477 warning-props))))))
3479 (defun org-element-timestamp-interpreter (timestamp contents)
3480 "Interpret TIMESTAMP object as Org syntax.
3481 CONTENTS is nil."
3482 (let* ((repeat-string
3483 (concat
3484 (case (org-element-property :repeater-type timestamp)
3485 (cumulate "+") (catch-up "++") (restart ".+"))
3486 (let ((val (org-element-property :repeater-value timestamp)))
3487 (and val (number-to-string val)))
3488 (case (org-element-property :repeater-unit timestamp)
3489 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3490 (warning-string
3491 (concat
3492 (case (org-element-property :warning-type timestamp)
3493 (first "--")
3494 (all "-"))
3495 (let ((val (org-element-property :warning-value timestamp)))
3496 (and val (number-to-string val)))
3497 (case (org-element-property :warning-unit timestamp)
3498 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3499 (build-ts-string
3500 ;; Build an Org timestamp string from TIME. ACTIVEP is
3501 ;; non-nil when time stamp is active. If WITH-TIME-P is
3502 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3503 ;; specify a time range in the timestamp. REPEAT-STRING is
3504 ;; the repeater string, if any.
3505 (lambda (time activep &optional with-time-p hour-end minute-end)
3506 (let ((ts (format-time-string
3507 (funcall (if with-time-p 'cdr 'car)
3508 org-time-stamp-formats)
3509 time)))
3510 (when (and hour-end minute-end)
3511 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3512 (setq ts
3513 (replace-match
3514 (format "\\&-%02d:%02d" hour-end minute-end)
3515 nil nil ts)))
3516 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3517 (dolist (s (list repeat-string warning-string))
3518 (when (org-string-nw-p s)
3519 (setq ts (concat (substring ts 0 -1)
3522 (substring ts -1)))))
3523 ;; Return value.
3524 ts)))
3525 (type (org-element-property :type timestamp)))
3526 (case type
3527 ((active inactive)
3528 (let* ((minute-start (org-element-property :minute-start timestamp))
3529 (minute-end (org-element-property :minute-end timestamp))
3530 (hour-start (org-element-property :hour-start timestamp))
3531 (hour-end (org-element-property :hour-end timestamp))
3532 (time-range-p (and hour-start hour-end minute-start minute-end
3533 (or (/= hour-start hour-end)
3534 (/= minute-start minute-end)))))
3535 (funcall
3536 build-ts-string
3537 (encode-time 0
3538 (or minute-start 0)
3539 (or hour-start 0)
3540 (org-element-property :day-start timestamp)
3541 (org-element-property :month-start timestamp)
3542 (org-element-property :year-start timestamp))
3543 (eq type 'active)
3544 (and hour-start minute-start)
3545 (and time-range-p hour-end)
3546 (and time-range-p minute-end))))
3547 ((active-range inactive-range)
3548 (let ((minute-start (org-element-property :minute-start timestamp))
3549 (minute-end (org-element-property :minute-end timestamp))
3550 (hour-start (org-element-property :hour-start timestamp))
3551 (hour-end (org-element-property :hour-end timestamp)))
3552 (concat
3553 (funcall
3554 build-ts-string (encode-time
3556 (or minute-start 0)
3557 (or hour-start 0)
3558 (org-element-property :day-start timestamp)
3559 (org-element-property :month-start timestamp)
3560 (org-element-property :year-start timestamp))
3561 (eq type 'active-range)
3562 (and hour-start minute-start))
3563 "--"
3564 (funcall build-ts-string
3565 (encode-time 0
3566 (or minute-end 0)
3567 (or hour-end 0)
3568 (org-element-property :day-end timestamp)
3569 (org-element-property :month-end timestamp)
3570 (org-element-property :year-end timestamp))
3571 (eq type 'active-range)
3572 (and hour-end minute-end))))))))
3575 ;;;; Underline
3577 (defun org-element-underline-parser ()
3578 "Parse underline object at point, if any.
3580 When at an underline object, return a list whose car is
3581 `underline' and cdr is a plist with `:begin', `:end',
3582 `:contents-begin' and `:contents-end' and `:post-blank' keywords.
3583 Otherwise, return nil.
3585 Assume point is at the first underscore marker."
3586 (save-excursion
3587 (unless (bolp) (backward-char 1))
3588 (when (looking-at org-emph-re)
3589 (let ((begin (match-beginning 2))
3590 (contents-begin (match-beginning 4))
3591 (contents-end (match-end 4))
3592 (post-blank (progn (goto-char (match-end 2))
3593 (skip-chars-forward " \t")))
3594 (end (point)))
3595 (list 'underline
3596 (list :begin begin
3597 :end end
3598 :contents-begin contents-begin
3599 :contents-end contents-end
3600 :post-blank post-blank))))))
3602 (defun org-element-underline-interpreter (underline contents)
3603 "Interpret UNDERLINE object as Org syntax.
3604 CONTENTS is the contents of the object."
3605 (format "_%s_" contents))
3608 ;;;; Verbatim
3610 (defun org-element-verbatim-parser ()
3611 "Parse verbatim object at point, if any.
3613 When at a verbatim object, return a list whose car is `verbatim'
3614 and cdr is a plist with `:value', `:begin', `:end' and
3615 `:post-blank' keywords. Otherwise, return nil.
3617 Assume point is at the first equal sign marker."
3618 (save-excursion
3619 (unless (bolp) (backward-char 1))
3620 (when (looking-at org-emph-re)
3621 (let ((begin (match-beginning 2))
3622 (value (org-match-string-no-properties 4))
3623 (post-blank (progn (goto-char (match-end 2))
3624 (skip-chars-forward " \t")))
3625 (end (point)))
3626 (list 'verbatim
3627 (list :value value
3628 :begin begin
3629 :end end
3630 :post-blank post-blank))))))
3632 (defun org-element-verbatim-interpreter (verbatim contents)
3633 "Interpret VERBATIM object as Org syntax.
3634 CONTENTS is nil."
3635 (format "=%s=" (org-element-property :value verbatim)))
3639 ;;; Parsing Element Starting At Point
3641 ;; `org-element--current-element' is the core function of this section.
3642 ;; It returns the Lisp representation of the element starting at
3643 ;; point.
3645 ;; `org-element--current-element' makes use of special modes. They
3646 ;; are activated for fixed element chaining (e.g., `plain-list' >
3647 ;; `item') or fixed conditional element chaining (e.g., `headline' >
3648 ;; `section'). Special modes are: `first-section', `item',
3649 ;; `node-property', `section' and `table-row'.
3651 (defun org-element--current-element
3652 (limit &optional granularity special structure)
3653 "Parse the element starting at point.
3655 Return value is a list like (TYPE PROPS) where TYPE is the type
3656 of the element and PROPS a plist of properties associated to the
3657 element.
3659 Possible types are defined in `org-element-all-elements'.
3661 LIMIT bounds the search.
3663 Optional argument GRANULARITY determines the depth of the
3664 recursion. Allowed values are `headline', `greater-element',
3665 `element', `object' or nil. When it is broader than `object' (or
3666 nil), secondary values will not be parsed, since they only
3667 contain objects.
3669 Optional argument SPECIAL, when non-nil, can be either
3670 `first-section', `item', `node-property', `section', and
3671 `table-row'.
3673 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3674 be computed.
3676 This function assumes point is always at the beginning of the
3677 element it has to parse."
3678 (save-excursion
3679 (let ((case-fold-search t)
3680 ;; Determine if parsing depth allows for secondary strings
3681 ;; parsing. It only applies to elements referenced in
3682 ;; `org-element-secondary-value-alist'.
3683 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3684 (cond
3685 ;; Item.
3686 ((eq special 'item)
3687 (org-element-item-parser limit structure raw-secondary-p))
3688 ;; Table Row.
3689 ((eq special 'table-row) (org-element-table-row-parser limit))
3690 ;; Node Property.
3691 ((eq special 'node-property) (org-element-node-property-parser limit))
3692 ;; Headline.
3693 ((org-with-limited-levels (org-at-heading-p))
3694 (org-element-headline-parser limit raw-secondary-p))
3695 ;; Sections (must be checked after headline).
3696 ((eq special 'section) (org-element-section-parser limit))
3697 ((eq special 'first-section)
3698 (org-element-section-parser
3699 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3700 limit)))
3701 ;; When not at bol, point is at the beginning of an item or
3702 ;; a footnote definition: next item is always a paragraph.
3703 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3704 ;; Planning and Clock.
3705 ((looking-at org-planning-or-clock-line-re)
3706 (if (equal (match-string 1) org-clock-string)
3707 (org-element-clock-parser limit)
3708 (org-element-planning-parser limit)))
3709 ;; Inlinetask.
3710 ((org-at-heading-p)
3711 (org-element-inlinetask-parser limit raw-secondary-p))
3712 ;; From there, elements can have affiliated keywords.
3713 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3714 (cond
3715 ;; Jumping over affiliated keywords put point off-limits.
3716 ;; Parse them as regular keywords.
3717 ((and (cdr affiliated) (>= (point) limit))
3718 (goto-char (car affiliated))
3719 (org-element-keyword-parser limit nil))
3720 ;; LaTeX Environment.
3721 ((looking-at org-element--latex-begin-environment)
3722 (org-element-latex-environment-parser limit affiliated))
3723 ;; Drawer and Property Drawer.
3724 ((looking-at org-drawer-regexp)
3725 (if (equal (match-string 1) "PROPERTIES")
3726 (org-element-property-drawer-parser limit affiliated)
3727 (org-element-drawer-parser limit affiliated)))
3728 ;; Fixed Width
3729 ((looking-at "[ \t]*:\\( \\|$\\)")
3730 (org-element-fixed-width-parser limit affiliated))
3731 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3732 ;; Keywords.
3733 ((looking-at "[ \t]*#")
3734 (goto-char (match-end 0))
3735 (cond ((looking-at "\\(?: \\|$\\)")
3736 (beginning-of-line)
3737 (org-element-comment-parser limit affiliated))
3738 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3739 (beginning-of-line)
3740 (let ((parser (assoc (upcase (match-string 1))
3741 org-element-block-name-alist)))
3742 (if parser (funcall (cdr parser) limit affiliated)
3743 (org-element-special-block-parser limit affiliated))))
3744 ((looking-at "\\+CALL:")
3745 (beginning-of-line)
3746 (org-element-babel-call-parser limit affiliated))
3747 ((looking-at "\\+BEGIN:? ")
3748 (beginning-of-line)
3749 (org-element-dynamic-block-parser limit affiliated))
3750 ((looking-at "\\+\\S-+:")
3751 (beginning-of-line)
3752 (org-element-keyword-parser limit affiliated))
3754 (beginning-of-line)
3755 (org-element-paragraph-parser limit affiliated))))
3756 ;; Footnote Definition.
3757 ((looking-at org-footnote-definition-re)
3758 (org-element-footnote-definition-parser limit affiliated))
3759 ;; Horizontal Rule.
3760 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3761 (org-element-horizontal-rule-parser limit affiliated))
3762 ;; Diary Sexp.
3763 ((looking-at "%%(")
3764 (org-element-diary-sexp-parser limit affiliated))
3765 ;; Table.
3766 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3767 ;; List.
3768 ((looking-at (org-item-re))
3769 (org-element-plain-list-parser
3770 limit affiliated
3771 (or structure (org-element--list-struct limit))))
3772 ;; Default element: Paragraph.
3773 (t (org-element-paragraph-parser limit affiliated)))))))))
3776 ;; Most elements can have affiliated keywords. When looking for an
3777 ;; element beginning, we want to move before them, as they belong to
3778 ;; that element, and, in the meantime, collect information they give
3779 ;; into appropriate properties. Hence the following function.
3781 (defun org-element--collect-affiliated-keywords (limit)
3782 "Collect affiliated keywords from point down to LIMIT.
3784 Return a list whose CAR is the position at the first of them and
3785 CDR a plist of keywords and values and move point to the
3786 beginning of the first line after them.
3788 As a special case, if element doesn't start at the beginning of
3789 the line (e.g., a paragraph starting an item), CAR is current
3790 position of point and CDR is nil."
3791 (if (not (bolp)) (list (point))
3792 (let ((case-fold-search t)
3793 (origin (point))
3794 ;; RESTRICT is the list of objects allowed in parsed
3795 ;; keywords value.
3796 (restrict (org-element-restriction 'keyword))
3797 output)
3798 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3799 (let* ((raw-kwd (upcase (match-string 1)))
3800 ;; Apply translation to RAW-KWD. From there, KWD is
3801 ;; the official keyword.
3802 (kwd (or (cdr (assoc raw-kwd
3803 org-element-keyword-translation-alist))
3804 raw-kwd))
3805 ;; Find main value for any keyword.
3806 (value
3807 (save-match-data
3808 (org-trim
3809 (buffer-substring-no-properties
3810 (match-end 0) (point-at-eol)))))
3811 ;; PARSEDP is non-nil when keyword should have its
3812 ;; value parsed.
3813 (parsedp (member kwd org-element-parsed-keywords))
3814 ;; If KWD is a dual keyword, find its secondary
3815 ;; value. Maybe parse it.
3816 (dualp (member kwd org-element-dual-keywords))
3817 (dual-value
3818 (and dualp
3819 (let ((sec (org-match-string-no-properties 2)))
3820 (if (or (not sec) (not parsedp)) sec
3821 (org-element-parse-secondary-string sec restrict)))))
3822 ;; Attribute a property name to KWD.
3823 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3824 ;; Now set final shape for VALUE.
3825 (when parsedp
3826 (setq value (org-element-parse-secondary-string value restrict)))
3827 (when dualp
3828 (setq value (and (or value dual-value) (cons value dual-value))))
3829 (when (or (member kwd org-element-multiple-keywords)
3830 ;; Attributes can always appear on multiple lines.
3831 (string-match "^ATTR_" kwd))
3832 (setq value (cons value (plist-get output kwd-sym))))
3833 ;; Eventually store the new value in OUTPUT.
3834 (setq output (plist-put output kwd-sym value))
3835 ;; Move to next keyword.
3836 (forward-line)))
3837 ;; If affiliated keywords are orphaned: move back to first one.
3838 ;; They will be parsed as a paragraph.
3839 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3840 ;; Return value.
3841 (cons origin output))))
3845 ;;; The Org Parser
3847 ;; The two major functions here are `org-element-parse-buffer', which
3848 ;; parses Org syntax inside the current buffer, taking into account
3849 ;; region, narrowing, or even visibility if specified, and
3850 ;; `org-element-parse-secondary-string', which parses objects within
3851 ;; a given string.
3853 ;; The (almost) almighty `org-element-map' allows to apply a function
3854 ;; on elements or objects matching some type, and accumulate the
3855 ;; resulting values. In an export situation, it also skips unneeded
3856 ;; parts of the parse tree.
3858 (defun org-element-parse-buffer (&optional granularity visible-only)
3859 "Recursively parse the buffer and return structure.
3860 If narrowing is in effect, only parse the visible part of the
3861 buffer.
3863 Optional argument GRANULARITY determines the depth of the
3864 recursion. It can be set to the following symbols:
3866 `headline' Only parse headlines.
3867 `greater-element' Don't recurse into greater elements excepted
3868 headlines and sections. Thus, elements
3869 parsed are the top-level ones.
3870 `element' Parse everything but objects and plain text.
3871 `object' Parse the complete buffer (default).
3873 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3874 elements.
3876 An element or an objects is represented as a list with the
3877 pattern (TYPE PROPERTIES CONTENTS), where :
3879 TYPE is a symbol describing the element or object. See
3880 `org-element-all-elements' and `org-element-all-objects' for an
3881 exhaustive list of such symbols. One can retrieve it with
3882 `org-element-type' function.
3884 PROPERTIES is the list of attributes attached to the element or
3885 object, as a plist. Although most of them are specific to the
3886 element or object type, all types share `:begin', `:end',
3887 `:post-blank' and `:parent' properties, which respectively
3888 refer to buffer position where the element or object starts,
3889 ends, the number of white spaces or blank lines after it, and
3890 the element or object containing it. Properties values can be
3891 obtained by using `org-element-property' function.
3893 CONTENTS is a list of elements, objects or raw strings
3894 contained in the current element or object, when applicable.
3895 One can access them with `org-element-contents' function.
3897 The Org buffer has `org-data' as type and nil as properties.
3898 `org-element-map' function can be used to find specific elements
3899 or objects within the parse tree.
3901 This function assumes that current major mode is `org-mode'."
3902 (save-excursion
3903 (goto-char (point-min))
3904 (org-skip-whitespace)
3905 (org-element--parse-elements
3906 (point-at-bol) (point-max)
3907 ;; Start in `first-section' mode so text before the first
3908 ;; headline belongs to a section.
3909 'first-section nil granularity visible-only (list 'org-data nil))))
3911 (defun org-element-parse-secondary-string (string restriction &optional parent)
3912 "Recursively parse objects in STRING and return structure.
3914 RESTRICTION is a symbol limiting the object types that will be
3915 looked after.
3917 Optional argument PARENT, when non-nil, is the element or object
3918 containing the secondary string. It is used to set correctly
3919 `:parent' property within the string."
3920 ;; Copy buffer-local variables listed in
3921 ;; `org-element-object-variables' into temporary buffer. This is
3922 ;; required since object parsing is dependent on these variables.
3923 (let ((pairs (delq nil (mapcar (lambda (var)
3924 (when (boundp var)
3925 (cons var (symbol-value var))))
3926 org-element-object-variables))))
3927 (with-temp-buffer
3928 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
3929 (insert string)
3930 (let ((secondary (org-element--parse-objects
3931 (point-min) (point-max) nil restriction)))
3932 (when parent
3933 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
3934 secondary))
3935 secondary))))
3937 (defun org-element-map
3938 (data types fun &optional info first-match no-recursion with-affiliated)
3939 "Map a function on selected elements or objects.
3941 DATA is a parse tree, an element, an object, a string, or a list
3942 of such constructs. TYPES is a symbol or list of symbols of
3943 elements or objects types (see `org-element-all-elements' and
3944 `org-element-all-objects' for a complete list of types). FUN is
3945 the function called on the matching element or object. It has to
3946 accept one argument: the element or object itself.
3948 When optional argument INFO is non-nil, it should be a plist
3949 holding export options. In that case, parts of the parse tree
3950 not exportable according to that property list will be skipped.
3952 When optional argument FIRST-MATCH is non-nil, stop at the first
3953 match for which FUN doesn't return nil, and return that value.
3955 Optional argument NO-RECURSION is a symbol or a list of symbols
3956 representing elements or objects types. `org-element-map' won't
3957 enter any recursive element or object whose type belongs to that
3958 list. Though, FUN can still be applied on them.
3960 When optional argument WITH-AFFILIATED is non-nil, FUN will also
3961 apply to matching objects within parsed affiliated keywords (see
3962 `org-element-parsed-keywords').
3964 Nil values returned from FUN do not appear in the results.
3967 Examples:
3968 ---------
3970 Assuming TREE is a variable containing an Org buffer parse tree,
3971 the following example will return a flat list of all `src-block'
3972 and `example-block' elements in it:
3974 \(org-element-map tree '(example-block src-block) 'identity)
3976 The following snippet will find the first headline with a level
3977 of 1 and a \"phone\" tag, and will return its beginning position:
3979 \(org-element-map tree 'headline
3980 \(lambda (hl)
3981 \(and (= (org-element-property :level hl) 1)
3982 \(member \"phone\" (org-element-property :tags hl))
3983 \(org-element-property :begin hl)))
3984 nil t)
3986 The next example will return a flat list of all `plain-list' type
3987 elements in TREE that are not a sub-list themselves:
3989 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
3991 Eventually, this example will return a flat list of all `bold'
3992 type objects containing a `latex-snippet' type object, even
3993 looking into captions:
3995 \(org-element-map tree 'bold
3996 \(lambda (b)
3997 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
3998 nil nil nil t)"
3999 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4000 (unless (listp types) (setq types (list types)))
4001 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4002 ;; Recursion depth is determined by --CATEGORY.
4003 (let* ((--category
4004 (catch 'found
4005 (let ((category 'greater-elements))
4006 (mapc (lambda (type)
4007 (cond ((or (memq type org-element-all-objects)
4008 (eq type 'plain-text))
4009 ;; If one object is found, the function
4010 ;; has to recurse into every object.
4011 (throw 'found 'objects))
4012 ((not (memq type org-element-greater-elements))
4013 ;; If one regular element is found, the
4014 ;; function has to recurse, at least,
4015 ;; into every element it encounters.
4016 (and (not (eq category 'elements))
4017 (setq category 'elements)))))
4018 types)
4019 category)))
4020 ;; Compute properties for affiliated keywords if necessary.
4021 (--affiliated-alist
4022 (and with-affiliated
4023 (mapcar (lambda (kwd)
4024 (cons kwd (intern (concat ":" (downcase kwd)))))
4025 org-element-affiliated-keywords)))
4026 --acc
4027 --walk-tree
4028 (--walk-tree
4029 (function
4030 (lambda (--data)
4031 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4032 ;; holding contextual information.
4033 (let ((--type (org-element-type --data)))
4034 (cond
4035 ((not --data))
4036 ;; Ignored element in an export context.
4037 ((and info (memq --data (plist-get info :ignore-list))))
4038 ;; List of elements or objects.
4039 ((not --type) (mapc --walk-tree --data))
4040 ;; Unconditionally enter parse trees.
4041 ((eq --type 'org-data)
4042 (mapc --walk-tree (org-element-contents --data)))
4044 ;; Check if TYPE is matching among TYPES. If so,
4045 ;; apply FUN to --DATA and accumulate return value
4046 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4047 (when (memq --type types)
4048 (let ((result (funcall fun --data)))
4049 (cond ((not result))
4050 (first-match (throw '--map-first-match result))
4051 (t (push result --acc)))))
4052 ;; If --DATA has a secondary string that can contain
4053 ;; objects with their type among TYPES, look into it.
4054 (when (and (eq --category 'objects) (not (stringp --data)))
4055 (let ((sec-prop
4056 (assq --type org-element-secondary-value-alist)))
4057 (when sec-prop
4058 (funcall --walk-tree
4059 (org-element-property (cdr sec-prop) --data)))))
4060 ;; If --DATA has any affiliated keywords and
4061 ;; WITH-AFFILIATED is non-nil, look for objects in
4062 ;; them.
4063 (when (and with-affiliated
4064 (eq --category 'objects)
4065 (memq --type org-element-all-elements))
4066 (mapc (lambda (kwd-pair)
4067 (let ((kwd (car kwd-pair))
4068 (value (org-element-property
4069 (cdr kwd-pair) --data)))
4070 ;; Pay attention to the type of value.
4071 ;; Preserve order for multiple keywords.
4072 (cond
4073 ((not value))
4074 ((and (member kwd org-element-multiple-keywords)
4075 (member kwd org-element-dual-keywords))
4076 (mapc (lambda (line)
4077 (funcall --walk-tree (cdr line))
4078 (funcall --walk-tree (car line)))
4079 (reverse value)))
4080 ((member kwd org-element-multiple-keywords)
4081 (mapc (lambda (line) (funcall --walk-tree line))
4082 (reverse value)))
4083 ((member kwd org-element-dual-keywords)
4084 (funcall --walk-tree (cdr value))
4085 (funcall --walk-tree (car value)))
4086 (t (funcall --walk-tree value)))))
4087 --affiliated-alist))
4088 ;; Determine if a recursion into --DATA is possible.
4089 (cond
4090 ;; --TYPE is explicitly removed from recursion.
4091 ((memq --type no-recursion))
4092 ;; --DATA has no contents.
4093 ((not (org-element-contents --data)))
4094 ;; Looking for greater elements but --DATA is simply
4095 ;; an element or an object.
4096 ((and (eq --category 'greater-elements)
4097 (not (memq --type org-element-greater-elements))))
4098 ;; Looking for elements but --DATA is an object.
4099 ((and (eq --category 'elements)
4100 (memq --type org-element-all-objects)))
4101 ;; In any other case, map contents.
4102 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4103 (catch '--map-first-match
4104 (funcall --walk-tree data)
4105 ;; Return value in a proper order.
4106 (nreverse --acc))))
4107 (put 'org-element-map 'lisp-indent-function 2)
4109 ;; The following functions are internal parts of the parser.
4111 ;; The first one, `org-element--parse-elements' acts at the element's
4112 ;; level.
4114 ;; The second one, `org-element--parse-objects' applies on all objects
4115 ;; of a paragraph or a secondary string.
4117 ;; More precisely, that function looks for every allowed object type
4118 ;; first. Then, it discards failed searches, keeps further matches,
4119 ;; and searches again types matched behind point, for subsequent
4120 ;; calls. Thus, searching for a given type fails only once, and every
4121 ;; object is searched only once at top level (but sometimes more for
4122 ;; nested types).
4124 (defun org-element--parse-elements
4125 (beg end special structure granularity visible-only acc)
4126 "Parse elements between BEG and END positions.
4128 SPECIAL prioritize some elements over the others. It can be set
4129 to `first-section', `section' `item' or `table-row'.
4131 When value is `item', STRUCTURE will be used as the current list
4132 structure.
4134 GRANULARITY determines the depth of the recursion. See
4135 `org-element-parse-buffer' for more information.
4137 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4138 elements.
4140 Elements are accumulated into ACC."
4141 (save-excursion
4142 (goto-char beg)
4143 ;; Visible only: skip invisible parts at the beginning of the
4144 ;; element.
4145 (when (and visible-only (org-invisible-p2))
4146 (goto-char (min (1+ (org-find-visible)) end)))
4147 ;; When parsing only headlines, skip any text before first one.
4148 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4149 (org-with-limited-levels (outline-next-heading)))
4150 ;; Main loop start.
4151 (while (< (point) end)
4152 ;; Find current element's type and parse it accordingly to
4153 ;; its category.
4154 (let* ((element (org-element--current-element
4155 end granularity special structure))
4156 (type (org-element-type element))
4157 (cbeg (org-element-property :contents-begin element)))
4158 (goto-char (org-element-property :end element))
4159 ;; Visible only: skip invisible parts between siblings.
4160 (when (and visible-only (org-invisible-p2))
4161 (goto-char (min (1+ (org-find-visible)) end)))
4162 ;; Fill ELEMENT contents by side-effect.
4163 (cond
4164 ;; If element has no contents, don't modify it.
4165 ((not cbeg))
4166 ;; Greater element: parse it between `contents-begin' and
4167 ;; `contents-end'. Make sure GRANULARITY allows the
4168 ;; recursion, or ELEMENT is a headline, in which case going
4169 ;; inside is mandatory, in order to get sub-level headings.
4170 ((and (memq type org-element-greater-elements)
4171 (or (memq granularity '(element object nil))
4172 (and (eq granularity 'greater-element)
4173 (eq type 'section))
4174 (eq type 'headline)))
4175 (org-element--parse-elements
4176 cbeg (org-element-property :contents-end element)
4177 ;; Possibly switch to a special mode.
4178 (case type
4179 (headline 'section)
4180 (plain-list 'item)
4181 (property-drawer 'node-property)
4182 (table 'table-row))
4183 (and (memq type '(item plain-list))
4184 (org-element-property :structure element))
4185 granularity visible-only element))
4186 ;; ELEMENT has contents. Parse objects inside, if
4187 ;; GRANULARITY allows it.
4188 ((memq granularity '(object nil))
4189 (org-element--parse-objects
4190 cbeg (org-element-property :contents-end element) element
4191 (org-element-restriction type))))
4192 (org-element-adopt-elements acc element)))
4193 ;; Return result.
4194 acc))
4196 (defconst org-element--object-regexp
4197 (mapconcat #'identity
4198 (let ((link-types (regexp-opt org-link-types)))
4199 (list
4200 ;; Sub/superscript.
4201 "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
4202 ;; Bold, code, italic, strike-through, underline and
4203 ;; verbatim.
4204 (concat "[*~=+_/]"
4205 (format "[^%s]" (nth 2 org-emphasis-regexp-components)))
4206 ;; Plain links.
4207 (concat "\\<" link-types ":")
4208 ;; Objects starting with "[": regular link, footnote
4209 ;; reference, statistics cookie, timestamp (inactive).
4210 "\\[\\(?:fn:\\|\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)\\|\\[\\)"
4211 ;; Objects starting with "@": export snippets.
4212 "@@"
4213 ;; Objects starting with "{": macro.
4214 "{{{"
4215 ;; Objects starting with "<" : timestamp (active,
4216 ;; diary), target, radio target and angular links.
4217 (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
4218 ;; Objects starting with "$": latex fragment.
4219 "\\$"
4220 ;; Objects starting with "\": line break, entity,
4221 ;; latex fragment.
4222 "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\)"
4223 ;; Objects starting with raw text: inline Babel
4224 ;; source block, inline Babel call.
4225 "\\(?:call\\|src\\)_"))
4226 "\\|")
4227 "Regexp possibly matching the beginning of an object.
4228 This regexp allows false positives. Dedicated parser (e.g.,
4229 `org-export-bold-parser') will take care of further filtering.
4230 Radio links are not matched by this regexp, as they are treated
4231 specially in `org-element--object-lex'.")
4233 (defun org-element--object-lex (restriction)
4234 "Return next object in current buffer or nil.
4235 RESTRICTION is a list of object types, as symbols, that should be
4236 looked after. This function assumes that the buffer is narrowed
4237 to an appropriate container (e.g., a paragraph)."
4238 (if (memq 'table-cell restriction) (org-element-table-cell-parser)
4239 (save-excursion
4240 (let ((limit (and org-target-link-regexp
4241 (save-excursion
4242 (or (bolp) (backward-char))
4243 (re-search-forward org-target-link-regexp nil t))
4244 (match-beginning 1)))
4245 found)
4246 (while (and (not found)
4247 (re-search-forward org-element--object-regexp limit t))
4248 (goto-char (match-beginning 0))
4249 (let ((result (match-string 0)))
4250 (setq found
4251 (cond
4252 ((eq (compare-strings result nil nil "call_" nil nil t) t)
4253 (and (memq 'inline-babel-call restriction)
4254 (org-element-inline-babel-call-parser)))
4255 ((eq (compare-strings result nil nil "src_" nil nil t) t)
4256 (and (memq 'inline-src-block restriction)
4257 (org-element-inline-src-block-parser)))
4259 (case (char-after)
4260 (?^ (and (memq 'superscript restriction)
4261 (org-element-superscript-parser)))
4262 (?_ (or (and (memq 'subscript restriction)
4263 (org-element-subscript-parser))
4264 (and (memq 'underline restriction)
4265 (org-element-underline-parser))))
4266 (?* (and (memq 'bold restriction)
4267 (org-element-bold-parser)))
4268 (?/ (and (memq 'italic restriction)
4269 (org-element-italic-parser)))
4270 (?~ (and (memq 'code restriction)
4271 (org-element-code-parser)))
4272 (?= (and (memq 'verbatim restriction)
4273 (org-element-verbatim-parser)))
4274 (?+ (and (memq 'strike-through restriction)
4275 (org-element-strike-through-parser)))
4276 (?@ (and (memq 'export-snippet restriction)
4277 (org-element-export-snippet-parser)))
4278 (?{ (and (memq 'macro restriction)
4279 (org-element-macro-parser)))
4280 (?$ (and (memq 'latex-fragment restriction)
4281 (org-element-latex-fragment-parser)))
4283 (if (eq (aref result 1) ?<)
4284 (or (and (memq 'radio-target restriction)
4285 (org-element-radio-target-parser))
4286 (and (memq 'target restriction)
4287 (org-element-target-parser)))
4288 (or (and (memq 'timestamp restriction)
4289 (org-element-timestamp-parser))
4290 (and (memq 'link restriction)
4291 (org-element-link-parser)))))
4292 (?\\
4293 (if (eq (aref result 1) ?\\)
4294 (and (memq 'line-break restriction)
4295 (org-element-line-break-parser))
4296 (or (and (memq 'entity restriction)
4297 (org-element-entity-parser))
4298 (and (memq 'latex-fragment restriction)
4299 (org-element-latex-fragment-parser)))))
4300 (?\[
4301 (if (eq (aref result 1) ?\[)
4302 (and (memq 'link restriction)
4303 (org-element-link-parser))
4304 (or (and (memq 'footnote-reference restriction)
4305 (org-element-footnote-reference-parser))
4306 (and (memq 'timestamp restriction)
4307 (org-element-timestamp-parser))
4308 (and (memq 'statistics-cookie restriction)
4309 (org-element-statistics-cookie-parser)))))
4310 ;; This is probably a plain link.
4311 (otherwise (and (or (memq 'link restriction)
4312 (memq 'plain-link restriction))
4313 (org-element-link-parser)))))))
4314 (or (eobp) (forward-char))))
4315 (cond (found)
4316 ;; Radio link.
4317 ((and limit (memq 'link restriction))
4318 (goto-char limit) (org-element-link-parser)))))))
4320 (defun org-element--parse-objects (beg end acc restriction)
4321 "Parse objects between BEG and END and return recursive structure.
4323 Objects are accumulated in ACC.
4325 RESTRICTION is a list of object successors which are allowed in
4326 the current object."
4327 (save-excursion
4328 (save-restriction
4329 (narrow-to-region beg end)
4330 (goto-char (point-min))
4331 (let (next-object)
4332 (while (and (not (eobp))
4333 (setq next-object (org-element--object-lex restriction)))
4334 ;; 1. Text before any object. Untabify it.
4335 (let ((obj-beg (org-element-property :begin next-object)))
4336 (unless (= (point) obj-beg)
4337 (setq acc
4338 (org-element-adopt-elements
4340 (replace-regexp-in-string
4341 "\t" (make-string tab-width ? )
4342 (buffer-substring-no-properties (point) obj-beg))))))
4343 ;; 2. Object...
4344 (let ((obj-end (org-element-property :end next-object))
4345 (cont-beg (org-element-property :contents-begin next-object)))
4346 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4347 ;; a recursive type.
4348 (when (and cont-beg
4349 (memq (car next-object) org-element-recursive-objects))
4350 (org-element--parse-objects
4351 cont-beg (org-element-property :contents-end next-object)
4352 next-object (org-element-restriction next-object)))
4353 (setq acc (org-element-adopt-elements acc next-object))
4354 (goto-char obj-end))))
4355 ;; 3. Text after last object. Untabify it.
4356 (unless (eobp)
4357 (setq acc
4358 (org-element-adopt-elements
4360 (replace-regexp-in-string
4361 "\t" (make-string tab-width ? )
4362 (buffer-substring-no-properties (point) end)))))
4363 ;; Result.
4364 acc)))
4368 ;;; Towards A Bijective Process
4370 ;; The parse tree obtained with `org-element-parse-buffer' is really
4371 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4372 ;; interpreted and expanded into a string with canonical Org syntax.
4373 ;; Hence `org-element-interpret-data'.
4375 ;; The function relies internally on
4376 ;; `org-element--interpret-affiliated-keywords'.
4378 ;;;###autoload
4379 (defun org-element-interpret-data (data &optional pseudo-objects)
4380 "Interpret DATA as Org syntax.
4382 DATA is a parse tree, an element, an object or a secondary string
4383 to interpret.
4385 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4386 new types that should be treated as objects. An unknown type not
4387 belonging to this list is seen as a pseudo-element instead. Both
4388 pseudo-objects and pseudo-elements are transparent entities, i.e.
4389 only their contents are interpreted.
4391 Return Org syntax as a string."
4392 (org-element--interpret-data-1 data nil pseudo-objects))
4394 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4395 "Interpret DATA as Org syntax.
4397 DATA is a parse tree, an element, an object or a secondary string
4398 to interpret. PARENT is used for recursive calls. It contains
4399 the element or object containing data, or nil. PSEUDO-OBJECTS
4400 are list of symbols defining new element or object types.
4401 Unknown types that don't belong to this list are treated as
4402 pseudo-elements instead.
4404 Return Org syntax as a string."
4405 (let* ((type (org-element-type data))
4406 ;; Find interpreter for current object or element. If it
4407 ;; doesn't exist (e.g. this is a pseudo object or element),
4408 ;; return contents, if any.
4409 (interpret
4410 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4411 (if (fboundp fun) fun (lambda (data contents) contents))))
4412 (results
4413 (cond
4414 ;; Secondary string.
4415 ((not type)
4416 (mapconcat
4417 (lambda (obj)
4418 (org-element--interpret-data-1 obj parent pseudo-objects))
4419 data ""))
4420 ;; Full Org document.
4421 ((eq type 'org-data)
4422 (mapconcat
4423 (lambda (obj)
4424 (org-element--interpret-data-1 obj parent pseudo-objects))
4425 (org-element-contents data) ""))
4426 ;; Plain text: return it.
4427 ((stringp data) data)
4428 ;; Element or object without contents.
4429 ((not (org-element-contents data)) (funcall interpret data nil))
4430 ;; Element or object with contents.
4432 (funcall interpret data
4433 ;; Recursively interpret contents.
4434 (mapconcat
4435 (lambda (obj)
4436 (org-element--interpret-data-1 obj data pseudo-objects))
4437 (org-element-contents
4438 (if (not (memq type '(paragraph verse-block)))
4439 data
4440 ;; Fix indentation of elements containing
4441 ;; objects. We ignore `table-row' elements
4442 ;; as they are one line long anyway.
4443 (org-element-normalize-contents
4444 data
4445 ;; When normalizing first paragraph of an
4446 ;; item or a footnote-definition, ignore
4447 ;; first line's indentation.
4448 (and (eq type 'paragraph)
4449 (equal data (car (org-element-contents parent)))
4450 (memq (org-element-type parent)
4451 '(footnote-definition item))))))
4452 ""))))))
4453 (if (memq type '(org-data plain-text nil)) results
4454 ;; Build white spaces. If no `:post-blank' property is
4455 ;; specified, assume its value is 0.
4456 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4457 (if (or (memq type org-element-all-objects)
4458 (memq type pseudo-objects))
4459 (concat results (make-string post-blank ?\s))
4460 (concat
4461 (org-element--interpret-affiliated-keywords data)
4462 (org-element-normalize-string results)
4463 (make-string post-blank ?\n)))))))
4465 (defun org-element--interpret-affiliated-keywords (element)
4466 "Return ELEMENT's affiliated keywords as Org syntax.
4467 If there is no affiliated keyword, return the empty string."
4468 (let ((keyword-to-org
4469 (function
4470 (lambda (key value)
4471 (let (dual)
4472 (when (member key org-element-dual-keywords)
4473 (setq dual (cdr value) value (car value)))
4474 (concat "#+" key
4475 (and dual
4476 (format "[%s]" (org-element-interpret-data dual)))
4477 ": "
4478 (if (member key org-element-parsed-keywords)
4479 (org-element-interpret-data value)
4480 value)
4481 "\n"))))))
4482 (mapconcat
4483 (lambda (prop)
4484 (let ((value (org-element-property prop element))
4485 (keyword (upcase (substring (symbol-name prop) 1))))
4486 (when value
4487 (if (or (member keyword org-element-multiple-keywords)
4488 ;; All attribute keywords can have multiple lines.
4489 (string-match "^ATTR_" keyword))
4490 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4491 (reverse value)
4493 (funcall keyword-to-org keyword value)))))
4494 ;; List all ELEMENT's properties matching an attribute line or an
4495 ;; affiliated keyword, but ignore translated keywords since they
4496 ;; cannot belong to the property list.
4497 (loop for prop in (nth 1 element) by 'cddr
4498 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4499 (or (string-match "^ATTR_" keyword)
4500 (and
4501 (member keyword org-element-affiliated-keywords)
4502 (not (assoc keyword
4503 org-element-keyword-translation-alist)))))
4504 collect prop)
4505 "")))
4507 ;; Because interpretation of the parse tree must return the same
4508 ;; number of blank lines between elements and the same number of white
4509 ;; space after objects, some special care must be given to white
4510 ;; spaces.
4512 ;; The first function, `org-element-normalize-string', ensures any
4513 ;; string different from the empty string will end with a single
4514 ;; newline character.
4516 ;; The second function, `org-element-normalize-contents', removes
4517 ;; global indentation from the contents of the current element.
4519 (defun org-element-normalize-string (s)
4520 "Ensure string S ends with a single newline character.
4522 If S isn't a string return it unchanged. If S is the empty
4523 string, return it. Otherwise, return a new string with a single
4524 newline character at its end."
4525 (cond
4526 ((not (stringp s)) s)
4527 ((string= "" s) "")
4528 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4529 (replace-match "\n" nil nil s)))))
4531 (defun org-element-normalize-contents (element &optional ignore-first)
4532 "Normalize plain text in ELEMENT's contents.
4534 ELEMENT must only contain plain text and objects.
4536 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4537 indentation to compute maximal common indentation.
4539 Return the normalized element that is element with global
4540 indentation removed from its contents. The function assumes that
4541 indentation is not done with TAB characters."
4542 (let* ((min-ind most-positive-fixnum)
4543 find-min-ind ; For byte-compiler.
4544 (find-min-ind
4545 (function
4546 ;; Return minimal common indentation within BLOB. This is
4547 ;; done by walking recursively BLOB and updating MIN-IND
4548 ;; along the way. FIRST-FLAG is non-nil when the first
4549 ;; string hasn't been seen yet. It is required as this
4550 ;; string is the only one whose indentation doesn't happen
4551 ;; after a newline character.
4552 (lambda (blob first-flag)
4553 (dolist (object (org-element-contents blob))
4554 (when (and first-flag (stringp object))
4555 (setq first-flag nil)
4556 (string-match "\\`\\( *\\)" object)
4557 (let ((len (length (match-string 1 object))))
4558 ;; An indentation of zero means no string will be
4559 ;; modified. Quit the process.
4560 (if (zerop len) (throw 'zero (setq min-ind 0))
4561 (setq min-ind (min len min-ind)))))
4562 (cond
4563 ((stringp object)
4564 (dolist (line (delq "" (cdr (org-split-string object " *\n"))))
4565 (setq min-ind (min (org-get-indentation line) min-ind))))
4566 ((memq (org-element-type object) org-element-recursive-objects)
4567 (funcall find-min-ind object first-flag))))))))
4568 ;; Find minimal indentation in ELEMENT.
4569 (catch 'zero (funcall find-min-ind element (not ignore-first)))
4570 (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
4571 ;; Build ELEMENT back, replacing each string with the same
4572 ;; string minus common indentation.
4573 (let* (build ; For byte compiler.
4574 (build
4575 (function
4576 (lambda (blob first-flag)
4577 ;; Return BLOB with all its strings indentation
4578 ;; shortened from MIN-IND white spaces. FIRST-FLAG
4579 ;; is non-nil when the first string hasn't been seen
4580 ;; yet.
4581 (setcdr (cdr blob)
4582 (mapcar
4583 #'(lambda (object)
4584 (when (and first-flag (stringp object))
4585 (setq first-flag nil)
4586 (setq object
4587 (replace-regexp-in-string
4588 (format "\\` \\{%d\\}" min-ind)
4589 "" object)))
4590 (cond
4591 ((stringp object)
4592 (replace-regexp-in-string
4593 (format "\n \\{%d\\}" min-ind) "\n" object))
4594 ((memq (org-element-type object)
4595 org-element-recursive-objects)
4596 (funcall build object first-flag))
4597 (t object)))
4598 (org-element-contents blob)))
4599 blob))))
4600 (funcall build element (not ignore-first))))))
4604 ;;; Cache
4606 ;; Implement a caching mechanism for `org-element-at-point' and
4607 ;; `org-element-context', which see.
4609 ;; A single public function is provided: `org-element-cache-reset'.
4611 ;; Cache is enabled by default, but can be disabled globally with
4612 ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
4613 ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
4614 ;; can be tweaked to control caching behaviour.
4616 ;; Internally, parsed elements are stored in an AVL tree,
4617 ;; `org-element--cache'. This tree is updated lazily: whenever
4618 ;; a change happens to the buffer, a synchronization request is
4619 ;; registered in `org-element--cache-sync-requests' (see
4620 ;; `org-element--cache-submit-request'). During idle time, requests
4621 ;; are processed by `org-element--cache-sync'. Synchronization also
4622 ;; happens when an element is required from the cache. In this case,
4623 ;; the process stops as soon as the needed element is up-to-date.
4625 ;; A synchronization request can only apply on a synchronized part of
4626 ;; the cache. Therefore, the cache is updated at least to the
4627 ;; location where the new request applies. Thus, requests are ordered
4628 ;; from left to right and all elements starting before the first
4629 ;; request are correct. This property is used by functions like
4630 ;; `org-element--cache-find' to retrieve elements in the part of the
4631 ;; cache that can be trusted.
4633 ;; A request applies to every element, starting from its original
4634 ;; location (or key, see below). When a request is processed, it
4635 ;; moves forward and may collide the next one. In this case, both
4636 ;; requests are merged into a new one that starts from that element.
4637 ;; As a consequence, the whole synchronization complexity does not
4638 ;; depend on the number of pending requests, but on the number of
4639 ;; elements the very first request will be applied on.
4641 ;; Elements cannot be accessed through their beginning position, which
4642 ;; may or may not be up-to-date. Instead, each element in the tree is
4643 ;; associated to a key, obtained with `org-element--cache-key'. This
4644 ;; mechanism is robust enough to preserve total order among elements
4645 ;; even when the tree is only partially synchronized.
4647 ;; Objects contained in an element are stored in a hash table,
4648 ;; `org-element--cache-objects'.
4651 (defvar org-element-use-cache t
4652 "Non nil when Org parser should cache its results.
4653 This is mostly for debugging purpose.")
4655 (defvar org-element-cache-sync-idle-time 0.6
4656 "Length, in seconds, of idle time before syncing cache.")
4658 (defvar org-element-cache-sync-duration (seconds-to-time 0.04)
4659 "Maximum duration, as a time value, for a cache synchronization.
4660 If the synchronization is not over after this delay, the process
4661 pauses and resumes after `org-element-cache-sync-break'
4662 seconds.")
4664 (defvar org-element-cache-sync-break (seconds-to-time 0.3)
4665 "Duration, as a time value, of the pause between synchronizations.
4666 See `org-element-cache-sync-duration' for more information.")
4669 ;;;; Data Structure
4671 (defvar org-element--cache nil
4672 "AVL tree used to cache elements.
4673 Each node of the tree contains an element. Comparison is done
4674 with `org-element--cache-compare'. This cache is used in
4675 `org-element-at-point'.")
4677 (defvar org-element--cache-objects nil
4678 "Hash table used as to cache objects.
4679 Key is an element, as returned by `org-element-at-point', and
4680 value is an alist where each association is:
4682 \(PARENT COMPLETEP . OBJECTS)
4684 where PARENT is an element or object, COMPLETEP is a boolean,
4685 non-nil when all direct children of parent are already cached and
4686 OBJECTS is a list of such children, as objects, from farthest to
4687 closest.
4689 In the following example, \\alpha, bold object and \\beta are
4690 contained within a paragraph
4692 \\alpha *\\beta*
4694 If the paragraph is completely parsed, OBJECTS-DATA will be
4696 \((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
4697 \(BOLD-OBJECT t ENTITY-OBJECT))
4699 whereas in a partially parsed paragraph, it could be
4701 \((PARAGRAPH nil ENTITY-OBJECT))
4703 This cache is used in `org-element-context'.")
4705 (defvar org-element--cache-sync-requests nil
4706 "List of pending synchronization requests.
4708 A request is a vector with the following pattern:
4710 \[NEXT BEG END OFFSET OUTREACH PARENT PHASE]
4712 Processing a synchronization request consists of three phases:
4714 0. Delete modified elements,
4715 1. Fill missing area in cache,
4716 2. Shift positions and re-parent elements after the changes.
4718 During phase 0, NEXT is the key of the first element to be
4719 removed, BEG and END is buffer position delimiting the
4720 modifications. Elements starting between them (inclusive) are
4721 removed and so are those contained within OUTREACH. PARENT, when
4722 non-nil, is the parent of the first element to be removed.
4724 During phase 1, NEXT is the key of the next known element in
4725 cache and BEG its beginning position. Parse buffer between that
4726 element and the one before it in order to determine the parent of
4727 the next element. Set PARENT to the element containing NEXT.
4729 During phase 2, NEXT is the key of the next element to shift in
4730 the parse tree. All elements starting from this one have their
4731 properties relatives to buffer positions shifted by integer
4732 OFFSET and, if they belong to element PARENT, are adopted by it.
4734 PHASE specifies the phase number, as an integer.")
4736 (defvar org-element--cache-sync-timer nil
4737 "Timer used for cache synchronization.")
4739 (defvar org-element--cache-sync-keys nil
4740 "Hash table used to store keys during synchronization.
4741 See `org-element--cache-key' for more information.")
4743 (defsubst org-element--cache-key (element)
4744 "Return a unique key for ELEMENT in cache tree.
4746 Keys are used to keep a total order among elements in the cache.
4747 Comparison is done with `org-element--cache-key-less-p'.
4749 When no synchronization is taking place, a key is simply the
4750 beginning position of the element, or that position plus one in
4751 the case of an first item (respectively row) in
4752 a list (respectively a table).
4754 During a synchronization, the key is the one the element had when
4755 the cache was synchronized for the last time. Elements added to
4756 cache during the synchronization get a new key generated with
4757 `org-element--cache-generate-key'.
4759 Such keys are stored in `org-element--cache-sync-keys'. The hash
4760 table is cleared once the synchronization is complete."
4761 (or (gethash element org-element--cache-sync-keys)
4762 (let* ((begin (org-element-property :begin element))
4763 ;; Increase beginning position of items (respectively
4764 ;; table rows) by one, so the first item can get
4765 ;; a different key from its parent list (respectively
4766 ;; table).
4767 (key (if (memq (org-element-type element) '(item table-row))
4768 (1+ begin)
4769 begin)))
4770 (if org-element--cache-sync-requests
4771 (puthash element key org-element--cache-sync-keys)
4772 key))))
4774 (defun org-element--cache-generate-key (lower upper)
4775 "Generate a key between LOWER and UPPER.
4777 LOWER and UPPER are integers or lists, possibly empty.
4779 If LOWER and UPPER are equals, return LOWER. Otherwise, return
4780 a unique key, as an integer or a list of integers, according to
4781 the following rules:
4783 - LOWER and UPPER are compared level-wise until values differ.
4785 - If, at a given level, LOWER and UPPER differ from more than
4786 2, the new key shares all the levels above with LOWER and
4787 gets a new level. Its value is the mean between LOWER and
4788 UPPER:
4790 \(1 2) + (1 4) --> (1 3)
4792 - If LOWER has no value to compare with, it is assumed that its
4793 value is `most-negative-fixnum'. E.g.,
4795 \(1 1) + (1 1 2)
4797 is equivalent to
4799 \(1 1 m) + (1 1 2)
4801 where m is `most-negative-fixnum'. Likewise, if UPPER is
4802 short of levels, the current value is `most-positive-fixnum'.
4804 - If they differ from only one, the new key inherits from
4805 current LOWER level and fork it at the next level. E.g.,
4807 \(2 1) + (3 3)
4809 is equivalent to
4811 \(2 1) + (2 M)
4813 where M is `most-positive-fixnum'.
4815 - If the key is only one level long, it is returned as an
4816 integer:
4818 \(1 2) + (3 2) --> 2
4820 When they are not equals, the function assumes that LOWER is
4821 lesser than UPPER, per `org-element--cache-key-less-p'."
4822 (if (equal lower upper) lower
4823 (let ((lower (if (integerp lower) (list lower) lower))
4824 (upper (if (integerp upper) (list upper) upper))
4825 skip-upper key)
4826 (catch 'exit
4827 (while t
4828 (let ((min (or (car lower) most-negative-fixnum))
4829 (max (cond (skip-upper most-positive-fixnum)
4830 ((car upper))
4831 (t most-positive-fixnum))))
4832 (if (< (1+ min) max)
4833 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
4834 (throw 'exit (if key (nreverse (cons mean key)) mean)))
4835 (when (and (< min max) (not skip-upper))
4836 ;; When at a given level, LOWER and UPPER differ from
4837 ;; 1, ignore UPPER altogether. Instead create a key
4838 ;; between LOWER and the greatest key with the same
4839 ;; prefix as LOWER so far.
4840 (setq skip-upper t))
4841 (push min key)
4842 (setq lower (cdr lower) upper (cdr upper)))))))))
4844 (defsubst org-element--cache-key-less-p (a b)
4845 "Non-nil if key A is less than key B.
4846 A and B are either integers or lists of integers, as returned by
4847 `org-element--cache-key'."
4848 (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
4849 (if (integerp b) (< (car a) b)
4850 (catch 'exit
4851 (while (and a b)
4852 (cond ((car-less-than-car a b) (throw 'exit t))
4853 ((car-less-than-car b a) (throw 'exit nil))
4854 (t (setq a (cdr a) b (cdr b)))))
4855 ;; If A is empty, either keys are equal (B is also empty) and
4856 ;; we return nil, or A is lesser than B (B is longer) and we
4857 ;; return a non-nil value.
4859 ;; If A is not empty, B is necessarily empty and A is greater
4860 ;; than B (A is longer). Therefore, return nil.
4861 (and (null a) b)))))
4863 (defun org-element--cache-compare (a b)
4864 "Non-nil when element A is located before element B."
4865 (org-element--cache-key-less-p (org-element--cache-key a)
4866 (org-element--cache-key b)))
4868 (defsubst org-element--cache-root ()
4869 "Return root value in cache.
4870 This function assumes `org-element--cache' is a valid AVL tree."
4871 (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
4874 ;;;; Tools
4876 (defsubst org-element--cache-active-p ()
4877 "Non-nil when cache is active in current buffer."
4878 (and org-element-use-cache
4879 (or (derived-mode-p 'org-mode) orgstruct-mode)))
4881 (defun org-element--cache-find (pos &optional side)
4882 "Find element in cache starting at POS or before.
4884 POS refers to a buffer position.
4886 When optional argument SIDE is non-nil, the function checks for
4887 elements starting at or past POS instead. If SIDE is `both', the
4888 function returns a cons cell where car is the first element
4889 starting at or before POS and cdr the first element starting
4890 after POS.
4892 The function can only find elements in the synchronized part of
4893 the cache."
4894 (let ((limit (and org-element--cache-sync-requests
4895 (aref (car org-element--cache-sync-requests) 0)))
4896 (node (org-element--cache-root))
4897 lower upper)
4898 (while node
4899 (let* ((element (avl-tree--node-data node))
4900 (begin (org-element-property :begin element)))
4901 (cond
4902 ((and limit
4903 (not (org-element--cache-key-less-p
4904 (org-element--cache-key element) limit)))
4905 (setq node (avl-tree--node-left node)))
4906 ((> begin pos)
4907 (setq upper element
4908 node (avl-tree--node-left node)))
4909 ((< begin pos)
4910 (setq lower element
4911 node (avl-tree--node-right node)))
4912 ;; We found an element in cache starting at POS. If `side'
4913 ;; is `both' we also want the next one in order to generate
4914 ;; a key in-between.
4916 ;; If the element is the first row or item in a table or
4917 ;; a plain list, we always return the table or the plain
4918 ;; list.
4920 ;; In any other case, we return the element found.
4921 ((eq side 'both)
4922 (setq lower element)
4923 (setq node (avl-tree--node-right node)))
4924 ((and (memq (org-element-type element) '(item table-row))
4925 (let ((parent (org-element-property :parent element)))
4926 (and (= (org-element-property :begin element)
4927 (org-element-property :contents-begin parent))
4928 (setq node nil
4929 lower parent
4930 upper parent)))))
4932 (setq node nil
4933 lower element
4934 upper element)))))
4935 (case side
4936 (both (cons lower upper))
4937 ((nil) lower)
4938 (otherwise upper))))
4940 (defun org-element--cache-put (element &optional data)
4941 "Store ELEMENT in current buffer's cache, if allowed.
4942 When optional argument DATA is non-nil, assume is it object data
4943 relative to ELEMENT and store it in the objects cache."
4944 (cond ((not (org-element--cache-active-p)) nil)
4945 ((not data)
4946 (when org-element--cache-sync-requests
4947 ;; During synchronization, first build an appropriate key
4948 ;; for the new element so `avl-tree-enter' can insert it at
4949 ;; the right spot in the cache.
4950 (let ((keys (org-element--cache-find
4951 (org-element-property :begin element) 'both)))
4952 (puthash element
4953 (org-element--cache-generate-key
4954 (and (car keys) (org-element--cache-key (car keys)))
4955 (cond ((cdr keys) (org-element--cache-key (cdr keys)))
4956 (org-element--cache-sync-requests
4957 (aref (car org-element--cache-sync-requests) 0))))
4958 org-element--cache-sync-keys)))
4959 (avl-tree-enter org-element--cache element))
4960 ;; Headlines are not stored in cache, so objects in titles are
4961 ;; not stored either.
4962 ((eq (org-element-type element) 'headline) nil)
4963 (t (puthash element data org-element--cache-objects))))
4965 (defsubst org-element--cache-remove (element)
4966 "Remove ELEMENT from cache.
4967 Assume ELEMENT belongs to cache and that a cache is active."
4968 (avl-tree-delete org-element--cache element)
4969 (remhash element org-element--cache-objects))
4972 ;;;; Synchronization
4974 (defsubst org-element--cache-set-timer (buffer)
4975 "Set idle timer for cache synchronization in BUFFER."
4976 (when org-element--cache-sync-timer
4977 (cancel-timer org-element--cache-sync-timer))
4978 (setq org-element--cache-sync-timer
4979 (run-with-idle-timer
4980 (let ((idle (current-idle-time)))
4981 (if idle (time-add idle org-element-cache-sync-break)
4982 org-element-cache-sync-idle-time))
4984 #'org-element--cache-sync
4985 buffer)))
4987 (defsubst org-element--cache-interrupt-p (time-limit)
4988 "Non-nil when synchronization process should be interrupted.
4989 TIME-LIMIT is a time value or nil."
4990 (and time-limit
4991 (or (input-pending-p)
4992 (time-less-p time-limit (current-time)))))
4994 (defsubst org-element--cache-shift-positions (element offset &optional props)
4995 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4997 Properties containing buffer positions are `:begin', `:end',
4998 `:contents-begin', `:contents-end' and `:structure'. When
4999 optional argument PROPS is a list of keywords, only shift
5000 properties provided in that list.
5002 Properties are modified by side-effect."
5003 (let ((properties (nth 1 element)))
5004 ;; Shift `:structure' property for the first plain list only: it
5005 ;; is the only one that really matters and it prevents from
5006 ;; shifting it more than once.
5007 (when (and (or (not props) (memq :structure props))
5008 (eq (org-element-type element) 'plain-list)
5009 (not (eq (org-element-type (plist-get properties :parent))
5010 'item)))
5011 (dolist (item (plist-get properties :structure))
5012 (incf (car item) offset)
5013 (incf (nth 6 item) offset)))
5014 (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
5015 (let ((value (and (or (not props) (memq key props))
5016 (plist-get properties key))))
5017 (and value (plist-put properties key (+ offset value)))))))
5019 (defun org-element--cache-sync (buffer &optional threshold future-change)
5020 "Synchronize cache with recent modification in BUFFER.
5022 When optional argument THRESHOLD is non-nil, do the
5023 synchronization for all elements starting before or at threshold,
5024 then exit. Otherwise, synchronize cache for as long as
5025 `org-element-cache-sync-duration' or until Emacs leaves idle
5026 state.
5028 FUTURE-CHANGE, when non-nil, is a buffer position where changes
5029 not registered yet in the cache are going to happen. It is used
5030 in `org-element--cache-submit-request', where cache is partially
5031 updated before current modification are actually submitted."
5032 (when (buffer-live-p buffer)
5033 (with-current-buffer buffer
5034 (let ((inhibit-quit t) request next)
5035 (when org-element--cache-sync-timer
5036 (cancel-timer org-element--cache-sync-timer))
5037 (catch 'interrupt
5038 (while org-element--cache-sync-requests
5039 (setq request (car org-element--cache-sync-requests)
5040 next (nth 1 org-element--cache-sync-requests))
5041 (org-element--cache-process-request
5042 request
5043 (and next (aref next 0))
5044 threshold
5045 (and (not threshold)
5046 (time-add (current-time)
5047 org-element-cache-sync-duration))
5048 future-change)
5049 ;; Request processed. Merge current and next offsets and
5050 ;; transfer ending position.
5051 (when next
5052 (incf (aref next 3) (aref request 3))
5053 (aset next 2 (aref request 2)))
5054 (setq org-element--cache-sync-requests
5055 (cdr org-element--cache-sync-requests))))
5056 ;; If more requests are awaiting, set idle timer accordingly.
5057 ;; Otherwise, reset keys.
5058 (if org-element--cache-sync-requests
5059 (org-element--cache-set-timer buffer)
5060 (clrhash org-element--cache-sync-keys))))))
5062 (defun org-element--cache-process-request
5063 (request next threshold time-limit future-change)
5064 "Process synchronization REQUEST for all entries before NEXT.
5066 REQUEST is a vector, built by `org-element--cache-submit-request'.
5068 NEXT is a cache key, as returned by `org-element--cache-key'.
5070 When non-nil, THRESHOLD is a buffer position. Synchronization
5071 stops as soon as a shifted element begins after it.
5073 When non-nil, TIME-LIMIT is a time value. Synchronization stops
5074 after this time or when Emacs exits idle state.
5076 When non-nil, FUTURE-CHANGE is a buffer position where changes
5077 not registered yet in the cache are going to happen. See
5078 `org-element--cache-submit-request' for more information.
5080 Throw `interrupt' if the process stops before completing the
5081 request."
5082 (catch 'quit
5083 (when (= (aref request 6) 0)
5084 ;; Phase 0.
5086 ;; Delete all elements starting after BEG, but not after buffer
5087 ;; position END or past element with key NEXT.
5089 ;; At each iteration, we start again at tree root since
5090 ;; a deletion modifies structure of the balanced tree.
5091 (catch 'end-phase
5092 (let ((beg (aref request 0))
5093 (end (aref request 2))
5094 (outreach (aref request 4)))
5095 (while t
5096 (when (org-element--cache-interrupt-p time-limit)
5097 (throw 'interrupt nil))
5098 ;; Find first element in cache with key BEG or after it.
5099 (let ((node (org-element--cache-root)) data data-key)
5100 (while node
5101 (let* ((element (avl-tree--node-data node))
5102 (key (org-element--cache-key element)))
5103 (cond
5104 ((org-element--cache-key-less-p key beg)
5105 (setq node (avl-tree--node-right node)))
5106 ((org-element--cache-key-less-p beg key)
5107 (setq data element
5108 data-key key
5109 node (avl-tree--node-left node)))
5110 (t (setq data element
5111 data-key key
5112 node nil)))))
5113 (if data
5114 (let ((pos (org-element-property :begin data)))
5115 (if (if (or (not next)
5116 (org-element--cache-key-less-p data-key next))
5117 (<= pos end)
5118 (let ((up data))
5119 (while (and up (not (eq up outreach)))
5120 (setq up (org-element-property :parent up)))
5121 up))
5122 (org-element--cache-remove data)
5123 (aset request 0 data-key)
5124 (aset request 1 pos)
5125 (aset request 6 1)
5126 (throw 'end-phase nil)))
5127 ;; No element starting after modifications left in
5128 ;; cache: further processing is futile.
5129 (throw 'quit t)))))))
5130 (when (= (aref request 6) 1)
5131 ;; Phase 1.
5133 ;; Phase 0 left a hole in the cache. Some elements after it
5134 ;; could have parents within. For example, in the following
5135 ;; buffer:
5137 ;; - item
5140 ;; Paragraph1
5142 ;; Paragraph2
5144 ;; if we remove a blank line between "item" and "Paragraph1",
5145 ;; everything down to "Paragraph2" is removed from cache. But
5146 ;; the paragraph now belongs to the list, and its `:parent'
5147 ;; property no longer is accurate.
5149 ;; Therefore we need to parse again elements in the hole, or at
5150 ;; least in its last section, so that we can re-parent
5151 ;; subsequent elements, during phase 2.
5153 ;; Note that we only need to get the parent from the first
5154 ;; element in cache after the hole.
5156 ;; When next key is lesser or equal to the current one, delegate
5157 ;; phase 1 processing to next request in order to preserve key
5158 ;; order among requests.
5159 (let ((key (aref request 0)))
5160 (when (and next (not (org-element--cache-key-less-p key next)))
5161 (let ((next-request (nth 1 org-element--cache-sync-requests)))
5162 (aset next-request 0 key)
5163 (aset next-request 1 (aref request 1))
5164 (aset next-request 6 1))
5165 (throw 'quit t)))
5166 ;; Next element will start at its beginning position plus
5167 ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
5168 ;; contains the real beginning position of the first element to
5169 ;; shift and re-parent.
5170 (let ((limit (+ (aref request 1) (aref request 3))))
5171 (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
5172 ((and future-change (>= limit future-change))
5173 ;; Changes are going to happen around this element and
5174 ;; they will trigger another phase 1 request. Skip the
5175 ;; current one.
5176 (aset request 6 2))
5178 (let ((parent (org-element--parse-to limit t time-limit)))
5179 (aset request 5 parent)
5180 (aset request 6 2))))))
5181 ;; Phase 2.
5183 ;; Shift all elements starting from key START, but before NEXT, by
5184 ;; OFFSET, and re-parent them when appropriate.
5186 ;; Elements are modified by side-effect so the tree structure
5187 ;; remains intact.
5189 ;; Once THRESHOLD, if any, is reached, or once there is an input
5190 ;; pending, exit. Before leaving, the current synchronization
5191 ;; request is updated.
5192 (let ((start (aref request 0))
5193 (offset (aref request 3))
5194 (parent (aref request 5))
5195 (node (org-element--cache-root))
5196 (stack (list nil))
5197 (leftp t)
5198 exit-flag)
5199 ;; No re-parenting nor shifting planned: request is over.
5200 (when (and (not parent) (zerop offset)) (throw 'quit t))
5201 (while node
5202 (let* ((data (avl-tree--node-data node))
5203 (key (org-element--cache-key data)))
5204 (if (and leftp (avl-tree--node-left node)
5205 (not (org-element--cache-key-less-p key start)))
5206 (progn (push node stack)
5207 (setq node (avl-tree--node-left node)))
5208 (unless (org-element--cache-key-less-p key start)
5209 ;; We reached NEXT. Request is complete.
5210 (when (equal key next) (throw 'quit t))
5211 ;; Handle interruption request. Update current request.
5212 (when (or exit-flag (org-element--cache-interrupt-p time-limit))
5213 (aset request 0 key)
5214 (aset request 5 parent)
5215 (throw 'interrupt nil))
5216 ;; Shift element.
5217 (unless (zerop offset)
5218 (org-element--cache-shift-positions data offset)
5219 ;; Shift associated objects data, if any.
5220 (dolist (object-data (gethash data org-element--cache-objects))
5221 (dolist (object (cddr object-data))
5222 (org-element--cache-shift-positions object offset))))
5223 (let ((begin (org-element-property :begin data)))
5224 ;; Update PARENT and re-parent DATA, only when
5225 ;; necessary. Propagate new structures for lists.
5226 (while (and parent
5227 (<= (org-element-property :end parent) begin))
5228 (setq parent (org-element-property :parent parent)))
5229 (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
5230 ((and parent
5231 (let ((p (org-element-property :parent data)))
5232 (or (not p)
5233 (< (org-element-property :begin p)
5234 (org-element-property :begin parent)))))
5235 (org-element-put-property data :parent parent)
5236 (let ((s (org-element-property :structure parent)))
5237 (when (and s (org-element-property :structure data))
5238 (org-element-put-property data :structure s)))))
5239 ;; Cache is up-to-date past THRESHOLD. Request
5240 ;; interruption.
5241 (when (and threshold (> begin threshold)) (setq exit-flag t))))
5242 (setq node (if (setq leftp (avl-tree--node-right node))
5243 (avl-tree--node-right node)
5244 (pop stack))))))
5245 ;; We reached end of tree: synchronization complete.
5246 t)))
5248 (defun org-element--parse-to (pos &optional syncp time-limit)
5249 "Parse elements in current section, down to POS.
5251 Start parsing from the closest between the last known element in
5252 cache or headline above. Return the smallest element containing
5253 POS.
5255 When optional argument SYNCP is non-nil, return the parent of the
5256 element containing POS instead. In that case, it is also
5257 possible to provide TIME-LIMIT, which is a time value specifying
5258 when the parsing should stop. The function throws `interrupt' if
5259 the process stopped before finding the expected result."
5260 (catch 'exit
5261 (org-with-wide-buffer
5262 (goto-char pos)
5263 (let* ((cached (and (org-element--cache-active-p)
5264 (org-element--cache-find pos nil)))
5265 (begin (org-element-property :begin cached))
5266 element next)
5267 (cond
5268 ;; Nothing in cache before point: start parsing from first
5269 ;; element following headline above, or first element in
5270 ;; buffer.
5271 ((not cached)
5272 (when (org-with-limited-levels (outline-previous-heading))
5273 (forward-line))
5274 (skip-chars-forward " \r\t\n")
5275 (beginning-of-line))
5276 ;; Cache returned exact match: return it.
5277 ((= pos begin)
5278 (throw 'exit (if syncp (org-element-property :parent cached) cached)))
5279 ;; There's a headline between cached value and POS: cached
5280 ;; value is invalid. Start parsing from first element
5281 ;; following the headline.
5282 ((re-search-backward
5283 (org-with-limited-levels org-outline-regexp-bol) begin t)
5284 (forward-line)
5285 (skip-chars-forward " \r\t\n")
5286 (beginning-of-line))
5287 ;; Check if CACHED or any of its ancestors contain point.
5289 ;; If there is such an element, we inspect it in order to know
5290 ;; if we return it or if we need to parse its contents.
5291 ;; Otherwise, we just start parsing from current location,
5292 ;; which is right after the top-most element containing
5293 ;; CACHED.
5295 ;; As a special case, if POS is at the end of the buffer, we
5296 ;; want to return the innermost element ending there.
5298 ;; Also, if we find an ancestor and discover that we need to
5299 ;; parse its contents, make sure we don't start from
5300 ;; `:contents-begin', as we would otherwise go past CACHED
5301 ;; again. Instead, in that situation, we will resume parsing
5302 ;; from NEXT, which is located after CACHED or its higher
5303 ;; ancestor not containing point.
5305 (let ((up cached)
5306 (pos (if (= (point-max) pos) (1- pos) pos)))
5307 (goto-char (or (org-element-property :contents-begin cached) begin))
5308 (while (let ((end (org-element-property :end up)))
5309 (and (<= end pos)
5310 (goto-char end)
5311 (setq up (org-element-property :parent up)))))
5312 (cond ((not up))
5313 ((eobp) (setq element up))
5314 (t (setq element up next (point)))))))
5315 ;; Parse successively each element until we reach POS.
5316 (let ((end (or (org-element-property :end element)
5317 (save-excursion
5318 (org-with-limited-levels (outline-next-heading))
5319 (point))))
5320 (parent element)
5321 special-flag)
5322 (while t
5323 (when syncp
5324 (cond ((= (point) pos) (throw 'exit parent))
5325 ((org-element--cache-interrupt-p time-limit)
5326 (throw 'interrupt nil))))
5327 (unless element
5328 (setq element (org-element--current-element
5329 end 'element special-flag
5330 (org-element-property :structure parent)))
5331 (org-element-put-property element :parent parent)
5332 (org-element--cache-put element))
5333 (let ((elem-end (org-element-property :end element))
5334 (type (org-element-type element)))
5335 (cond
5336 ;; Skip any element ending before point. Also skip
5337 ;; element ending at point (unless it is also the end of
5338 ;; buffer) since we're sure that another element begins
5339 ;; after it.
5340 ((and (<= elem-end pos) (/= (point-max) elem-end))
5341 (goto-char elem-end))
5342 ;; A non-greater element contains point: return it.
5343 ((not (memq type org-element-greater-elements))
5344 (throw 'exit element))
5345 ;; Otherwise, we have to decide if ELEMENT really
5346 ;; contains POS. In that case we start parsing from
5347 ;; contents' beginning.
5349 ;; If POS is at contents' beginning but it is also at
5350 ;; the beginning of the first item in a list or a table.
5351 ;; In that case, we need to create an anchor for that
5352 ;; list or table, so return it.
5354 ;; Also, if POS is at the end of the buffer, no element
5355 ;; can start after it, but more than one may end there.
5356 ;; Arbitrarily, we choose to return the innermost of
5357 ;; such elements.
5358 ((let ((cbeg (org-element-property :contents-begin element))
5359 (cend (org-element-property :contents-end element)))
5360 (when (or syncp
5361 (and cbeg cend
5362 (or (< cbeg pos)
5363 (and (= cbeg pos)
5364 (not (memq type '(plain-list table)))))
5365 (or (> cend pos)
5366 (and (= cend pos) (= (point-max) pos)))))
5367 (goto-char (or next cbeg))
5368 (setq next nil
5369 special-flag (case type
5370 (plain-list 'item)
5371 (property-drawer 'node-property)
5372 (table 'table-row))
5373 parent element
5374 end cend))))
5375 ;; Otherwise, return ELEMENT as it is the smallest
5376 ;; element containing POS.
5377 (t (throw 'exit element))))
5378 (setq element nil)))))))
5381 ;;;; Staging Buffer Changes
5383 (defconst org-element--cache-sensitive-re
5384 (concat
5385 org-outline-regexp-bol "\\|"
5386 "^[ \t]*\\(?:"
5387 ;; Blocks
5388 "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
5389 ;; LaTeX environments.
5390 "\\\\\\(?:begin{[A-Za-z0-9]+\\*?}\\|end{[A-Za-z0-9]+\\*?}[ \t]*$\\)" "\\|"
5391 ;; Drawers.
5392 ":\\S-+:[ \t]*$"
5393 "\\)")
5394 "Regexp matching a sensitive line, structure wise.
5395 A sensitive line is a headline, inlinetask, block, drawer, or
5396 latex-environment boundary. When such a line is modified,
5397 structure changes in the document may propagate in the whole
5398 section, possibly making cache invalid.")
5400 (defvar org-element--cache-change-warning nil
5401 "Non-nil when a sensitive line is about to be changed.
5402 It is a symbol among nil, t and `headline'.")
5404 (defun org-element--cache-before-change (beg end)
5405 "Request extension of area going to be modified if needed.
5406 BEG and END are the beginning and end of the range of changed
5407 text. See `before-change-functions' for more information."
5408 (when (org-element--cache-active-p)
5409 (org-with-wide-buffer
5410 (goto-char beg)
5411 (beginning-of-line)
5412 (let ((bottom (save-excursion (goto-char end) (line-end-position))))
5413 (setq org-element--cache-change-warning
5414 (save-match-data
5415 (if (and (org-with-limited-levels (org-at-heading-p))
5416 (= (line-end-position) bottom))
5417 'headline
5418 (let ((case-fold-search t))
5419 (re-search-forward
5420 org-element--cache-sensitive-re bottom t)))))))))
5422 (defun org-element--cache-after-change (beg end pre)
5423 "Update buffer modifications for current buffer.
5424 BEG and END are the beginning and end of the range of changed
5425 text, and the length in bytes of the pre-change text replaced by
5426 that range. See `after-change-functions' for more information."
5427 (when (org-element--cache-active-p)
5428 (org-with-wide-buffer
5429 (goto-char beg)
5430 (beginning-of-line)
5431 (save-match-data
5432 (let ((top (point))
5433 (bottom (save-excursion (goto-char end) (line-end-position))))
5434 ;; Determine if modified area needs to be extended, according
5435 ;; to both previous and current state. We make a special
5436 ;; case for headline editing: if a headline is modified but
5437 ;; not removed, do not extend.
5438 (when (case org-element--cache-change-warning
5439 ((t) t)
5440 (headline
5441 (not (and (org-with-limited-levels (org-at-heading-p))
5442 (= (line-end-position) bottom))))
5443 (otherwise
5444 (let ((case-fold-search t))
5445 (re-search-forward
5446 org-element--cache-sensitive-re bottom t))))
5447 ;; Effectively extend modified area.
5448 (org-with-limited-levels
5449 (setq top (progn (goto-char top)
5450 (when (outline-previous-heading) (forward-line))
5451 (point)))
5452 (setq bottom (progn (goto-char bottom)
5453 (if (outline-next-heading) (1- (point))
5454 (point))))))
5455 ;; Store synchronization request.
5456 (let ((offset (- end beg pre)))
5457 (org-element--cache-submit-request top (- bottom offset) offset)))))
5458 ;; Activate a timer to process the request during idle time.
5459 (org-element--cache-set-timer (current-buffer))))
5461 (defun org-element--cache-for-removal (beg end offset)
5462 "Return first element to remove from cache.
5464 BEG and END are buffer positions delimiting buffer modifications.
5465 OFFSET is the size of the changes.
5467 Returned element is usually the first element in cache containing
5468 any position between BEG and END. As an exception, greater
5469 elements around the changes that are robust to contents
5470 modifications are preserved and updated according to the
5471 changes."
5472 (let* ((elements (org-element--cache-find (1- beg) 'both))
5473 (before (car elements))
5474 (after (cdr elements)))
5475 (if (not before) after
5476 (let ((up before)
5477 (robust-flag t))
5478 (while up
5479 (if (and (memq (org-element-type up)
5480 '(center-block drawer dynamic-block
5481 property-drawer quote-block
5482 special-block))
5483 (<= (org-element-property :contents-begin up) beg)
5484 (> (org-element-property :contents-end up) end))
5485 ;; UP is a robust greater element containing changes.
5486 ;; We only need to extend its ending boundaries.
5487 (org-element--cache-shift-positions
5488 up offset '(:contents-end :end))
5489 (setq before up)
5490 (when robust-flag (setq robust-flag nil)))
5491 (setq up (org-element-property :parent up)))
5492 ;; We're at top level element containing ELEMENT: if it's
5493 ;; altered by buffer modifications, it is first element in
5494 ;; cache to be removed. Otherwise, that first element is the
5495 ;; following one.
5497 ;; As a special case, do not remove BEFORE if it is a robust
5498 ;; container for current changes.
5499 (if (or (< (org-element-property :end before) beg) robust-flag) after
5500 before)))))
5502 (defun org-element--cache-submit-request (beg end offset)
5503 "Submit a new cache synchronization request for current buffer.
5504 BEG and END are buffer positions delimiting the minimal area
5505 where cache data should be removed. OFFSET is the size of the
5506 change, as an integer."
5507 (let ((next (car org-element--cache-sync-requests))
5508 delete-to delete-from)
5509 (if (and next
5510 (zerop (aref next 6))
5511 (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
5512 (<= (setq delete-from (aref next 1)) end))
5513 ;; Current changes can be merged with first sync request: we
5514 ;; can save a partial cache synchronization.
5515 (progn
5516 (incf (aref next 3) offset)
5517 ;; If last change happened within area to be removed, extend
5518 ;; boundaries of robust parents, if any. Otherwise, find
5519 ;; first element to remove and update request accordingly.
5520 (if (> beg delete-from)
5521 (let ((up (aref next 5)))
5522 (while up
5523 (org-element--cache-shift-positions
5524 up offset '(:contents-end :end))
5525 (setq up (org-element-property :parent up))))
5526 (let ((first (org-element--cache-for-removal beg delete-to offset)))
5527 (when first
5528 (aset next 0 (org-element--cache-key first))
5529 (aset next 1 (org-element-property :begin first))
5530 (aset next 5 (org-element-property :parent first))))))
5531 ;; Ensure cache is correct up to END. Also make sure that NEXT,
5532 ;; if any, is no longer a 0-phase request, thus ensuring that
5533 ;; phases are properly ordered. We need to provide OFFSET as
5534 ;; optional parameter since current modifications are not known
5535 ;; yet to the otherwise correct part of the cache (i.e, before
5536 ;; the first request).
5537 (when next (org-element--cache-sync (current-buffer) end beg))
5538 (let ((first (org-element--cache-for-removal beg end offset)))
5539 (if first
5540 (push (let ((beg (org-element-property :begin first))
5541 (key (org-element--cache-key first)))
5542 (cond
5543 ;; When changes happen before the first known
5544 ;; element, re-parent and shift the rest of the
5545 ;; cache.
5546 ((> beg end) (vector key beg nil offset nil nil 1))
5547 ;; Otherwise, we find the first non robust
5548 ;; element containing END. All elements between
5549 ;; FIRST and this one are to be removed.
5551 ;; Among them, some could be located outside the
5552 ;; synchronized part of the cache, in which case
5553 ;; comparing buffer positions to find them is
5554 ;; useless. Instead, we store the element
5555 ;; containing them in the request itself. All
5556 ;; its children will be removed.
5557 ((let ((first-end (org-element-property :end first)))
5558 (and (> first-end end)
5559 (vector key beg first-end offset first
5560 (org-element-property :parent first) 0))))
5562 (let* ((element (org-element--cache-find end))
5563 (end (org-element-property :end element))
5564 (up element))
5565 (while (and (setq up (org-element-property :parent up))
5566 (>= (org-element-property :begin up) beg))
5567 (setq end (org-element-property :end up)
5568 element up))
5569 (vector key beg end offset element
5570 (org-element-property :parent first) 0)))))
5571 org-element--cache-sync-requests)
5572 ;; No element to remove. No need to re-parent either.
5573 ;; Simply shift additional elements, if any, by OFFSET.
5574 (when org-element--cache-sync-requests
5575 (incf (aref (car org-element--cache-sync-requests) 3) offset)))))))
5578 ;;;; Public Functions
5580 ;;;###autoload
5581 (defun org-element-cache-reset (&optional all)
5582 "Reset cache in current buffer.
5583 When optional argument ALL is non-nil, reset cache in all Org
5584 buffers."
5585 (interactive "P")
5586 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
5587 (with-current-buffer buffer
5588 (when (org-element--cache-active-p)
5589 (org-set-local 'org-element--cache
5590 (avl-tree-create #'org-element--cache-compare))
5591 (org-set-local 'org-element--cache-objects (make-hash-table :test #'eq))
5592 (org-set-local 'org-element--cache-sync-keys
5593 (make-hash-table :weakness 'key :test #'eq))
5594 (org-set-local 'org-element--cache-change-warning nil)
5595 (org-set-local 'org-element--cache-sync-requests nil)
5596 (org-set-local 'org-element--cache-sync-timer nil)
5597 (add-hook 'before-change-functions
5598 #'org-element--cache-before-change nil t)
5599 (add-hook 'after-change-functions
5600 #'org-element--cache-after-change nil t)))))
5602 ;;;###autoload
5603 (defun org-element-cache-refresh (pos)
5604 "Refresh cache at position POS."
5605 (when (org-element--cache-active-p)
5606 (org-element--cache-sync (current-buffer) pos)
5607 (org-element--cache-submit-request pos pos 0)
5608 (org-element--cache-set-timer (current-buffer))))
5612 ;;; The Toolbox
5614 ;; The first move is to implement a way to obtain the smallest element
5615 ;; containing point. This is the job of `org-element-at-point'. It
5616 ;; basically jumps back to the beginning of section containing point
5617 ;; and proceed, one element after the other, with
5618 ;; `org-element--current-element' until the container is found. Note:
5619 ;; When using `org-element-at-point', secondary values are never
5620 ;; parsed since the function focuses on elements, not on objects.
5622 ;; At a deeper level, `org-element-context' lists all elements and
5623 ;; objects containing point.
5625 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
5626 ;; internally by navigation and manipulation tools.
5629 ;;;###autoload
5630 (defun org-element-at-point ()
5631 "Determine closest element around point.
5633 Return value is a list like (TYPE PROPS) where TYPE is the type
5634 of the element and PROPS a plist of properties associated to the
5635 element.
5637 Possible types are defined in `org-element-all-elements'.
5638 Properties depend on element or object type, but always include
5639 `:begin', `:end', `:parent' and `:post-blank' properties.
5641 As a special case, if point is at the very beginning of the first
5642 item in a list or sub-list, returned element will be that list
5643 instead of the item. Likewise, if point is at the beginning of
5644 the first row of a table, returned element will be the table
5645 instead of the first row.
5647 When point is at the end of the buffer, return the innermost
5648 element ending there."
5649 (org-with-wide-buffer
5650 (let ((origin (point)))
5651 (end-of-line)
5652 (skip-chars-backward " \r\t\n")
5653 (cond
5654 ;; Within blank lines at the beginning of buffer, return nil.
5655 ((bobp) nil)
5656 ;; Within blank lines right after a headline, return that
5657 ;; headline.
5658 ((org-with-limited-levels (org-at-heading-p))
5659 (beginning-of-line)
5660 (org-element-headline-parser (point-max) t))
5661 ;; Otherwise parse until we find element containing ORIGIN.
5663 (when (org-element--cache-active-p)
5664 (if (not org-element--cache) (org-element-cache-reset)
5665 (org-element--cache-sync (current-buffer) origin)))
5666 (org-element--parse-to origin))))))
5668 ;;;###autoload
5669 (defun org-element-context (&optional element)
5670 "Return smallest element or object around point.
5672 Return value is a list like (TYPE PROPS) where TYPE is the type
5673 of the element or object and PROPS a plist of properties
5674 associated to it.
5676 Possible types are defined in `org-element-all-elements' and
5677 `org-element-all-objects'. Properties depend on element or
5678 object type, but always include `:begin', `:end', `:parent' and
5679 `:post-blank'.
5681 As a special case, if point is right after an object and not at
5682 the beginning of any other object, return that object.
5684 Optional argument ELEMENT, when non-nil, is the closest element
5685 containing point, as returned by `org-element-at-point'.
5686 Providing it allows for quicker computation."
5687 (catch 'objects-forbidden
5688 (org-with-wide-buffer
5689 (let* ((pos (point))
5690 (element (or element (org-element-at-point)))
5691 (type (org-element-type element)))
5692 ;; If point is inside an element containing objects or
5693 ;; a secondary string, narrow buffer to the container and
5694 ;; proceed with parsing. Otherwise, return ELEMENT.
5695 (cond
5696 ;; At a parsed affiliated keyword, check if we're inside main
5697 ;; or dual value.
5698 ((let ((post (org-element-property :post-affiliated element)))
5699 (and post (< pos post)))
5700 (beginning-of-line)
5701 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5702 (cond
5703 ((not (member-ignore-case (match-string 1)
5704 org-element-parsed-keywords))
5705 (throw 'objects-forbidden element))
5706 ((< (match-end 0) pos)
5707 (narrow-to-region (match-end 0) (line-end-position)))
5708 ((and (match-beginning 2)
5709 (>= pos (match-beginning 2))
5710 (< pos (match-end 2)))
5711 (narrow-to-region (match-beginning 2) (match-end 2)))
5712 (t (throw 'objects-forbidden element)))
5713 ;; Also change type to retrieve correct restrictions.
5714 (setq type 'keyword))
5715 ;; At an item, objects can only be located within tag, if any.
5716 ((eq type 'item)
5717 (let ((tag (org-element-property :tag element)))
5718 (if (not tag) (throw 'objects-forbidden element)
5719 (beginning-of-line)
5720 (search-forward tag (line-end-position))
5721 (goto-char (match-beginning 0))
5722 (if (and (>= pos (point)) (< pos (match-end 0)))
5723 (narrow-to-region (point) (match-end 0))
5724 (throw 'objects-forbidden element)))))
5725 ;; At an headline or inlinetask, objects are in title.
5726 ((memq type '(headline inlinetask))
5727 (goto-char (org-element-property :begin element))
5728 (skip-chars-forward "*")
5729 (if (and (> pos (point)) (< pos (line-end-position)))
5730 (narrow-to-region (point) (line-end-position))
5731 (throw 'objects-forbidden element)))
5732 ;; At a paragraph, a table-row or a verse block, objects are
5733 ;; located within their contents.
5734 ((memq type '(paragraph table-row verse-block))
5735 (let ((cbeg (org-element-property :contents-begin element))
5736 (cend (org-element-property :contents-end element)))
5737 ;; CBEG is nil for table rules.
5738 (if (and cbeg cend (>= pos cbeg)
5739 (or (< pos cend) (and (= pos cend) (eobp))))
5740 (narrow-to-region cbeg cend)
5741 (throw 'objects-forbidden element))))
5742 ;; At a parsed keyword, objects are located within value.
5743 ((eq type 'keyword)
5744 (if (not (member (org-element-property :key element)
5745 org-element-document-properties))
5746 (throw 'objects-forbidden element)
5747 (beginning-of-line)
5748 (search-forward ":")
5749 (if (and (>= pos (point)) (< pos (line-end-position)))
5750 (narrow-to-region (point) (line-end-position))
5751 (throw 'objects-forbidden element))))
5752 ;; At a planning line, if point is at a timestamp, return it,
5753 ;; otherwise, return element.
5754 ((eq type 'planning)
5755 (dolist (p '(:closed :deadline :scheduled))
5756 (let ((timestamp (org-element-property p element)))
5757 (when (and timestamp
5758 (<= (org-element-property :begin timestamp) pos)
5759 (> (org-element-property :end timestamp) pos))
5760 (throw 'objects-forbidden timestamp))))
5761 ;; All other locations cannot contain objects: bail out.
5762 (throw 'objects-forbidden element))
5763 (t (throw 'objects-forbidden element)))
5764 (goto-char (point-min))
5765 (let ((restriction (org-element-restriction type))
5766 (parent element)
5767 (cache (cond ((not (org-element--cache-active-p)) nil)
5768 (org-element--cache-objects
5769 (gethash element org-element--cache-objects))
5770 (t (org-element-cache-reset) nil)))
5771 next object-data last)
5772 (prog1
5773 (catch 'exit
5774 (while t
5775 ;; When entering PARENT for the first time, get list
5776 ;; of objects within known so far. Store it in
5777 ;; OBJECT-DATA.
5778 (unless next
5779 (let ((data (assq parent cache)))
5780 (if data (setq object-data data)
5781 (push (setq object-data (list parent nil)) cache))))
5782 ;; Find NEXT object for analysis.
5783 (catch 'found
5784 ;; If NEXT is non-nil, we already exhausted the
5785 ;; cache so we can parse buffer to find the object
5786 ;; after it.
5787 (if next (setq next (org-element--object-lex restriction))
5788 ;; Otherwise, check if cache can help us.
5789 (let ((objects (cddr object-data))
5790 (completep (nth 1 object-data)))
5791 (cond
5792 ((and (not objects) completep) (throw 'exit parent))
5793 ((not objects)
5794 (setq next (org-element--object-lex restriction)))
5796 (let ((cache-limit
5797 (org-element-property :end (car objects))))
5798 (if (>= cache-limit pos)
5799 ;; Cache contains the information needed.
5800 (dolist (object objects (throw 'exit parent))
5801 (when (<= (org-element-property :begin object)
5802 pos)
5803 (if (>= (org-element-property :end object)
5804 pos)
5805 (throw 'found (setq next object))
5806 (throw 'exit parent))))
5807 (goto-char cache-limit)
5808 (setq next
5809 (org-element--object-lex restriction))))))))
5810 ;; If we have a new object to analyze, store it in
5811 ;; cache. Otherwise record that there is nothing
5812 ;; more to parse in this element at this depth.
5813 (if next
5814 (progn (org-element-put-property next :parent parent)
5815 (push next (cddr object-data)))
5816 (setcar (cdr object-data) t)))
5817 ;; Process NEXT, if any, in order to know if we need
5818 ;; to skip it, return it or move into it.
5819 (if (or (not next) (> (org-element-property :begin next) pos))
5820 (throw 'exit (or last parent))
5821 (let ((end (org-element-property :end next))
5822 (cbeg (org-element-property :contents-begin next))
5823 (cend (org-element-property :contents-end next)))
5824 (cond
5825 ;; Skip objects ending before point. Also skip
5826 ;; objects ending at point unless it is also the
5827 ;; end of buffer, since we want to return the
5828 ;; innermost object.
5829 ((and (<= end pos) (/= (point-max) end))
5830 (goto-char end)
5831 ;; For convenience, when object ends at POS,
5832 ;; without any space, store it in LAST, as we
5833 ;; will return it if no object starts here.
5834 (when (and (= end pos)
5835 (not (memq (char-before) '(?\s ?\t))))
5836 (setq last next)))
5837 ;; If POS is within a container object, move
5838 ;; into that object.
5839 ((and cbeg cend
5840 (>= pos cbeg)
5841 (or (< pos cend)
5842 ;; At contents' end, if there is no
5843 ;; space before point, also move into
5844 ;; object, for consistency with
5845 ;; convenience feature above.
5846 (and (= pos cend)
5847 (or (= (point-max) pos)
5848 (not (memq (char-before pos)
5849 '(?\s ?\t)))))))
5850 (goto-char cbeg)
5851 (narrow-to-region (point) cend)
5852 (setq parent next
5853 restriction (org-element-restriction next)
5854 next nil
5855 object-data nil))
5856 ;; Otherwise, return NEXT.
5857 (t (throw 'exit next)))))))
5858 ;; Store results in cache, if applicable.
5859 (org-element--cache-put element cache)))))))
5861 (defun org-element-nested-p (elem-A elem-B)
5862 "Non-nil when elements ELEM-A and ELEM-B are nested."
5863 (let ((beg-A (org-element-property :begin elem-A))
5864 (beg-B (org-element-property :begin elem-B))
5865 (end-A (org-element-property :end elem-A))
5866 (end-B (org-element-property :end elem-B)))
5867 (or (and (>= beg-A beg-B) (<= end-A end-B))
5868 (and (>= beg-B beg-A) (<= end-B end-A)))))
5870 (defun org-element-swap-A-B (elem-A elem-B)
5871 "Swap elements ELEM-A and ELEM-B.
5872 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5873 end of ELEM-A."
5874 (goto-char (org-element-property :begin elem-A))
5875 ;; There are two special cases when an element doesn't start at bol:
5876 ;; the first paragraph in an item or in a footnote definition.
5877 (let ((specialp (not (bolp))))
5878 ;; Only a paragraph without any affiliated keyword can be moved at
5879 ;; ELEM-A position in such a situation. Note that the case of
5880 ;; a footnote definition is impossible: it cannot contain two
5881 ;; paragraphs in a row because it cannot contain a blank line.
5882 (if (and specialp
5883 (or (not (eq (org-element-type elem-B) 'paragraph))
5884 (/= (org-element-property :begin elem-B)
5885 (org-element-property :contents-begin elem-B))))
5886 (error "Cannot swap elements"))
5887 ;; In a special situation, ELEM-A will have no indentation. We'll
5888 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5889 (let* ((ind-B (when specialp
5890 (goto-char (org-element-property :begin elem-B))
5891 (org-get-indentation)))
5892 (beg-A (org-element-property :begin elem-A))
5893 (end-A (save-excursion
5894 (goto-char (org-element-property :end elem-A))
5895 (skip-chars-backward " \r\t\n")
5896 (point-at-eol)))
5897 (beg-B (org-element-property :begin elem-B))
5898 (end-B (save-excursion
5899 (goto-char (org-element-property :end elem-B))
5900 (skip-chars-backward " \r\t\n")
5901 (point-at-eol)))
5902 ;; Store overlays responsible for visibility status. We
5903 ;; also need to store their boundaries as they will be
5904 ;; removed from buffer.
5905 (overlays
5906 (cons
5907 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5908 (overlays-in beg-A end-A))
5909 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5910 (overlays-in beg-B end-B))))
5911 ;; Get contents.
5912 (body-A (buffer-substring beg-A end-A))
5913 (body-B (delete-and-extract-region beg-B end-B)))
5914 (goto-char beg-B)
5915 (when specialp
5916 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5917 (org-indent-to-column ind-B))
5918 (insert body-A)
5919 ;; Restore ex ELEM-A overlays.
5920 (let ((offset (- beg-B beg-A)))
5921 (mapc (lambda (ov)
5922 (move-overlay
5923 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5924 (car overlays))
5925 (goto-char beg-A)
5926 (delete-region beg-A end-A)
5927 (insert body-B)
5928 ;; Restore ex ELEM-B overlays.
5929 (mapc (lambda (ov)
5930 (move-overlay
5931 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5932 (cdr overlays)))
5933 (goto-char (org-element-property :end elem-B)))))
5935 (defun org-element-remove-indentation (s &optional n)
5936 "Remove maximum common indentation in string S and return it.
5937 When optional argument N is a positive integer, remove exactly
5938 that much characters from indentation, if possible, or return
5939 S as-is otherwise. Unlike to `org-remove-indentation', this
5940 function doesn't call `untabify' on S."
5941 (catch 'exit
5942 (with-temp-buffer
5943 (insert s)
5944 (goto-char (point-min))
5945 ;; Find maximum common indentation, if not specified.
5946 (setq n (or n
5947 (let ((min-ind (point-max)))
5948 (save-excursion
5949 (while (re-search-forward "^[ \t]*\\S-" nil t)
5950 (let ((ind (1- (current-column))))
5951 (if (zerop ind) (throw 'exit s)
5952 (setq min-ind (min min-ind ind))))))
5953 min-ind)))
5954 (if (zerop n) s
5955 ;; Remove exactly N indentation, but give up if not possible.
5956 (while (not (eobp))
5957 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5958 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5959 ((< ind n) (throw 'exit s))
5960 (t (org-indent-line-to (- ind n))))
5961 (forward-line)))
5962 (buffer-string)))))
5966 (provide 'org-element)
5968 ;; Local variables:
5969 ;; generated-autoload-file: "org-loaddefs.el"
5970 ;; End:
5972 ;;; org-element.el ends here