org-element: Optimize parser only when cache is active
[org-mode.git] / lisp / org-element.el
blob7050b75acecea195513e15ab6463f3019c6d09c6
1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012-2013 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', `quote-section' `section' and
35 ;; `table-row' types), it can also accept a fixed set of keywords as
36 ;; attributes. Those are called "affiliated keywords" to distinguish
37 ;; them from other keywords, which are full-fledged elements. Almost
38 ;; all affiliated keywords are referenced in
39 ;; `org-element-affiliated-keywords'; the others are export attributes
40 ;; and start with "ATTR_" prefix.
42 ;; Element containing other elements (and only elements) are called
43 ;; greater elements. Concerned types are: `center-block', `drawer',
44 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
45 ;; `item', `plain-list', `property-drawer', `quote-block', `section'
46 ;; and `special-block'.
48 ;; Other element types are: `babel-call', `clock', `comment',
49 ;; `comment-block', `diary-sexp', `example-block', `export-block',
50 ;; `fixed-width', `horizontal-rule', `keyword', `latex-environment',
51 ;; `node-property', `paragraph', `planning', `quote-section',
52 ;; `src-block', `table', `table-row' and `verse-block'. Among them,
53 ;; `paragraph' and `verse-block' types can contain Org objects and
54 ;; plain text.
56 ;; Objects are related to document's contents. Some of them are
57 ;; recursive. Associated types are of the following: `bold', `code',
58 ;; `entity', `export-snippet', `footnote-reference',
59 ;; `inline-babel-call', `inline-src-block', `italic',
60 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
61 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
62 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
64 ;; Some elements also have special properties whose value can hold
65 ;; objects themselves (i.e. an item tag or a headline name). Such
66 ;; values are called "secondary strings". Any object belongs to
67 ;; either an element or a secondary string.
69 ;; Notwithstanding affiliated keywords, each greater element, element
70 ;; and object has a fixed set of properties attached to it. Among
71 ;; them, four are shared by all types: `:begin' and `:end', which
72 ;; refer to the beginning and ending buffer positions of the
73 ;; considered element or object, `:post-blank', which holds the number
74 ;; of blank lines, or white spaces, at its end and `:parent' which
75 ;; refers to the element or object containing it. Greater elements,
76 ;; elements and objects containing objects will also have
77 ;; `:contents-begin' and `:contents-end' properties to delimit
78 ;; contents. Eventually, greater elements and elements accepting
79 ;; affiliated keywords will have a `:post-affiliated' property,
80 ;; referring to the buffer position after all such keywords.
82 ;; At the lowest level, a `:parent' property is also attached to any
83 ;; string, as a text property.
85 ;; Lisp-wise, an element or an object can be represented as a list.
86 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
87 ;; TYPE is a symbol describing the Org element or object.
88 ;; PROPERTIES is the property list attached to it. See docstring of
89 ;; appropriate parsing function to get an exhaustive
90 ;; list.
91 ;; CONTENTS is a list of elements, objects or raw strings contained
92 ;; in the current element or object, when applicable.
94 ;; An Org buffer is a nested list of such elements and objects, whose
95 ;; type is `org-data' and properties is nil.
97 ;; The first part of this file defines Org syntax, while the second
98 ;; one provide accessors and setters functions.
100 ;; The next part implements a parser and an interpreter for each
101 ;; element and object type in Org syntax.
103 ;; The following part creates a fully recursive buffer parser. It
104 ;; also provides a tool to map a function to elements or objects
105 ;; matching some criteria in the parse tree. Functions of interest
106 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
107 ;; extent, `org-element-parse-secondary-string'.
109 ;; The penultimate part is the cradle of an interpreter for the
110 ;; obtained parse tree: `org-element-interpret-data'.
112 ;; The library ends by furnishing `org-element-at-point' function, and
113 ;; a way to give information about document structure around point
114 ;; with `org-element-context'. A simple cache mechanism is also
115 ;; provided for these functions.
118 ;;; Code:
120 (eval-when-compile (require 'cl))
121 (require 'org)
125 ;;; Definitions And Rules
127 ;; Define elements, greater elements and specify recursive objects,
128 ;; along with the affiliated keywords recognized. Also set up
129 ;; restrictions on recursive objects combinations.
131 ;; These variables really act as a control center for the parsing
132 ;; process.
134 (defconst org-element-paragraph-separate
135 (concat "^\\(?:"
136 ;; Headlines, inlinetasks.
137 org-outline-regexp "\\|"
138 ;; Footnote definitions.
139 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
140 ;; Diary sexps.
141 "%%(" "\\|"
142 "[ \t]*\\(?:"
143 ;; Empty lines.
144 "$" "\\|"
145 ;; Tables (any type).
146 "\\(?:|\\|\\+-[-+]\\)" "\\|"
147 ;; Blocks (any type), Babel calls and keywords. Note: this
148 ;; is only an indication and need some thorough check.
149 "#\\(?:[+ ]\\|$\\)" "\\|"
150 ;; Drawers (any type) and fixed-width areas. This is also
151 ;; only an indication.
152 ":" "\\|"
153 ;; Horizontal rules.
154 "-\\{5,\\}[ \t]*$" "\\|"
155 ;; LaTeX environments.
156 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
157 ;; Planning and Clock lines.
158 (regexp-opt (list org-scheduled-string
159 org-deadline-string
160 org-closed-string
161 org-clock-string))
162 "\\|"
163 ;; Lists.
164 (let ((term (case org-plain-list-ordered-item-terminator
165 (?\) ")") (?. "\\.") (otherwise "[.)]")))
166 (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
167 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
168 "\\(?:[ \t]\\|$\\)"))
169 "\\)\\)")
170 "Regexp to separate paragraphs in an Org buffer.
171 In the case of lines starting with \"#\" and \":\", this regexp
172 is not sufficient to know if point is at a paragraph ending. See
173 `org-element-paragraph-parser' for more information.")
175 (defconst org-element-all-elements
176 '(babel-call center-block clock comment comment-block diary-sexp drawer
177 dynamic-block example-block export-block fixed-width
178 footnote-definition headline horizontal-rule inlinetask item
179 keyword latex-environment node-property paragraph plain-list
180 planning property-drawer quote-block quote-section section
181 special-block src-block table table-row verse-block)
182 "Complete list of element types.")
184 (defconst org-element-greater-elements
185 '(center-block drawer dynamic-block footnote-definition headline inlinetask
186 item plain-list property-drawer quote-block section
187 special-block table)
188 "List of recursive element types aka Greater Elements.")
190 (defconst org-element-all-successors
191 '(export-snippet footnote-reference inline-babel-call inline-src-block
192 latex-or-entity line-break link macro plain-link radio-target
193 statistics-cookie sub/superscript table-cell target
194 text-markup timestamp)
195 "Complete list of successors.")
197 (defconst org-element-object-successor-alist
198 '((subscript . sub/superscript) (superscript . sub/superscript)
199 (bold . text-markup) (code . text-markup) (italic . text-markup)
200 (strike-through . text-markup) (underline . text-markup)
201 (verbatim . text-markup) (entity . latex-or-entity)
202 (latex-fragment . latex-or-entity))
203 "Alist of translations between object type and successor name.
204 Sharing the same successor comes handy when, for example, the
205 regexp matching one object can also match the other object.")
207 (defconst org-element-all-objects
208 '(bold code entity export-snippet footnote-reference inline-babel-call
209 inline-src-block italic line-break latex-fragment link macro
210 radio-target statistics-cookie strike-through subscript superscript
211 table-cell target timestamp underline verbatim)
212 "Complete list of object types.")
214 (defconst org-element-recursive-objects
215 '(bold italic link subscript radio-target strike-through superscript
216 table-cell underline)
217 "List of recursive object types.")
219 (defvar org-element-block-name-alist
220 '(("CENTER" . org-element-center-block-parser)
221 ("COMMENT" . org-element-comment-block-parser)
222 ("EXAMPLE" . org-element-example-block-parser)
223 ("QUOTE" . org-element-quote-block-parser)
224 ("SRC" . org-element-src-block-parser)
225 ("VERSE" . org-element-verse-block-parser))
226 "Alist between block names and the associated parsing function.
227 Names must be uppercase. Any block whose name has no association
228 is parsed with `org-element-special-block-parser'.")
230 (defconst org-element-link-type-is-file
231 '("file" "file+emacs" "file+sys" "docview")
232 "List of link types equivalent to \"file\".
233 Only these types can accept search options and an explicit
234 application to open them.")
236 (defconst org-element-affiliated-keywords
237 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
238 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
239 "List of affiliated keywords as strings.
240 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
241 are affiliated keywords and need not to be in this list.")
243 (defconst org-element--affiliated-re
244 (format "[ \t]*#\\+%s:"
245 ;; Regular affiliated keywords.
246 (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
247 (regexp-opt org-element-affiliated-keywords)))
248 "Regexp matching any affiliated keyword.
250 Keyword name is put in match group 1. Moreover, if keyword
251 belongs to `org-element-dual-keywords', put the dual value in
252 match group 2.
254 Don't modify it, set `org-element-affiliated-keywords' instead.")
256 (defconst org-element-keyword-translation-alist
257 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
258 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
259 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
260 "Alist of usual translations for keywords.
261 The key is the old name and the value the new one. The property
262 holding their value will be named after the translated name.")
264 (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
265 "List of affiliated keywords that can occur more than once in an element.
267 Their value will be consed into a list of strings, which will be
268 returned as the value of the property.
270 This list is checked after translations have been applied. See
271 `org-element-keyword-translation-alist'.
273 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
274 allow multiple occurrences and need not to be in this list.")
276 (defconst org-element-parsed-keywords '("CAPTION")
277 "List of affiliated keywords whose value can be parsed.
279 Their value will be stored as a secondary string: a list of
280 strings and objects.
282 This list is checked after translations have been applied. See
283 `org-element-keyword-translation-alist'.")
285 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
286 "List of affiliated keywords which can have a secondary value.
288 In Org syntax, they can be written with optional square brackets
289 before the colons. For example, RESULTS keyword can be
290 associated to a hash value with the following:
292 #+RESULTS[hash-string]: some-source
294 This list is checked after translations have been applied. See
295 `org-element-keyword-translation-alist'.")
297 (defconst org-element-document-properties '("AUTHOR" "DATE" "TITLE")
298 "List of properties associated to the whole document.
299 Any keyword in this list will have its value parsed and stored as
300 a secondary string.")
302 (defconst org-element-object-restrictions
303 (let* ((standard-set
304 (remq 'plain-link (remq 'table-cell org-element-all-successors)))
305 (standard-set-no-line-break (remq 'line-break standard-set)))
306 `((bold ,@standard-set)
307 (footnote-reference ,@standard-set)
308 (headline ,@standard-set-no-line-break)
309 (inlinetask ,@standard-set-no-line-break)
310 (italic ,@standard-set)
311 (item ,@standard-set-no-line-break)
312 (keyword ,@standard-set)
313 ;; Ignore all links excepted plain links in a link description.
314 ;; Also ignore radio-targets and line breaks.
315 (link export-snippet inline-babel-call inline-src-block latex-or-entity
316 macro plain-link statistics-cookie sub/superscript text-markup)
317 (paragraph ,@standard-set)
318 ;; Remove any variable object from radio target as it would
319 ;; prevent it from being properly recognized.
320 (radio-target latex-or-entity sub/superscript)
321 (strike-through ,@standard-set)
322 (subscript ,@standard-set)
323 (superscript ,@standard-set)
324 ;; Ignore inline babel call and inline src block as formulas are
325 ;; possible. Also ignore line breaks and statistics cookies.
326 (table-cell export-snippet footnote-reference latex-or-entity link macro
327 radio-target sub/superscript target text-markup timestamp)
328 (table-row table-cell)
329 (underline ,@standard-set)
330 (verse-block ,@standard-set)))
331 "Alist of objects restrictions.
333 CAR is an element or object type containing objects and CDR is
334 a list of successors that will be called within an element or
335 object of such type.
337 For example, in a `radio-target' object, one can only find
338 entities, latex-fragments, subscript and superscript.
340 This alist also applies to secondary string. For example, an
341 `headline' type element doesn't directly contain objects, but
342 still has an entry since one of its properties (`:title') does.")
344 (defconst org-element-secondary-value-alist
345 '((headline . :title)
346 (inlinetask . :title)
347 (item . :tag)
348 (footnote-reference . :inline-definition))
349 "Alist between element types and location of secondary value.")
351 (defconst org-element-object-variables '(org-link-abbrev-alist-local)
352 "List of buffer-local variables used when parsing objects.
353 These variables are copied to the temporary buffer created by
354 `org-export-secondary-string'.")
358 ;;; Accessors and Setters
360 ;; Provide four accessors: `org-element-type', `org-element-property'
361 ;; `org-element-contents' and `org-element-restriction'.
363 ;; Setter functions allow to modify elements by side effect. There is
364 ;; `org-element-put-property', `org-element-set-contents',
365 ;; `org-element-set-element' and `org-element-adopt-element'. Note
366 ;; that `org-element-set-element' and `org-element-adopt-elements' are
367 ;; higher level functions since also update `:parent' property.
369 (defsubst org-element-type (element)
370 "Return type of ELEMENT.
372 The function returns the type of the element or object provided.
373 It can also return the following special value:
374 `plain-text' for a string
375 `org-data' for a complete document
376 nil in any other case."
377 (cond
378 ((not (consp element)) (and (stringp element) 'plain-text))
379 ((symbolp (car element)) (car element))))
381 (defsubst org-element-property (property element)
382 "Extract the value from the PROPERTY of an ELEMENT."
383 (if (stringp element) (get-text-property 0 property element)
384 (plist-get (nth 1 element) property)))
386 (defsubst org-element-contents (element)
387 "Extract contents from an ELEMENT."
388 (cond ((not (consp element)) nil)
389 ((symbolp (car element)) (nthcdr 2 element))
390 (t element)))
392 (defsubst org-element-restriction (element)
393 "Return restriction associated to ELEMENT.
394 ELEMENT can be an element, an object or a symbol representing an
395 element or object type."
396 (cdr (assq (if (symbolp element) element (org-element-type element))
397 org-element-object-restrictions)))
399 (defsubst org-element-put-property (element property value)
400 "In ELEMENT set PROPERTY to VALUE.
401 Return modified element."
402 (if (stringp element) (org-add-props element nil property value)
403 (setcar (cdr element) (plist-put (nth 1 element) property value))
404 element))
406 (defsubst org-element-set-contents (element &rest contents)
407 "Set ELEMENT contents to CONTENTS.
408 Return modified element."
409 (cond ((not element) (list contents))
410 ((not (symbolp (car element))) contents)
411 ((cdr element) (setcdr (cdr element) contents))
412 (t (nconc element contents))))
414 (defsubst org-element-set-element (old new)
415 "Replace element or object OLD with element or object NEW.
416 The function takes care of setting `:parent' property for NEW."
417 ;; Since OLD is going to be changed into NEW by side-effect, first
418 ;; make sure that every element or object within NEW has OLD as
419 ;; parent.
420 (mapc (lambda (blob) (org-element-put-property blob :parent old))
421 (org-element-contents new))
422 ;; Transfer contents.
423 (apply 'org-element-set-contents old (org-element-contents new))
424 ;; Ensure NEW has same parent as OLD, then overwrite OLD properties
425 ;; with NEW's.
426 (org-element-put-property new :parent (org-element-property :parent old))
427 (setcar (cdr old) (nth 1 new))
428 ;; Transfer type.
429 (setcar old (car new)))
431 (defsubst org-element-adopt-elements (parent &rest children)
432 "Append elements to the contents of another element.
434 PARENT is an element or object. CHILDREN can be elements,
435 objects, or a strings.
437 The function takes care of setting `:parent' property for CHILD.
438 Return parent element."
439 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
440 ;; string: parent is the list itself.
441 (mapc (lambda (child)
442 (org-element-put-property child :parent (or parent children)))
443 children)
444 ;; Add CHILDREN at the end of PARENT contents.
445 (when parent
446 (apply 'org-element-set-contents
447 parent
448 (nconc (org-element-contents parent) children)))
449 ;; Return modified PARENT element.
450 (or parent children))
454 ;;; Greater elements
456 ;; For each greater element type, we define a parser and an
457 ;; interpreter.
459 ;; A parser returns the element or object as the list described above.
460 ;; Most of them accepts no argument. Though, exceptions exist. Hence
461 ;; every element containing a secondary string (see
462 ;; `org-element-secondary-value-alist') will accept an optional
463 ;; argument to toggle parsing of that secondary string. Moreover,
464 ;; `item' parser requires current list's structure as its first
465 ;; element.
467 ;; An interpreter accepts two arguments: the list representation of
468 ;; the element or object, and its contents. The latter may be nil,
469 ;; depending on the element or object considered. It returns the
470 ;; appropriate Org syntax, as a string.
472 ;; Parsing functions must follow the naming convention:
473 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
474 ;; defined in `org-element-greater-elements'.
476 ;; Similarly, interpreting functions must follow the naming
477 ;; convention: org-element-TYPE-interpreter.
479 ;; With the exception of `headline' and `item' types, greater elements
480 ;; cannot contain other greater elements of their own type.
482 ;; Beside implementing a parser and an interpreter, adding a new
483 ;; greater element requires to tweak `org-element--current-element'.
484 ;; Moreover, the newly defined type must be added to both
485 ;; `org-element-all-elements' and `org-element-greater-elements'.
488 ;;;; Center Block
490 (defun org-element-center-block-parser (limit affiliated)
491 "Parse a center block.
493 LIMIT bounds the search. AFFILIATED is a list of which CAR is
494 the buffer position at the beginning of the first affiliated
495 keyword and CDR is a plist of affiliated keywords along with
496 their value.
498 Return a list whose CAR is `center-block' and CDR is a plist
499 containing `:begin', `:end', `:contents-begin', `:contents-end',
500 `:post-blank' and `:post-affiliated' keywords.
502 Assume point is at the beginning of the block."
503 (let ((case-fold-search t))
504 (if (not (save-excursion
505 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
506 ;; Incomplete block: parse it as a paragraph.
507 (org-element-paragraph-parser limit affiliated)
508 (let ((block-end-line (match-beginning 0)))
509 (let* ((begin (car affiliated))
510 (post-affiliated (point))
511 ;; Empty blocks have no contents.
512 (contents-begin (progn (forward-line)
513 (and (< (point) block-end-line)
514 (point))))
515 (contents-end (and contents-begin block-end-line))
516 (pos-before-blank (progn (goto-char block-end-line)
517 (forward-line)
518 (point)))
519 (end (save-excursion
520 (skip-chars-forward " \r\t\n" limit)
521 (if (eobp) (point) (line-beginning-position)))))
522 (list 'center-block
523 (nconc
524 (list :begin begin
525 :end end
526 :contents-begin contents-begin
527 :contents-end contents-end
528 :post-blank (count-lines pos-before-blank end)
529 :post-affiliated post-affiliated)
530 (cdr affiliated))))))))
532 (defun org-element-center-block-interpreter (center-block contents)
533 "Interpret CENTER-BLOCK element as Org syntax.
534 CONTENTS is the contents of the element."
535 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
538 ;;;; Drawer
540 (defun org-element-drawer-parser (limit affiliated)
541 "Parse a drawer.
543 LIMIT bounds the search. AFFILIATED is a list of which CAR is
544 the buffer position at the beginning of the first affiliated
545 keyword and CDR is a plist of affiliated keywords along with
546 their value.
548 Return a list whose CAR is `drawer' and CDR is a plist containing
549 `:drawer-name', `:begin', `:end', `:contents-begin',
550 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
552 Assume point is at beginning of drawer."
553 (let ((case-fold-search t))
554 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
555 ;; Incomplete drawer: parse it as a paragraph.
556 (org-element-paragraph-parser limit affiliated)
557 (save-excursion
558 (let* ((drawer-end-line (match-beginning 0))
559 (name (progn (looking-at org-drawer-regexp)
560 (org-match-string-no-properties 1)))
561 (begin (car affiliated))
562 (post-affiliated (point))
563 ;; Empty drawers have no contents.
564 (contents-begin (progn (forward-line)
565 (and (< (point) drawer-end-line)
566 (point))))
567 (contents-end (and contents-begin drawer-end-line))
568 (pos-before-blank (progn (goto-char drawer-end-line)
569 (forward-line)
570 (point)))
571 (end (progn (skip-chars-forward " \r\t\n" limit)
572 (if (eobp) (point) (line-beginning-position)))))
573 (list 'drawer
574 (nconc
575 (list :begin begin
576 :end end
577 :drawer-name name
578 :contents-begin contents-begin
579 :contents-end contents-end
580 :post-blank (count-lines pos-before-blank end)
581 :post-affiliated post-affiliated)
582 (cdr affiliated))))))))
584 (defun org-element-drawer-interpreter (drawer contents)
585 "Interpret DRAWER element as Org syntax.
586 CONTENTS is the contents of the element."
587 (format ":%s:\n%s:END:"
588 (org-element-property :drawer-name drawer)
589 contents))
592 ;;;; Dynamic Block
594 (defun org-element-dynamic-block-parser (limit affiliated)
595 "Parse a dynamic block.
597 LIMIT bounds the search. AFFILIATED is a list of which CAR is
598 the buffer position at the beginning of the first affiliated
599 keyword and CDR is a plist of affiliated keywords along with
600 their value.
602 Return a list whose CAR is `dynamic-block' and CDR is a plist
603 containing `:block-name', `:begin', `:end', `:contents-begin',
604 `:contents-end', `:arguments', `:post-blank' and
605 `:post-affiliated' keywords.
607 Assume point is at beginning of dynamic block."
608 (let ((case-fold-search t))
609 (if (not (save-excursion
610 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
611 ;; Incomplete block: parse it as a paragraph.
612 (org-element-paragraph-parser limit affiliated)
613 (let ((block-end-line (match-beginning 0)))
614 (save-excursion
615 (let* ((name (progn (looking-at org-dblock-start-re)
616 (org-match-string-no-properties 1)))
617 (arguments (org-match-string-no-properties 3))
618 (begin (car affiliated))
619 (post-affiliated (point))
620 ;; Empty blocks have no contents.
621 (contents-begin (progn (forward-line)
622 (and (< (point) block-end-line)
623 (point))))
624 (contents-end (and contents-begin block-end-line))
625 (pos-before-blank (progn (goto-char block-end-line)
626 (forward-line)
627 (point)))
628 (end (progn (skip-chars-forward " \r\t\n" limit)
629 (if (eobp) (point) (line-beginning-position)))))
630 (list 'dynamic-block
631 (nconc
632 (list :begin begin
633 :end end
634 :block-name name
635 :arguments arguments
636 :contents-begin contents-begin
637 :contents-end contents-end
638 :post-blank (count-lines pos-before-blank end)
639 :post-affiliated post-affiliated)
640 (cdr affiliated)))))))))
642 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
643 "Interpret DYNAMIC-BLOCK element as Org syntax.
644 CONTENTS is the contents of the element."
645 (format "#+BEGIN: %s%s\n%s#+END:"
646 (org-element-property :block-name dynamic-block)
647 (let ((args (org-element-property :arguments dynamic-block)))
648 (and args (concat " " args)))
649 contents))
652 ;;;; Footnote Definition
654 (defun org-element-footnote-definition-parser (limit affiliated)
655 "Parse a footnote definition.
657 LIMIT bounds the search. AFFILIATED is a list of which CAR is
658 the buffer position at the beginning of the first affiliated
659 keyword and CDR is a plist of affiliated keywords along with
660 their value.
662 Return a list whose CAR is `footnote-definition' and CDR is
663 a plist containing `:label', `:begin' `:end', `:contents-begin',
664 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
666 Assume point is at the beginning of the footnote definition."
667 (save-excursion
668 (let* ((label (progn (looking-at org-footnote-definition-re)
669 (org-match-string-no-properties 1)))
670 (begin (car affiliated))
671 (post-affiliated (point))
672 (ending (save-excursion
673 (if (progn
674 (end-of-line)
675 (re-search-forward
676 (concat org-outline-regexp-bol "\\|"
677 org-footnote-definition-re "\\|"
678 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
679 (match-beginning 0)
680 (point))))
681 (contents-begin (progn
682 (search-forward "]")
683 (skip-chars-forward " \r\t\n" ending)
684 (cond ((= (point) ending) nil)
685 ((= (line-beginning-position) begin) (point))
686 (t (line-beginning-position)))))
687 (contents-end (and contents-begin ending))
688 (end (progn (goto-char ending)
689 (skip-chars-forward " \r\t\n" limit)
690 (if (eobp) (point) (line-beginning-position)))))
691 (list 'footnote-definition
692 (nconc
693 (list :label label
694 :begin begin
695 :end end
696 :contents-begin contents-begin
697 :contents-end contents-end
698 :post-blank (count-lines ending end)
699 :post-affiliated post-affiliated)
700 (cdr affiliated))))))
702 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
703 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
704 CONTENTS is the contents of the footnote-definition."
705 (concat (format "[%s]" (org-element-property :label footnote-definition))
707 contents))
710 ;;;; Headline
712 (defun org-element-headline-parser (limit &optional raw-secondary-p)
713 "Parse a headline.
715 Return a list whose CAR is `headline' and CDR is a plist
716 containing `:raw-value', `:title', `:alt-title', `:begin',
717 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
718 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
719 `:scheduled', `:deadline', `:closed', `:quotedp', `:archivedp',
720 `:commentedp' and `:footnote-section-p' keywords.
722 The plist also contains any property set in the property drawer,
723 with its name in upper cases and colons added at the
724 beginning (i.e. `:CUSTOM_ID').
726 When RAW-SECONDARY-P is non-nil, headline's title will not be
727 parsed as a secondary string, but as a plain string instead.
729 Assume point is at beginning of the headline."
730 (save-excursion
731 (let* ((components (org-heading-components))
732 (level (nth 1 components))
733 (todo (nth 2 components))
734 (todo-type
735 (and todo (if (member todo org-done-keywords) 'done 'todo)))
736 (tags (let ((raw-tags (nth 5 components)))
737 (and raw-tags (org-split-string raw-tags ":"))))
738 (raw-value (or (nth 4 components) ""))
739 (quotedp
740 (let ((case-fold-search nil))
741 (string-match (format "^%s\\( \\|$\\)" org-quote-string)
742 raw-value)))
743 (commentedp
744 (let ((case-fold-search nil))
745 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
746 raw-value)))
747 (archivedp (member org-archive-tag tags))
748 (footnote-section-p (and org-footnote-section
749 (string= org-footnote-section raw-value)))
750 ;; Upcase property names. It avoids confusion between
751 ;; properties obtained through property drawer and default
752 ;; properties from the parser (e.g. `:end' and :END:)
753 (standard-props
754 (let (plist)
755 (mapc
756 (lambda (p)
757 (setq plist
758 (plist-put plist
759 (intern (concat ":" (upcase (car p))))
760 (cdr p))))
761 (org-entry-properties nil 'standard))
762 plist))
763 (time-props
764 ;; Read time properties on the line below the headline.
765 (save-excursion
766 (when (progn (forward-line)
767 (looking-at org-planning-or-clock-line-re))
768 (let ((end (line-end-position)) plist)
769 (while (re-search-forward
770 org-keyword-time-not-clock-regexp end t)
771 (goto-char (match-end 1))
772 (skip-chars-forward " \t")
773 (let ((keyword (match-string 1))
774 (time (org-element-timestamp-parser)))
775 (cond ((equal keyword org-scheduled-string)
776 (setq plist (plist-put plist :scheduled time)))
777 ((equal keyword org-deadline-string)
778 (setq plist (plist-put plist :deadline time)))
779 (t (setq plist (plist-put plist :closed time))))))
780 plist))))
781 (begin (point))
782 (end (save-excursion (goto-char (org-end-of-subtree t t))))
783 (pos-after-head (progn (forward-line) (point)))
784 (contents-begin (save-excursion
785 (skip-chars-forward " \r\t\n" end)
786 (and (/= (point) end) (line-beginning-position))))
787 (contents-end (and contents-begin
788 (progn (goto-char end)
789 (skip-chars-backward " \r\t\n")
790 (forward-line)
791 (point)))))
792 ;; Clean RAW-VALUE from any quote or comment string.
793 (when (or quotedp commentedp)
794 (let ((case-fold-search nil))
795 (setq raw-value
796 (replace-regexp-in-string
797 (concat
798 (regexp-opt (list org-quote-string org-comment-string))
799 "\\(?: \\|$\\)")
801 raw-value))))
802 ;; Clean TAGS from archive tag, if any.
803 (when archivedp (setq tags (delete org-archive-tag tags)))
804 (let ((headline
805 (list 'headline
806 (nconc
807 (list :raw-value raw-value
808 :begin begin
809 :end end
810 :pre-blank
811 (if (not contents-begin) 0
812 (count-lines pos-after-head contents-begin))
813 :contents-begin contents-begin
814 :contents-end contents-end
815 :level level
816 :priority (nth 3 components)
817 :tags tags
818 :todo-keyword todo
819 :todo-type todo-type
820 :post-blank (count-lines
821 (if (not contents-end) pos-after-head
822 (goto-char contents-end)
823 (forward-line)
824 (point))
825 end)
826 :footnote-section-p footnote-section-p
827 :archivedp archivedp
828 :commentedp commentedp
829 :quotedp quotedp)
830 time-props
831 standard-props))))
832 (let ((alt-title (org-element-property :ALT_TITLE headline)))
833 (when alt-title
834 (org-element-put-property
835 headline :alt-title
836 (if raw-secondary-p alt-title
837 (org-element-parse-secondary-string
838 alt-title (org-element-restriction 'headline) headline)))))
839 (org-element-put-property
840 headline :title
841 (if raw-secondary-p raw-value
842 (org-element-parse-secondary-string
843 raw-value (org-element-restriction 'headline) headline)))))))
845 (defun org-element-headline-interpreter (headline contents)
846 "Interpret HEADLINE element as Org syntax.
847 CONTENTS is the contents of the element."
848 (let* ((level (org-element-property :level headline))
849 (todo (org-element-property :todo-keyword headline))
850 (priority (org-element-property :priority headline))
851 (title (org-element-interpret-data
852 (org-element-property :title headline)))
853 (tags (let ((tag-list (if (org-element-property :archivedp headline)
854 (cons org-archive-tag
855 (org-element-property :tags headline))
856 (org-element-property :tags headline))))
857 (and tag-list
858 (format ":%s:" (mapconcat 'identity tag-list ":")))))
859 (commentedp (org-element-property :commentedp headline))
860 (quotedp (org-element-property :quotedp headline))
861 (pre-blank (or (org-element-property :pre-blank headline) 0))
862 (heading (concat (make-string (org-reduced-level level) ?*)
863 (and todo (concat " " todo))
864 (and quotedp (concat " " org-quote-string))
865 (and commentedp (concat " " org-comment-string))
866 (and priority
867 (format " [#%s]" (char-to-string priority)))
868 (cond ((and org-footnote-section
869 (org-element-property
870 :footnote-section-p headline))
871 (concat " " org-footnote-section))
872 (title (concat " " title))))))
873 (concat heading
874 ;; Align tags.
875 (when tags
876 (cond
877 ((zerop org-tags-column) (format " %s" tags))
878 ((< org-tags-column 0)
879 (concat
880 (make-string
881 (max (- (+ org-tags-column (length heading) (length tags))) 1)
883 tags))
885 (concat
886 (make-string (max (- org-tags-column (length heading)) 1) ? )
887 tags))))
888 (make-string (1+ pre-blank) 10)
889 contents)))
892 ;;;; Inlinetask
894 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
895 "Parse an inline task.
897 Return a list whose CAR is `inlinetask' and CDR is a plist
898 containing `:title', `:begin', `:end', `:contents-begin' and
899 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
900 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
901 `:closed' and `:post-blank' keywords.
903 The plist also contains any property set in the property drawer,
904 with its name in upper cases and colons added at the
905 beginning (i.e. `:CUSTOM_ID').
907 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
908 title will not be parsed as a secondary string, but as a plain
909 string instead.
911 Assume point is at beginning of the inline task."
912 (save-excursion
913 (let* ((begin (point))
914 (components (org-heading-components))
915 (todo (nth 2 components))
916 (todo-type (and todo
917 (if (member todo org-done-keywords) 'done 'todo)))
918 (tags (let ((raw-tags (nth 5 components)))
919 (and raw-tags (org-split-string raw-tags ":"))))
920 (raw-value (or (nth 4 components) ""))
921 ;; Upcase property names. It avoids confusion between
922 ;; properties obtained through property drawer and default
923 ;; properties from the parser (e.g. `:end' and :END:)
924 (standard-props
925 (let (plist)
926 (mapc
927 (lambda (p)
928 (setq plist
929 (plist-put plist
930 (intern (concat ":" (upcase (car p))))
931 (cdr p))))
932 (org-entry-properties nil 'standard))
933 plist))
934 (time-props
935 ;; Read time properties on the line below the inlinetask
936 ;; opening string.
937 (save-excursion
938 (when (progn (forward-line)
939 (looking-at org-planning-or-clock-line-re))
940 (let ((end (line-end-position)) plist)
941 (while (re-search-forward
942 org-keyword-time-not-clock-regexp end t)
943 (goto-char (match-end 1))
944 (skip-chars-forward " \t")
945 (let ((keyword (match-string 1))
946 (time (org-element-timestamp-parser)))
947 (cond ((equal keyword org-scheduled-string)
948 (setq plist (plist-put plist :scheduled time)))
949 ((equal keyword org-deadline-string)
950 (setq plist (plist-put plist :deadline time)))
951 (t (setq plist (plist-put plist :closed time))))))
952 plist))))
953 (task-end (save-excursion
954 (end-of-line)
955 (and (re-search-forward "^\\*+ END" limit t)
956 (match-beginning 0))))
957 (contents-begin (progn (forward-line)
958 (and task-end (< (point) task-end) (point))))
959 (contents-end (and contents-begin task-end))
960 (before-blank (if (not task-end) (point)
961 (goto-char task-end)
962 (forward-line)
963 (point)))
964 (end (progn (skip-chars-forward " \r\t\n" limit)
965 (if (eobp) (point) (line-beginning-position))))
966 (inlinetask
967 (list 'inlinetask
968 (nconc
969 (list :raw-value raw-value
970 :begin begin
971 :end end
972 :contents-begin contents-begin
973 :contents-end contents-end
974 :level (nth 1 components)
975 :priority (nth 3 components)
976 :tags tags
977 :todo-keyword todo
978 :todo-type todo-type
979 :post-blank (count-lines before-blank end))
980 time-props
981 standard-props))))
982 (org-element-put-property
983 inlinetask :title
984 (if raw-secondary-p raw-value
985 (org-element-parse-secondary-string
986 raw-value
987 (org-element-restriction 'inlinetask)
988 inlinetask))))))
990 (defun org-element-inlinetask-interpreter (inlinetask contents)
991 "Interpret INLINETASK element as Org syntax.
992 CONTENTS is the contents of inlinetask."
993 (let* ((level (org-element-property :level inlinetask))
994 (todo (org-element-property :todo-keyword inlinetask))
995 (priority (org-element-property :priority inlinetask))
996 (title (org-element-interpret-data
997 (org-element-property :title inlinetask)))
998 (tags (let ((tag-list (org-element-property :tags inlinetask)))
999 (and tag-list
1000 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1001 (task (concat (make-string level ?*)
1002 (and todo (concat " " todo))
1003 (and priority
1004 (format " [#%s]" (char-to-string priority)))
1005 (and title (concat " " title)))))
1006 (concat task
1007 ;; Align tags.
1008 (when tags
1009 (cond
1010 ((zerop org-tags-column) (format " %s" tags))
1011 ((< org-tags-column 0)
1012 (concat
1013 (make-string
1014 (max (- (+ org-tags-column (length task) (length tags))) 1)
1016 tags))
1018 (concat
1019 (make-string (max (- org-tags-column (length task)) 1) ? )
1020 tags))))
1021 ;; Prefer degenerate inlinetasks when there are no
1022 ;; contents.
1023 (when contents
1024 (concat "\n"
1025 contents
1026 (make-string level ?*) " END")))))
1029 ;;;; Item
1031 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1032 "Parse an item.
1034 STRUCT is the structure of the plain list.
1036 Return a list whose CAR is `item' and CDR is a plist containing
1037 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1038 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1039 keywords.
1041 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1042 any, will not be parsed as a secondary string, but as a plain
1043 string instead.
1045 Assume point is at the beginning of the item."
1046 (save-excursion
1047 (beginning-of-line)
1048 (looking-at org-list-full-item-re)
1049 (let* ((begin (point))
1050 (bullet (org-match-string-no-properties 1))
1051 (checkbox (let ((box (org-match-string-no-properties 3)))
1052 (cond ((equal "[ ]" box) 'off)
1053 ((equal "[X]" box) 'on)
1054 ((equal "[-]" box) 'trans))))
1055 (counter (let ((c (org-match-string-no-properties 2)))
1056 (save-match-data
1057 (cond
1058 ((not c) nil)
1059 ((string-match "[A-Za-z]" c)
1060 (- (string-to-char (upcase (match-string 0 c)))
1061 64))
1062 ((string-match "[0-9]+" c)
1063 (string-to-number (match-string 0 c)))))))
1064 (end (progn (goto-char (nth 6 (assq (point) struct)))
1065 (unless (bolp) (forward-line))
1066 (point)))
1067 (contents-begin
1068 (progn (goto-char
1069 ;; Ignore tags in un-ordered lists: they are just
1070 ;; a part of item's body.
1071 (if (and (match-beginning 4)
1072 (save-match-data (string-match "[.)]" bullet)))
1073 (match-beginning 4)
1074 (match-end 0)))
1075 (skip-chars-forward " \r\t\n" limit)
1076 ;; If first line isn't empty, contents really start
1077 ;; at the text after item's meta-data.
1078 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1079 (contents-end (progn (goto-char end)
1080 (skip-chars-backward " \r\t\n")
1081 (forward-line)
1082 (point)))
1083 (item
1084 (list 'item
1085 (list :bullet bullet
1086 :begin begin
1087 :end end
1088 ;; CONTENTS-BEGIN and CONTENTS-END may be
1089 ;; mixed up in the case of an empty item
1090 ;; separated from the next by a blank line.
1091 ;; Thus ensure the former is always the
1092 ;; smallest.
1093 :contents-begin (min contents-begin contents-end)
1094 :contents-end (max contents-begin contents-end)
1095 :checkbox checkbox
1096 :counter counter
1097 :structure struct
1098 :post-blank (count-lines contents-end end)))))
1099 (org-element-put-property
1100 item :tag
1101 (let ((raw-tag (org-list-get-tag begin struct)))
1102 (and raw-tag
1103 (if raw-secondary-p raw-tag
1104 (org-element-parse-secondary-string
1105 raw-tag (org-element-restriction 'item) item))))))))
1107 (defun org-element-item-interpreter (item contents)
1108 "Interpret ITEM element as Org syntax.
1109 CONTENTS is the contents of the element."
1110 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1111 (org-list-bullet-string
1112 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1113 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1114 (t "1.")))))
1115 (checkbox (org-element-property :checkbox item))
1116 (counter (org-element-property :counter item))
1117 (tag (let ((tag (org-element-property :tag item)))
1118 (and tag (org-element-interpret-data tag))))
1119 ;; Compute indentation.
1120 (ind (make-string (length bullet) 32))
1121 (item-starts-with-par-p
1122 (eq (org-element-type (car (org-element-contents item)))
1123 'paragraph)))
1124 ;; Indent contents.
1125 (concat
1126 bullet
1127 (and counter (format "[@%d] " counter))
1128 (case checkbox
1129 (on "[X] ")
1130 (off "[ ] ")
1131 (trans "[-] "))
1132 (and tag (format "%s :: " tag))
1133 (when contents
1134 (let ((contents (replace-regexp-in-string
1135 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1136 (if item-starts-with-par-p (org-trim contents)
1137 (concat "\n" contents)))))))
1140 ;;;; Plain List
1142 (defun org-element--list-struct (limit)
1143 ;; Return structure of list at point. Internal function. See
1144 ;; `org-list-struct' for details.
1145 (let ((case-fold-search t)
1146 (top-ind limit)
1147 (item-re (org-item-re))
1148 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1149 items struct)
1150 (save-excursion
1151 (catch 'exit
1152 (while t
1153 (cond
1154 ;; At limit: end all items.
1155 ((>= (point) limit)
1156 (throw 'exit
1157 (let ((end (progn (skip-chars-backward " \r\t\n")
1158 (forward-line)
1159 (point))))
1160 (dolist (item items (sort (nconc items struct)
1161 'car-less-than-car))
1162 (setcar (nthcdr 6 item) end)))))
1163 ;; At list end: end all items.
1164 ((looking-at org-list-end-re)
1165 (throw 'exit (dolist (item items (sort (nconc items struct)
1166 'car-less-than-car))
1167 (setcar (nthcdr 6 item) (point)))))
1168 ;; At a new item: end previous sibling.
1169 ((looking-at item-re)
1170 (let ((ind (save-excursion (skip-chars-forward " \t")
1171 (current-column))))
1172 (setq top-ind (min top-ind ind))
1173 (while (and items (<= ind (nth 1 (car items))))
1174 (let ((item (pop items)))
1175 (setcar (nthcdr 6 item) (point))
1176 (push item struct)))
1177 (push (progn (looking-at org-list-full-item-re)
1178 (let ((bullet (match-string-no-properties 1)))
1179 (list (point)
1181 bullet
1182 (match-string-no-properties 2) ; counter
1183 (match-string-no-properties 3) ; checkbox
1184 ;; Description tag.
1185 (and (save-match-data
1186 (string-match "[-+*]" bullet))
1187 (match-string-no-properties 4))
1188 ;; Ending position, unknown so far.
1189 nil)))
1190 items))
1191 (forward-line 1))
1192 ;; Skip empty lines.
1193 ((looking-at "^[ \t]*$") (forward-line))
1194 ;; Skip inline tasks and blank lines along the way.
1195 ((and inlinetask-re (looking-at inlinetask-re))
1196 (forward-line)
1197 (let ((origin (point)))
1198 (when (re-search-forward inlinetask-re limit t)
1199 (if (looking-at "^\\*+ END[ \t]*$") (forward-line)
1200 (goto-char origin)))))
1201 ;; At some text line. Check if it ends any previous item.
1203 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1204 (when (<= ind top-ind)
1205 (skip-chars-backward " \r\t\n")
1206 (forward-line))
1207 (while (<= ind (nth 1 (car items)))
1208 (let ((item (pop items)))
1209 (setcar (nthcdr 6 item) (line-beginning-position))
1210 (push item struct)
1211 (unless items
1212 (throw 'exit (sort struct 'car-less-than-car))))))
1213 ;; Skip blocks (any type) and drawers contents.
1214 (cond
1215 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1216 (re-search-forward
1217 (format "^[ \t]*#\\+END%s[ \t]*$"
1218 (org-match-string-no-properties 1))
1219 limit t)))
1220 ((and (looking-at org-drawer-regexp)
1221 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1222 (forward-line))))))))
1224 (defun org-element-plain-list-parser (limit affiliated structure)
1225 "Parse a plain list.
1227 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1228 the buffer position at the beginning of the first affiliated
1229 keyword and CDR is a plist of affiliated keywords along with
1230 their value. STRUCTURE is the structure of the plain list being
1231 parsed.
1233 Return a list whose CAR is `plain-list' and CDR is a plist
1234 containing `:type', `:begin', `:end', `:contents-begin' and
1235 `:contents-end', `:structure', `:post-blank' and
1236 `:post-affiliated' keywords.
1238 Assume point is at the beginning of the list."
1239 (save-excursion
1240 (let* ((struct (or structure (org-element--list-struct limit)))
1241 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1242 ((nth 5 (assq (point) struct)) 'descriptive)
1243 (t 'unordered)))
1244 (contents-begin (point))
1245 (begin (car affiliated))
1246 (contents-end (let* ((item (assq contents-begin struct))
1247 (ind (nth 1 item))
1248 (pos (nth 6 item)))
1249 (while (and (setq item (assq pos struct))
1250 (= (nth 1 item) ind))
1251 (setq pos (nth 6 item)))
1252 pos))
1253 (end (progn (goto-char contents-end)
1254 (skip-chars-forward " \r\t\n" limit)
1255 (if (= (point) limit) limit (line-beginning-position)))))
1256 ;; Return value.
1257 (list 'plain-list
1258 (nconc
1259 (list :type type
1260 :begin begin
1261 :end end
1262 :contents-begin contents-begin
1263 :contents-end contents-end
1264 :structure struct
1265 :post-blank (count-lines contents-end end)
1266 :post-affiliated contents-begin)
1267 (cdr affiliated))))))
1269 (defun org-element-plain-list-interpreter (plain-list contents)
1270 "Interpret PLAIN-LIST element as Org syntax.
1271 CONTENTS is the contents of the element."
1272 (with-temp-buffer
1273 (insert contents)
1274 (goto-char (point-min))
1275 (org-list-repair)
1276 (buffer-string)))
1279 ;;;; Property Drawer
1281 (defun org-element-property-drawer-parser (limit affiliated)
1282 "Parse a property drawer.
1284 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1285 the buffer position at the beginning of the first affiliated
1286 keyword and CDR is a plist of affiliated keywords along with
1287 their value.
1289 Return a list whose CAR is `property-drawer' and CDR is a plist
1290 containing `:begin', `:end', `:contents-begin', `:contents-end',
1291 `:post-blank' and `:post-affiliated' keywords.
1293 Assume point is at the beginning of the property drawer."
1294 (save-excursion
1295 (let ((case-fold-search t))
1296 (if (not (save-excursion
1297 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1298 ;; Incomplete drawer: parse it as a paragraph.
1299 (org-element-paragraph-parser limit affiliated)
1300 (save-excursion
1301 (let* ((drawer-end-line (match-beginning 0))
1302 (begin (car affiliated))
1303 (post-affiliated (point))
1304 (contents-begin (progn (forward-line)
1305 (and (< (point) drawer-end-line)
1306 (point))))
1307 (contents-end (and contents-begin drawer-end-line))
1308 (pos-before-blank (progn (goto-char drawer-end-line)
1309 (forward-line)
1310 (point)))
1311 (end (progn (skip-chars-forward " \r\t\n" limit)
1312 (if (eobp) (point) (line-beginning-position)))))
1313 (list 'property-drawer
1314 (nconc
1315 (list :begin begin
1316 :end end
1317 :contents-begin contents-begin
1318 :contents-end contents-end
1319 :post-blank (count-lines pos-before-blank end)
1320 :post-affiliated post-affiliated)
1321 (cdr affiliated)))))))))
1323 (defun org-element-property-drawer-interpreter (property-drawer contents)
1324 "Interpret PROPERTY-DRAWER element as Org syntax.
1325 CONTENTS is the properties within the drawer."
1326 (format ":PROPERTIES:\n%s:END:" contents))
1329 ;;;; Quote Block
1331 (defun org-element-quote-block-parser (limit affiliated)
1332 "Parse a quote block.
1334 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1335 the buffer position at the beginning of the first affiliated
1336 keyword and CDR is a plist of affiliated keywords along with
1337 their value.
1339 Return a list whose CAR is `quote-block' and CDR is a plist
1340 containing `:begin', `:end', `:contents-begin', `:contents-end',
1341 `:post-blank' and `:post-affiliated' keywords.
1343 Assume point is at the beginning of the block."
1344 (let ((case-fold-search t))
1345 (if (not (save-excursion
1346 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1347 ;; Incomplete block: parse it as a paragraph.
1348 (org-element-paragraph-parser limit affiliated)
1349 (let ((block-end-line (match-beginning 0)))
1350 (save-excursion
1351 (let* ((begin (car affiliated))
1352 (post-affiliated (point))
1353 ;; Empty blocks have no contents.
1354 (contents-begin (progn (forward-line)
1355 (and (< (point) block-end-line)
1356 (point))))
1357 (contents-end (and contents-begin block-end-line))
1358 (pos-before-blank (progn (goto-char block-end-line)
1359 (forward-line)
1360 (point)))
1361 (end (progn (skip-chars-forward " \r\t\n" limit)
1362 (if (eobp) (point) (line-beginning-position)))))
1363 (list 'quote-block
1364 (nconc
1365 (list :begin begin
1366 :end end
1367 :contents-begin contents-begin
1368 :contents-end contents-end
1369 :post-blank (count-lines pos-before-blank end)
1370 :post-affiliated post-affiliated)
1371 (cdr affiliated)))))))))
1373 (defun org-element-quote-block-interpreter (quote-block contents)
1374 "Interpret QUOTE-BLOCK element as Org syntax.
1375 CONTENTS is the contents of the element."
1376 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1379 ;;;; Section
1381 (defun org-element-section-parser (limit)
1382 "Parse a section.
1384 LIMIT bounds the search.
1386 Return a list whose CAR is `section' and CDR is a plist
1387 containing `:begin', `:end', `:contents-begin', `contents-end'
1388 and `:post-blank' keywords."
1389 (save-excursion
1390 ;; Beginning of section is the beginning of the first non-blank
1391 ;; line after previous headline.
1392 (let ((begin (point))
1393 (end (progn (org-with-limited-levels (outline-next-heading))
1394 (point)))
1395 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1396 (forward-line)
1397 (point))))
1398 (list 'section
1399 (list :begin begin
1400 :end end
1401 :contents-begin begin
1402 :contents-end pos-before-blank
1403 :post-blank (count-lines pos-before-blank end))))))
1405 (defun org-element-section-interpreter (section contents)
1406 "Interpret SECTION element as Org syntax.
1407 CONTENTS is the contents of the element."
1408 contents)
1411 ;;;; Special Block
1413 (defun org-element-special-block-parser (limit affiliated)
1414 "Parse a special block.
1416 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1417 the buffer position at the beginning of the first affiliated
1418 keyword and CDR is a plist of affiliated keywords along with
1419 their value.
1421 Return a list whose CAR is `special-block' and CDR is a plist
1422 containing `:type', `:begin', `:end', `:contents-begin',
1423 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1425 Assume point is at the beginning of the block."
1426 (let* ((case-fold-search t)
1427 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1428 (upcase (match-string-no-properties 1)))))
1429 (if (not (save-excursion
1430 (re-search-forward
1431 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1432 limit t)))
1433 ;; Incomplete block: parse it as a paragraph.
1434 (org-element-paragraph-parser limit affiliated)
1435 (let ((block-end-line (match-beginning 0)))
1436 (save-excursion
1437 (let* ((begin (car affiliated))
1438 (post-affiliated (point))
1439 ;; Empty blocks have no contents.
1440 (contents-begin (progn (forward-line)
1441 (and (< (point) block-end-line)
1442 (point))))
1443 (contents-end (and contents-begin block-end-line))
1444 (pos-before-blank (progn (goto-char block-end-line)
1445 (forward-line)
1446 (point)))
1447 (end (progn (skip-chars-forward " \r\t\n" limit)
1448 (if (eobp) (point) (line-beginning-position)))))
1449 (list 'special-block
1450 (nconc
1451 (list :type type
1452 :begin begin
1453 :end end
1454 :contents-begin contents-begin
1455 :contents-end contents-end
1456 :post-blank (count-lines pos-before-blank end)
1457 :post-affiliated post-affiliated)
1458 (cdr affiliated)))))))))
1460 (defun org-element-special-block-interpreter (special-block contents)
1461 "Interpret SPECIAL-BLOCK element as Org syntax.
1462 CONTENTS is the contents of the element."
1463 (let ((block-type (org-element-property :type special-block)))
1464 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1468 ;;; Elements
1470 ;; For each element, a parser and an interpreter are also defined.
1471 ;; Both follow the same naming convention used for greater elements.
1473 ;; Also, as for greater elements, adding a new element type is done
1474 ;; through the following steps: implement a parser and an interpreter,
1475 ;; tweak `org-element--current-element' so that it recognizes the new
1476 ;; type and add that new type to `org-element-all-elements'.
1478 ;; As a special case, when the newly defined type is a block type,
1479 ;; `org-element-block-name-alist' has to be modified accordingly.
1482 ;;;; Babel Call
1484 (defun org-element-babel-call-parser (limit affiliated)
1485 "Parse a babel call.
1487 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1488 the buffer position at the beginning of the first affiliated
1489 keyword and CDR is a plist of affiliated keywords along with
1490 their value.
1492 Return a list whose CAR is `babel-call' and CDR is a plist
1493 containing `:begin', `:end', `:value', `:post-blank' and
1494 `:post-affiliated' as keywords."
1495 (save-excursion
1496 (let ((begin (car affiliated))
1497 (post-affiliated (point))
1498 (value (progn (let ((case-fold-search t))
1499 (re-search-forward "call:[ \t]*" nil t))
1500 (buffer-substring-no-properties (point)
1501 (line-end-position))))
1502 (pos-before-blank (progn (forward-line) (point)))
1503 (end (progn (skip-chars-forward " \r\t\n" limit)
1504 (if (eobp) (point) (line-beginning-position)))))
1505 (list 'babel-call
1506 (nconc
1507 (list :begin begin
1508 :end end
1509 :value value
1510 :post-blank (count-lines pos-before-blank end)
1511 :post-affiliated post-affiliated)
1512 (cdr affiliated))))))
1514 (defun org-element-babel-call-interpreter (babel-call contents)
1515 "Interpret BABEL-CALL element as Org syntax.
1516 CONTENTS is nil."
1517 (concat "#+CALL: " (org-element-property :value babel-call)))
1520 ;;;; Clock
1522 (defun org-element-clock-parser (limit)
1523 "Parse a clock.
1525 LIMIT bounds the search.
1527 Return a list whose CAR is `clock' and CDR is a plist containing
1528 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1529 as keywords."
1530 (save-excursion
1531 (let* ((case-fold-search nil)
1532 (begin (point))
1533 (value (progn (search-forward org-clock-string (line-end-position) t)
1534 (skip-chars-forward " \t")
1535 (org-element-timestamp-parser)))
1536 (duration (and (search-forward " => " (line-end-position) t)
1537 (progn (skip-chars-forward " \t")
1538 (looking-at "\\(\\S-+\\)[ \t]*$"))
1539 (org-match-string-no-properties 1)))
1540 (status (if duration 'closed 'running))
1541 (post-blank (let ((before-blank (progn (forward-line) (point))))
1542 (skip-chars-forward " \r\t\n" limit)
1543 (skip-chars-backward " \t")
1544 (unless (bolp) (end-of-line))
1545 (count-lines before-blank (point))))
1546 (end (point)))
1547 (list 'clock
1548 (list :status status
1549 :value value
1550 :duration duration
1551 :begin begin
1552 :end end
1553 :post-blank post-blank)))))
1555 (defun org-element-clock-interpreter (clock contents)
1556 "Interpret CLOCK element as Org syntax.
1557 CONTENTS is nil."
1558 (concat org-clock-string " "
1559 (org-element-timestamp-interpreter
1560 (org-element-property :value clock) nil)
1561 (let ((duration (org-element-property :duration clock)))
1562 (and duration
1563 (concat " => "
1564 (apply 'format
1565 "%2s:%02s"
1566 (org-split-string duration ":")))))))
1569 ;;;; Comment
1571 (defun org-element-comment-parser (limit affiliated)
1572 "Parse a comment.
1574 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1575 the buffer position at the beginning of the first affiliated
1576 keyword and CDR is a plist of affiliated keywords along with
1577 their value.
1579 Return a list whose CAR is `comment' and CDR is a plist
1580 containing `:begin', `:end', `:value', `:post-blank',
1581 `:post-affiliated' keywords.
1583 Assume point is at comment beginning."
1584 (save-excursion
1585 (let* ((begin (car affiliated))
1586 (post-affiliated (point))
1587 (value (prog2 (looking-at "[ \t]*# ?")
1588 (buffer-substring-no-properties
1589 (match-end 0) (line-end-position))
1590 (forward-line)))
1591 (com-end
1592 ;; Get comments ending.
1593 (progn
1594 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1595 ;; Accumulate lines without leading hash and first
1596 ;; whitespace.
1597 (setq value
1598 (concat value
1599 "\n"
1600 (buffer-substring-no-properties
1601 (match-end 0) (line-end-position))))
1602 (forward-line))
1603 (point)))
1604 (end (progn (goto-char com-end)
1605 (skip-chars-forward " \r\t\n" limit)
1606 (if (eobp) (point) (line-beginning-position)))))
1607 (list 'comment
1608 (nconc
1609 (list :begin begin
1610 :end end
1611 :value value
1612 :post-blank (count-lines com-end end)
1613 :post-affiliated post-affiliated)
1614 (cdr affiliated))))))
1616 (defun org-element-comment-interpreter (comment contents)
1617 "Interpret COMMENT element as Org syntax.
1618 CONTENTS is nil."
1619 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1622 ;;;; Comment Block
1624 (defun org-element-comment-block-parser (limit affiliated)
1625 "Parse an export block.
1627 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1628 the buffer position at the beginning of the first affiliated
1629 keyword and CDR is a plist of affiliated keywords along with
1630 their value.
1632 Return a list whose CAR is `comment-block' and CDR is a plist
1633 containing `:begin', `:end', `:value', `:post-blank' and
1634 `:post-affiliated' keywords.
1636 Assume point is at comment block beginning."
1637 (let ((case-fold-search t))
1638 (if (not (save-excursion
1639 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1640 ;; Incomplete block: parse it as a paragraph.
1641 (org-element-paragraph-parser limit affiliated)
1642 (let ((contents-end (match-beginning 0)))
1643 (save-excursion
1644 (let* ((begin (car affiliated))
1645 (post-affiliated (point))
1646 (contents-begin (progn (forward-line) (point)))
1647 (pos-before-blank (progn (goto-char contents-end)
1648 (forward-line)
1649 (point)))
1650 (end (progn (skip-chars-forward " \r\t\n" limit)
1651 (if (eobp) (point) (line-beginning-position))))
1652 (value (buffer-substring-no-properties
1653 contents-begin contents-end)))
1654 (list 'comment-block
1655 (nconc
1656 (list :begin begin
1657 :end end
1658 :value value
1659 :post-blank (count-lines pos-before-blank end)
1660 :post-affiliated post-affiliated)
1661 (cdr affiliated)))))))))
1663 (defun org-element-comment-block-interpreter (comment-block contents)
1664 "Interpret COMMENT-BLOCK element as Org syntax.
1665 CONTENTS is nil."
1666 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1667 (org-remove-indentation (org-element-property :value comment-block))))
1670 ;;;; Diary Sexp
1672 (defun org-element-diary-sexp-parser (limit affiliated)
1673 "Parse a diary sexp.
1675 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1676 the buffer position at the beginning of the first affiliated
1677 keyword and CDR is a plist of affiliated keywords along with
1678 their value.
1680 Return a list whose CAR is `diary-sexp' and CDR is a plist
1681 containing `:begin', `:end', `:value', `:post-blank' and
1682 `:post-affiliated' keywords."
1683 (save-excursion
1684 (let ((begin (car affiliated))
1685 (post-affiliated (point))
1686 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1687 (org-match-string-no-properties 1)))
1688 (pos-before-blank (progn (forward-line) (point)))
1689 (end (progn (skip-chars-forward " \r\t\n" limit)
1690 (if (eobp) (point) (line-beginning-position)))))
1691 (list 'diary-sexp
1692 (nconc
1693 (list :value value
1694 :begin begin
1695 :end end
1696 :post-blank (count-lines pos-before-blank end)
1697 :post-affiliated post-affiliated)
1698 (cdr affiliated))))))
1700 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1701 "Interpret DIARY-SEXP as Org syntax.
1702 CONTENTS is nil."
1703 (org-element-property :value diary-sexp))
1706 ;;;; Example Block
1708 (defun org-element-example-block-parser (limit affiliated)
1709 "Parse an example block.
1711 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1712 the buffer position at the beginning of the first affiliated
1713 keyword and CDR is a plist of affiliated keywords along with
1714 their value.
1716 Return a list whose CAR is `example-block' and CDR is a plist
1717 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1718 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1719 `:value', `:post-blank' and `:post-affiliated' keywords."
1720 (let ((case-fold-search t))
1721 (if (not (save-excursion
1722 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1723 ;; Incomplete block: parse it as a paragraph.
1724 (org-element-paragraph-parser limit affiliated)
1725 (let ((contents-end (match-beginning 0)))
1726 (save-excursion
1727 (let* ((switches
1728 (progn
1729 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1730 (org-match-string-no-properties 1)))
1731 ;; Switches analysis
1732 (number-lines
1733 (cond ((not switches) nil)
1734 ((string-match "-n\\>" switches) 'new)
1735 ((string-match "+n\\>" switches) 'continued)))
1736 (preserve-indent
1737 (and switches (string-match "-i\\>" switches)))
1738 ;; Should labels be retained in (or stripped from) example
1739 ;; blocks?
1740 (retain-labels
1741 (or (not switches)
1742 (not (string-match "-r\\>" switches))
1743 (and number-lines (string-match "-k\\>" switches))))
1744 ;; What should code-references use - labels or
1745 ;; line-numbers?
1746 (use-labels
1747 (or (not switches)
1748 (and retain-labels
1749 (not (string-match "-k\\>" switches)))))
1750 (label-fmt
1751 (and switches
1752 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1753 (match-string 1 switches)))
1754 ;; Standard block parsing.
1755 (begin (car affiliated))
1756 (post-affiliated (point))
1757 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1758 (contents-begin (progn (forward-line) (point)))
1759 (value (org-element-remove-indentation
1760 (org-unescape-code-in-string
1761 (buffer-substring-no-properties
1762 contents-begin contents-end))
1763 block-ind))
1764 (pos-before-blank (progn (goto-char contents-end)
1765 (forward-line)
1766 (point)))
1767 (end (progn (skip-chars-forward " \r\t\n" limit)
1768 (if (eobp) (point) (line-beginning-position)))))
1769 (list 'example-block
1770 (nconc
1771 (list :begin begin
1772 :end end
1773 :value value
1774 :switches switches
1775 :number-lines number-lines
1776 :preserve-indent preserve-indent
1777 :retain-labels retain-labels
1778 :use-labels use-labels
1779 :label-fmt label-fmt
1780 :post-blank (count-lines pos-before-blank end)
1781 :post-affiliated post-affiliated)
1782 (cdr affiliated)))))))))
1784 (defun org-element-example-block-interpreter (example-block contents)
1785 "Interpret EXAMPLE-BLOCK element as Org syntax.
1786 CONTENTS is nil."
1787 (let ((switches (org-element-property :switches example-block))
1788 (value (org-element-property :value example-block)))
1789 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1790 (org-escape-code-in-string
1791 (if (or org-src-preserve-indentation
1792 (org-element-property :preserve-indent example-block))
1793 value
1794 (org-element-remove-indentation value)))
1795 "#+END_EXAMPLE")))
1798 ;;;; Export Block
1800 (defun org-element-export-block-parser (limit affiliated)
1801 "Parse an export block.
1803 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1804 the buffer position at the beginning of the first affiliated
1805 keyword and CDR is a plist of affiliated keywords along with
1806 their value.
1808 Return a list whose CAR is `export-block' and CDR is a plist
1809 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1810 `:post-affiliated' keywords.
1812 Assume point is at export-block beginning."
1813 (let* ((case-fold-search t)
1814 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1815 (upcase (org-match-string-no-properties 1)))))
1816 (if (not (save-excursion
1817 (re-search-forward
1818 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1819 ;; Incomplete block: parse it as a paragraph.
1820 (org-element-paragraph-parser limit affiliated)
1821 (let ((contents-end (match-beginning 0)))
1822 (save-excursion
1823 (let* ((begin (car affiliated))
1824 (post-affiliated (point))
1825 (contents-begin (progn (forward-line) (point)))
1826 (pos-before-blank (progn (goto-char contents-end)
1827 (forward-line)
1828 (point)))
1829 (end (progn (skip-chars-forward " \r\t\n" limit)
1830 (if (eobp) (point) (line-beginning-position))))
1831 (value (buffer-substring-no-properties contents-begin
1832 contents-end)))
1833 (list 'export-block
1834 (nconc
1835 (list :begin begin
1836 :end end
1837 :type type
1838 :value value
1839 :post-blank (count-lines pos-before-blank end)
1840 :post-affiliated post-affiliated)
1841 (cdr affiliated)))))))))
1843 (defun org-element-export-block-interpreter (export-block contents)
1844 "Interpret EXPORT-BLOCK element as Org syntax.
1845 CONTENTS is nil."
1846 (let ((type (org-element-property :type export-block)))
1847 (concat (format "#+BEGIN_%s\n" type)
1848 (org-element-property :value export-block)
1849 (format "#+END_%s" type))))
1852 ;;;; Fixed-width
1854 (defun org-element-fixed-width-parser (limit affiliated)
1855 "Parse a fixed-width section.
1857 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1858 the buffer position at the beginning of the first affiliated
1859 keyword and CDR is a plist of affiliated keywords along with
1860 their value.
1862 Return a list whose CAR is `fixed-width' and CDR is a plist
1863 containing `:begin', `:end', `:value', `:post-blank' and
1864 `:post-affiliated' keywords.
1866 Assume point is at the beginning of the fixed-width area."
1867 (save-excursion
1868 (let* ((begin (car affiliated))
1869 (post-affiliated (point))
1870 value
1871 (end-area
1872 (progn
1873 (while (and (< (point) limit)
1874 (looking-at "[ \t]*:\\( \\|$\\)"))
1875 ;; Accumulate text without starting colons.
1876 (setq value
1877 (concat value
1878 (buffer-substring-no-properties
1879 (match-end 0) (point-at-eol))
1880 "\n"))
1881 (forward-line))
1882 (point)))
1883 (end (progn (skip-chars-forward " \r\t\n" limit)
1884 (if (eobp) (point) (line-beginning-position)))))
1885 (list 'fixed-width
1886 (nconc
1887 (list :begin begin
1888 :end end
1889 :value value
1890 :post-blank (count-lines end-area end)
1891 :post-affiliated post-affiliated)
1892 (cdr affiliated))))))
1894 (defun org-element-fixed-width-interpreter (fixed-width contents)
1895 "Interpret FIXED-WIDTH element as Org syntax.
1896 CONTENTS is nil."
1897 (let ((value (org-element-property :value fixed-width)))
1898 (and value
1899 (replace-regexp-in-string
1900 "^" ": "
1901 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1904 ;;;; Horizontal Rule
1906 (defun org-element-horizontal-rule-parser (limit affiliated)
1907 "Parse an horizontal rule.
1909 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1910 the buffer position at the beginning of the first affiliated
1911 keyword and CDR is a plist of affiliated keywords along with
1912 their value.
1914 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1915 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1916 keywords."
1917 (save-excursion
1918 (let ((begin (car affiliated))
1919 (post-affiliated (point))
1920 (post-hr (progn (forward-line) (point)))
1921 (end (progn (skip-chars-forward " \r\t\n" limit)
1922 (if (eobp) (point) (line-beginning-position)))))
1923 (list 'horizontal-rule
1924 (nconc
1925 (list :begin begin
1926 :end end
1927 :post-blank (count-lines post-hr end)
1928 :post-affiliated post-affiliated)
1929 (cdr affiliated))))))
1931 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1932 "Interpret HORIZONTAL-RULE element as Org syntax.
1933 CONTENTS is nil."
1934 "-----")
1937 ;;;; Keyword
1939 (defun org-element-keyword-parser (limit affiliated)
1940 "Parse a keyword at point.
1942 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1943 the buffer position at the beginning of the first affiliated
1944 keyword and CDR is a plist of affiliated keywords along with
1945 their value.
1947 Return a list whose CAR is `keyword' and CDR is a plist
1948 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1949 `:post-affiliated' keywords."
1950 (save-excursion
1951 (let ((begin (car affiliated))
1952 (post-affiliated (point))
1953 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1954 (upcase (org-match-string-no-properties 1))))
1955 (value (org-trim (buffer-substring-no-properties
1956 (match-end 0) (point-at-eol))))
1957 (pos-before-blank (progn (forward-line) (point)))
1958 (end (progn (skip-chars-forward " \r\t\n" limit)
1959 (if (eobp) (point) (line-beginning-position)))))
1960 (list 'keyword
1961 (nconc
1962 (list :key key
1963 :value value
1964 :begin begin
1965 :end end
1966 :post-blank (count-lines pos-before-blank end)
1967 :post-affiliated post-affiliated)
1968 (cdr affiliated))))))
1970 (defun org-element-keyword-interpreter (keyword contents)
1971 "Interpret KEYWORD element as Org syntax.
1972 CONTENTS is nil."
1973 (format "#+%s: %s"
1974 (org-element-property :key keyword)
1975 (org-element-property :value keyword)))
1978 ;;;; Latex Environment
1980 (defun org-element-latex-environment-parser (limit affiliated)
1981 "Parse a LaTeX environment.
1983 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1984 the buffer position at the beginning of the first affiliated
1985 keyword and CDR is a plist of affiliated keywords along with
1986 their value.
1988 Return a list whose CAR is `latex-environment' and CDR is a plist
1989 containing `:begin', `:end', `:value', `:post-blank' and
1990 `:post-affiliated' keywords.
1992 Assume point is at the beginning of the latex environment."
1993 (save-excursion
1994 (let ((case-fold-search t)
1995 (code-begin (point)))
1996 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
1997 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
1998 (regexp-quote (match-string 1)))
1999 limit t))
2000 ;; Incomplete latex environment: parse it as a paragraph.
2001 (org-element-paragraph-parser limit affiliated)
2002 (let* ((code-end (progn (forward-line) (point)))
2003 (begin (car affiliated))
2004 (value (buffer-substring-no-properties code-begin code-end))
2005 (end (progn (skip-chars-forward " \r\t\n" limit)
2006 (if (eobp) (point) (line-beginning-position)))))
2007 (list 'latex-environment
2008 (nconc
2009 (list :begin begin
2010 :end end
2011 :value value
2012 :post-blank (count-lines code-end end)
2013 :post-affiliated code-begin)
2014 (cdr affiliated))))))))
2016 (defun org-element-latex-environment-interpreter (latex-environment contents)
2017 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2018 CONTENTS is nil."
2019 (org-element-property :value latex-environment))
2022 ;;;; Node Property
2024 (defun org-element-node-property-parser (limit)
2025 "Parse a node-property at point.
2027 LIMIT bounds the search.
2029 Return a list whose CAR is `node-property' and CDR is a plist
2030 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2031 keywords."
2032 (save-excursion
2033 (looking-at org-property-re)
2034 (let ((case-fold-search t)
2035 (begin (point))
2036 (key (org-match-string-no-properties 2))
2037 (value (org-match-string-no-properties 3))
2038 (pos-before-blank (progn (forward-line) (point)))
2039 (end (progn (skip-chars-forward " \r\t\n" limit)
2040 (if (eobp) (point) (point-at-bol)))))
2041 (list 'node-property
2042 (list :key key
2043 :value value
2044 :begin begin
2045 :end end
2046 :post-blank (count-lines pos-before-blank end))))))
2048 (defun org-element-node-property-interpreter (node-property contents)
2049 "Interpret NODE-PROPERTY element as Org syntax.
2050 CONTENTS is nil."
2051 (format org-property-format
2052 (format ":%s:" (org-element-property :key node-property))
2053 (org-element-property :value node-property)))
2056 ;;;; Paragraph
2058 (defun org-element-paragraph-parser (limit affiliated)
2059 "Parse a paragraph.
2061 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2062 the buffer position at the beginning of the first affiliated
2063 keyword and CDR is a plist of affiliated keywords along with
2064 their value.
2066 Return a list whose CAR is `paragraph' and CDR is a plist
2067 containing `:begin', `:end', `:contents-begin' and
2068 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2070 Assume point is at the beginning of the paragraph."
2071 (save-excursion
2072 (let* ((begin (car affiliated))
2073 (contents-begin (point))
2074 (before-blank
2075 (let ((case-fold-search t))
2076 (end-of-line)
2077 (if (not (re-search-forward
2078 org-element-paragraph-separate limit 'm))
2079 limit
2080 ;; A matching `org-element-paragraph-separate' is not
2081 ;; necessarily the end of the paragraph. In
2082 ;; particular, lines starting with # or : as a first
2083 ;; non-space character are ambiguous. We have check
2084 ;; if they are valid Org syntax (i.e. not an
2085 ;; incomplete keyword).
2086 (beginning-of-line)
2087 (while (not
2089 ;; There's no ambiguity for other symbols or
2090 ;; empty lines: stop here.
2091 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2092 ;; Stop at valid fixed-width areas.
2093 (looking-at "[ \t]*:\\(?: \\|$\\)")
2094 ;; Stop at drawers.
2095 (and (looking-at org-drawer-regexp)
2096 (save-excursion
2097 (re-search-forward
2098 "^[ \t]*:END:[ \t]*$" limit t)))
2099 ;; Stop at valid comments.
2100 (looking-at "[ \t]*#\\(?: \\|$\\)")
2101 ;; Stop at valid dynamic blocks.
2102 (and (looking-at org-dblock-start-re)
2103 (save-excursion
2104 (re-search-forward
2105 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2106 ;; Stop at valid blocks.
2107 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2108 (save-excursion
2109 (re-search-forward
2110 (format "^[ \t]*#\\+END_%s[ \t]*$"
2111 (regexp-quote
2112 (org-match-string-no-properties 1)))
2113 limit t)))
2114 ;; Stop at valid latex environments.
2115 (and (looking-at
2116 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2117 (save-excursion
2118 (re-search-forward
2119 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2120 (regexp-quote
2121 (org-match-string-no-properties 1)))
2122 limit t)))
2123 ;; Stop at valid keywords.
2124 (looking-at "[ \t]*#\\+\\S-+:")
2125 ;; Skip everything else.
2126 (not
2127 (progn
2128 (end-of-line)
2129 (re-search-forward org-element-paragraph-separate
2130 limit 'm)))))
2131 (beginning-of-line)))
2132 (if (= (point) limit) limit
2133 (goto-char (line-beginning-position)))))
2134 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2135 (forward-line)
2136 (point)))
2137 (end (progn (skip-chars-forward " \r\t\n" limit)
2138 (if (eobp) (point) (line-beginning-position)))))
2139 (list 'paragraph
2140 (nconc
2141 (list :begin begin
2142 :end end
2143 :contents-begin contents-begin
2144 :contents-end contents-end
2145 :post-blank (count-lines before-blank end)
2146 :post-affiliated contents-begin)
2147 (cdr affiliated))))))
2149 (defun org-element-paragraph-interpreter (paragraph contents)
2150 "Interpret PARAGRAPH element as Org syntax.
2151 CONTENTS is the contents of the element."
2152 contents)
2155 ;;;; Planning
2157 (defun org-element-planning-parser (limit)
2158 "Parse a planning.
2160 LIMIT bounds the search.
2162 Return a list whose CAR is `planning' and CDR is a plist
2163 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2164 and `:post-blank' keywords."
2165 (save-excursion
2166 (let* ((case-fold-search nil)
2167 (begin (point))
2168 (post-blank (let ((before-blank (progn (forward-line) (point))))
2169 (skip-chars-forward " \r\t\n" limit)
2170 (skip-chars-backward " \t")
2171 (unless (bolp) (end-of-line))
2172 (count-lines before-blank (point))))
2173 (end (point))
2174 closed deadline scheduled)
2175 (goto-char begin)
2176 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2177 (goto-char (match-end 1))
2178 (skip-chars-forward " \t" end)
2179 (let ((keyword (match-string 1))
2180 (time (org-element-timestamp-parser)))
2181 (cond ((equal keyword org-closed-string) (setq closed time))
2182 ((equal keyword org-deadline-string) (setq deadline time))
2183 (t (setq scheduled time)))))
2184 (list 'planning
2185 (list :closed closed
2186 :deadline deadline
2187 :scheduled scheduled
2188 :begin begin
2189 :end end
2190 :post-blank post-blank)))))
2192 (defun org-element-planning-interpreter (planning contents)
2193 "Interpret PLANNING element as Org syntax.
2194 CONTENTS is nil."
2195 (mapconcat
2196 'identity
2197 (delq nil
2198 (list (let ((deadline (org-element-property :deadline planning)))
2199 (when deadline
2200 (concat org-deadline-string " "
2201 (org-element-timestamp-interpreter deadline nil))))
2202 (let ((scheduled (org-element-property :scheduled planning)))
2203 (when scheduled
2204 (concat org-scheduled-string " "
2205 (org-element-timestamp-interpreter scheduled nil))))
2206 (let ((closed (org-element-property :closed planning)))
2207 (when closed
2208 (concat org-closed-string " "
2209 (org-element-timestamp-interpreter closed nil))))))
2210 " "))
2213 ;;;; Quote Section
2215 (defun org-element-quote-section-parser (limit)
2216 "Parse a quote section.
2218 LIMIT bounds the search.
2220 Return a list whose CAR is `quote-section' and CDR is a plist
2221 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2223 Assume point is at beginning of the section."
2224 (save-excursion
2225 (let* ((begin (point))
2226 (end (progn (org-with-limited-levels (outline-next-heading))
2227 (point)))
2228 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2229 (forward-line)
2230 (point)))
2231 (value (buffer-substring-no-properties begin pos-before-blank)))
2232 (list 'quote-section
2233 (list :begin begin
2234 :end end
2235 :value value
2236 :post-blank (count-lines pos-before-blank end))))))
2238 (defun org-element-quote-section-interpreter (quote-section contents)
2239 "Interpret QUOTE-SECTION element as Org syntax.
2240 CONTENTS is nil."
2241 (org-element-property :value quote-section))
2244 ;;;; Src Block
2246 (defun org-element-src-block-parser (limit affiliated)
2247 "Parse a src block.
2249 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2250 the buffer position at the beginning of the first affiliated
2251 keyword and CDR is a plist of affiliated keywords along with
2252 their value.
2254 Return a list whose CAR is `src-block' and CDR is a plist
2255 containing `:language', `:switches', `:parameters', `:begin',
2256 `:end', `:number-lines', `:retain-labels', `:use-labels',
2257 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2258 `:post-affiliated' keywords.
2260 Assume point is at the beginning of the block."
2261 (let ((case-fold-search t))
2262 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2263 limit t)))
2264 ;; Incomplete block: parse it as a paragraph.
2265 (org-element-paragraph-parser limit affiliated)
2266 (let ((contents-end (match-beginning 0)))
2267 (save-excursion
2268 (let* ((begin (car affiliated))
2269 (post-affiliated (point))
2270 ;; Get language as a string.
2271 (language
2272 (progn
2273 (looking-at
2274 (concat "^[ \t]*#\\+BEGIN_SRC"
2275 "\\(?: +\\(\\S-+\\)\\)?"
2276 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2277 "\\(.*\\)[ \t]*$"))
2278 (org-match-string-no-properties 1)))
2279 ;; Get switches.
2280 (switches (org-match-string-no-properties 2))
2281 ;; Get parameters.
2282 (parameters (org-match-string-no-properties 3))
2283 ;; Switches analysis
2284 (number-lines
2285 (cond ((not switches) nil)
2286 ((string-match "-n\\>" switches) 'new)
2287 ((string-match "+n\\>" switches) 'continued)))
2288 (preserve-indent (and switches
2289 (string-match "-i\\>" switches)))
2290 (label-fmt
2291 (and switches
2292 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2293 (match-string 1 switches)))
2294 ;; Should labels be retained in (or stripped from)
2295 ;; src blocks?
2296 (retain-labels
2297 (or (not switches)
2298 (not (string-match "-r\\>" switches))
2299 (and number-lines (string-match "-k\\>" switches))))
2300 ;; What should code-references use - labels or
2301 ;; line-numbers?
2302 (use-labels
2303 (or (not switches)
2304 (and retain-labels
2305 (not (string-match "-k\\>" switches)))))
2306 ;; Indentation.
2307 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2308 ;; Retrieve code.
2309 (value (org-element-remove-indentation
2310 (org-unescape-code-in-string
2311 (buffer-substring-no-properties
2312 (progn (forward-line) (point)) contents-end))
2313 block-ind))
2314 (pos-before-blank (progn (goto-char contents-end)
2315 (forward-line)
2316 (point)))
2317 ;; Get position after ending blank lines.
2318 (end (progn (skip-chars-forward " \r\t\n" limit)
2319 (if (eobp) (point) (line-beginning-position)))))
2320 (list 'src-block
2321 (nconc
2322 (list :language language
2323 :switches (and (org-string-nw-p switches)
2324 (org-trim switches))
2325 :parameters (and (org-string-nw-p parameters)
2326 (org-trim parameters))
2327 :begin begin
2328 :end end
2329 :number-lines number-lines
2330 :preserve-indent preserve-indent
2331 :retain-labels retain-labels
2332 :use-labels use-labels
2333 :label-fmt label-fmt
2334 :value value
2335 :post-blank (count-lines pos-before-blank end)
2336 :post-affiliated post-affiliated)
2337 (cdr affiliated)))))))))
2339 (defun org-element-src-block-interpreter (src-block contents)
2340 "Interpret SRC-BLOCK element as Org syntax.
2341 CONTENTS is nil."
2342 (let ((lang (org-element-property :language src-block))
2343 (switches (org-element-property :switches src-block))
2344 (params (org-element-property :parameters src-block))
2345 (value
2346 (let ((val (org-element-property :value src-block)))
2347 (cond
2348 ((or org-src-preserve-indentation
2349 (org-element-property :preserve-indent src-block))
2350 val)
2351 ((zerop org-edit-src-content-indentation) val)
2353 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2354 (replace-regexp-in-string
2355 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2356 (concat (format "#+BEGIN_SRC%s\n"
2357 (concat (and lang (concat " " lang))
2358 (and switches (concat " " switches))
2359 (and params (concat " " params))))
2360 (org-escape-code-in-string value)
2361 "#+END_SRC")))
2364 ;;;; Table
2366 (defun org-element-table-parser (limit affiliated)
2367 "Parse a table at point.
2369 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2370 the buffer position at the beginning of the first affiliated
2371 keyword and CDR is a plist of affiliated keywords along with
2372 their value.
2374 Return a list whose CAR is `table' and CDR is a plist containing
2375 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2376 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2377 keywords.
2379 Assume point is at the beginning of the table."
2380 (save-excursion
2381 (let* ((case-fold-search t)
2382 (table-begin (point))
2383 (type (if (org-at-table.el-p) 'table.el 'org))
2384 (begin (car affiliated))
2385 (table-end
2386 (if (re-search-forward org-table-any-border-regexp limit 'm)
2387 (goto-char (match-beginning 0))
2388 (point)))
2389 (tblfm (let (acc)
2390 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2391 (push (org-match-string-no-properties 1) acc)
2392 (forward-line))
2393 acc))
2394 (pos-before-blank (point))
2395 (end (progn (skip-chars-forward " \r\t\n" limit)
2396 (if (eobp) (point) (line-beginning-position)))))
2397 (list 'table
2398 (nconc
2399 (list :begin begin
2400 :end end
2401 :type type
2402 :tblfm tblfm
2403 ;; Only `org' tables have contents. `table.el' tables
2404 ;; use a `:value' property to store raw table as
2405 ;; a string.
2406 :contents-begin (and (eq type 'org) table-begin)
2407 :contents-end (and (eq type 'org) table-end)
2408 :value (and (eq type 'table.el)
2409 (buffer-substring-no-properties
2410 table-begin table-end))
2411 :post-blank (count-lines pos-before-blank end)
2412 :post-affiliated table-begin)
2413 (cdr affiliated))))))
2415 (defun org-element-table-interpreter (table contents)
2416 "Interpret TABLE element as Org syntax.
2417 CONTENTS is nil."
2418 (if (eq (org-element-property :type table) 'table.el)
2419 (org-remove-indentation (org-element-property :value table))
2420 (concat (with-temp-buffer (insert contents)
2421 (org-table-align)
2422 (buffer-string))
2423 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2424 (reverse (org-element-property :tblfm table))
2425 "\n"))))
2428 ;;;; Table Row
2430 (defun org-element-table-row-parser (limit)
2431 "Parse table row at point.
2433 LIMIT bounds the search.
2435 Return a list whose CAR is `table-row' and CDR is a plist
2436 containing `:begin', `:end', `:contents-begin', `:contents-end',
2437 `:type' and `:post-blank' keywords."
2438 (save-excursion
2439 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2440 (begin (point))
2441 ;; A table rule has no contents. In that case, ensure
2442 ;; CONTENTS-BEGIN matches CONTENTS-END.
2443 (contents-begin (and (eq type 'standard)
2444 (search-forward "|")
2445 (point)))
2446 (contents-end (and (eq type 'standard)
2447 (progn
2448 (end-of-line)
2449 (skip-chars-backward " \t")
2450 (point))))
2451 (end (progn (forward-line) (point))))
2452 (list 'table-row
2453 (list :type type
2454 :begin begin
2455 :end end
2456 :contents-begin contents-begin
2457 :contents-end contents-end
2458 :post-blank 0)))))
2460 (defun org-element-table-row-interpreter (table-row contents)
2461 "Interpret TABLE-ROW element as Org syntax.
2462 CONTENTS is the contents of the table row."
2463 (if (eq (org-element-property :type table-row) 'rule) "|-"
2464 (concat "| " contents)))
2467 ;;;; Verse Block
2469 (defun org-element-verse-block-parser (limit affiliated)
2470 "Parse a verse block.
2472 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2473 the buffer position at the beginning of the first affiliated
2474 keyword and CDR is a plist of affiliated keywords along with
2475 their value.
2477 Return a list whose CAR is `verse-block' and CDR is a plist
2478 containing `:begin', `:end', `:contents-begin', `:contents-end',
2479 `:post-blank' and `:post-affiliated' keywords.
2481 Assume point is at beginning of the block."
2482 (let ((case-fold-search t))
2483 (if (not (save-excursion
2484 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2485 ;; Incomplete block: parse it as a paragraph.
2486 (org-element-paragraph-parser limit affiliated)
2487 (let ((contents-end (match-beginning 0)))
2488 (save-excursion
2489 (let* ((begin (car affiliated))
2490 (post-affiliated (point))
2491 (contents-begin (progn (forward-line) (point)))
2492 (pos-before-blank (progn (goto-char contents-end)
2493 (forward-line)
2494 (point)))
2495 (end (progn (skip-chars-forward " \r\t\n" limit)
2496 (if (eobp) (point) (line-beginning-position)))))
2497 (list 'verse-block
2498 (nconc
2499 (list :begin begin
2500 :end end
2501 :contents-begin contents-begin
2502 :contents-end contents-end
2503 :post-blank (count-lines pos-before-blank end)
2504 :post-affiliated post-affiliated)
2505 (cdr affiliated)))))))))
2507 (defun org-element-verse-block-interpreter (verse-block contents)
2508 "Interpret VERSE-BLOCK element as Org syntax.
2509 CONTENTS is verse block contents."
2510 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2514 ;;; Objects
2516 ;; Unlike to elements, interstices can be found between objects.
2517 ;; That's why, along with the parser, successor functions are provided
2518 ;; for each object. Some objects share the same successor (i.e. `code'
2519 ;; and `verbatim' objects).
2521 ;; A successor must accept a single argument bounding the search. It
2522 ;; will return either a cons cell whose CAR is the object's type, as
2523 ;; a symbol, and CDR the position of its next occurrence, or nil.
2525 ;; Successors follow the naming convention:
2526 ;; org-element-NAME-successor, where NAME is the name of the
2527 ;; successor, as defined in `org-element-all-successors'.
2529 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2530 ;; object types they can contain will be specified in
2531 ;; `org-element-object-restrictions'.
2533 ;; Adding a new type of object is simple. Implement a successor,
2534 ;; a parser, and an interpreter for it, all following the naming
2535 ;; convention. Register type in `org-element-all-objects' and
2536 ;; successor in `org-element-all-successors'. Maybe tweak
2537 ;; restrictions about it, and that's it.
2540 ;;;; Bold
2542 (defun org-element-bold-parser ()
2543 "Parse bold object at point.
2545 Return a list whose CAR is `bold' and CDR is a plist with
2546 `:begin', `:end', `:contents-begin' and `:contents-end' and
2547 `:post-blank' keywords.
2549 Assume point is at the first star marker."
2550 (save-excursion
2551 (unless (bolp) (backward-char 1))
2552 (looking-at org-emph-re)
2553 (let ((begin (match-beginning 2))
2554 (contents-begin (match-beginning 4))
2555 (contents-end (match-end 4))
2556 (post-blank (progn (goto-char (match-end 2))
2557 (skip-chars-forward " \t")))
2558 (end (point)))
2559 (list 'bold
2560 (list :begin begin
2561 :end end
2562 :contents-begin contents-begin
2563 :contents-end contents-end
2564 :post-blank post-blank)))))
2566 (defun org-element-bold-interpreter (bold contents)
2567 "Interpret BOLD object as Org syntax.
2568 CONTENTS is the contents of the object."
2569 (format "*%s*" contents))
2571 (defun org-element-text-markup-successor ()
2572 "Search for the next text-markup object.
2574 Return value is a cons cell whose CAR is a symbol among `bold',
2575 `italic', `underline', `strike-through', `code' and `verbatim'
2576 and CDR is beginning position."
2577 (save-excursion
2578 (unless (bolp) (backward-char))
2579 (when (re-search-forward org-emph-re nil t)
2580 (let ((marker (match-string 3)))
2581 (cons (cond
2582 ((equal marker "*") 'bold)
2583 ((equal marker "/") 'italic)
2584 ((equal marker "_") 'underline)
2585 ((equal marker "+") 'strike-through)
2586 ((equal marker "~") 'code)
2587 ((equal marker "=") 'verbatim)
2588 (t (error "Unknown marker at %d" (match-beginning 3))))
2589 (match-beginning 2))))))
2592 ;;;; Code
2594 (defun org-element-code-parser ()
2595 "Parse code object at point.
2597 Return a list whose CAR is `code' and CDR is a plist with
2598 `:value', `:begin', `:end' and `:post-blank' keywords.
2600 Assume point is at the first tilde marker."
2601 (save-excursion
2602 (unless (bolp) (backward-char 1))
2603 (looking-at org-emph-re)
2604 (let ((begin (match-beginning 2))
2605 (value (org-match-string-no-properties 4))
2606 (post-blank (progn (goto-char (match-end 2))
2607 (skip-chars-forward " \t")))
2608 (end (point)))
2609 (list 'code
2610 (list :value value
2611 :begin begin
2612 :end end
2613 :post-blank post-blank)))))
2615 (defun org-element-code-interpreter (code contents)
2616 "Interpret CODE object as Org syntax.
2617 CONTENTS is nil."
2618 (format "~%s~" (org-element-property :value code)))
2621 ;;;; Entity
2623 (defun org-element-entity-parser ()
2624 "Parse entity at point.
2626 Return a list whose CAR is `entity' and CDR a plist with
2627 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2628 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2629 keywords.
2631 Assume point is at the beginning of the entity."
2632 (save-excursion
2633 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2634 (let* ((value (org-entity-get (match-string 1)))
2635 (begin (match-beginning 0))
2636 (bracketsp (string= (match-string 2) "{}"))
2637 (post-blank (progn (goto-char (match-end 1))
2638 (when bracketsp (forward-char 2))
2639 (skip-chars-forward " \t")))
2640 (end (point)))
2641 (list 'entity
2642 (list :name (car value)
2643 :latex (nth 1 value)
2644 :latex-math-p (nth 2 value)
2645 :html (nth 3 value)
2646 :ascii (nth 4 value)
2647 :latin1 (nth 5 value)
2648 :utf-8 (nth 6 value)
2649 :begin begin
2650 :end end
2651 :use-brackets-p bracketsp
2652 :post-blank post-blank)))))
2654 (defun org-element-entity-interpreter (entity contents)
2655 "Interpret ENTITY object as Org syntax.
2656 CONTENTS is nil."
2657 (concat "\\"
2658 (org-element-property :name entity)
2659 (when (org-element-property :use-brackets-p entity) "{}")))
2661 (defun org-element-latex-or-entity-successor ()
2662 "Search for the next latex-fragment or entity object.
2664 Return value is a cons cell whose CAR is `entity' or
2665 `latex-fragment' and CDR is beginning position."
2666 (save-excursion
2667 (unless (bolp) (backward-char))
2668 (let ((matchers (cdr org-latex-regexps))
2669 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2670 (entity-re
2671 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2672 (when (re-search-forward
2673 (concat (mapconcat #'cadr matchers "\\|") "\\|" entity-re) nil t)
2674 (goto-char (match-beginning 0))
2675 (if (looking-at entity-re)
2676 ;; Determine if it's a real entity or a LaTeX command.
2677 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2678 (match-beginning 0))
2679 ;; No entity nor command: point is at a LaTeX fragment.
2680 ;; Determine its type to get the correct beginning position.
2681 (cons 'latex-fragment
2682 (catch 'return
2683 (dolist (e matchers)
2684 (when (looking-at (nth 1 e))
2685 (throw 'return (match-beginning (nth 2 e)))))
2686 (point))))))))
2689 ;;;; Export Snippet
2691 (defun org-element-export-snippet-parser ()
2692 "Parse export snippet at point.
2694 Return a list whose CAR is `export-snippet' and CDR a plist with
2695 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2696 keywords.
2698 Assume point is at the beginning of the snippet."
2699 (save-excursion
2700 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2701 (let* ((begin (match-beginning 0))
2702 (back-end (org-match-string-no-properties 1))
2703 (value (buffer-substring-no-properties
2704 (point)
2705 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2706 (post-blank (skip-chars-forward " \t"))
2707 (end (point)))
2708 (list 'export-snippet
2709 (list :back-end back-end
2710 :value value
2711 :begin begin
2712 :end end
2713 :post-blank post-blank)))))
2715 (defun org-element-export-snippet-interpreter (export-snippet contents)
2716 "Interpret EXPORT-SNIPPET object as Org syntax.
2717 CONTENTS is nil."
2718 (format "@@%s:%s@@"
2719 (org-element-property :back-end export-snippet)
2720 (org-element-property :value export-snippet)))
2722 (defun org-element-export-snippet-successor ()
2723 "Search for the next export-snippet object.
2725 Return value is a cons cell whose CAR is `export-snippet' and CDR
2726 its beginning position."
2727 (save-excursion
2728 (let (beg)
2729 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2730 (setq beg (match-beginning 0))
2731 (search-forward "@@" nil t))
2732 (cons 'export-snippet beg)))))
2735 ;;;; Footnote Reference
2737 (defun org-element-footnote-reference-parser ()
2738 "Parse footnote reference at point.
2740 Return a list whose CAR is `footnote-reference' and CDR a plist
2741 with `:label', `:type', `:inline-definition', `:begin', `:end'
2742 and `:post-blank' as keywords."
2743 (save-excursion
2744 (looking-at org-footnote-re)
2745 (let* ((begin (point))
2746 (label (or (org-match-string-no-properties 2)
2747 (org-match-string-no-properties 3)
2748 (and (match-string 1)
2749 (concat "fn:" (org-match-string-no-properties 1)))))
2750 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2751 (inner-begin (match-end 0))
2752 (inner-end
2753 (let ((count 1))
2754 (forward-char)
2755 (while (and (> count 0) (re-search-forward "[][]" nil t))
2756 (if (equal (match-string 0) "[") (incf count) (decf count)))
2757 (1- (point))))
2758 (post-blank (progn (goto-char (1+ inner-end))
2759 (skip-chars-forward " \t")))
2760 (end (point))
2761 (footnote-reference
2762 (list 'footnote-reference
2763 (list :label label
2764 :type type
2765 :begin begin
2766 :end end
2767 :post-blank post-blank))))
2768 (org-element-put-property
2769 footnote-reference :inline-definition
2770 (and (eq type 'inline)
2771 (org-element-parse-secondary-string
2772 (buffer-substring inner-begin inner-end)
2773 (org-element-restriction 'footnote-reference)
2774 footnote-reference))))))
2776 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2777 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2778 CONTENTS is nil."
2779 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2780 (def
2781 (let ((inline-def
2782 (org-element-property :inline-definition footnote-reference)))
2783 (if (not inline-def) ""
2784 (concat ":" (org-element-interpret-data inline-def))))))
2785 (format "[%s]" (concat label def))))
2787 (defun org-element-footnote-reference-successor ()
2788 "Search for the next footnote-reference object.
2790 Return value is a cons cell whose CAR is `footnote-reference' and
2791 CDR is beginning position."
2792 (save-excursion
2793 (catch 'exit
2794 (while (re-search-forward org-footnote-re nil t)
2795 (save-excursion
2796 (let ((beg (match-beginning 0))
2797 (count 1))
2798 (backward-char)
2799 (while (re-search-forward "[][]" nil t)
2800 (if (equal (match-string 0) "[") (incf count) (decf count))
2801 (when (zerop count)
2802 (throw 'exit (cons 'footnote-reference beg))))))))))
2805 ;;;; Inline Babel Call
2807 (defun org-element-inline-babel-call-parser ()
2808 "Parse inline babel call at point.
2810 Return a list whose CAR is `inline-babel-call' and CDR a plist
2811 with `:begin', `:end', `:value' and `:post-blank' as keywords.
2813 Assume point is at the beginning of the babel call."
2814 (save-excursion
2815 (unless (bolp) (backward-char))
2816 (let ((case-fold-search t))
2817 (looking-at org-babel-inline-lob-one-liner-regexp))
2818 (let ((begin (match-end 1))
2819 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2820 (post-blank (progn (goto-char (match-end 0))
2821 (skip-chars-forward " \t")))
2822 (end (point)))
2823 (list 'inline-babel-call
2824 (list :begin begin
2825 :end end
2826 :value value
2827 :post-blank post-blank)))))
2829 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2830 "Interpret INLINE-BABEL-CALL object as Org syntax.
2831 CONTENTS is nil."
2832 (org-element-property :value inline-babel-call))
2834 (defun org-element-inline-babel-call-successor ()
2835 "Search for the next inline-babel-call object.
2837 Return value is a cons cell whose CAR is `inline-babel-call' and
2838 CDR is beginning position."
2839 (save-excursion
2840 ;; Use a simplified version of
2841 ;; `org-babel-inline-lob-one-liner-regexp'.
2842 (when (re-search-forward
2843 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2844 nil t)
2845 (cons 'inline-babel-call (match-beginning 0)))))
2848 ;;;; Inline Src Block
2850 (defun org-element-inline-src-block-parser ()
2851 "Parse inline source block at point.
2853 Return a list whose CAR is `inline-src-block' and CDR a plist
2854 with `:begin', `:end', `:language', `:value', `:parameters' and
2855 `:post-blank' as keywords.
2857 Assume point is at the beginning of the inline src block."
2858 (save-excursion
2859 (unless (bolp) (backward-char))
2860 (looking-at org-babel-inline-src-block-regexp)
2861 (let ((begin (match-beginning 1))
2862 (language (org-match-string-no-properties 2))
2863 (parameters (org-match-string-no-properties 4))
2864 (value (org-match-string-no-properties 5))
2865 (post-blank (progn (goto-char (match-end 0))
2866 (skip-chars-forward " \t")))
2867 (end (point)))
2868 (list 'inline-src-block
2869 (list :language language
2870 :value value
2871 :parameters parameters
2872 :begin begin
2873 :end end
2874 :post-blank post-blank)))))
2876 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2877 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2878 CONTENTS is nil."
2879 (let ((language (org-element-property :language inline-src-block))
2880 (arguments (org-element-property :parameters inline-src-block))
2881 (body (org-element-property :value inline-src-block)))
2882 (format "src_%s%s{%s}"
2883 language
2884 (if arguments (format "[%s]" arguments) "")
2885 body)))
2887 (defun org-element-inline-src-block-successor ()
2888 "Search for the next inline-babel-call element.
2890 Return value is a cons cell whose CAR is `inline-babel-call' and
2891 CDR is beginning position."
2892 (save-excursion
2893 (unless (bolp) (backward-char))
2894 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2895 (cons 'inline-src-block (match-beginning 1)))))
2897 ;;;; Italic
2899 (defun org-element-italic-parser ()
2900 "Parse italic object at point.
2902 Return a list whose CAR is `italic' and CDR is a plist with
2903 `:begin', `:end', `:contents-begin' and `:contents-end' and
2904 `:post-blank' keywords.
2906 Assume point is at the first slash marker."
2907 (save-excursion
2908 (unless (bolp) (backward-char 1))
2909 (looking-at org-emph-re)
2910 (let ((begin (match-beginning 2))
2911 (contents-begin (match-beginning 4))
2912 (contents-end (match-end 4))
2913 (post-blank (progn (goto-char (match-end 2))
2914 (skip-chars-forward " \t")))
2915 (end (point)))
2916 (list 'italic
2917 (list :begin begin
2918 :end end
2919 :contents-begin contents-begin
2920 :contents-end contents-end
2921 :post-blank post-blank)))))
2923 (defun org-element-italic-interpreter (italic contents)
2924 "Interpret ITALIC object as Org syntax.
2925 CONTENTS is the contents of the object."
2926 (format "/%s/" contents))
2929 ;;;; Latex Fragment
2931 (defun org-element-latex-fragment-parser ()
2932 "Parse LaTeX fragment at point.
2934 Return a list whose CAR is `latex-fragment' and CDR a plist with
2935 `:value', `:begin', `:end', and `:post-blank' as keywords.
2937 Assume point is at the beginning of the LaTeX fragment."
2938 (save-excursion
2939 (let* ((begin (point))
2940 (substring-match
2941 (catch 'exit
2942 (dolist (e (cdr org-latex-regexps))
2943 (let ((latex-regexp (nth 1 e)))
2944 (when (or (looking-at latex-regexp)
2945 (and (not (bobp))
2946 (save-excursion
2947 (backward-char)
2948 (looking-at latex-regexp))))
2949 (throw 'exit (nth 2 e)))))
2950 ;; None found: it's a macro.
2951 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2953 (value (org-match-string-no-properties substring-match))
2954 (post-blank (progn (goto-char (match-end substring-match))
2955 (skip-chars-forward " \t")))
2956 (end (point)))
2957 (list 'latex-fragment
2958 (list :value value
2959 :begin begin
2960 :end end
2961 :post-blank post-blank)))))
2963 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2964 "Interpret LATEX-FRAGMENT object as Org syntax.
2965 CONTENTS is nil."
2966 (org-element-property :value latex-fragment))
2968 ;;;; Line Break
2970 (defun org-element-line-break-parser ()
2971 "Parse line break at point.
2973 Return a list whose CAR is `line-break', and CDR a plist with
2974 `:begin', `:end' and `:post-blank' keywords.
2976 Assume point is at the beginning of the line break."
2977 (list 'line-break
2978 (list :begin (point)
2979 :end (progn (forward-line) (point))
2980 :post-blank 0)))
2982 (defun org-element-line-break-interpreter (line-break contents)
2983 "Interpret LINE-BREAK object as Org syntax.
2984 CONTENTS is nil."
2985 "\\\\\n")
2987 (defun org-element-line-break-successor ()
2988 "Search for the next line-break object.
2990 Return value is a cons cell whose CAR is `line-break' and CDR is
2991 beginning position."
2992 (save-excursion
2993 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
2994 (goto-char (match-beginning 1)))))
2995 ;; A line break can only happen on a non-empty line.
2996 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2997 (cons 'line-break beg)))))
3000 ;;;; Link
3002 (defun org-element-link-parser ()
3003 "Parse link at point.
3005 Return a list whose CAR is `link' and CDR a plist with `:type',
3006 `:path', `:raw-link', `:application', `:search-option', `:begin',
3007 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3008 keywords.
3010 Assume point is at the beginning of the link."
3011 (save-excursion
3012 (let ((begin (point))
3013 end contents-begin contents-end link-end post-blank path type
3014 raw-link link search-option application)
3015 (cond
3016 ;; Type 1: Text targeted from a radio target.
3017 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3018 (setq type "radio"
3019 link-end (match-end 0)
3020 path (org-match-string-no-properties 0)))
3021 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3022 ((looking-at org-bracket-link-regexp)
3023 (setq contents-begin (match-beginning 3)
3024 contents-end (match-end 3)
3025 link-end (match-end 0)
3026 ;; RAW-LINK is the original link. Expand any
3027 ;; abbreviation in it.
3028 raw-link (org-translate-link
3029 (org-link-expand-abbrev
3030 (org-match-string-no-properties 1))))
3031 ;; Determine TYPE of link and set PATH accordingly.
3032 (cond
3033 ;; File type.
3034 ((or (file-name-absolute-p raw-link)
3035 (string-match "^\\.\\.?/" raw-link))
3036 (setq type "file" path raw-link))
3037 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3038 ((string-match org-link-re-with-space3 raw-link)
3039 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3040 ;; Id type: PATH is the id.
3041 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3042 (setq type "id" path (match-string 1 raw-link)))
3043 ;; Code-ref type: PATH is the name of the reference.
3044 ((string-match "^(\\(.*\\))$" raw-link)
3045 (setq type "coderef" path (match-string 1 raw-link)))
3046 ;; Custom-id type: PATH is the name of the custom id.
3047 ((= (aref raw-link 0) ?#)
3048 (setq type "custom-id" path (substring raw-link 1)))
3049 ;; Fuzzy type: Internal link either matches a target, an
3050 ;; headline name or nothing. PATH is the target or
3051 ;; headline's name.
3052 (t (setq type "fuzzy" path raw-link))))
3053 ;; Type 3: Plain link, i.e. http://orgmode.org
3054 ((looking-at org-plain-link-re)
3055 (setq raw-link (org-match-string-no-properties 0)
3056 type (org-match-string-no-properties 1)
3057 link-end (match-end 0)
3058 path (org-match-string-no-properties 2)))
3059 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3060 ((looking-at org-angle-link-re)
3061 (setq raw-link (buffer-substring-no-properties
3062 (match-beginning 1) (match-end 2))
3063 type (org-match-string-no-properties 1)
3064 link-end (match-end 0)
3065 path (org-match-string-no-properties 2))))
3066 ;; In any case, deduce end point after trailing white space from
3067 ;; LINK-END variable.
3068 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3069 end (point))
3070 ;; Extract search option and opening application out of
3071 ;; "file"-type links.
3072 (when (member type org-element-link-type-is-file)
3073 ;; Application.
3074 (cond ((string-match "^file\\+\\(.*\\)$" type)
3075 (setq application (match-string 1 type)))
3076 ((not (string-match "^file" type))
3077 (setq application type)))
3078 ;; Extract search option from PATH.
3079 (when (string-match "::\\(.*\\)$" path)
3080 (setq search-option (match-string 1 path)
3081 path (replace-match "" nil nil path)))
3082 ;; Make sure TYPE always reports "file".
3083 (setq type "file"))
3084 (list 'link
3085 (list :type type
3086 :path path
3087 :raw-link (or raw-link path)
3088 :application application
3089 :search-option search-option
3090 :begin begin
3091 :end end
3092 :contents-begin contents-begin
3093 :contents-end contents-end
3094 :post-blank post-blank)))))
3096 (defun org-element-link-interpreter (link contents)
3097 "Interpret LINK object as Org syntax.
3098 CONTENTS is the contents of the object, or nil."
3099 (let ((type (org-element-property :type link))
3100 (raw-link (org-element-property :raw-link link)))
3101 (if (string= type "radio") raw-link
3102 (format "[[%s]%s]"
3103 raw-link
3104 (if contents (format "[%s]" contents) "")))))
3106 (defun org-element-link-successor ()
3107 "Search for the next link object.
3109 Return value is a cons cell whose CAR is `link' and CDR is
3110 beginning position."
3111 (save-excursion
3112 (let ((link-regexp
3113 (if (not org-target-link-regexp) org-any-link-re
3114 (concat org-any-link-re "\\|" org-target-link-regexp))))
3115 (when (re-search-forward link-regexp nil t)
3116 (cons 'link (match-beginning 0))))))
3118 (defun org-element-plain-link-successor ()
3119 "Search for the next plain link object.
3121 Return value is a cons cell whose CAR is `link' and CDR is
3122 beginning position."
3123 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3124 (cons 'link (match-beginning 0))))
3127 ;;;; Macro
3129 (defun org-element-macro-parser ()
3130 "Parse macro at point.
3132 Return a list whose CAR is `macro' and CDR a plist with `:key',
3133 `:args', `:begin', `:end', `:value' and `:post-blank' as
3134 keywords.
3136 Assume point is at the macro."
3137 (save-excursion
3138 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3139 (let ((begin (point))
3140 (key (downcase (org-match-string-no-properties 1)))
3141 (value (org-match-string-no-properties 0))
3142 (post-blank (progn (goto-char (match-end 0))
3143 (skip-chars-forward " \t")))
3144 (end (point))
3145 (args (let ((args (org-match-string-no-properties 3)))
3146 (when args
3147 ;; Do not use `org-split-string' since empty
3148 ;; strings are meaningful here.
3149 (split-string
3150 (replace-regexp-in-string
3151 "\\(\\\\*\\)\\(,\\)"
3152 (lambda (str)
3153 (let ((len (length (match-string 1 str))))
3154 (concat (make-string (/ len 2) ?\\)
3155 (if (zerop (mod len 2)) "\000" ","))))
3156 args nil t)
3157 "\000")))))
3158 (list 'macro
3159 (list :key key
3160 :value value
3161 :args args
3162 :begin begin
3163 :end end
3164 :post-blank post-blank)))))
3166 (defun org-element-macro-interpreter (macro contents)
3167 "Interpret MACRO object as Org syntax.
3168 CONTENTS is nil."
3169 (org-element-property :value macro))
3171 (defun org-element-macro-successor ()
3172 "Search for the next macro object.
3174 Return value is cons cell whose CAR is `macro' and CDR is
3175 beginning position."
3176 (save-excursion
3177 (when (re-search-forward
3178 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3179 nil t)
3180 (cons 'macro (match-beginning 0)))))
3183 ;;;; Radio-target
3185 (defun org-element-radio-target-parser ()
3186 "Parse radio target at point.
3188 Return a list whose CAR is `radio-target' and CDR a plist with
3189 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3190 and `:post-blank' as keywords.
3192 Assume point is at the radio target."
3193 (save-excursion
3194 (looking-at org-radio-target-regexp)
3195 (let ((begin (point))
3196 (contents-begin (match-beginning 1))
3197 (contents-end (match-end 1))
3198 (value (org-match-string-no-properties 1))
3199 (post-blank (progn (goto-char (match-end 0))
3200 (skip-chars-forward " \t")))
3201 (end (point)))
3202 (list 'radio-target
3203 (list :begin begin
3204 :end end
3205 :contents-begin contents-begin
3206 :contents-end contents-end
3207 :post-blank post-blank
3208 :value value)))))
3210 (defun org-element-radio-target-interpreter (target contents)
3211 "Interpret TARGET object as Org syntax.
3212 CONTENTS is the contents of the object."
3213 (concat "<<<" contents ">>>"))
3215 (defun org-element-radio-target-successor ()
3216 "Search for the next radio-target object.
3218 Return value is a cons cell whose CAR is `radio-target' and CDR
3219 is beginning position."
3220 (save-excursion
3221 (when (re-search-forward org-radio-target-regexp nil t)
3222 (cons 'radio-target (match-beginning 0)))))
3225 ;;;; Statistics Cookie
3227 (defun org-element-statistics-cookie-parser ()
3228 "Parse statistics cookie at point.
3230 Return a list whose CAR is `statistics-cookie', and CDR a plist
3231 with `:begin', `:end', `:value' and `:post-blank' keywords.
3233 Assume point is at the beginning of the statistics-cookie."
3234 (save-excursion
3235 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3236 (let* ((begin (point))
3237 (value (buffer-substring-no-properties
3238 (match-beginning 0) (match-end 0)))
3239 (post-blank (progn (goto-char (match-end 0))
3240 (skip-chars-forward " \t")))
3241 (end (point)))
3242 (list 'statistics-cookie
3243 (list :begin begin
3244 :end end
3245 :value value
3246 :post-blank post-blank)))))
3248 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3249 "Interpret STATISTICS-COOKIE object as Org syntax.
3250 CONTENTS is nil."
3251 (org-element-property :value statistics-cookie))
3253 (defun org-element-statistics-cookie-successor ()
3254 "Search for the next statistics cookie object.
3256 Return value is a cons cell whose CAR is `statistics-cookie' and
3257 CDR is beginning position."
3258 (save-excursion
3259 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3260 (cons 'statistics-cookie (match-beginning 0)))))
3263 ;;;; Strike-Through
3265 (defun org-element-strike-through-parser ()
3266 "Parse strike-through object at point.
3268 Return a list whose CAR is `strike-through' and CDR is a plist
3269 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3270 `:post-blank' keywords.
3272 Assume point is at the first plus sign marker."
3273 (save-excursion
3274 (unless (bolp) (backward-char 1))
3275 (looking-at org-emph-re)
3276 (let ((begin (match-beginning 2))
3277 (contents-begin (match-beginning 4))
3278 (contents-end (match-end 4))
3279 (post-blank (progn (goto-char (match-end 2))
3280 (skip-chars-forward " \t")))
3281 (end (point)))
3282 (list 'strike-through
3283 (list :begin begin
3284 :end end
3285 :contents-begin contents-begin
3286 :contents-end contents-end
3287 :post-blank post-blank)))))
3289 (defun org-element-strike-through-interpreter (strike-through contents)
3290 "Interpret STRIKE-THROUGH object as Org syntax.
3291 CONTENTS is the contents of the object."
3292 (format "+%s+" contents))
3295 ;;;; Subscript
3297 (defun org-element-subscript-parser ()
3298 "Parse subscript at point.
3300 Return a list whose CAR is `subscript' and CDR a plist with
3301 `:begin', `:end', `:contents-begin', `:contents-end',
3302 `:use-brackets-p' and `:post-blank' as keywords.
3304 Assume point is at the underscore."
3305 (save-excursion
3306 (unless (bolp) (backward-char))
3307 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3309 (not (looking-at org-match-substring-regexp))))
3310 (begin (match-beginning 2))
3311 (contents-begin (or (match-beginning 5)
3312 (match-beginning 3)))
3313 (contents-end (or (match-end 5) (match-end 3)))
3314 (post-blank (progn (goto-char (match-end 0))
3315 (skip-chars-forward " \t")))
3316 (end (point)))
3317 (list 'subscript
3318 (list :begin begin
3319 :end end
3320 :use-brackets-p bracketsp
3321 :contents-begin contents-begin
3322 :contents-end contents-end
3323 :post-blank post-blank)))))
3325 (defun org-element-subscript-interpreter (subscript contents)
3326 "Interpret SUBSCRIPT object as Org syntax.
3327 CONTENTS is the contents of the object."
3328 (format
3329 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3330 contents))
3332 (defun org-element-sub/superscript-successor ()
3333 "Search for the next sub/superscript object.
3335 Return value is a cons cell whose CAR is either `subscript' or
3336 `superscript' and CDR is beginning position."
3337 (save-excursion
3338 (unless (bolp) (backward-char))
3339 (when (re-search-forward org-match-substring-regexp nil t)
3340 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3341 (match-beginning 2)))))
3344 ;;;; Superscript
3346 (defun org-element-superscript-parser ()
3347 "Parse superscript at point.
3349 Return a list whose CAR is `superscript' and CDR a plist with
3350 `:begin', `:end', `:contents-begin', `:contents-end',
3351 `:use-brackets-p' and `:post-blank' as keywords.
3353 Assume point is at the caret."
3354 (save-excursion
3355 (unless (bolp) (backward-char))
3356 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3357 (not (looking-at org-match-substring-regexp))))
3358 (begin (match-beginning 2))
3359 (contents-begin (or (match-beginning 5)
3360 (match-beginning 3)))
3361 (contents-end (or (match-end 5) (match-end 3)))
3362 (post-blank (progn (goto-char (match-end 0))
3363 (skip-chars-forward " \t")))
3364 (end (point)))
3365 (list 'superscript
3366 (list :begin begin
3367 :end end
3368 :use-brackets-p bracketsp
3369 :contents-begin contents-begin
3370 :contents-end contents-end
3371 :post-blank post-blank)))))
3373 (defun org-element-superscript-interpreter (superscript contents)
3374 "Interpret SUPERSCRIPT object as Org syntax.
3375 CONTENTS is the contents of the object."
3376 (format
3377 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3378 contents))
3381 ;;;; Table Cell
3383 (defun org-element-table-cell-parser ()
3384 "Parse table cell at point.
3386 Return a list whose CAR is `table-cell' and CDR is a plist
3387 containing `:begin', `:end', `:contents-begin', `:contents-end'
3388 and `:post-blank' keywords."
3389 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3390 (let* ((begin (match-beginning 0))
3391 (end (match-end 0))
3392 (contents-begin (match-beginning 1))
3393 (contents-end (match-end 1)))
3394 (list 'table-cell
3395 (list :begin begin
3396 :end end
3397 :contents-begin contents-begin
3398 :contents-end contents-end
3399 :post-blank 0))))
3401 (defun org-element-table-cell-interpreter (table-cell contents)
3402 "Interpret TABLE-CELL element as Org syntax.
3403 CONTENTS is the contents of the cell, or nil."
3404 (concat " " contents " |"))
3406 (defun org-element-table-cell-successor ()
3407 "Search for the next table-cell object.
3409 Return value is a cons cell whose CAR is `table-cell' and CDR is
3410 beginning position."
3411 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3414 ;;;; Target
3416 (defun org-element-target-parser ()
3417 "Parse target at point.
3419 Return a list whose CAR is `target' and CDR a plist with
3420 `:begin', `:end', `:value' and `:post-blank' as keywords.
3422 Assume point is at the target."
3423 (save-excursion
3424 (looking-at org-target-regexp)
3425 (let ((begin (point))
3426 (value (org-match-string-no-properties 1))
3427 (post-blank (progn (goto-char (match-end 0))
3428 (skip-chars-forward " \t")))
3429 (end (point)))
3430 (list 'target
3431 (list :begin begin
3432 :end end
3433 :value value
3434 :post-blank post-blank)))))
3436 (defun org-element-target-interpreter (target contents)
3437 "Interpret TARGET object as Org syntax.
3438 CONTENTS is nil."
3439 (format "<<%s>>" (org-element-property :value target)))
3441 (defun org-element-target-successor ()
3442 "Search for the next target object.
3444 Return value is a cons cell whose CAR is `target' and CDR is
3445 beginning position."
3446 (save-excursion
3447 (when (re-search-forward org-target-regexp nil t)
3448 (cons 'target (match-beginning 0)))))
3451 ;;;; Timestamp
3453 (defun org-element-timestamp-parser ()
3454 "Parse time stamp at point.
3456 Return a list whose CAR is `timestamp', and CDR a plist with
3457 `:type', `:raw-value', `:year-start', `:month-start',
3458 `:day-start', `:hour-start', `:minute-start', `:year-end',
3459 `:month-end', `:day-end', `:hour-end', `:minute-end',
3460 `:repeater-type', `:repeater-value', `:repeater-unit',
3461 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3462 `:end', `:value' and `:post-blank' keywords.
3464 Assume point is at the beginning of the timestamp."
3465 (save-excursion
3466 (let* ((begin (point))
3467 (activep (eq (char-after) ?<))
3468 (raw-value
3469 (progn
3470 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3471 (match-string-no-properties 0)))
3472 (date-start (match-string-no-properties 1))
3473 (date-end (match-string 3))
3474 (diaryp (match-beginning 2))
3475 (post-blank (progn (goto-char (match-end 0))
3476 (skip-chars-forward " \t")))
3477 (end (point))
3478 (time-range
3479 (and (not diaryp)
3480 (string-match
3481 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3482 date-start)
3483 (cons (string-to-number (match-string 2 date-start))
3484 (string-to-number (match-string 3 date-start)))))
3485 (type (cond (diaryp 'diary)
3486 ((and activep (or date-end time-range)) 'active-range)
3487 (activep 'active)
3488 ((or date-end time-range) 'inactive-range)
3489 (t 'inactive)))
3490 (repeater-props
3491 (and (not diaryp)
3492 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3493 raw-value)
3494 (list
3495 :repeater-type
3496 (let ((type (match-string 1 raw-value)))
3497 (cond ((equal "++" type) 'catch-up)
3498 ((equal ".+" type) 'restart)
3499 (t 'cumulate)))
3500 :repeater-value (string-to-number (match-string 2 raw-value))
3501 :repeater-unit
3502 (case (string-to-char (match-string 3 raw-value))
3503 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3504 (warning-props
3505 (and (not diaryp)
3506 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3507 (list
3508 :warning-type (if (match-string 1 raw-value) 'first 'all)
3509 :warning-value (string-to-number (match-string 2 raw-value))
3510 :warning-unit
3511 (case (string-to-char (match-string 3 raw-value))
3512 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3513 year-start month-start day-start hour-start minute-start year-end
3514 month-end day-end hour-end minute-end)
3515 ;; Parse date-start.
3516 (unless diaryp
3517 (let ((date (org-parse-time-string date-start t)))
3518 (setq year-start (nth 5 date)
3519 month-start (nth 4 date)
3520 day-start (nth 3 date)
3521 hour-start (nth 2 date)
3522 minute-start (nth 1 date))))
3523 ;; Compute date-end. It can be provided directly in time-stamp,
3524 ;; or extracted from time range. Otherwise, it defaults to the
3525 ;; same values as date-start.
3526 (unless diaryp
3527 (let ((date (and date-end (org-parse-time-string date-end t))))
3528 (setq year-end (or (nth 5 date) year-start)
3529 month-end (or (nth 4 date) month-start)
3530 day-end (or (nth 3 date) day-start)
3531 hour-end (or (nth 2 date) (car time-range) hour-start)
3532 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3533 (list 'timestamp
3534 (nconc (list :type type
3535 :raw-value raw-value
3536 :year-start year-start
3537 :month-start month-start
3538 :day-start day-start
3539 :hour-start hour-start
3540 :minute-start minute-start
3541 :year-end year-end
3542 :month-end month-end
3543 :day-end day-end
3544 :hour-end hour-end
3545 :minute-end minute-end
3546 :begin begin
3547 :end end
3548 :post-blank post-blank)
3549 repeater-props
3550 warning-props)))))
3552 (defun org-element-timestamp-interpreter (timestamp contents)
3553 "Interpret TIMESTAMP object as Org syntax.
3554 CONTENTS is nil."
3555 (let* ((repeat-string
3556 (concat
3557 (case (org-element-property :repeater-type timestamp)
3558 (cumulate "+") (catch-up "++") (restart ".+"))
3559 (let ((val (org-element-property :repeater-value timestamp)))
3560 (and val (number-to-string val)))
3561 (case (org-element-property :repeater-unit timestamp)
3562 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3563 (warning-string
3564 (concat
3565 (case (org-element-property :warning-type timestamp)
3566 (first "--")
3567 (all "-"))
3568 (let ((val (org-element-property :warning-value timestamp)))
3569 (and val (number-to-string val)))
3570 (case (org-element-property :warning-unit timestamp)
3571 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3572 (build-ts-string
3573 ;; Build an Org timestamp string from TIME. ACTIVEP is
3574 ;; non-nil when time stamp is active. If WITH-TIME-P is
3575 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3576 ;; specify a time range in the timestamp. REPEAT-STRING is
3577 ;; the repeater string, if any.
3578 (lambda (time activep &optional with-time-p hour-end minute-end)
3579 (let ((ts (format-time-string
3580 (funcall (if with-time-p 'cdr 'car)
3581 org-time-stamp-formats)
3582 time)))
3583 (when (and hour-end minute-end)
3584 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3585 (setq ts
3586 (replace-match
3587 (format "\\&-%02d:%02d" hour-end minute-end)
3588 nil nil ts)))
3589 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3590 (dolist (s (list repeat-string warning-string))
3591 (when (org-string-nw-p s)
3592 (setq ts (concat (substring ts 0 -1)
3595 (substring ts -1)))))
3596 ;; Return value.
3597 ts)))
3598 (type (org-element-property :type timestamp)))
3599 (case type
3600 ((active inactive)
3601 (let* ((minute-start (org-element-property :minute-start timestamp))
3602 (minute-end (org-element-property :minute-end timestamp))
3603 (hour-start (org-element-property :hour-start timestamp))
3604 (hour-end (org-element-property :hour-end timestamp))
3605 (time-range-p (and hour-start hour-end minute-start minute-end
3606 (or (/= hour-start hour-end)
3607 (/= minute-start minute-end)))))
3608 (funcall
3609 build-ts-string
3610 (encode-time 0
3611 (or minute-start 0)
3612 (or hour-start 0)
3613 (org-element-property :day-start timestamp)
3614 (org-element-property :month-start timestamp)
3615 (org-element-property :year-start timestamp))
3616 (eq type 'active)
3617 (and hour-start minute-start)
3618 (and time-range-p hour-end)
3619 (and time-range-p minute-end))))
3620 ((active-range inactive-range)
3621 (let ((minute-start (org-element-property :minute-start timestamp))
3622 (minute-end (org-element-property :minute-end timestamp))
3623 (hour-start (org-element-property :hour-start timestamp))
3624 (hour-end (org-element-property :hour-end timestamp)))
3625 (concat
3626 (funcall
3627 build-ts-string (encode-time
3629 (or minute-start 0)
3630 (or hour-start 0)
3631 (org-element-property :day-start timestamp)
3632 (org-element-property :month-start timestamp)
3633 (org-element-property :year-start timestamp))
3634 (eq type 'active-range)
3635 (and hour-start minute-start))
3636 "--"
3637 (funcall build-ts-string
3638 (encode-time 0
3639 (or minute-end 0)
3640 (or hour-end 0)
3641 (org-element-property :day-end timestamp)
3642 (org-element-property :month-end timestamp)
3643 (org-element-property :year-end timestamp))
3644 (eq type 'active-range)
3645 (and hour-end minute-end))))))))
3647 (defun org-element-timestamp-successor ()
3648 "Search for the next timestamp object.
3650 Return value is a cons cell whose CAR is `timestamp' and CDR is
3651 beginning position."
3652 (save-excursion
3653 (when (re-search-forward
3654 (concat org-ts-regexp-both
3655 "\\|"
3656 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3657 "\\|"
3658 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3659 nil t)
3660 (cons 'timestamp (match-beginning 0)))))
3663 ;;;; Underline
3665 (defun org-element-underline-parser ()
3666 "Parse underline object at point.
3668 Return a list whose CAR is `underline' and CDR is a plist with
3669 `:begin', `:end', `:contents-begin' and `:contents-end' and
3670 `:post-blank' keywords.
3672 Assume point is at the first underscore marker."
3673 (save-excursion
3674 (unless (bolp) (backward-char 1))
3675 (looking-at org-emph-re)
3676 (let ((begin (match-beginning 2))
3677 (contents-begin (match-beginning 4))
3678 (contents-end (match-end 4))
3679 (post-blank (progn (goto-char (match-end 2))
3680 (skip-chars-forward " \t")))
3681 (end (point)))
3682 (list 'underline
3683 (list :begin begin
3684 :end end
3685 :contents-begin contents-begin
3686 :contents-end contents-end
3687 :post-blank post-blank)))))
3689 (defun org-element-underline-interpreter (underline contents)
3690 "Interpret UNDERLINE object as Org syntax.
3691 CONTENTS is the contents of the object."
3692 (format "_%s_" contents))
3695 ;;;; Verbatim
3697 (defun org-element-verbatim-parser ()
3698 "Parse verbatim object at point.
3700 Return a list whose CAR is `verbatim' and CDR is a plist with
3701 `:value', `:begin', `:end' and `:post-blank' keywords.
3703 Assume point is at the first equal sign marker."
3704 (save-excursion
3705 (unless (bolp) (backward-char 1))
3706 (looking-at org-emph-re)
3707 (let ((begin (match-beginning 2))
3708 (value (org-match-string-no-properties 4))
3709 (post-blank (progn (goto-char (match-end 2))
3710 (skip-chars-forward " \t")))
3711 (end (point)))
3712 (list 'verbatim
3713 (list :value value
3714 :begin begin
3715 :end end
3716 :post-blank post-blank)))))
3718 (defun org-element-verbatim-interpreter (verbatim contents)
3719 "Interpret VERBATIM object as Org syntax.
3720 CONTENTS is nil."
3721 (format "=%s=" (org-element-property :value verbatim)))
3725 ;;; Parsing Element Starting At Point
3727 ;; `org-element--current-element' is the core function of this section.
3728 ;; It returns the Lisp representation of the element starting at
3729 ;; point.
3731 ;; `org-element--current-element' makes use of special modes. They
3732 ;; are activated for fixed element chaining (i.e. `plain-list' >
3733 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3734 ;; `section'). Special modes are: `first-section', `item',
3735 ;; `node-property', `quote-section', `section' and `table-row'.
3737 (defun org-element--current-element
3738 (limit &optional granularity special structure)
3739 "Parse the element starting at point.
3741 Return value is a list like (TYPE PROPS) where TYPE is the type
3742 of the element and PROPS a plist of properties associated to the
3743 element.
3745 Possible types are defined in `org-element-all-elements'.
3747 LIMIT bounds the search.
3749 Optional argument GRANULARITY determines the depth of the
3750 recursion. Allowed values are `headline', `greater-element',
3751 `element', `object' or nil. When it is broader than `object' (or
3752 nil), secondary values will not be parsed, since they only
3753 contain objects.
3755 Optional argument SPECIAL, when non-nil, can be either
3756 `first-section', `item', `node-property', `quote-section',
3757 `section', and `table-row'.
3759 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3760 be computed.
3762 This function assumes point is always at the beginning of the
3763 element it has to parse."
3764 (save-excursion
3765 (let ((case-fold-search t)
3766 ;; Determine if parsing depth allows for secondary strings
3767 ;; parsing. It only applies to elements referenced in
3768 ;; `org-element-secondary-value-alist'.
3769 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3770 (cond
3771 ;; Item.
3772 ((eq special 'item)
3773 (org-element-item-parser limit structure raw-secondary-p))
3774 ;; Table Row.
3775 ((eq special 'table-row) (org-element-table-row-parser limit))
3776 ;; Node Property.
3777 ((eq special 'node-property) (org-element-node-property-parser limit))
3778 ;; Headline.
3779 ((org-with-limited-levels (org-at-heading-p))
3780 (org-element-headline-parser limit raw-secondary-p))
3781 ;; Sections (must be checked after headline).
3782 ((eq special 'section) (org-element-section-parser limit))
3783 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3784 ((eq special 'first-section)
3785 (org-element-section-parser
3786 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3787 limit)))
3788 ;; When not at bol, point is at the beginning of an item or
3789 ;; a footnote definition: next item is always a paragraph.
3790 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3791 ;; Planning and Clock.
3792 ((looking-at org-planning-or-clock-line-re)
3793 (if (equal (match-string 1) org-clock-string)
3794 (org-element-clock-parser limit)
3795 (org-element-planning-parser limit)))
3796 ;; Inlinetask.
3797 ((org-at-heading-p)
3798 (org-element-inlinetask-parser limit raw-secondary-p))
3799 ;; From there, elements can have affiliated keywords.
3800 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3801 (cond
3802 ;; Jumping over affiliated keywords put point off-limits.
3803 ;; Parse them as regular keywords.
3804 ((and (cdr affiliated) (>= (point) limit))
3805 (goto-char (car affiliated))
3806 (org-element-keyword-parser limit nil))
3807 ;; LaTeX Environment.
3808 ((looking-at
3809 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3810 (org-element-latex-environment-parser limit affiliated))
3811 ;; Drawer and Property Drawer.
3812 ((looking-at org-drawer-regexp)
3813 (if (equal (match-string 1) "PROPERTIES")
3814 (org-element-property-drawer-parser limit affiliated)
3815 (org-element-drawer-parser limit affiliated)))
3816 ;; Fixed Width
3817 ((looking-at "[ \t]*:\\( \\|$\\)")
3818 (org-element-fixed-width-parser limit affiliated))
3819 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3820 ;; Keywords.
3821 ((looking-at "[ \t]*#")
3822 (goto-char (match-end 0))
3823 (cond ((looking-at "\\(?: \\|$\\)")
3824 (beginning-of-line)
3825 (org-element-comment-parser limit affiliated))
3826 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3827 (beginning-of-line)
3828 (let ((parser (assoc (upcase (match-string 1))
3829 org-element-block-name-alist)))
3830 (if parser (funcall (cdr parser) limit affiliated)
3831 (org-element-special-block-parser limit affiliated))))
3832 ((looking-at "\\+CALL:")
3833 (beginning-of-line)
3834 (org-element-babel-call-parser limit affiliated))
3835 ((looking-at "\\+BEGIN:? ")
3836 (beginning-of-line)
3837 (org-element-dynamic-block-parser limit affiliated))
3838 ((looking-at "\\+\\S-+:")
3839 (beginning-of-line)
3840 (org-element-keyword-parser limit affiliated))
3842 (beginning-of-line)
3843 (org-element-paragraph-parser limit affiliated))))
3844 ;; Footnote Definition.
3845 ((looking-at org-footnote-definition-re)
3846 (org-element-footnote-definition-parser limit affiliated))
3847 ;; Horizontal Rule.
3848 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3849 (org-element-horizontal-rule-parser limit affiliated))
3850 ;; Diary Sexp.
3851 ((looking-at "%%(")
3852 (org-element-diary-sexp-parser limit affiliated))
3853 ;; Table.
3854 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3855 ;; List.
3856 ((looking-at (org-item-re))
3857 (org-element-plain-list-parser
3858 limit affiliated
3859 (or structure (org-element--list-struct limit))))
3860 ;; Default element: Paragraph.
3861 (t (org-element-paragraph-parser limit affiliated)))))))))
3864 ;; Most elements can have affiliated keywords. When looking for an
3865 ;; element beginning, we want to move before them, as they belong to
3866 ;; that element, and, in the meantime, collect information they give
3867 ;; into appropriate properties. Hence the following function.
3869 (defun org-element--collect-affiliated-keywords (limit)
3870 "Collect affiliated keywords from point down to LIMIT.
3872 Return a list whose CAR is the position at the first of them and
3873 CDR a plist of keywords and values and move point to the
3874 beginning of the first line after them.
3876 As a special case, if element doesn't start at the beginning of
3877 the line (i.e. a paragraph starting an item), CAR is current
3878 position of point and CDR is nil."
3879 (if (not (bolp)) (list (point))
3880 (let ((case-fold-search t)
3881 (origin (point))
3882 ;; RESTRICT is the list of objects allowed in parsed
3883 ;; keywords value.
3884 (restrict (org-element-restriction 'keyword))
3885 output)
3886 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3887 (let* ((raw-kwd (upcase (match-string 1)))
3888 ;; Apply translation to RAW-KWD. From there, KWD is
3889 ;; the official keyword.
3890 (kwd (or (cdr (assoc raw-kwd
3891 org-element-keyword-translation-alist))
3892 raw-kwd))
3893 ;; Find main value for any keyword.
3894 (value
3895 (save-match-data
3896 (org-trim
3897 (buffer-substring-no-properties
3898 (match-end 0) (point-at-eol)))))
3899 ;; PARSEDP is non-nil when keyword should have its
3900 ;; value parsed.
3901 (parsedp (member kwd org-element-parsed-keywords))
3902 ;; If KWD is a dual keyword, find its secondary
3903 ;; value. Maybe parse it.
3904 (dualp (member kwd org-element-dual-keywords))
3905 (dual-value
3906 (and dualp
3907 (let ((sec (org-match-string-no-properties 2)))
3908 (if (or (not sec) (not parsedp)) sec
3909 (org-element-parse-secondary-string sec restrict)))))
3910 ;; Attribute a property name to KWD.
3911 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3912 ;; Now set final shape for VALUE.
3913 (when parsedp
3914 (setq value (org-element-parse-secondary-string value restrict)))
3915 (when dualp
3916 (setq value (and (or value dual-value) (cons value dual-value))))
3917 (when (or (member kwd org-element-multiple-keywords)
3918 ;; Attributes can always appear on multiple lines.
3919 (string-match "^ATTR_" kwd))
3920 (setq value (cons value (plist-get output kwd-sym))))
3921 ;; Eventually store the new value in OUTPUT.
3922 (setq output (plist-put output kwd-sym value))
3923 ;; Move to next keyword.
3924 (forward-line)))
3925 ;; If affiliated keywords are orphaned: move back to first one.
3926 ;; They will be parsed as a paragraph.
3927 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3928 ;; Return value.
3929 (cons origin output))))
3933 ;;; The Org Parser
3935 ;; The two major functions here are `org-element-parse-buffer', which
3936 ;; parses Org syntax inside the current buffer, taking into account
3937 ;; region, narrowing, or even visibility if specified, and
3938 ;; `org-element-parse-secondary-string', which parses objects within
3939 ;; a given string.
3941 ;; The (almost) almighty `org-element-map' allows to apply a function
3942 ;; on elements or objects matching some type, and accumulate the
3943 ;; resulting values. In an export situation, it also skips unneeded
3944 ;; parts of the parse tree.
3946 (defun org-element-parse-buffer (&optional granularity visible-only)
3947 "Recursively parse the buffer and return structure.
3948 If narrowing is in effect, only parse the visible part of the
3949 buffer.
3951 Optional argument GRANULARITY determines the depth of the
3952 recursion. It can be set to the following symbols:
3954 `headline' Only parse headlines.
3955 `greater-element' Don't recurse into greater elements excepted
3956 headlines and sections. Thus, elements
3957 parsed are the top-level ones.
3958 `element' Parse everything but objects and plain text.
3959 `object' Parse the complete buffer (default).
3961 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3962 elements.
3964 An element or an objects is represented as a list with the
3965 pattern (TYPE PROPERTIES CONTENTS), where :
3967 TYPE is a symbol describing the element or object. See
3968 `org-element-all-elements' and `org-element-all-objects' for an
3969 exhaustive list of such symbols. One can retrieve it with
3970 `org-element-type' function.
3972 PROPERTIES is the list of attributes attached to the element or
3973 object, as a plist. Although most of them are specific to the
3974 element or object type, all types share `:begin', `:end',
3975 `:post-blank' and `:parent' properties, which respectively
3976 refer to buffer position where the element or object starts,
3977 ends, the number of white spaces or blank lines after it, and
3978 the element or object containing it. Properties values can be
3979 obtained by using `org-element-property' function.
3981 CONTENTS is a list of elements, objects or raw strings
3982 contained in the current element or object, when applicable.
3983 One can access them with `org-element-contents' function.
3985 The Org buffer has `org-data' as type and nil as properties.
3986 `org-element-map' function can be used to find specific elements
3987 or objects within the parse tree.
3989 This function assumes that current major mode is `org-mode'."
3990 (save-excursion
3991 (goto-char (point-min))
3992 (org-skip-whitespace)
3993 (org-element--parse-elements
3994 (point-at-bol) (point-max)
3995 ;; Start in `first-section' mode so text before the first
3996 ;; headline belongs to a section.
3997 'first-section nil granularity visible-only (list 'org-data nil))))
3999 (defun org-element-parse-secondary-string (string restriction &optional parent)
4000 "Recursively parse objects in STRING and return structure.
4002 RESTRICTION is a symbol limiting the object types that will be
4003 looked after.
4005 Optional argument PARENT, when non-nil, is the element or object
4006 containing the secondary string. It is used to set correctly
4007 `:parent' property within the string."
4008 ;; Copy buffer-local variables listed in
4009 ;; `org-element-object-variables' into temporary buffer. This is
4010 ;; required since object parsing is dependent on these variables.
4011 (let ((pairs (delq nil (mapcar (lambda (var)
4012 (when (boundp var)
4013 (cons var (symbol-value var))))
4014 org-element-object-variables))))
4015 (with-temp-buffer
4016 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4017 (insert string)
4018 (let ((secondary (org-element--parse-objects
4019 (point-min) (point-max) nil restriction)))
4020 (when parent
4021 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4022 secondary))
4023 secondary))))
4025 (defun org-element-map
4026 (data types fun &optional info first-match no-recursion with-affiliated)
4027 "Map a function on selected elements or objects.
4029 DATA is a parse tree, an element, an object, a string, or a list
4030 of such constructs. TYPES is a symbol or list of symbols of
4031 elements or objects types (see `org-element-all-elements' and
4032 `org-element-all-objects' for a complete list of types). FUN is
4033 the function called on the matching element or object. It has to
4034 accept one argument: the element or object itself.
4036 When optional argument INFO is non-nil, it should be a plist
4037 holding export options. In that case, parts of the parse tree
4038 not exportable according to that property list will be skipped.
4040 When optional argument FIRST-MATCH is non-nil, stop at the first
4041 match for which FUN doesn't return nil, and return that value.
4043 Optional argument NO-RECURSION is a symbol or a list of symbols
4044 representing elements or objects types. `org-element-map' won't
4045 enter any recursive element or object whose type belongs to that
4046 list. Though, FUN can still be applied on them.
4048 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4049 apply to matching objects within parsed affiliated keywords (see
4050 `org-element-parsed-keywords').
4052 Nil values returned from FUN do not appear in the results.
4055 Examples:
4056 ---------
4058 Assuming TREE is a variable containing an Org buffer parse tree,
4059 the following example will return a flat list of all `src-block'
4060 and `example-block' elements in it:
4062 \(org-element-map tree '(example-block src-block) 'identity)
4064 The following snippet will find the first headline with a level
4065 of 1 and a \"phone\" tag, and will return its beginning position:
4067 \(org-element-map tree 'headline
4068 \(lambda (hl)
4069 \(and (= (org-element-property :level hl) 1)
4070 \(member \"phone\" (org-element-property :tags hl))
4071 \(org-element-property :begin hl)))
4072 nil t)
4074 The next example will return a flat list of all `plain-list' type
4075 elements in TREE that are not a sub-list themselves:
4077 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4079 Eventually, this example will return a flat list of all `bold'
4080 type objects containing a `latex-snippet' type object, even
4081 looking into captions:
4083 \(org-element-map tree 'bold
4084 \(lambda (b)
4085 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4086 nil nil nil t)"
4087 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4088 (unless (listp types) (setq types (list types)))
4089 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4090 ;; Recursion depth is determined by --CATEGORY.
4091 (let* ((--category
4092 (catch 'found
4093 (let ((category 'greater-elements))
4094 (mapc (lambda (type)
4095 (cond ((or (memq type org-element-all-objects)
4096 (eq type 'plain-text))
4097 ;; If one object is found, the function
4098 ;; has to recurse into every object.
4099 (throw 'found 'objects))
4100 ((not (memq type org-element-greater-elements))
4101 ;; If one regular element is found, the
4102 ;; function has to recurse, at least,
4103 ;; into every element it encounters.
4104 (and (not (eq category 'elements))
4105 (setq category 'elements)))))
4106 types)
4107 category)))
4108 ;; Compute properties for affiliated keywords if necessary.
4109 (--affiliated-alist
4110 (and with-affiliated
4111 (mapcar (lambda (kwd)
4112 (cons kwd (intern (concat ":" (downcase kwd)))))
4113 org-element-affiliated-keywords)))
4114 --acc
4115 --walk-tree
4116 (--walk-tree
4117 (function
4118 (lambda (--data)
4119 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4120 ;; holding contextual information.
4121 (let ((--type (org-element-type --data)))
4122 (cond
4123 ((not --data))
4124 ;; Ignored element in an export context.
4125 ((and info (memq --data (plist-get info :ignore-list))))
4126 ;; List of elements or objects.
4127 ((not --type) (mapc --walk-tree --data))
4128 ;; Unconditionally enter parse trees.
4129 ((eq --type 'org-data)
4130 (mapc --walk-tree (org-element-contents --data)))
4132 ;; Check if TYPE is matching among TYPES. If so,
4133 ;; apply FUN to --DATA and accumulate return value
4134 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4135 (when (memq --type types)
4136 (let ((result (funcall fun --data)))
4137 (cond ((not result))
4138 (first-match (throw '--map-first-match result))
4139 (t (push result --acc)))))
4140 ;; If --DATA has a secondary string that can contain
4141 ;; objects with their type among TYPES, look into it.
4142 (when (and (eq --category 'objects) (not (stringp --data)))
4143 (let ((sec-prop
4144 (assq --type org-element-secondary-value-alist)))
4145 (when sec-prop
4146 (funcall --walk-tree
4147 (org-element-property (cdr sec-prop) --data)))))
4148 ;; If --DATA has any affiliated keywords and
4149 ;; WITH-AFFILIATED is non-nil, look for objects in
4150 ;; them.
4151 (when (and with-affiliated
4152 (eq --category 'objects)
4153 (memq --type org-element-all-elements))
4154 (mapc (lambda (kwd-pair)
4155 (let ((kwd (car kwd-pair))
4156 (value (org-element-property
4157 (cdr kwd-pair) --data)))
4158 ;; Pay attention to the type of value.
4159 ;; Preserve order for multiple keywords.
4160 (cond
4161 ((not value))
4162 ((and (member kwd org-element-multiple-keywords)
4163 (member kwd org-element-dual-keywords))
4164 (mapc (lambda (line)
4165 (funcall --walk-tree (cdr line))
4166 (funcall --walk-tree (car line)))
4167 (reverse value)))
4168 ((member kwd org-element-multiple-keywords)
4169 (mapc (lambda (line) (funcall --walk-tree line))
4170 (reverse value)))
4171 ((member kwd org-element-dual-keywords)
4172 (funcall --walk-tree (cdr value))
4173 (funcall --walk-tree (car value)))
4174 (t (funcall --walk-tree value)))))
4175 --affiliated-alist))
4176 ;; Determine if a recursion into --DATA is possible.
4177 (cond
4178 ;; --TYPE is explicitly removed from recursion.
4179 ((memq --type no-recursion))
4180 ;; --DATA has no contents.
4181 ((not (org-element-contents --data)))
4182 ;; Looking for greater elements but --DATA is simply
4183 ;; an element or an object.
4184 ((and (eq --category 'greater-elements)
4185 (not (memq --type org-element-greater-elements))))
4186 ;; Looking for elements but --DATA is an object.
4187 ((and (eq --category 'elements)
4188 (memq --type org-element-all-objects)))
4189 ;; In any other case, map contents.
4190 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4191 (catch '--map-first-match
4192 (funcall --walk-tree data)
4193 ;; Return value in a proper order.
4194 (nreverse --acc))))
4195 (put 'org-element-map 'lisp-indent-function 2)
4197 ;; The following functions are internal parts of the parser.
4199 ;; The first one, `org-element--parse-elements' acts at the element's
4200 ;; level.
4202 ;; The second one, `org-element--parse-objects' applies on all objects
4203 ;; of a paragraph or a secondary string. It uses
4204 ;; `org-element--get-next-object-candidates' to optimize the search of
4205 ;; the next object in the buffer.
4207 ;; More precisely, that function looks for every allowed object type
4208 ;; first. Then, it discards failed searches, keeps further matches,
4209 ;; and searches again types matched behind point, for subsequent
4210 ;; calls. Thus, searching for a given type fails only once, and every
4211 ;; object is searched only once at top level (but sometimes more for
4212 ;; nested types).
4214 (defun org-element--parse-elements
4215 (beg end special structure granularity visible-only acc)
4216 "Parse elements between BEG and END positions.
4218 SPECIAL prioritize some elements over the others. It can be set
4219 to `first-section', `quote-section', `section' `item' or
4220 `table-row'.
4222 When value is `item', STRUCTURE will be used as the current list
4223 structure.
4225 GRANULARITY determines the depth of the recursion. See
4226 `org-element-parse-buffer' for more information.
4228 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4229 elements.
4231 Elements are accumulated into ACC."
4232 (save-excursion
4233 (goto-char beg)
4234 ;; Visible only: skip invisible parts at the beginning of the
4235 ;; element.
4236 (when (and visible-only (org-invisible-p2))
4237 (goto-char (min (1+ (org-find-visible)) end)))
4238 ;; When parsing only headlines, skip any text before first one.
4239 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4240 (org-with-limited-levels (outline-next-heading)))
4241 ;; Main loop start.
4242 (while (< (point) end)
4243 ;; Find current element's type and parse it accordingly to
4244 ;; its category.
4245 (let* ((element (org-element--current-element
4246 end granularity special structure))
4247 (type (org-element-type element))
4248 (cbeg (org-element-property :contents-begin element)))
4249 (goto-char (org-element-property :end element))
4250 ;; Visible only: skip invisible parts between siblings.
4251 (when (and visible-only (org-invisible-p2))
4252 (goto-char (min (1+ (org-find-visible)) end)))
4253 ;; Fill ELEMENT contents by side-effect.
4254 (cond
4255 ;; If element has no contents, don't modify it.
4256 ((not cbeg))
4257 ;; Greater element: parse it between `contents-begin' and
4258 ;; `contents-end'. Make sure GRANULARITY allows the
4259 ;; recursion, or ELEMENT is a headline, in which case going
4260 ;; inside is mandatory, in order to get sub-level headings.
4261 ((and (memq type org-element-greater-elements)
4262 (or (memq granularity '(element object nil))
4263 (and (eq granularity 'greater-element)
4264 (eq type 'section))
4265 (eq type 'headline)))
4266 (org-element--parse-elements
4267 cbeg (org-element-property :contents-end element)
4268 ;; Possibly switch to a special mode.
4269 (case type
4270 (headline
4271 (if (org-element-property :quotedp element) 'quote-section
4272 'section))
4273 (plain-list 'item)
4274 (property-drawer 'node-property)
4275 (table 'table-row))
4276 (and (memq type '(item plain-list))
4277 (org-element-property :structure element))
4278 granularity visible-only element))
4279 ;; ELEMENT has contents. Parse objects inside, if
4280 ;; GRANULARITY allows it.
4281 ((memq granularity '(object nil))
4282 (org-element--parse-objects
4283 cbeg (org-element-property :contents-end element) element
4284 (org-element-restriction type))))
4285 (org-element-adopt-elements acc element)))
4286 ;; Return result.
4287 acc))
4289 (defun org-element--parse-objects (beg end acc restriction)
4290 "Parse objects between BEG and END and return recursive structure.
4292 Objects are accumulated in ACC.
4294 RESTRICTION is a list of object successors which are allowed in
4295 the current object."
4296 (let ((candidates 'initial))
4297 (save-excursion
4298 (save-restriction
4299 (narrow-to-region beg end)
4300 (goto-char (point-min))
4301 (while (and (not (eobp))
4302 (setq candidates
4303 (org-element--get-next-object-candidates
4304 restriction candidates)))
4305 (let ((next-object
4306 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4307 (save-excursion
4308 (goto-char pos)
4309 (funcall (intern (format "org-element-%s-parser"
4310 (car (rassq pos candidates)))))))))
4311 ;; 1. Text before any object. Untabify it.
4312 (let ((obj-beg (org-element-property :begin next-object)))
4313 (unless (= (point) obj-beg)
4314 (setq acc
4315 (org-element-adopt-elements
4317 (replace-regexp-in-string
4318 "\t" (make-string tab-width ? )
4319 (buffer-substring-no-properties (point) obj-beg))))))
4320 ;; 2. Object...
4321 (let ((obj-end (org-element-property :end next-object))
4322 (cont-beg (org-element-property :contents-begin next-object)))
4323 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4324 ;; a recursive type.
4325 (when (and cont-beg
4326 (memq (car next-object) org-element-recursive-objects))
4327 (org-element--parse-objects
4328 cont-beg (org-element-property :contents-end next-object)
4329 next-object (org-element-restriction next-object)))
4330 (setq acc (org-element-adopt-elements acc next-object))
4331 (goto-char obj-end))))
4332 ;; 3. Text after last object. Untabify it.
4333 (unless (eobp)
4334 (setq acc
4335 (org-element-adopt-elements
4337 (replace-regexp-in-string
4338 "\t" (make-string tab-width ? )
4339 (buffer-substring-no-properties (point) end)))))
4340 ;; Result.
4341 acc))))
4343 (defun org-element--get-next-object-candidates (restriction objects)
4344 "Return an alist of candidates for the next object.
4346 RESTRICTION is a list of object types, as symbols. Only
4347 candidates with such types are looked after.
4349 OBJECTS is the previous candidates alist. If it is set to
4350 `initial', no search has been done before, and all symbols in
4351 RESTRICTION should be looked after.
4353 Return value is an alist whose CAR is the object type and CDR its
4354 beginning position."
4355 (delq
4357 (if (eq objects 'initial)
4358 ;; When searching for the first time, look for every successor
4359 ;; allowed in RESTRICTION.
4360 (mapcar
4361 (lambda (res)
4362 (funcall (intern (format "org-element-%s-successor" res))))
4363 restriction)
4364 ;; Focus on objects returned during last search. Keep those
4365 ;; still after point. Search again objects before it.
4366 (mapcar
4367 (lambda (obj)
4368 (if (>= (cdr obj) (point)) obj
4369 (let* ((type (car obj))
4370 (succ (or (cdr (assq type org-element-object-successor-alist))
4371 type)))
4372 (and succ
4373 (funcall (intern (format "org-element-%s-successor" succ)))))))
4374 objects))))
4378 ;;; Towards A Bijective Process
4380 ;; The parse tree obtained with `org-element-parse-buffer' is really
4381 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4382 ;; interpreted and expanded into a string with canonical Org syntax.
4383 ;; Hence `org-element-interpret-data'.
4385 ;; The function relies internally on
4386 ;; `org-element--interpret-affiliated-keywords'.
4388 ;;;###autoload
4389 (defun org-element-interpret-data (data &optional pseudo-objects)
4390 "Interpret DATA as Org syntax.
4392 DATA is a parse tree, an element, an object or a secondary string
4393 to interpret.
4395 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4396 new types that should be treated as objects. An unknown type not
4397 belonging to this list is seen as a pseudo-element instead. Both
4398 pseudo-objects and pseudo-elements are transparent entities, i.e.
4399 only their contents are interpreted.
4401 Return Org syntax as a string."
4402 (org-element--interpret-data-1 data nil pseudo-objects))
4404 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4405 "Interpret DATA as Org syntax.
4407 DATA is a parse tree, an element, an object or a secondary string
4408 to interpret. PARENT is used for recursive calls. It contains
4409 the element or object containing data, or nil. PSEUDO-OBJECTS
4410 are list of symbols defining new element or object types.
4411 Unknown types that don't belong to this list are treated as
4412 pseudo-elements instead.
4414 Return Org syntax as a string."
4415 (let* ((type (org-element-type data))
4416 ;; Find interpreter for current object or element. If it
4417 ;; doesn't exist (e.g. this is a pseudo object or element),
4418 ;; return contents, if any.
4419 (interpret
4420 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4421 (if (fboundp fun) fun (lambda (data contents) contents))))
4422 (results
4423 (cond
4424 ;; Secondary string.
4425 ((not type)
4426 (mapconcat
4427 (lambda (obj)
4428 (org-element--interpret-data-1 obj parent pseudo-objects))
4429 data ""))
4430 ;; Full Org document.
4431 ((eq type 'org-data)
4432 (mapconcat
4433 (lambda (obj)
4434 (org-element--interpret-data-1 obj parent pseudo-objects))
4435 (org-element-contents data) ""))
4436 ;; Plain text: remove `:parent' text property from output.
4437 ((stringp data) (org-no-properties data))
4438 ;; Element or object without contents.
4439 ((not (org-element-contents data)) (funcall interpret data nil))
4440 ;; Element or object with contents.
4442 (funcall interpret data
4443 ;; Recursively interpret contents.
4444 (mapconcat
4445 (lambda (obj)
4446 (org-element--interpret-data-1 obj data pseudo-objects))
4447 (org-element-contents
4448 (if (not (memq type '(paragraph verse-block)))
4449 data
4450 ;; Fix indentation of elements containing
4451 ;; objects. We ignore `table-row' elements
4452 ;; as they are one line long anyway.
4453 (org-element-normalize-contents
4454 data
4455 ;; When normalizing first paragraph of an
4456 ;; item or a footnote-definition, ignore
4457 ;; first line's indentation.
4458 (and (eq type 'paragraph)
4459 (equal data (car (org-element-contents parent)))
4460 (memq (org-element-type parent)
4461 '(footnote-definition item))))))
4462 ""))))))
4463 (if (memq type '(org-data plain-text nil)) results
4464 ;; Build white spaces. If no `:post-blank' property is
4465 ;; specified, assume its value is 0.
4466 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4467 (if (or (memq type org-element-all-objects)
4468 (memq type pseudo-objects))
4469 (concat results (make-string post-blank ?\s))
4470 (concat
4471 (org-element--interpret-affiliated-keywords data)
4472 (org-element-normalize-string results)
4473 (make-string post-blank ?\n)))))))
4475 (defun org-element--interpret-affiliated-keywords (element)
4476 "Return ELEMENT's affiliated keywords as Org syntax.
4477 If there is no affiliated keyword, return the empty string."
4478 (let ((keyword-to-org
4479 (function
4480 (lambda (key value)
4481 (let (dual)
4482 (when (member key org-element-dual-keywords)
4483 (setq dual (cdr value) value (car value)))
4484 (concat "#+" key
4485 (and dual
4486 (format "[%s]" (org-element-interpret-data dual)))
4487 ": "
4488 (if (member key org-element-parsed-keywords)
4489 (org-element-interpret-data value)
4490 value)
4491 "\n"))))))
4492 (mapconcat
4493 (lambda (prop)
4494 (let ((value (org-element-property prop element))
4495 (keyword (upcase (substring (symbol-name prop) 1))))
4496 (when value
4497 (if (or (member keyword org-element-multiple-keywords)
4498 ;; All attribute keywords can have multiple lines.
4499 (string-match "^ATTR_" keyword))
4500 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4501 (reverse value)
4503 (funcall keyword-to-org keyword value)))))
4504 ;; List all ELEMENT's properties matching an attribute line or an
4505 ;; affiliated keyword, but ignore translated keywords since they
4506 ;; cannot belong to the property list.
4507 (loop for prop in (nth 1 element) by 'cddr
4508 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4509 (or (string-match "^ATTR_" keyword)
4510 (and
4511 (member keyword org-element-affiliated-keywords)
4512 (not (assoc keyword
4513 org-element-keyword-translation-alist)))))
4514 collect prop)
4515 "")))
4517 ;; Because interpretation of the parse tree must return the same
4518 ;; number of blank lines between elements and the same number of white
4519 ;; space after objects, some special care must be given to white
4520 ;; spaces.
4522 ;; The first function, `org-element-normalize-string', ensures any
4523 ;; string different from the empty string will end with a single
4524 ;; newline character.
4526 ;; The second function, `org-element-normalize-contents', removes
4527 ;; global indentation from the contents of the current element.
4529 (defun org-element-normalize-string (s)
4530 "Ensure string S ends with a single newline character.
4532 If S isn't a string return it unchanged. If S is the empty
4533 string, return it. Otherwise, return a new string with a single
4534 newline character at its end."
4535 (cond
4536 ((not (stringp s)) s)
4537 ((string= "" s) "")
4538 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4539 (replace-match "\n" nil nil s)))))
4541 (defun org-element-normalize-contents (element &optional ignore-first)
4542 "Normalize plain text in ELEMENT's contents.
4544 ELEMENT must only contain plain text and objects.
4546 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4547 indentation to compute maximal common indentation.
4549 Return the normalized element that is element with global
4550 indentation removed from its contents. The function assumes that
4551 indentation is not done with TAB characters."
4552 (let* (ind-list ; for byte-compiler
4553 collect-inds ; for byte-compiler
4554 (collect-inds
4555 (function
4556 ;; Return list of indentations within BLOB. This is done by
4557 ;; walking recursively BLOB and updating IND-LIST along the
4558 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4559 ;; been seen yet. It is required as this string is the only
4560 ;; one whose indentation doesn't happen after a newline
4561 ;; character.
4562 (lambda (blob first-flag)
4563 (mapc
4564 (lambda (object)
4565 (when (and first-flag (stringp object))
4566 (setq first-flag nil)
4567 (string-match "\\`\\( *\\)" object)
4568 (let ((len (length (match-string 1 object))))
4569 ;; An indentation of zero means no string will be
4570 ;; modified. Quit the process.
4571 (if (zerop len) (throw 'zero (setq ind-list nil))
4572 (push len ind-list))))
4573 (cond
4574 ((stringp object)
4575 (let ((start 0))
4576 ;; Avoid matching blank or empty lines.
4577 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4578 (not (equal (match-string 2 object) " ")))
4579 (setq start (match-end 0))
4580 (push (length (match-string 1 object)) ind-list))))
4581 ((memq (org-element-type object) org-element-recursive-objects)
4582 (funcall collect-inds object first-flag))))
4583 (org-element-contents blob))))))
4584 ;; Collect indentation list in ELEMENT. Possibly remove first
4585 ;; value if IGNORE-FIRST is non-nil.
4586 (catch 'zero (funcall collect-inds element (not ignore-first)))
4587 (if (not ind-list) element
4588 ;; Build ELEMENT back, replacing each string with the same
4589 ;; string minus common indentation.
4590 (let* (build ; For byte compiler.
4591 (build
4592 (function
4593 (lambda (blob mci first-flag)
4594 ;; Return BLOB with all its strings indentation
4595 ;; shortened from MCI white spaces. FIRST-FLAG is
4596 ;; non-nil when the first string hasn't been seen
4597 ;; yet.
4598 (setcdr (cdr blob)
4599 (mapcar
4600 (lambda (object)
4601 (when (and first-flag (stringp object))
4602 (setq first-flag nil)
4603 (setq object
4604 (replace-regexp-in-string
4605 (format "\\` \\{%d\\}" mci) "" object)))
4606 (cond
4607 ((stringp object)
4608 (replace-regexp-in-string
4609 (format "\n \\{%d\\}" mci) "\n" object))
4610 ((memq (org-element-type object)
4611 org-element-recursive-objects)
4612 (funcall build object mci first-flag))
4613 (t object)))
4614 (org-element-contents blob)))
4615 blob))))
4616 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4620 ;;; The Toolbox
4622 ;; The first move is to implement a way to obtain the smallest element
4623 ;; containing point. This is the job of `org-element-at-point'. It
4624 ;; basically jumps back to the beginning of section containing point
4625 ;; and proceed, one element after the other, with
4626 ;; `org-element--current-element' until the container is found. Note:
4627 ;; When using `org-element-at-point', secondary values are never
4628 ;; parsed since the function focuses on elements, not on objects.
4630 ;; At a deeper level, `org-element-context' lists all elements and
4631 ;; objects containing point.
4633 ;; Both functions benefit from a simple caching mechanism. It is
4634 ;; enabled by default, but can be disabled globally with
4635 ;; `org-element-use-cache'. Also `org-element-cache-reset' clears or
4636 ;; initializes cache for current buffer. Values are retrieved and put
4637 ;; into cache with respectively, `org-element-cache-get' and
4638 ;; `org-element-cache-put'. `org-element--cache-sync-idle-time' and
4639 ;; `org-element--cache-merge-changes-threshold' are used internally to
4640 ;; control caching behaviour.
4642 ;; Eventually `org-element-nested-p' and `org-element-swap-A-B' may be
4643 ;; used internally by navigation and manipulation tools.
4645 (defvar org-element-use-cache t
4646 "Non nil when Org parser should cache its results.")
4648 (defvar org-element--cache nil
4649 "Hash table used as a cache for parser.
4650 Key is a buffer position and value is a cons cell with the
4651 pattern:
4653 \(ELEMENT . OBJECTS-DATA)
4655 where ELEMENT is the element starting at the key and OBJECTS-DATA
4656 is an alist where each association is:
4658 \(POS CANDIDATES . OBJECTS)
4660 where POS is a buffer position, CANDIDATES is the last know list
4661 of successors (see `org-element--get-next-object-candidates') in
4662 container starting at POS and OBJECTS is a list of objects known
4663 to live within that container, from farthest to closest.
4665 In the following example, \\alpha, bold object and \\beta start
4666 at, respectively, positions 1, 7 and 8,
4668 \\alpha *\\beta*
4670 If the paragraph is completely parsed, OBJECTS-DATA will be
4672 \((1 nil BOLD-OBJECT ENTITY-OBJECT)
4673 \(8 nil ENTITY-OBJECT))
4675 whereas in a partially parsed paragraph, it could be
4677 \((1 ((entity . 1) (bold . 7)) ENTITY-OBJECT))
4679 This cache is used in both `org-element-at-point' and
4680 `org-element-context'. The former uses ELEMENT only and the
4681 latter OBJECTS-DATA only.")
4683 (defvar org-element--cache-sync-idle-time 0.5
4684 "Number of seconds of idle time wait before syncing buffer cache.
4685 Syncing also happens when current modification is too distant
4686 from the stored one (for more information, see
4687 `org-element--cache-merge-changes-threshold').")
4689 (defvar org-element--cache-merge-changes-threshold 200
4690 "Number of characters triggering cache syncing.
4692 The cache mechanism only stores one buffer modification at any
4693 given time. When another change happens, it replaces it with
4694 a change containing both the stored modification and the current
4695 one. This is a trade-off, as merging them prevents another
4696 syncing, but every element between them is then lost.
4698 This variable determines the maximum size, in characters, we
4699 accept to lose in order to avoid syncing the cache.")
4701 (defvar org-element--cache-status nil
4702 "Contains data about cache validity for current buffer.
4704 Value is a vector of seven elements,
4706 [ACTIVEP BEGIN END OFFSET TIMER PREVIOUS-STATE]
4708 ACTIVEP is a boolean non-nil when changes described in the other
4709 slots are valid for current buffer.
4711 BEGIN and END are the beginning and ending position of the area
4712 for which cache cannot be trusted.
4714 OFFSET it an integer specifying the number to add to position of
4715 elements after that area.
4717 TIMER is a timer used to apply these changes to cache when Emacs
4718 is idle.
4720 PREVIOUS-STATE is a symbol referring to the state of the buffer
4721 before a change happens. It is used to know if sensitive
4722 areas (block boundaries, headlines) were modified. It can be set
4723 to nil, `headline' or `other'.")
4725 ;;;###autoload
4726 (defun org-element-cache-reset (&optional all)
4727 "Reset cache in current buffer.
4728 When optional argument ALL is non-nil, reset cache in all Org
4729 buffers. This function will do nothing if
4730 `org-element-use-cache' is nil."
4731 (interactive "P")
4732 (when org-element-use-cache
4733 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
4734 (with-current-buffer buffer
4735 (when (derived-mode-p 'org-mode)
4736 (if (org-bound-and-true-p org-element--cache)
4737 (clrhash org-element--cache)
4738 (org-set-local 'org-element--cache
4739 (make-hash-table :size 5003 :test 'eq)))
4740 (org-set-local 'org-element--cache-status (make-vector 6 nil))
4741 (add-hook 'before-change-functions
4742 'org-element--cache-before-change nil t)
4743 (add-hook 'after-change-functions
4744 'org-element--cache-record-change nil t))))))
4746 (defsubst org-element--cache-pending-changes-p ()
4747 "Non-nil when changes are not integrated in cache yet."
4748 (and org-element--cache-status
4749 (aref org-element--cache-status 0)))
4751 (defsubst org-element--cache-push-change (beg end offset)
4752 "Push change to current buffer staging area.
4753 BEG and END and the beginning and ending position of the
4754 modification area. OFFSET is the size of the change, as an
4755 integer."
4756 (aset org-element--cache-status 1 beg)
4757 (aset org-element--cache-status 2 end)
4758 (aset org-element--cache-status 3 offset)
4759 (let ((timer (aref org-element--cache-status 4)))
4760 (if timer (timer-activate-when-idle timer t)
4761 (aset org-element--cache-status 4
4762 (run-with-idle-timer org-element--cache-sync-idle-time
4764 #'org-element--cache-sync
4765 (current-buffer)))))
4766 (aset org-element--cache-status 0 t))
4768 (defsubst org-element--cache-cancel-changes ()
4769 "Remove any cache change set for current buffer."
4770 (let ((timer (aref org-element--cache-status 4)))
4771 (and timer (cancel-timer timer)))
4772 (aset org-element--cache-status 0 nil))
4774 (defsubst org-element--cache-get-key (element)
4775 "Return expected key for ELEMENT in cache."
4776 (let ((begin (org-element-property :begin element)))
4777 (if (and (memq (org-element-type element) '(item table-row))
4778 (= (org-element-property :contents-begin
4779 (org-element-property :parent element))
4780 begin))
4781 ;; Special key for first item (resp. table-row) in a plain
4782 ;; list (resp. table).
4783 (1+ begin)
4784 begin)))
4786 (defsubst org-element-cache-get (pos &optional type)
4787 "Return data stored at key POS in current buffer cache.
4788 When optional argument TYPE is `element', retrieve the element
4789 starting at POS. When it is `objects', return the list of object
4790 types along with their beginning position within that element.
4791 Otherwise, return the full data. In any case, return nil if no
4792 data is found, or if caching is not allowed."
4793 (when (and org-element-use-cache org-element--cache)
4794 ;; If there are pending changes, first sync them.
4795 (when (org-element--cache-pending-changes-p)
4796 (org-element--cache-sync (current-buffer)))
4797 (let ((data (gethash pos org-element--cache)))
4798 (case type
4799 (element (car data))
4800 (objects (cdr data))
4801 (otherwise data)))))
4803 (defsubst org-element-cache-put (pos data)
4804 "Store data in current buffer's cache, if allowed.
4805 POS is a buffer position, which will be used as a key. DATA is
4806 the value to store. Nothing will be stored if
4807 `org-element-use-cache' is nil. Return DATA in any case."
4808 (if (not org-element-use-cache) data
4809 (unless org-element--cache (org-element-cache-reset))
4810 (puthash pos data org-element--cache)))
4812 (defsubst org-element--cache-shift-positions (element offset)
4813 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4814 Properties containing buffer positions are `:begin', `:end',
4815 `:contents-begin', `:contents-end' and `:structure'. They are
4816 modified by side-effect. Return modified element."
4817 (let ((properties (nth 1 element)))
4818 ;; Shift :structure property for the first plain list only: it is
4819 ;; the only one that really matters and it prevents from shifting
4820 ;; it more than once.
4821 (when (and (eq (org-element-type element) 'plain-list)
4822 (not (eq (org-element-type (plist-get properties :parent))
4823 'item)))
4824 (dolist (item (plist-get properties :structure))
4825 (incf (car item) offset)
4826 (incf (nth 6 item) offset)))
4827 (plist-put properties :begin (+ (plist-get properties :begin) offset))
4828 (plist-put properties :end (+ (plist-get properties :end) offset))
4829 (dolist (key '(:contents-begin :contents-end :post-affiliated))
4830 (let ((value (plist-get properties key)))
4831 (and value (plist-put properties key (+ offset value))))))
4832 element)
4834 (defconst org-element--cache-opening-line
4835 (concat "^[ \t]*\\(?:"
4836 "#\\+BEGIN[:_]" "\\|"
4837 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
4838 ":\\S-+:[ \t]*$"
4839 "\\)")
4840 "Regexp matching an element opening line.
4841 When such a line is modified, modifications may propagate after
4842 modified area. In that situation, every element between that
4843 area and next section is removed from cache.")
4845 (defconst org-element--cache-closing-line
4846 (concat "^[ \t]*\\(?:"
4847 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
4848 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
4849 ":END:[ \t]*$"
4850 "\\)")
4851 "Regexp matching an element closing line.
4852 When such a line is modified, modifications may propagate before
4853 modified area. In that situation, every element between that
4854 area and previous section is removed from cache.")
4856 (defun org-element--cache-before-change (beg end)
4857 "Request extension of area going to be modified if needed.
4858 BEG and END are the beginning and end of the range of changed
4859 text. See `before-change-functions' for more information."
4860 (let ((inhibit-quit t))
4861 (org-with-wide-buffer
4862 (goto-char beg)
4863 (beginning-of-line)
4864 (let ((top (point))
4865 (bottom (save-excursion (goto-char end) (line-end-position)))
4866 (sensitive-re
4867 ;; A sensitive line is a headline or a block (or drawer,
4868 ;; or latex-environment) boundary. Inserting one can
4869 ;; modify buffer drastically both above and below that
4870 ;; line, possibly making cache invalid. Therefore, we
4871 ;; need to pay special attention to changes happening to
4872 ;; them.
4873 (concat
4874 "\\(" (org-with-limited-levels org-outline-regexp-bol) "\\)" "\\|"
4875 org-element--cache-closing-line "\\|"
4876 org-element--cache-opening-line)))
4877 (save-match-data
4878 (aset org-element--cache-status 5
4879 (cond ((not (re-search-forward sensitive-re bottom t)) nil)
4880 ((and (match-beginning 1)
4881 (progn (goto-char bottom)
4882 (or (not (re-search-backward sensitive-re
4883 (match-end 1) t))
4884 (match-beginning 1))))
4885 'headline)
4886 (t 'other))))))))
4888 (defun org-element--cache-record-change (beg end pre)
4889 "Update buffer modifications for current buffer.
4891 BEG and END are the beginning and end of the range of changed
4892 text, and the length in bytes of the pre-change text replaced by
4893 that range. See `after-change-functions' for more information.
4895 If there are already pending changes, try to merge them into
4896 a bigger change record. If that's not possible, the function
4897 will first synchronize cache with previous change and store the
4898 new one."
4899 (let ((inhibit-quit t))
4900 (when (and org-element-use-cache org-element--cache)
4901 (org-with-wide-buffer
4902 (goto-char beg)
4903 (beginning-of-line)
4904 (let ((top (point))
4905 (bottom (save-excursion (goto-char end) (line-end-position))))
4906 (org-with-limited-levels
4907 (save-match-data
4908 ;; Determine if modified area needs to be extended,
4909 ;; according to both previous and current state. We make
4910 ;; a special case for headline editing: if a headline is
4911 ;; modified but not removed, do not extend.
4912 (when (let ((previous-state (aref org-element--cache-status 5))
4913 (sensitive-re
4914 (concat "\\(" org-outline-regexp-bol "\\)" "\\|"
4915 org-element--cache-closing-line "\\|"
4916 org-element--cache-opening-line)))
4917 (cond ((eq previous-state 'other))
4918 ((not (re-search-forward sensitive-re bottom t))
4919 (eq previous-state 'headline))
4920 ((match-beginning 1)
4921 (or (not (eq previous-state 'headline))
4922 (and (progn (goto-char bottom)
4923 (re-search-backward
4924 sensitive-re (match-end 1) t))
4925 (not (match-beginning 1)))))
4926 (t)))
4927 ;; Effectively extend modified area.
4928 (setq top (progn (goto-char top)
4929 (outline-previous-heading)
4930 ;; Headline above is inclusive.
4931 (point)))
4932 (setq bottom (progn (goto-char bottom)
4933 (outline-next-heading)
4934 ;; Headline below is exclusive.
4935 (if (eobp) (point) (1- (point))))))))
4936 ;; Store changes.
4937 (let ((offset (- end beg pre)))
4938 (if (not (org-element--cache-pending-changes-p))
4939 ;; No pending changes. Store the new ones.
4940 (org-element--cache-push-change top (- bottom offset) offset)
4941 (let* ((current-start (aref org-element--cache-status 1))
4942 (current-end (+ (aref org-element--cache-status 2)
4943 (aref org-element--cache-status 3)))
4944 (gap (max (- beg current-end) (- current-start end))))
4945 (if (> gap org-element--cache-merge-changes-threshold)
4946 ;; If we cannot merge two change sets (i.e. they
4947 ;; modify distinct buffer parts) first apply current
4948 ;; change set and store new one. This way, there is
4949 ;; never more than one pending change set, which
4950 ;; avoids handling costly merges.
4951 (progn (org-element--cache-sync (current-buffer))
4952 (org-element--cache-push-change
4953 top (- bottom offset) offset))
4954 ;; Change sets can be merged. We can expand the area
4955 ;; that requires an update, and postpone the sync.
4956 (timer-activate-when-idle (aref org-element--cache-status 4) t)
4957 (aset org-element--cache-status 0 t)
4958 (aset org-element--cache-status 1 (min top current-start))
4959 (aset org-element--cache-status 2
4960 (- (max current-end bottom) offset))
4961 (incf (aref org-element--cache-status 3) offset))))))))))
4963 (defun org-element--cache-sync (buffer)
4964 "Synchronize cache with recent modification in BUFFER.
4965 Elements ending before modification area are kept in cache.
4966 Elements starting after modification area have their position
4967 shifted by the size of the modification. Every other element is
4968 removed from the cache."
4969 (when (buffer-live-p buffer)
4970 (with-current-buffer buffer
4971 (when (org-element--cache-pending-changes-p)
4972 (let ((inhibit-quit t)
4973 (beg (aref org-element--cache-status 1))
4974 (end (aref org-element--cache-status 2))
4975 (offset (aref org-element--cache-status 3))
4976 new-keys)
4977 (maphash
4978 #'(lambda (key value)
4979 (cond
4980 ((memq key new-keys))
4981 ((> key end)
4982 ;; Shift every element starting after END by OFFSET.
4983 ;; We also need to shift keys, since they refer to
4984 ;; buffer positions.
4986 ;; Upon shifting a key a conflict can occur if the
4987 ;; shifted key also refers to some element in the
4988 ;; cache. In this case, we temporarily associate
4989 ;; both elements, as a cons cell, to the shifted key,
4990 ;; following the pattern (SHIFTED . CURRENT).
4992 ;; Such a conflict can only occur if shifted key hash
4993 ;; hasn't been processed by `maphash' yet.
4994 (unless (zerop offset)
4995 (let* ((conflictp (consp (caar value)))
4996 (value-to-shift (if conflictp (cdr value) value)))
4997 ;; Shift element part.
4998 (org-element--cache-shift-positions (car value-to-shift) offset)
4999 ;; Shift objects part.
5000 (dolist (object-data (cdr value-to-shift))
5001 (incf (car object-data) offset)
5002 (dolist (successor (nth 1 object-data))
5003 (incf (cdr successor) offset))
5004 (dolist (object (cddr object-data))
5005 (org-element--cache-shift-positions object offset)))
5006 ;; Shift key-value pair.
5007 (let* ((new-key (+ key offset))
5008 (new-value (gethash new-key org-element--cache)))
5009 ;; Put new value to shifted key.
5011 ;; If one already exists, do not overwrite it:
5012 ;; store it as the car of a cons cell instead,
5013 ;; and handle it when `maphash' reaches
5014 ;; NEW-KEY.
5016 ;; If there is no element stored at NEW-KEY or
5017 ;; if NEW-KEY is going to be removed anyway
5018 ;; (i.e., it is before END), just store new
5019 ;; value there and make sure it will not be
5020 ;; processed again by storing NEW-KEY in
5021 ;; NEW-KEYS.
5022 (puthash new-key
5023 (if (and new-value (> new-key end))
5024 (cons value-to-shift new-value)
5025 (push new-key new-keys)
5026 value-to-shift)
5027 org-element--cache)
5028 ;; If current value contains two elements, car
5029 ;; should be the new value, since cdr has been
5030 ;; shifted already.
5031 (if conflictp
5032 (puthash key (car value) org-element--cache)
5033 (remhash key org-element--cache))))))
5034 ;; Remove every element between BEG and END, since
5035 ;; this is where changes happened.
5036 ((>= key beg) (remhash key org-element--cache))
5037 ;; Preserve any element ending before BEG. If it
5038 ;; overlaps the BEG-END area, remove it.
5040 (let ((element (car value)))
5041 (if (>= (org-element-property :end element) beg)
5042 (remhash key org-element--cache)
5043 ;; Special case: footnote definitions and plain
5044 ;; lists can end with blank lines. Modifying
5045 ;; those can also alter last element inside. We
5046 ;; must therefore remove them from cache.
5047 (let ((parent (org-element-property :parent element)))
5048 (when (and parent (eq (org-element-type parent) 'item))
5049 (setq parent (org-element-property :parent parent)))
5050 (when (and (memq (org-element-type parent)
5051 '(footnote-definition plain-list))
5052 (>= (org-element-property :end parent) beg)
5053 (= (org-element-property :contents-end parent)
5054 (org-element-property :end element)))
5055 (remhash key org-element--cache))))))))
5056 org-element--cache)
5057 ;; Signal cache as up-to-date.
5058 (org-element--cache-cancel-changes))))))
5060 ;;;###autoload
5061 (defun org-element-at-point ()
5062 "Determine closest element around point.
5064 Return value is a list like (TYPE PROPS) where TYPE is the type
5065 of the element and PROPS a plist of properties associated to the
5066 element.
5068 Possible types are defined in `org-element-all-elements'.
5069 Properties depend on element or object type, but always include
5070 `:begin', `:end', `:parent' and `:post-blank' properties.
5072 As a special case, if point is at the very beginning of a list or
5073 sub-list, returned element will be that list instead of the first
5074 item. In the same way, if point is at the beginning of the first
5075 row of a table, returned element will be the table instead of the
5076 first row."
5077 (org-with-wide-buffer
5078 (let ((origin (point)) element parent end)
5079 (end-of-line)
5080 (skip-chars-backward " \r\t\n")
5081 (cond
5082 ((bobp) nil)
5083 ((org-with-limited-levels (org-at-heading-p))
5084 (beginning-of-line)
5085 (or (org-element-cache-get (point) 'element)
5086 (car (org-element-cache-put
5087 (point)
5088 (list (org-element-headline-parser (point-max) t))))))
5090 (catch 'loop
5091 (when org-element-use-cache
5092 ;; Opportunistic shortcut. Instead of going back to
5093 ;; headline above (or beginning of buffer) and descending
5094 ;; again, first try to find a known element above current
5095 ;; position. Give up after 3 tries or when we hit
5096 ;; a headline (or beginning of buffer).
5097 (beginning-of-line)
5098 (skip-chars-backward " \r\t\n")
5099 (dotimes (i 3)
5100 (unless (re-search-backward org-element-paragraph-separate nil t)
5101 (throw 'loop (goto-char (point-min))))
5102 (cond ((not (org-string-match-p "\\S-" (match-string 0)))
5103 (when (bobp) (throw 'loop nil))
5104 ;; An element cannot start at a headline, so check
5105 ;; first non-blank line below.
5106 (skip-chars-forward " \r\t\n" origin)
5107 (beginning-of-line))
5108 ((org-looking-at-p org-element--affiliated-re)
5109 ;; At an affiliated keyword, make sure to move to
5110 ;; the first one.
5111 (if (re-search-backward "^[ \t]*[^#]" nil t)
5112 (forward-line)
5113 (throw 'loop (goto-char (point-min)))))
5114 ((org-looking-at-p "^[ \t]*:\\(?: \\|$\\)")
5115 ;; At a fixed width area or a property drawer, reach
5116 ;; the beginning of the element.
5117 (if (re-search-backward "^[ \t]*[^:]" nil t)
5118 (forward-line)
5119 (throw 'loop (goto-char (point-min))))))
5120 (when (org-with-limited-levels (org-at-heading-p))
5121 ;; Tough luck: we're back at a headline above. Move to
5122 ;; beginning of section.
5123 (forward-line)
5124 (skip-chars-forward " \r\t\n")
5125 (beginning-of-line)
5126 (throw 'loop nil))
5127 (let ((cached (org-element-cache-get (point) 'element)))
5128 ;; Search successful: we know an element before point
5129 ;; which is not an headline. If it has a common
5130 ;; ancestor with ORIGIN, set this ancestor as the
5131 ;; current parent and the element as the one to check.
5132 ;; Otherwise, move at top level and start parsing right
5133 ;; after its broader ancestor.
5134 (when cached
5135 (let ((cache-end (org-element-property :end cached)))
5136 (if (or (> cache-end origin)
5137 (and (= cache-end origin) (= (point-max) origin)))
5138 (setq element cached
5139 parent (org-element-property :parent cached)
5140 end cache-end)
5141 (goto-char cache-end)
5142 (let ((up cached))
5143 (while (and (setq up (org-element-property :parent up))
5144 (<= (org-element-property :end up) origin))
5145 (goto-char (org-element-property :end up)))
5146 (when up
5147 (setq element up
5148 parent (org-element-property :parent up)
5149 end (org-element-property :end up))))))
5150 (throw 'loop nil)))))
5151 ;; Opportunistic search failed. Move back to beginning of
5152 ;; section in current headline, if any, or to first non-empty
5153 ;; line in buffer otherwise.
5154 (org-with-limited-levels (outline-previous-heading))
5155 (unless (bobp) (forward-line))
5156 (skip-chars-forward " \r\t\n")
5157 (beginning-of-line))
5158 ;; Now we are at the beginning of an element, start parsing.
5159 (unless end
5160 (save-excursion (org-with-limited-levels (outline-next-heading))
5161 (setq end (point))))
5162 (let (type special-flag struct)
5163 ;; Parse successively each element, skipping those ending
5164 ;; before original position.
5165 (catch 'exit
5166 (while t
5167 (unless element
5168 (setq element
5169 (let* ((pos (if (and (memq special-flag '(item table-row))
5170 (memq type '(plain-list table)))
5171 ;; First item (resp. row) in
5172 ;; plain list (resp. table) gets
5173 ;; a special key in cache.
5174 (1+ (point))
5175 (point)))
5176 (cached (org-element-cache-get pos 'element)))
5177 (cond
5178 ((not cached)
5179 (let ((element (org-element--current-element
5180 end 'element special-flag struct)))
5181 (when (derived-mode-p 'org-mode)
5182 (org-element-cache-put pos (cons element nil)))
5183 (org-element-put-property element :parent parent)))
5184 ;; When changes happened in the middle of
5185 ;; a list, its structure ends up being
5186 ;; invalid. Therefore, we make sure to use
5187 ;; a valid one.
5188 ((and struct (memq (org-element-type cached)
5189 '(item plain-list)))
5190 (org-element-put-property cached :structure struct))
5191 (t cached)))))
5192 (setq type (org-element-type element))
5193 (cond
5194 ;; 1. Skip any element ending before point. Also skip
5195 ;; element ending at point when we're sure that
5196 ;; another element has started.
5197 ((let ((elem-end (org-element-property :end element)))
5198 (when (or (< elem-end origin)
5199 (and (= elem-end origin) (/= elem-end end)))
5200 (goto-char elem-end)))
5201 (setq element nil))
5202 ;; 2. An element containing point is always the element at
5203 ;; point.
5204 ((not (memq type org-element-greater-elements))
5205 (throw 'exit element))
5206 ;; 3. At any other greater element type, if point is
5207 ;; within contents, move into it.
5209 (let ((cbeg (org-element-property :contents-begin element))
5210 (cend (org-element-property :contents-end element)))
5211 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
5212 ;; Create an anchor for tables and plain
5213 ;; lists: when point is at the very beginning
5214 ;; of these elements, ignoring affiliated
5215 ;; keywords, target them instead of their
5216 ;; contents.
5217 (and (= cbeg origin) (memq type '(plain-list table)))
5218 ;; When point is at contents end, do not move
5219 ;; into elements with an explicit ending, but
5220 ;; return that element instead.
5221 (and (= cend origin)
5222 (or (memq type
5223 '(center-block
5224 drawer dynamic-block inlinetask
5225 property-drawer quote-block
5226 special-block))
5227 ;; Corner case: if a list ends at
5228 ;; the end of a buffer without
5229 ;; a final new line, return last
5230 ;; element in last item instead.
5231 (and (memq type '(item plain-list))
5232 (progn (goto-char cend)
5233 (or (bolp) (not (eobp))))))))
5234 (throw 'exit element)
5235 (case type
5236 (plain-list
5237 (setq special-flag 'item
5238 struct (org-element-property :structure element)))
5239 (item (setq special-flag nil))
5240 (property-drawer
5241 (setq special-flag 'node-property struct nil))
5242 (table (setq special-flag 'table-row struct nil))
5243 (otherwise (setq special-flag nil struct nil)))
5244 (setq parent element element nil end cend)
5245 (goto-char cbeg)))))))))))))
5247 ;;;###autoload
5248 (defun org-element-context (&optional element)
5249 "Return closest element or object around point.
5251 Return value is a list like (TYPE PROPS) where TYPE is the type
5252 of the element or object and PROPS a plist of properties
5253 associated to it.
5255 Possible types are defined in `org-element-all-elements' and
5256 `org-element-all-objects'. Properties depend on element or
5257 object type, but always include `:begin', `:end', `:parent' and
5258 `:post-blank'.
5260 Optional argument ELEMENT, when non-nil, is the closest element
5261 containing point, as returned by `org-element-at-point'.
5262 Providing it allows for quicker computation."
5263 (catch 'objects-forbidden
5264 (org-with-wide-buffer
5265 (let* ((origin (point))
5266 (element (or element (org-element-at-point)))
5267 (type (org-element-type element)))
5268 ;; If point is inside an element containing objects or
5269 ;; a secondary string, narrow buffer to the container and
5270 ;; proceed with parsing. Otherwise, return ELEMENT.
5271 (cond
5272 ;; At a parsed affiliated keyword, check if we're inside main
5273 ;; or dual value.
5274 ((let ((post (org-element-property :post-affiliated element)))
5275 (and post (< origin post)))
5276 (beginning-of-line)
5277 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5278 (cond
5279 ((not (member-ignore-case (match-string 1)
5280 org-element-parsed-keywords))
5281 (throw 'objects-forbidden element))
5282 ((< (match-end 0) origin)
5283 (narrow-to-region (match-end 0) (line-end-position)))
5284 ((and (match-beginning 2)
5285 (>= origin (match-beginning 2))
5286 (< origin (match-end 2)))
5287 (narrow-to-region (match-beginning 2) (match-end 2)))
5288 (t (throw 'objects-forbidden element)))
5289 ;; Also change type to retrieve correct restrictions.
5290 (setq type 'keyword))
5291 ;; At an item, objects can only be located within tag, if any.
5292 ((eq type 'item)
5293 (let ((tag (org-element-property :tag element)))
5294 (if (not tag) (throw 'objects-forbidden element)
5295 (beginning-of-line)
5296 (search-forward tag (line-end-position))
5297 (goto-char (match-beginning 0))
5298 (if (and (>= origin (point)) (< origin (match-end 0)))
5299 (narrow-to-region (point) (match-end 0))
5300 (throw 'objects-forbidden element)))))
5301 ;; At an headline or inlinetask, objects are in title.
5302 ((memq type '(headline inlinetask))
5303 (goto-char (org-element-property :begin element))
5304 (skip-chars-forward "* ")
5305 (if (and (>= origin (point)) (< origin (line-end-position)))
5306 (narrow-to-region (point) (line-end-position))
5307 (throw 'objects-forbidden element)))
5308 ;; At a paragraph, a table-row or a verse block, objects are
5309 ;; located within their contents.
5310 ((memq type '(paragraph table-row verse-block))
5311 (let ((cbeg (org-element-property :contents-begin element))
5312 (cend (org-element-property :contents-end element)))
5313 ;; CBEG is nil for table rules.
5314 (if (and cbeg cend (>= origin cbeg) (< origin cend))
5315 (narrow-to-region cbeg cend)
5316 (throw 'objects-forbidden element))))
5317 ;; At a parsed keyword, objects are located within value.
5318 ((eq type 'keyword)
5319 (if (not (member (org-element-property :key element)
5320 org-element-document-properties))
5321 (throw 'objects-forbidden element)
5322 (beginning-of-line)
5323 (search-forward ":")
5324 (if (and (>= origin (point)) (< origin (line-end-position)))
5325 (narrow-to-region (point) (line-end-position))
5326 (throw 'objects-forbidden element))))
5327 ;; All other locations cannot contain objects: bail out.
5328 (t (throw 'objects-forbidden element)))
5329 (goto-char (point-min))
5330 (let* ((restriction (org-element-restriction type))
5331 (parent element)
5332 (candidates 'initial)
5333 (cache-key (org-element--cache-get-key element))
5334 (cache (org-element-cache-get cache-key 'objects))
5335 objects-data next update-cache-flag)
5336 (prog1
5337 (catch 'exit
5338 (while t
5339 ;; Get list of next object candidates in CANDIDATES.
5340 ;; When entering for the first time PARENT, grab it
5341 ;; from cache, if available, or compute it. Then,
5342 ;; for each subsequent iteration in PARENT, always
5343 ;; compute it since we're beyond cache anyway.
5344 (when (and (not next) org-element-use-cache)
5345 (let ((data (assq (point) cache)))
5346 (if data (setq candidates (nth 1 (setq objects-data data)))
5347 (push (setq objects-data (list (point) 'initial))
5348 cache))))
5349 (when (or next (eq 'initial candidates))
5350 (setq candidates
5351 (org-element--get-next-object-candidates
5352 restriction candidates))
5353 (when org-element-use-cache
5354 (setcar (cdr objects-data) candidates)
5355 (or update-cache-flag (setq update-cache-flag t))))
5356 ;; Compare ORIGIN with next object starting position,
5357 ;; if any.
5359 ;; If ORIGIN is lesser or if there is no object
5360 ;; following, look for a previous object that might
5361 ;; contain it in cache. If there is no cache, we
5362 ;; didn't miss any object so simply return PARENT.
5364 ;; If ORIGIN is greater or equal, parse next
5365 ;; candidate for further processing.
5366 (let ((closest
5367 (and candidates
5368 (rassq (apply #'min (mapcar #'cdr candidates))
5369 candidates))))
5370 (if (or (not closest) (> (cdr closest) origin))
5371 (catch 'found
5372 (dolist (obj (cddr objects-data) (throw 'exit parent))
5373 (when (<= (org-element-property :begin obj) origin)
5374 (if (<= (org-element-property :end obj) origin)
5375 ;; Object ends before ORIGIN and we
5376 ;; know next one in cache starts
5377 ;; after it: bail out.
5378 (throw 'exit parent)
5379 (throw 'found (setq next obj))))))
5380 (goto-char (cdr closest))
5381 (setq next
5382 (funcall (intern (format "org-element-%s-parser"
5383 (car closest)))))
5384 (when org-element-use-cache
5385 (push next (cddr objects-data))
5386 (or update-cache-flag (setq update-cache-flag t)))))
5387 ;; Process NEXT to know if we need to skip it, return
5388 ;; it or move into it.
5389 (let ((cbeg (org-element-property :contents-begin next))
5390 (cend (org-element-property :contents-end next))
5391 (obj-end (org-element-property :end next)))
5392 (cond
5393 ;; ORIGIN is after NEXT, so skip it.
5394 ((<= obj-end origin) (goto-char obj-end))
5395 ;; ORIGIN is within a non-recursive next or
5396 ;; at an object boundaries: Return that object.
5397 ((or (not cbeg) (< origin cbeg) (>= origin cend))
5398 (throw 'exit
5399 (org-element-put-property next :parent parent)))
5400 ;; Otherwise, move into NEXT and reset flags as we
5401 ;; shift parent.
5402 (t (goto-char cbeg)
5403 (narrow-to-region (point) cend)
5404 (org-element-put-property next :parent parent)
5405 (setq parent next
5406 restriction (org-element-restriction next)
5407 next nil
5408 objects-data nil
5409 candidates 'initial))))))
5410 ;; Update cache if required.
5411 (when (and update-cache-flag (derived-mode-p 'org-mode))
5412 (org-element-cache-put cache-key (cons element cache)))))))))
5414 (defun org-element-nested-p (elem-A elem-B)
5415 "Non-nil when elements ELEM-A and ELEM-B are nested."
5416 (let ((beg-A (org-element-property :begin elem-A))
5417 (beg-B (org-element-property :begin elem-B))
5418 (end-A (org-element-property :end elem-A))
5419 (end-B (org-element-property :end elem-B)))
5420 (or (and (>= beg-A beg-B) (<= end-A end-B))
5421 (and (>= beg-B beg-A) (<= end-B end-A)))))
5423 (defun org-element-swap-A-B (elem-A elem-B)
5424 "Swap elements ELEM-A and ELEM-B.
5425 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5426 end of ELEM-A."
5427 (goto-char (org-element-property :begin elem-A))
5428 ;; There are two special cases when an element doesn't start at bol:
5429 ;; the first paragraph in an item or in a footnote definition.
5430 (let ((specialp (not (bolp))))
5431 ;; Only a paragraph without any affiliated keyword can be moved at
5432 ;; ELEM-A position in such a situation. Note that the case of
5433 ;; a footnote definition is impossible: it cannot contain two
5434 ;; paragraphs in a row because it cannot contain a blank line.
5435 (if (and specialp
5436 (or (not (eq (org-element-type elem-B) 'paragraph))
5437 (/= (org-element-property :begin elem-B)
5438 (org-element-property :contents-begin elem-B))))
5439 (error "Cannot swap elements"))
5440 ;; In a special situation, ELEM-A will have no indentation. We'll
5441 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5442 (let* ((ind-B (when specialp
5443 (goto-char (org-element-property :begin elem-B))
5444 (org-get-indentation)))
5445 (beg-A (org-element-property :begin elem-A))
5446 (end-A (save-excursion
5447 (goto-char (org-element-property :end elem-A))
5448 (skip-chars-backward " \r\t\n")
5449 (point-at-eol)))
5450 (beg-B (org-element-property :begin elem-B))
5451 (end-B (save-excursion
5452 (goto-char (org-element-property :end elem-B))
5453 (skip-chars-backward " \r\t\n")
5454 (point-at-eol)))
5455 ;; Store overlays responsible for visibility status. We
5456 ;; also need to store their boundaries as they will be
5457 ;; removed from buffer.
5458 (overlays
5459 (cons
5460 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5461 (overlays-in beg-A end-A))
5462 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5463 (overlays-in beg-B end-B))))
5464 ;; Get contents.
5465 (body-A (buffer-substring beg-A end-A))
5466 (body-B (delete-and-extract-region beg-B end-B)))
5467 (goto-char beg-B)
5468 (when specialp
5469 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5470 (org-indent-to-column ind-B))
5471 (insert body-A)
5472 ;; Restore ex ELEM-A overlays.
5473 (let ((offset (- beg-B beg-A)))
5474 (mapc (lambda (ov)
5475 (move-overlay
5476 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5477 (car overlays))
5478 (goto-char beg-A)
5479 (delete-region beg-A end-A)
5480 (insert body-B)
5481 ;; Restore ex ELEM-B overlays.
5482 (mapc (lambda (ov)
5483 (move-overlay
5484 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5485 (cdr overlays)))
5486 (goto-char (org-element-property :end elem-B)))))
5488 (defun org-element-remove-indentation (s &optional n)
5489 "Remove maximum common indentation in string S and return it.
5490 When optional argument N is a positive integer, remove exactly
5491 that much characters from indentation, if possible, or return
5492 S as-is otherwise. Unlike to `org-remove-indentation', this
5493 function doesn't call `untabify' on S."
5494 (catch 'exit
5495 (with-temp-buffer
5496 (insert s)
5497 (goto-char (point-min))
5498 ;; Find maximum common indentation, if not specified.
5499 (setq n (or n
5500 (let ((min-ind (point-max)))
5501 (save-excursion
5502 (while (re-search-forward "^[ \t]*\\S-" nil t)
5503 (let ((ind (1- (current-column))))
5504 (if (zerop ind) (throw 'exit s)
5505 (setq min-ind (min min-ind ind))))))
5506 min-ind)))
5507 (if (zerop n) s
5508 ;; Remove exactly N indentation, but give up if not possible.
5509 (while (not (eobp))
5510 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5511 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5512 ((< ind n) (throw 'exit s))
5513 (t (org-indent-line-to (- ind n))))
5514 (forward-line)))
5515 (buffer-string)))))
5518 (provide 'org-element)
5520 ;; Local variables:
5521 ;; generated-autoload-file: "org-loaddefs.el"
5522 ;; End:
5524 ;;; org-element.el ends here