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