95b775060debeabad768c09adf9c43f20a16dd69
[org-mode.git] / lisp / org-element.el
blob95b775060debeabad768c09adf9c43f20a16dd69
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'.
117 ;;; Code:
119 (eval-when-compile (require 'cl))
120 (require 'org)
124 ;;; Definitions And Rules
126 ;; Define elements, greater elements and specify recursive objects,
127 ;; along with the affiliated keywords recognized. Also set up
128 ;; restrictions on recursive objects combinations.
130 ;; These variables really act as a control center for the parsing
131 ;; process.
133 (defconst org-element-paragraph-separate
134 (concat "^\\(?:"
135 ;; Headlines, inlinetasks.
136 org-outline-regexp "\\|"
137 ;; Footnote definitions.
138 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
139 ;; Diary sexps.
140 "%%(" "\\|"
141 "[ \t]*\\(?:"
142 ;; Empty lines.
143 "$" "\\|"
144 ;; Tables (any type).
145 "\\(?:|\\|\\+-[-+]\\)" "\\|"
146 ;; Blocks (any type), Babel calls, drawers (any type),
147 ;; fixed-width areas and keywords. Note: this is only an
148 ;; indication and need some thorough check.
149 "[#:]" "\\|"
150 ;; Horizontal rules.
151 "-\\{5,\\}[ \t]*$" "\\|"
152 ;; LaTeX environments.
153 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
154 ;; Planning and Clock lines.
155 (regexp-opt (list org-scheduled-string
156 org-deadline-string
157 org-closed-string
158 org-clock-string))
159 "\\|"
160 ;; Lists.
161 (let ((term (case org-plain-list-ordered-item-terminator
162 (?\) ")") (?. "\\.") (otherwise "[.)]")))
163 (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
164 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
165 "\\(?:[ \t]\\|$\\)"))
166 "\\)\\)")
167 "Regexp to separate paragraphs in an Org buffer.
168 In the case of lines starting with \"#\" and \":\", this regexp
169 is not sufficient to know if point is at a paragraph ending. See
170 `org-element-paragraph-parser' for more information.")
172 (defconst org-element-all-elements
173 '(babel-call center-block clock comment comment-block diary-sexp drawer
174 dynamic-block example-block export-block fixed-width
175 footnote-definition headline horizontal-rule inlinetask item
176 keyword latex-environment node-property paragraph plain-list
177 planning property-drawer quote-block quote-section section
178 special-block src-block table table-row verse-block)
179 "Complete list of element types.")
181 (defconst org-element-greater-elements
182 '(center-block drawer dynamic-block footnote-definition headline inlinetask
183 item plain-list property-drawer quote-block section
184 special-block table)
185 "List of recursive element types aka Greater Elements.")
187 (defconst org-element-all-successors
188 '(export-snippet footnote-reference inline-babel-call inline-src-block
189 latex-or-entity line-break link macro plain-link radio-target
190 statistics-cookie sub/superscript table-cell target
191 text-markup timestamp)
192 "Complete list of successors.")
194 (defconst org-element-object-successor-alist
195 '((subscript . sub/superscript) (superscript . sub/superscript)
196 (bold . text-markup) (code . text-markup) (italic . text-markup)
197 (strike-through . text-markup) (underline . text-markup)
198 (verbatim . text-markup) (entity . latex-or-entity)
199 (latex-fragment . latex-or-entity))
200 "Alist of translations between object type and successor name.
201 Sharing the same successor comes handy when, for example, the
202 regexp matching one object can also match the other object.")
204 (defconst org-element-all-objects
205 '(bold code entity export-snippet footnote-reference inline-babel-call
206 inline-src-block italic line-break latex-fragment link macro
207 radio-target statistics-cookie strike-through subscript superscript
208 table-cell target timestamp underline verbatim)
209 "Complete list of object types.")
211 (defconst org-element-recursive-objects
212 '(bold italic link subscript radio-target strike-through superscript
213 table-cell underline)
214 "List of recursive object types.")
216 (defvar org-element-block-name-alist
217 '(("CENTER" . org-element-center-block-parser)
218 ("COMMENT" . org-element-comment-block-parser)
219 ("EXAMPLE" . org-element-example-block-parser)
220 ("QUOTE" . org-element-quote-block-parser)
221 ("SRC" . org-element-src-block-parser)
222 ("VERSE" . org-element-verse-block-parser))
223 "Alist between block names and the associated parsing function.
224 Names must be uppercase. Any block whose name has no association
225 is parsed with `org-element-special-block-parser'.")
227 (defconst org-element-link-type-is-file
228 '("file" "file+emacs" "file+sys" "docview")
229 "List of link types equivalent to \"file\".
230 Only these types can accept search options and an explicit
231 application to open them.")
233 (defconst org-element-affiliated-keywords
234 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
235 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
236 "List of affiliated keywords as strings.
237 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
238 are affiliated keywords and need not to be in this list.")
240 (defconst org-element--affiliated-re
241 (format "[ \t]*#\\+%s:"
242 ;; Regular affiliated keywords.
243 (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
244 (regexp-opt org-element-affiliated-keywords)))
245 "Regexp matching any affiliated keyword.
247 Keyword name is put in match group 1. Moreover, if keyword
248 belongs to `org-element-dual-keywords', put the dual value in
249 match group 2.
251 Don't modify it, set `org-element-affiliated-keywords' instead.")
253 (defconst org-element-keyword-translation-alist
254 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
255 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
256 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
257 "Alist of usual translations for keywords.
258 The key is the old name and the value the new one. The property
259 holding their value will be named after the translated name.")
261 (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
262 "List of affiliated keywords that can occur more than once in an element.
264 Their value will be consed into a list of strings, which will be
265 returned as the value of the property.
267 This list is checked after translations have been applied. See
268 `org-element-keyword-translation-alist'.
270 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
271 allow multiple occurrences and need not to be in this list.")
273 (defconst org-element-parsed-keywords '("CAPTION")
274 "List of affiliated keywords whose value can be parsed.
276 Their value will be stored as a secondary string: a list of
277 strings and objects.
279 This list is checked after translations have been applied. See
280 `org-element-keyword-translation-alist'.")
282 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
283 "List of affiliated keywords which can have a secondary value.
285 In Org syntax, they can be written with optional square brackets
286 before the colons. For example, RESULTS keyword can be
287 associated to a hash value with the following:
289 #+RESULTS[hash-string]: some-source
291 This list is checked after translations have been applied. See
292 `org-element-keyword-translation-alist'.")
294 (defconst org-element-document-properties '("AUTHOR" "DATE" "TITLE")
295 "List of properties associated to the whole document.
296 Any keyword in this list will have its value parsed and stored as
297 a secondary string.")
299 (defconst org-element-object-restrictions
300 (let* ((standard-set
301 (remq 'plain-link (remq 'table-cell org-element-all-successors)))
302 (standard-set-no-line-break (remq 'line-break standard-set)))
303 `((bold ,@standard-set)
304 (footnote-reference ,@standard-set)
305 (headline ,@standard-set-no-line-break)
306 (inlinetask ,@standard-set-no-line-break)
307 (italic ,@standard-set)
308 (item ,@standard-set-no-line-break)
309 (keyword ,@standard-set)
310 ;; Ignore all links excepted plain links in a link description.
311 ;; Also ignore radio-targets and line breaks.
312 (link export-snippet inline-babel-call inline-src-block latex-or-entity
313 macro plain-link statistics-cookie sub/superscript text-markup)
314 (paragraph ,@standard-set)
315 ;; Remove any variable object from radio target as it would
316 ;; prevent it from being properly recognized.
317 (radio-target latex-or-entity sub/superscript)
318 (strike-through ,@standard-set)
319 (subscript ,@standard-set)
320 (superscript ,@standard-set)
321 ;; Ignore inline babel call and inline src block as formulas are
322 ;; possible. Also ignore line breaks and statistics cookies.
323 (table-cell export-snippet footnote-reference latex-or-entity link macro
324 radio-target sub/superscript target text-markup timestamp)
325 (table-row table-cell)
326 (underline ,@standard-set)
327 (verse-block ,@standard-set)))
328 "Alist of objects restrictions.
330 CAR is an element or object type containing objects and CDR is
331 a list of successors that will be called within an element or
332 object of such type.
334 For example, in a `radio-target' object, one can only find
335 entities, latex-fragments, subscript and superscript.
337 This alist also applies to secondary string. For example, an
338 `headline' type element doesn't directly contain objects, but
339 still has an entry since one of its properties (`:title') does.")
341 (defconst org-element-secondary-value-alist
342 '((headline . :title)
343 (inlinetask . :title)
344 (item . :tag)
345 (footnote-reference . :inline-definition))
346 "Alist between element types and location of secondary value.")
348 (defconst org-element-object-variables '(org-link-abbrev-alist-local)
349 "List of buffer-local variables used when parsing objects.
350 These variables are copied to the temporary buffer created by
351 `org-export-secondary-string'.")
355 ;;; Accessors and Setters
357 ;; Provide four accessors: `org-element-type', `org-element-property'
358 ;; `org-element-contents' and `org-element-restriction'.
360 ;; Setter functions allow to modify elements by side effect. There is
361 ;; `org-element-put-property', `org-element-set-contents',
362 ;; `org-element-set-element' and `org-element-adopt-element'. Note
363 ;; that `org-element-set-element' and `org-element-adopt-elements' are
364 ;; higher level functions since also update `:parent' property.
366 (defsubst org-element-type (element)
367 "Return type of ELEMENT.
369 The function returns the type of the element or object provided.
370 It can also return the following special value:
371 `plain-text' for a string
372 `org-data' for a complete document
373 nil in any other case."
374 (cond
375 ((not (consp element)) (and (stringp element) 'plain-text))
376 ((symbolp (car element)) (car element))))
378 (defsubst org-element-property (property element)
379 "Extract the value from the PROPERTY of an ELEMENT."
380 (if (stringp element) (get-text-property 0 property element)
381 (plist-get (nth 1 element) property)))
383 (defsubst org-element-contents (element)
384 "Extract contents from an ELEMENT."
385 (cond ((not (consp element)) nil)
386 ((symbolp (car element)) (nthcdr 2 element))
387 (t element)))
389 (defsubst org-element-restriction (element)
390 "Return restriction associated to ELEMENT.
391 ELEMENT can be an element, an object or a symbol representing an
392 element or object type."
393 (cdr (assq (if (symbolp element) element (org-element-type element))
394 org-element-object-restrictions)))
396 (defsubst org-element-put-property (element property value)
397 "In ELEMENT set PROPERTY to VALUE.
398 Return modified element."
399 (if (stringp element) (org-add-props element nil property value)
400 (setcar (cdr element) (plist-put (nth 1 element) property value))
401 element))
403 (defsubst org-element-set-contents (element &rest contents)
404 "Set ELEMENT contents to CONTENTS.
405 Return modified element."
406 (cond ((not element) (list contents))
407 ((not (symbolp (car element))) contents)
408 ((cdr element) (setcdr (cdr element) contents))
409 (t (nconc element contents))))
411 (defsubst org-element-set-element (old new)
412 "Replace element or object OLD with element or object NEW.
413 The function takes care of setting `:parent' property for NEW."
414 ;; Since OLD is going to be changed into NEW by side-effect, first
415 ;; make sure that every element or object within NEW has OLD as
416 ;; parent.
417 (mapc (lambda (blob) (org-element-put-property blob :parent old))
418 (org-element-contents new))
419 ;; Transfer contents.
420 (apply 'org-element-set-contents old (org-element-contents new))
421 ;; Ensure NEW has same parent as OLD, then overwrite OLD properties
422 ;; with NEW's.
423 (org-element-put-property new :parent (org-element-property :parent old))
424 (setcar (cdr old) (nth 1 new))
425 ;; Transfer type.
426 (setcar old (car new)))
428 (defsubst org-element-adopt-elements (parent &rest children)
429 "Append elements to the contents of another element.
431 PARENT is an element or object. CHILDREN can be elements,
432 objects, or a strings.
434 The function takes care of setting `:parent' property for CHILD.
435 Return parent element."
436 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
437 ;; string: parent is the list itself.
438 (mapc (lambda (child)
439 (org-element-put-property child :parent (or parent children)))
440 children)
441 ;; Add CHILDREN at the end of PARENT contents.
442 (when parent
443 (apply 'org-element-set-contents
444 parent
445 (nconc (org-element-contents parent) children)))
446 ;; Return modified PARENT element.
447 (or parent children))
451 ;;; Greater elements
453 ;; For each greater element type, we define a parser and an
454 ;; interpreter.
456 ;; A parser returns the element or object as the list described above.
457 ;; Most of them accepts no argument. Though, exceptions exist. Hence
458 ;; every element containing a secondary string (see
459 ;; `org-element-secondary-value-alist') will accept an optional
460 ;; argument to toggle parsing of that secondary string. Moreover,
461 ;; `item' parser requires current list's structure as its first
462 ;; element.
464 ;; An interpreter accepts two arguments: the list representation of
465 ;; the element or object, and its contents. The latter may be nil,
466 ;; depending on the element or object considered. It returns the
467 ;; appropriate Org syntax, as a string.
469 ;; Parsing functions must follow the naming convention:
470 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
471 ;; defined in `org-element-greater-elements'.
473 ;; Similarly, interpreting functions must follow the naming
474 ;; convention: org-element-TYPE-interpreter.
476 ;; With the exception of `headline' and `item' types, greater elements
477 ;; cannot contain other greater elements of their own type.
479 ;; Beside implementing a parser and an interpreter, adding a new
480 ;; greater element requires to tweak `org-element--current-element'.
481 ;; Moreover, the newly defined type must be added to both
482 ;; `org-element-all-elements' and `org-element-greater-elements'.
485 ;;;; Center Block
487 (defun org-element-center-block-parser (limit affiliated)
488 "Parse a center block.
490 LIMIT bounds the search. AFFILIATED is a list of which CAR is
491 the buffer position at the beginning of the first affiliated
492 keyword and CDR is a plist of affiliated keywords along with
493 their value.
495 Return a list whose CAR is `center-block' and CDR is a plist
496 containing `:begin', `:end', `:contents-begin', `:contents-end',
497 `:post-blank' and `:post-affiliated' keywords.
499 Assume point is at the beginning of the block."
500 (let ((case-fold-search t))
501 (if (not (save-excursion
502 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
503 ;; Incomplete block: parse it as a paragraph.
504 (org-element-paragraph-parser limit affiliated)
505 (let ((block-end-line (match-beginning 0)))
506 (let* ((begin (car affiliated))
507 (post-affiliated (point))
508 ;; Empty blocks have no contents.
509 (contents-begin (progn (forward-line)
510 (and (< (point) block-end-line)
511 (point))))
512 (contents-end (and contents-begin block-end-line))
513 (pos-before-blank (progn (goto-char block-end-line)
514 (forward-line)
515 (point)))
516 (end (save-excursion (skip-chars-forward " \r\t\n" limit)
517 (skip-chars-backward " \t")
518 (if (bolp) (point) (line-end-position)))))
519 (list 'center-block
520 (nconc
521 (list :begin begin
522 :end end
523 :contents-begin contents-begin
524 :contents-end contents-end
525 :post-blank (count-lines pos-before-blank end)
526 :post-affiliated post-affiliated)
527 (cdr affiliated))))))))
529 (defun org-element-center-block-interpreter (center-block contents)
530 "Interpret CENTER-BLOCK element as Org syntax.
531 CONTENTS is the contents of the element."
532 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
535 ;;;; Drawer
537 (defun org-element-drawer-parser (limit affiliated)
538 "Parse a drawer.
540 LIMIT bounds the search. AFFILIATED is a list of which CAR is
541 the buffer position at the beginning of the first affiliated
542 keyword and CDR is a plist of affiliated keywords along with
543 their value.
545 Return a list whose CAR is `drawer' and CDR is a plist containing
546 `:drawer-name', `:begin', `:end', `:contents-begin',
547 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
549 Assume point is at beginning of drawer."
550 (let ((case-fold-search t))
551 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
552 ;; Incomplete drawer: parse it as a paragraph.
553 (org-element-paragraph-parser limit affiliated)
554 (save-excursion
555 (let* ((drawer-end-line (match-beginning 0))
556 (name (progn (looking-at org-drawer-regexp)
557 (org-match-string-no-properties 1)))
558 (begin (car affiliated))
559 (post-affiliated (point))
560 ;; Empty drawers have no contents.
561 (contents-begin (progn (forward-line)
562 (and (< (point) drawer-end-line)
563 (point))))
564 (contents-end (and contents-begin drawer-end-line))
565 (pos-before-blank (progn (goto-char drawer-end-line)
566 (forward-line)
567 (point)))
568 (end (progn (skip-chars-forward " \r\t\n" limit)
569 (skip-chars-backward " \t")
570 (if (bolp) (point) (line-end-position)))))
571 (list 'drawer
572 (nconc
573 (list :begin begin
574 :end end
575 :drawer-name name
576 :contents-begin contents-begin
577 :contents-end contents-end
578 :post-blank (count-lines pos-before-blank end)
579 :post-affiliated post-affiliated)
580 (cdr affiliated))))))))
582 (defun org-element-drawer-interpreter (drawer contents)
583 "Interpret DRAWER element as Org syntax.
584 CONTENTS is the contents of the element."
585 (format ":%s:\n%s:END:"
586 (org-element-property :drawer-name drawer)
587 contents))
590 ;;;; Dynamic Block
592 (defun org-element-dynamic-block-parser (limit affiliated)
593 "Parse a dynamic block.
595 LIMIT bounds the search. AFFILIATED is a list of which CAR is
596 the buffer position at the beginning of the first affiliated
597 keyword and CDR is a plist of affiliated keywords along with
598 their value.
600 Return a list whose CAR is `dynamic-block' and CDR is a plist
601 containing `:block-name', `:begin', `:end', `:contents-begin',
602 `:contents-end', `:arguments', `:post-blank' and
603 `:post-affiliated' keywords.
605 Assume point is at beginning of dynamic block."
606 (let ((case-fold-search t))
607 (if (not (save-excursion
608 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
609 ;; Incomplete block: parse it as a paragraph.
610 (org-element-paragraph-parser limit affiliated)
611 (let ((block-end-line (match-beginning 0)))
612 (save-excursion
613 (let* ((name (progn (looking-at org-dblock-start-re)
614 (org-match-string-no-properties 1)))
615 (arguments (org-match-string-no-properties 3))
616 (begin (car affiliated))
617 (post-affiliated (point))
618 ;; Empty blocks have no contents.
619 (contents-begin (progn (forward-line)
620 (and (< (point) block-end-line)
621 (point))))
622 (contents-end (and contents-begin block-end-line))
623 (pos-before-blank (progn (goto-char block-end-line)
624 (forward-line)
625 (point)))
626 (end (progn (skip-chars-forward " \r\t\n" limit)
627 (skip-chars-backward " \t")
628 (if (bolp) (point) (line-end-position)))))
629 (list 'dynamic-block
630 (nconc
631 (list :begin begin
632 :end end
633 :block-name name
634 :arguments arguments
635 :contents-begin contents-begin
636 :contents-end contents-end
637 :post-blank (count-lines pos-before-blank end)
638 :post-affiliated post-affiliated)
639 (cdr affiliated)))))))))
641 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
642 "Interpret DYNAMIC-BLOCK element as Org syntax.
643 CONTENTS is the contents of the element."
644 (format "#+BEGIN: %s%s\n%s#+END:"
645 (org-element-property :block-name dynamic-block)
646 (let ((args (org-element-property :arguments dynamic-block)))
647 (and args (concat " " args)))
648 contents))
651 ;;;; Footnote Definition
653 (defun org-element-footnote-definition-parser (limit affiliated)
654 "Parse a footnote definition.
656 LIMIT bounds the search. AFFILIATED is a list of which CAR is
657 the buffer position at the beginning of the first affiliated
658 keyword and CDR is a plist of affiliated keywords along with
659 their value.
661 Return a list whose CAR is `footnote-definition' and CDR is
662 a plist containing `:label', `:begin' `:end', `:contents-begin',
663 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
665 Assume point is at the beginning of the footnote definition."
666 (save-excursion
667 (let* ((label (progn (looking-at org-footnote-definition-re)
668 (org-match-string-no-properties 1)))
669 (begin (car affiliated))
670 (post-affiliated (point))
671 (ending (save-excursion
672 (if (progn
673 (end-of-line)
674 (re-search-forward
675 (concat org-outline-regexp-bol "\\|"
676 org-footnote-definition-re "\\|"
677 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
678 (match-beginning 0)
679 (point))))
680 (contents-begin (progn
681 (search-forward "]")
682 (skip-chars-forward " \r\t\n" ending)
683 (cond ((= (point) ending) nil)
684 ((= (line-beginning-position) begin) (point))
685 (t (line-beginning-position)))))
686 (contents-end (and contents-begin ending))
687 (end (progn (goto-char ending)
688 (skip-chars-forward " \r\t\n" limit)
689 (skip-chars-backward " \t")
690 (if (bolp) (point) (line-end-position)))))
691 (list 'footnote-definition
692 (nconc
693 (list :label label
694 :begin begin
695 :end end
696 :contents-begin contents-begin
697 :contents-end contents-end
698 :post-blank (count-lines ending end)
699 :post-affiliated post-affiliated)
700 (cdr affiliated))))))
702 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
703 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
704 CONTENTS is the contents of the footnote-definition."
705 (concat (format "[%s]" (org-element-property :label footnote-definition))
707 contents))
710 ;;;; Headline
712 (defun org-element-headline-parser (limit &optional raw-secondary-p)
713 "Parse a headline.
715 Return a list whose CAR is `headline' and CDR is a plist
716 containing `:raw-value', `:title', `:alt-title', `:begin',
717 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
718 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
719 `:scheduled', `:deadline', `:closed', `:quotedp', `:archivedp',
720 `:commentedp' and `:footnote-section-p' keywords.
722 The plist also contains any property set in the property drawer,
723 with its name in upper cases and colons added at the
724 beginning (i.e. `:CUSTOM_ID').
726 When RAW-SECONDARY-P is non-nil, headline's title will not be
727 parsed as a secondary string, but as a plain string instead.
729 Assume point is at beginning of the headline."
730 (save-excursion
731 (let* ((components (org-heading-components))
732 (level (nth 1 components))
733 (todo (nth 2 components))
734 (todo-type
735 (and todo (if (member todo org-done-keywords) 'done 'todo)))
736 (tags (let ((raw-tags (nth 5 components)))
737 (and raw-tags (org-split-string raw-tags ":"))))
738 (raw-value (or (nth 4 components) ""))
739 (quotedp
740 (let ((case-fold-search nil))
741 (string-match (format "^%s\\( \\|$\\)" org-quote-string)
742 raw-value)))
743 (commentedp
744 (let ((case-fold-search nil))
745 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
746 raw-value)))
747 (archivedp (member org-archive-tag tags))
748 (footnote-section-p (and org-footnote-section
749 (string= org-footnote-section raw-value)))
750 ;; Upcase property names. It avoids confusion between
751 ;; properties obtained through property drawer and default
752 ;; properties from the parser (e.g. `:end' and :END:)
753 (standard-props
754 (let (plist)
755 (mapc
756 (lambda (p)
757 (setq plist
758 (plist-put plist
759 (intern (concat ":" (upcase (car p))))
760 (cdr p))))
761 (org-entry-properties nil 'standard))
762 plist))
763 (time-props
764 ;; Read time properties on the line below the headline.
765 (save-excursion
766 (when (progn (forward-line)
767 (looking-at org-planning-or-clock-line-re))
768 (let ((end (line-end-position)) plist)
769 (while (re-search-forward
770 org-keyword-time-not-clock-regexp end t)
771 (goto-char (match-end 1))
772 (skip-chars-forward " \t")
773 (let ((keyword (match-string 1))
774 (time (org-element-timestamp-parser)))
775 (cond ((equal keyword org-scheduled-string)
776 (setq plist (plist-put plist :scheduled time)))
777 ((equal keyword org-deadline-string)
778 (setq plist (plist-put plist :deadline time)))
779 (t (setq plist (plist-put plist :closed time))))))
780 plist))))
781 (begin (point))
782 (end (save-excursion (goto-char (org-end-of-subtree t t))))
783 (pos-after-head (progn (forward-line) (point)))
784 (contents-begin (save-excursion
785 (skip-chars-forward " \r\t\n" end)
786 (and (/= (point) end) (line-beginning-position))))
787 (contents-end (and contents-begin
788 (progn (goto-char end)
789 (skip-chars-backward " \r\t\n")
790 (forward-line)
791 (point)))))
792 ;; Clean RAW-VALUE from any quote or comment string.
793 (when (or quotedp commentedp)
794 (let ((case-fold-search nil))
795 (setq raw-value
796 (replace-regexp-in-string
797 (concat
798 (regexp-opt (list org-quote-string org-comment-string))
799 "\\(?: \\|$\\)")
801 raw-value))))
802 ;; Clean TAGS from archive tag, if any.
803 (when archivedp (setq tags (delete org-archive-tag tags)))
804 (let ((headline
805 (list 'headline
806 (nconc
807 (list :raw-value raw-value
808 :begin begin
809 :end end
810 :pre-blank
811 (if (not contents-begin) 0
812 (count-lines pos-after-head contents-begin))
813 :contents-begin contents-begin
814 :contents-end contents-end
815 :level level
816 :priority (nth 3 components)
817 :tags tags
818 :todo-keyword todo
819 :todo-type todo-type
820 :post-blank (count-lines
821 (if (not contents-end) pos-after-head
822 (goto-char contents-end)
823 (forward-line)
824 (point))
825 end)
826 :footnote-section-p footnote-section-p
827 :archivedp archivedp
828 :commentedp commentedp
829 :quotedp quotedp)
830 time-props
831 standard-props))))
832 (let ((alt-title (org-element-property :ALT_TITLE headline)))
833 (when alt-title
834 (org-element-put-property
835 headline :alt-title
836 (if raw-secondary-p alt-title
837 (org-element-parse-secondary-string
838 alt-title (org-element-restriction 'headline) headline)))))
839 (org-element-put-property
840 headline :title
841 (if raw-secondary-p raw-value
842 (org-element-parse-secondary-string
843 raw-value (org-element-restriction 'headline) headline)))))))
845 (defun org-element-headline-interpreter (headline contents)
846 "Interpret HEADLINE element as Org syntax.
847 CONTENTS is the contents of the element."
848 (let* ((level (org-element-property :level headline))
849 (todo (org-element-property :todo-keyword headline))
850 (priority (org-element-property :priority headline))
851 (title (org-element-interpret-data
852 (org-element-property :title headline)))
853 (tags (let ((tag-list (if (org-element-property :archivedp headline)
854 (cons org-archive-tag
855 (org-element-property :tags headline))
856 (org-element-property :tags headline))))
857 (and tag-list
858 (format ":%s:" (mapconcat 'identity tag-list ":")))))
859 (commentedp (org-element-property :commentedp headline))
860 (quotedp (org-element-property :quotedp headline))
861 (pre-blank (or (org-element-property :pre-blank headline) 0))
862 (heading (concat (make-string level ?*)
863 (and todo (concat " " todo))
864 (and quotedp (concat " " org-quote-string))
865 (and commentedp (concat " " org-comment-string))
866 (and priority
867 (format " [#%s]" (char-to-string priority)))
868 (cond ((and org-footnote-section
869 (org-element-property
870 :footnote-section-p headline))
871 (concat " " org-footnote-section))
872 (title (concat " " title))))))
873 (concat heading
874 ;; Align tags.
875 (when tags
876 (cond
877 ((zerop org-tags-column) (format " %s" tags))
878 ((< org-tags-column 0)
879 (concat
880 (make-string
881 (max (- (+ org-tags-column (length heading) (length tags))) 1)
883 tags))
885 (concat
886 (make-string (max (- org-tags-column (length heading)) 1) ? )
887 tags))))
888 (make-string (1+ pre-blank) 10)
889 contents)))
892 ;;;; Inlinetask
894 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
895 "Parse an inline task.
897 Return a list whose CAR is `inlinetask' and CDR is a plist
898 containing `:title', `:begin', `:end', `:contents-begin' and
899 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
900 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
901 `:closed' and `:post-blank' keywords.
903 The plist also contains any property set in the property drawer,
904 with its name in upper cases and colons added at the
905 beginning (i.e. `:CUSTOM_ID').
907 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
908 title will not be parsed as a secondary string, but as a plain
909 string instead.
911 Assume point is at beginning of the inline task."
912 (save-excursion
913 (let* ((begin (point))
914 (components (org-heading-components))
915 (todo (nth 2 components))
916 (todo-type (and todo
917 (if (member todo org-done-keywords) 'done 'todo)))
918 (tags (let ((raw-tags (nth 5 components)))
919 (and raw-tags (org-split-string raw-tags ":"))))
920 (raw-value (or (nth 4 components) ""))
921 ;; Upcase property names. It avoids confusion between
922 ;; properties obtained through property drawer and default
923 ;; properties from the parser (e.g. `:end' and :END:)
924 (standard-props
925 (let (plist)
926 (mapc
927 (lambda (p)
928 (setq plist
929 (plist-put plist
930 (intern (concat ":" (upcase (car p))))
931 (cdr p))))
932 (org-entry-properties nil 'standard))
933 plist))
934 (time-props
935 ;; Read time properties on the line below the inlinetask
936 ;; opening string.
937 (save-excursion
938 (when (progn (forward-line)
939 (looking-at org-planning-or-clock-line-re))
940 (let ((end (line-end-position)) plist)
941 (while (re-search-forward
942 org-keyword-time-not-clock-regexp end t)
943 (goto-char (match-end 1))
944 (skip-chars-forward " \t")
945 (let ((keyword (match-string 1))
946 (time (org-element-timestamp-parser)))
947 (cond ((equal keyword org-scheduled-string)
948 (setq plist (plist-put plist :scheduled time)))
949 ((equal keyword org-deadline-string)
950 (setq plist (plist-put plist :deadline time)))
951 (t (setq plist (plist-put plist :closed time))))))
952 plist))))
953 (task-end (save-excursion
954 (end-of-line)
955 (and (re-search-forward "^\\*+ END" limit t)
956 (match-beginning 0))))
957 (contents-begin (progn (forward-line)
958 (and task-end (< (point) task-end) (point))))
959 (contents-end (and contents-begin task-end))
960 (before-blank (if (not task-end) (point)
961 (goto-char task-end)
962 (forward-line)
963 (point)))
964 (end (progn (skip-chars-forward " \r\t\n" limit)
965 (skip-chars-backward " \t")
966 (if (bolp) (point) (line-end-position))))
967 (inlinetask
968 (list 'inlinetask
969 (nconc
970 (list :raw-value raw-value
971 :begin begin
972 :end end
973 :contents-begin contents-begin
974 :contents-end contents-end
975 :level (nth 1 components)
976 :priority (nth 3 components)
977 :tags tags
978 :todo-keyword todo
979 :todo-type todo-type
980 :post-blank (count-lines before-blank end))
981 time-props
982 standard-props))))
983 (org-element-put-property
984 inlinetask :title
985 (if raw-secondary-p raw-value
986 (org-element-parse-secondary-string
987 raw-value
988 (org-element-restriction 'inlinetask)
989 inlinetask))))))
991 (defun org-element-inlinetask-interpreter (inlinetask contents)
992 "Interpret INLINETASK element as Org syntax.
993 CONTENTS is the contents of inlinetask."
994 (let* ((level (org-element-property :level inlinetask))
995 (todo (org-element-property :todo-keyword inlinetask))
996 (priority (org-element-property :priority inlinetask))
997 (title (org-element-interpret-data
998 (org-element-property :title inlinetask)))
999 (tags (let ((tag-list (org-element-property :tags inlinetask)))
1000 (and tag-list
1001 (format ":%s:" (mapconcat 'identity tag-list ":")))))
1002 (task (concat (make-string level ?*)
1003 (and todo (concat " " todo))
1004 (and priority
1005 (format " [#%s]" (char-to-string priority)))
1006 (and title (concat " " title)))))
1007 (concat task
1008 ;; Align tags.
1009 (when tags
1010 (cond
1011 ((zerop org-tags-column) (format " %s" tags))
1012 ((< org-tags-column 0)
1013 (concat
1014 (make-string
1015 (max (- (+ org-tags-column (length task) (length tags))) 1)
1017 tags))
1019 (concat
1020 (make-string (max (- org-tags-column (length task)) 1) ? )
1021 tags))))
1022 ;; Prefer degenerate inlinetasks when there are no
1023 ;; contents.
1024 (when contents
1025 (concat "\n"
1026 contents
1027 (make-string level ?*) " END")))))
1030 ;;;; Item
1032 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1033 "Parse an item.
1035 STRUCT is the structure of the plain list.
1037 Return a list whose CAR is `item' and CDR is a plist containing
1038 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1039 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1040 keywords.
1042 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1043 any, will not be parsed as a secondary string, but as a plain
1044 string instead.
1046 Assume point is at the beginning of the item."
1047 (save-excursion
1048 (beginning-of-line)
1049 (looking-at org-list-full-item-re)
1050 (let* ((begin (point))
1051 (bullet (org-match-string-no-properties 1))
1052 (checkbox (let ((box (org-match-string-no-properties 3)))
1053 (cond ((equal "[ ]" box) 'off)
1054 ((equal "[X]" box) 'on)
1055 ((equal "[-]" box) 'trans))))
1056 (counter (let ((c (org-match-string-no-properties 2)))
1057 (save-match-data
1058 (cond
1059 ((not c) nil)
1060 ((string-match "[A-Za-z]" c)
1061 (- (string-to-char (upcase (match-string 0 c)))
1062 64))
1063 ((string-match "[0-9]+" c)
1064 (string-to-number (match-string 0 c)))))))
1065 (end (save-excursion (goto-char (org-list-get-item-end begin struct))
1066 (unless (bolp) (forward-line))
1067 (point)))
1068 (contents-begin
1069 (progn (goto-char
1070 ;; Ignore tags in un-ordered lists: they are just
1071 ;; a part of item's body.
1072 (if (and (match-beginning 4)
1073 (save-match-data (string-match "[.)]" bullet)))
1074 (match-beginning 4)
1075 (match-end 0)))
1076 (skip-chars-forward " \r\t\n" limit)
1077 ;; If first line isn't empty, contents really start
1078 ;; at the text after item's meta-data.
1079 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1080 (contents-end (progn (goto-char end)
1081 (skip-chars-backward " \r\t\n")
1082 (forward-line)
1083 (point)))
1084 (item
1085 (list 'item
1086 (list :bullet bullet
1087 :begin begin
1088 :end end
1089 ;; CONTENTS-BEGIN and CONTENTS-END may be
1090 ;; mixed up in the case of an empty item
1091 ;; separated from the next by a blank line.
1092 ;; Thus ensure the former is always the
1093 ;; smallest.
1094 :contents-begin (min contents-begin contents-end)
1095 :contents-end (max contents-begin contents-end)
1096 :checkbox checkbox
1097 :counter counter
1098 :structure struct
1099 :post-blank (count-lines contents-end end)))))
1100 (org-element-put-property
1101 item :tag
1102 (let ((raw-tag (org-list-get-tag begin struct)))
1103 (and raw-tag
1104 (if raw-secondary-p raw-tag
1105 (org-element-parse-secondary-string
1106 raw-tag (org-element-restriction 'item) item))))))))
1108 (defun org-element-item-interpreter (item contents)
1109 "Interpret ITEM element as Org syntax.
1110 CONTENTS is the contents of the element."
1111 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1112 (org-list-bullet-string
1113 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1114 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1115 (t "1.")))))
1116 (checkbox (org-element-property :checkbox item))
1117 (counter (org-element-property :counter item))
1118 (tag (let ((tag (org-element-property :tag item)))
1119 (and tag (org-element-interpret-data tag))))
1120 ;; Compute indentation.
1121 (ind (make-string (length bullet) 32))
1122 (item-starts-with-par-p
1123 (eq (org-element-type (car (org-element-contents item)))
1124 'paragraph)))
1125 ;; Indent contents.
1126 (concat
1127 bullet
1128 (and counter (format "[@%d] " counter))
1129 (case checkbox
1130 (on "[X] ")
1131 (off "[ ] ")
1132 (trans "[-] "))
1133 (and tag (format "%s :: " tag))
1134 (when contents
1135 (let ((contents (replace-regexp-in-string
1136 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1137 (if item-starts-with-par-p (org-trim contents)
1138 (concat "\n" contents)))))))
1141 ;;;; Plain List
1143 (defun org-element--list-struct (limit)
1144 ;; Return structure of list at point. Internal function. See
1145 ;; `org-list-struct' for details.
1146 (let ((case-fold-search t)
1147 (top-ind limit)
1148 (item-re (org-item-re))
1149 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1150 items struct)
1151 (save-excursion
1152 (catch 'exit
1153 (while t
1154 (cond
1155 ;; At limit: end all items.
1156 ((>= (point) limit)
1157 (throw 'exit
1158 (let ((end (progn (skip-chars-backward " \r\t\n")
1159 (forward-line)
1160 (point))))
1161 (dolist (item items (sort (nconc items struct)
1162 'car-less-than-car))
1163 (setcar (nthcdr 6 item) end)))))
1164 ;; At list end: end all items.
1165 ((looking-at org-list-end-re)
1166 (throw 'exit (dolist (item items (sort (nconc items struct)
1167 'car-less-than-car))
1168 (setcar (nthcdr 6 item) (point)))))
1169 ;; At a new item: end previous sibling.
1170 ((looking-at item-re)
1171 (let ((ind (save-excursion (skip-chars-forward " \t")
1172 (current-column))))
1173 (setq top-ind (min top-ind ind))
1174 (while (and items (<= ind (nth 1 (car items))))
1175 (let ((item (pop items)))
1176 (setcar (nthcdr 6 item) (point))
1177 (push item struct)))
1178 (push (progn (looking-at org-list-full-item-re)
1179 (let ((bullet (match-string-no-properties 1)))
1180 (list (point)
1182 bullet
1183 (match-string-no-properties 2) ; counter
1184 (match-string-no-properties 3) ; checkbox
1185 ;; Description tag.
1186 (and (save-match-data
1187 (string-match "[-+*]" bullet))
1188 (match-string-no-properties 4))
1189 ;; Ending position, unknown so far.
1190 nil)))
1191 items))
1192 (forward-line 1))
1193 ;; Skip empty lines.
1194 ((looking-at "^[ \t]*$") (forward-line))
1195 ;; Skip inline tasks and blank lines along the way.
1196 ((and inlinetask-re (looking-at inlinetask-re))
1197 (forward-line)
1198 (let ((origin (point)))
1199 (when (re-search-forward inlinetask-re limit t)
1200 (if (looking-at "^\\*+ END[ \t]*$") (forward-line)
1201 (goto-char origin)))))
1202 ;; At some text line. Check if it ends any previous item.
1204 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1205 (when (<= ind top-ind)
1206 (skip-chars-backward " \r\t\n")
1207 (forward-line))
1208 (while (<= ind (nth 1 (car items)))
1209 (let ((item (pop items)))
1210 (setcar (nthcdr 6 item) (line-beginning-position))
1211 (push item struct)
1212 (unless items
1213 (throw 'exit (sort struct 'car-less-than-car))))))
1214 ;; Skip blocks (any type) and drawers contents.
1215 (cond
1216 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1217 (re-search-forward
1218 (format "^[ \t]*#\\+END%s[ \t]*$"
1219 (org-match-string-no-properties 1))
1220 limit t)))
1221 ((and (looking-at org-drawer-regexp)
1222 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1223 (forward-line))))))))
1225 (defun org-element-plain-list-parser (limit affiliated structure)
1226 "Parse a plain list.
1228 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1229 the buffer position at the beginning of the first affiliated
1230 keyword and CDR is a plist of affiliated keywords along with
1231 their value. STRUCTURE is the structure of the plain list being
1232 parsed.
1234 Return a list whose CAR is `plain-list' and CDR is a plist
1235 containing `:type', `:begin', `:end', `:contents-begin' and
1236 `:contents-end', `:structure', `:post-blank' and
1237 `:post-affiliated' keywords.
1239 Assume point is at the beginning of the list."
1240 (save-excursion
1241 (let* ((struct (or structure (org-element--list-struct limit)))
1242 (prevs (org-list-prevs-alist struct))
1243 (type (org-list-get-list-type (point) struct prevs))
1244 (contents-begin (point))
1245 (begin (car affiliated))
1246 (contents-end
1247 (progn (goto-char (org-list-get-list-end (point) struct prevs))
1248 (unless (bolp) (forward-line))
1249 (point)))
1250 (end (progn (skip-chars-forward " \r\t\n" limit)
1251 (if (= (point) limit) limit (line-beginning-position)))))
1252 ;; Return value.
1253 (list 'plain-list
1254 (nconc
1255 (list :type type
1256 :begin begin
1257 :end end
1258 :contents-begin contents-begin
1259 :contents-end contents-end
1260 :structure struct
1261 :post-blank (count-lines contents-end end)
1262 :post-affiliated contents-begin)
1263 (cdr affiliated))))))
1265 (defun org-element-plain-list-interpreter (plain-list contents)
1266 "Interpret PLAIN-LIST element as Org syntax.
1267 CONTENTS is the contents of the element."
1268 (with-temp-buffer
1269 (insert contents)
1270 (goto-char (point-min))
1271 (org-list-repair)
1272 (buffer-string)))
1275 ;;;; Property Drawer
1277 (defun org-element-property-drawer-parser (limit affiliated)
1278 "Parse a property drawer.
1280 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1281 the buffer position at the beginning of the first affiliated
1282 keyword and CDR is a plist of affiliated keywords along with
1283 their value.
1285 Return a list whose CAR is `property-drawer' and CDR is a plist
1286 containing `:begin', `:end', `:contents-begin', `:contents-end',
1287 `:post-blank' and `:post-affiliated' keywords.
1289 Assume point is at the beginning of the property drawer."
1290 (save-excursion
1291 (let ((case-fold-search t))
1292 (if (not (save-excursion
1293 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1294 ;; Incomplete drawer: parse it as a paragraph.
1295 (org-element-paragraph-parser limit affiliated)
1296 (save-excursion
1297 (let* ((drawer-end-line (match-beginning 0))
1298 (begin (car affiliated))
1299 (post-affiliated (point))
1300 (contents-begin (progn (forward-line)
1301 (and (< (point) drawer-end-line)
1302 (point))))
1303 (contents-end (and contents-begin drawer-end-line))
1304 (pos-before-blank (progn (goto-char drawer-end-line)
1305 (forward-line)
1306 (point)))
1307 (end (progn (skip-chars-forward " \r\t\n" limit)
1308 (skip-chars-backward " \t")
1309 (if (bolp) (point) (line-end-position)))))
1310 (list 'property-drawer
1311 (nconc
1312 (list :begin begin
1313 :end end
1314 :contents-begin contents-begin
1315 :contents-end contents-end
1316 :post-blank (count-lines pos-before-blank end)
1317 :post-affiliated post-affiliated)
1318 (cdr affiliated)))))))))
1320 (defun org-element-property-drawer-interpreter (property-drawer contents)
1321 "Interpret PROPERTY-DRAWER element as Org syntax.
1322 CONTENTS is the properties within the drawer."
1323 (format ":PROPERTIES:\n%s:END:" contents))
1326 ;;;; Quote Block
1328 (defun org-element-quote-block-parser (limit affiliated)
1329 "Parse a quote block.
1331 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1332 the buffer position at the beginning of the first affiliated
1333 keyword and CDR is a plist of affiliated keywords along with
1334 their value.
1336 Return a list whose CAR is `quote-block' and CDR is a plist
1337 containing `:begin', `:end', `:contents-begin', `:contents-end',
1338 `:post-blank' and `:post-affiliated' keywords.
1340 Assume point is at the beginning of the block."
1341 (let ((case-fold-search t))
1342 (if (not (save-excursion
1343 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1344 ;; Incomplete block: parse it as a paragraph.
1345 (org-element-paragraph-parser limit affiliated)
1346 (let ((block-end-line (match-beginning 0)))
1347 (save-excursion
1348 (let* ((begin (car affiliated))
1349 (post-affiliated (point))
1350 ;; Empty blocks have no contents.
1351 (contents-begin (progn (forward-line)
1352 (and (< (point) block-end-line)
1353 (point))))
1354 (contents-end (and contents-begin block-end-line))
1355 (pos-before-blank (progn (goto-char block-end-line)
1356 (forward-line)
1357 (point)))
1358 (end (progn (skip-chars-forward " \r\t\n" limit)
1359 (skip-chars-backward " \t")
1360 (if (bolp) (point) (line-end-position)))))
1361 (list 'quote-block
1362 (nconc
1363 (list :begin begin
1364 :end end
1365 :contents-begin contents-begin
1366 :contents-end contents-end
1367 :post-blank (count-lines pos-before-blank end)
1368 :post-affiliated post-affiliated)
1369 (cdr affiliated)))))))))
1371 (defun org-element-quote-block-interpreter (quote-block contents)
1372 "Interpret QUOTE-BLOCK element as Org syntax.
1373 CONTENTS is the contents of the element."
1374 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1377 ;;;; Section
1379 (defun org-element-section-parser (limit)
1380 "Parse a section.
1382 LIMIT bounds the search.
1384 Return a list whose CAR is `section' and CDR is a plist
1385 containing `:begin', `:end', `:contents-begin', `contents-end'
1386 and `:post-blank' keywords."
1387 (save-excursion
1388 ;; Beginning of section is the beginning of the first non-blank
1389 ;; line after previous headline.
1390 (let ((begin (point))
1391 (end (progn (org-with-limited-levels (outline-next-heading))
1392 (point)))
1393 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1394 (forward-line)
1395 (point))))
1396 (list 'section
1397 (list :begin begin
1398 :end end
1399 :contents-begin begin
1400 :contents-end pos-before-blank
1401 :post-blank (count-lines pos-before-blank end))))))
1403 (defun org-element-section-interpreter (section contents)
1404 "Interpret SECTION element as Org syntax.
1405 CONTENTS is the contents of the element."
1406 contents)
1409 ;;;; Special Block
1411 (defun org-element-special-block-parser (limit affiliated)
1412 "Parse a special block.
1414 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1415 the buffer position at the beginning of the first affiliated
1416 keyword and CDR is a plist of affiliated keywords along with
1417 their value.
1419 Return a list whose CAR is `special-block' and CDR is a plist
1420 containing `:type', `:begin', `:end', `:contents-begin',
1421 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1423 Assume point is at the beginning of the block."
1424 (let* ((case-fold-search t)
1425 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1426 (upcase (match-string-no-properties 1)))))
1427 (if (not (save-excursion
1428 (re-search-forward
1429 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1430 limit t)))
1431 ;; Incomplete block: parse it as a paragraph.
1432 (org-element-paragraph-parser limit affiliated)
1433 (let ((block-end-line (match-beginning 0)))
1434 (save-excursion
1435 (let* ((begin (car affiliated))
1436 (post-affiliated (point))
1437 ;; Empty blocks have no contents.
1438 (contents-begin (progn (forward-line)
1439 (and (< (point) block-end-line)
1440 (point))))
1441 (contents-end (and contents-begin block-end-line))
1442 (pos-before-blank (progn (goto-char block-end-line)
1443 (forward-line)
1444 (point)))
1445 (end (progn (skip-chars-forward " \r\t\n" limit)
1446 (skip-chars-backward " \t")
1447 (if (bolp) (point) (line-end-position)))))
1448 (list 'special-block
1449 (nconc
1450 (list :type type
1451 :begin begin
1452 :end end
1453 :contents-begin contents-begin
1454 :contents-end contents-end
1455 :post-blank (count-lines pos-before-blank end)
1456 :post-affiliated post-affiliated)
1457 (cdr affiliated)))))))))
1459 (defun org-element-special-block-interpreter (special-block contents)
1460 "Interpret SPECIAL-BLOCK element as Org syntax.
1461 CONTENTS is the contents of the element."
1462 (let ((block-type (org-element-property :type special-block)))
1463 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1467 ;;; Elements
1469 ;; For each element, a parser and an interpreter are also defined.
1470 ;; Both follow the same naming convention used for greater elements.
1472 ;; Also, as for greater elements, adding a new element type is done
1473 ;; through the following steps: implement a parser and an interpreter,
1474 ;; tweak `org-element--current-element' so that it recognizes the new
1475 ;; type and add that new type to `org-element-all-elements'.
1477 ;; As a special case, when the newly defined type is a block type,
1478 ;; `org-element-block-name-alist' has to be modified accordingly.
1481 ;;;; Babel Call
1483 (defun org-element-babel-call-parser (limit affiliated)
1484 "Parse a babel call.
1486 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1487 the buffer position at the beginning of the first affiliated
1488 keyword and CDR is a plist of affiliated keywords along with
1489 their value.
1491 Return a list whose CAR is `babel-call' and CDR is a plist
1492 containing `:begin', `:end', `:value', `:post-blank' and
1493 `:post-affiliated' as keywords."
1494 (save-excursion
1495 (let ((begin (car affiliated))
1496 (post-affiliated (point))
1497 (value (progn (let ((case-fold-search t))
1498 (re-search-forward "call:[ \t]*" nil t))
1499 (buffer-substring-no-properties (point)
1500 (line-end-position))))
1501 (pos-before-blank (progn (forward-line) (point)))
1502 (end (progn (skip-chars-forward " \r\t\n" limit)
1503 (skip-chars-backward " \t")
1504 (if (bolp) (point) (line-end-position)))))
1505 (list 'babel-call
1506 (nconc
1507 (list :begin begin
1508 :end end
1509 :value value
1510 :post-blank (count-lines pos-before-blank end)
1511 :post-affiliated post-affiliated)
1512 (cdr affiliated))))))
1514 (defun org-element-babel-call-interpreter (babel-call contents)
1515 "Interpret BABEL-CALL element as Org syntax.
1516 CONTENTS is nil."
1517 (concat "#+CALL: " (org-element-property :value babel-call)))
1520 ;;;; Clock
1522 (defun org-element-clock-parser (limit)
1523 "Parse a clock.
1525 LIMIT bounds the search.
1527 Return a list whose CAR is `clock' and CDR is a plist containing
1528 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1529 as keywords."
1530 (save-excursion
1531 (let* ((case-fold-search nil)
1532 (begin (point))
1533 (value (progn (search-forward org-clock-string (line-end-position) t)
1534 (skip-chars-forward " \t")
1535 (org-element-timestamp-parser)))
1536 (duration (and (search-forward " => " (line-end-position) t)
1537 (progn (skip-chars-forward " \t")
1538 (looking-at "\\(\\S-+\\)[ \t]*$"))
1539 (org-match-string-no-properties 1)))
1540 (status (if duration 'closed 'running))
1541 (post-blank (let ((before-blank (progn (forward-line) (point))))
1542 (skip-chars-forward " \r\t\n" limit)
1543 (skip-chars-backward " \t")
1544 (unless (bolp) (end-of-line))
1545 (count-lines before-blank (point))))
1546 (end (point)))
1547 (list 'clock
1548 (list :status status
1549 :value value
1550 :duration duration
1551 :begin begin
1552 :end end
1553 :post-blank post-blank)))))
1555 (defun org-element-clock-interpreter (clock contents)
1556 "Interpret CLOCK element as Org syntax.
1557 CONTENTS is nil."
1558 (concat org-clock-string " "
1559 (org-element-timestamp-interpreter
1560 (org-element-property :value clock) nil)
1561 (let ((duration (org-element-property :duration clock)))
1562 (and duration
1563 (concat " => "
1564 (apply 'format
1565 "%2s:%02s"
1566 (org-split-string duration ":")))))))
1569 ;;;; Comment
1571 (defun org-element-comment-parser (limit affiliated)
1572 "Parse a comment.
1574 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1575 the buffer position at the beginning of the first affiliated
1576 keyword and CDR is a plist of affiliated keywords along with
1577 their value.
1579 Return a list whose CAR is `comment' and CDR is a plist
1580 containing `:begin', `:end', `:value', `:post-blank',
1581 `:post-affiliated' keywords.
1583 Assume point is at comment beginning."
1584 (save-excursion
1585 (let* ((begin (car affiliated))
1586 (post-affiliated (point))
1587 (value (prog2 (looking-at "[ \t]*# ?")
1588 (buffer-substring-no-properties
1589 (match-end 0) (line-end-position))
1590 (forward-line)))
1591 (com-end
1592 ;; Get comments ending.
1593 (progn
1594 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1595 ;; Accumulate lines without leading hash and first
1596 ;; whitespace.
1597 (setq value
1598 (concat value
1599 "\n"
1600 (buffer-substring-no-properties
1601 (match-end 0) (line-end-position))))
1602 (forward-line))
1603 (point)))
1604 (end (progn (goto-char com-end)
1605 (skip-chars-forward " \r\t\n" limit)
1606 (skip-chars-backward " \t")
1607 (if (bolp) (point) (line-end-position)))))
1608 (list 'comment
1609 (nconc
1610 (list :begin begin
1611 :end end
1612 :value value
1613 :post-blank (count-lines com-end end)
1614 :post-affiliated post-affiliated)
1615 (cdr affiliated))))))
1617 (defun org-element-comment-interpreter (comment contents)
1618 "Interpret COMMENT element as Org syntax.
1619 CONTENTS is nil."
1620 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1623 ;;;; Comment Block
1625 (defun org-element-comment-block-parser (limit affiliated)
1626 "Parse an export block.
1628 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1629 the buffer position at the beginning of the first affiliated
1630 keyword and CDR is a plist of affiliated keywords along with
1631 their value.
1633 Return a list whose CAR is `comment-block' and CDR is a plist
1634 containing `:begin', `:end', `:value', `:post-blank' and
1635 `:post-affiliated' keywords.
1637 Assume point is at comment block beginning."
1638 (let ((case-fold-search t))
1639 (if (not (save-excursion
1640 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1641 ;; Incomplete block: parse it as a paragraph.
1642 (org-element-paragraph-parser limit affiliated)
1643 (let ((contents-end (match-beginning 0)))
1644 (save-excursion
1645 (let* ((begin (car affiliated))
1646 (post-affiliated (point))
1647 (contents-begin (progn (forward-line) (point)))
1648 (pos-before-blank (progn (goto-char contents-end)
1649 (forward-line)
1650 (point)))
1651 (end (progn (skip-chars-forward " \r\t\n" limit)
1652 (skip-chars-backward " \t")
1653 (if (bolp) (point) (line-end-position))))
1654 (value (buffer-substring-no-properties
1655 contents-begin contents-end)))
1656 (list 'comment-block
1657 (nconc
1658 (list :begin begin
1659 :end end
1660 :value value
1661 :post-blank (count-lines pos-before-blank end)
1662 :post-affiliated post-affiliated)
1663 (cdr affiliated)))))))))
1665 (defun org-element-comment-block-interpreter (comment-block contents)
1666 "Interpret COMMENT-BLOCK element as Org syntax.
1667 CONTENTS is nil."
1668 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1669 (org-remove-indentation (org-element-property :value comment-block))))
1672 ;;;; Diary Sexp
1674 (defun org-element-diary-sexp-parser (limit affiliated)
1675 "Parse a diary sexp.
1677 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1678 the buffer position at the beginning of the first affiliated
1679 keyword and CDR is a plist of affiliated keywords along with
1680 their value.
1682 Return a list whose CAR is `diary-sexp' and CDR is a plist
1683 containing `:begin', `:end', `:value', `:post-blank' and
1684 `:post-affiliated' keywords."
1685 (save-excursion
1686 (let ((begin (car affiliated))
1687 (post-affiliated (point))
1688 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1689 (org-match-string-no-properties 1)))
1690 (pos-before-blank (progn (forward-line) (point)))
1691 (end (progn (skip-chars-forward " \r\t\n" limit)
1692 (skip-chars-backward " \t")
1693 (if (bolp) (point) (line-end-position)))))
1694 (list 'diary-sexp
1695 (nconc
1696 (list :value value
1697 :begin begin
1698 :end end
1699 :post-blank (count-lines pos-before-blank end)
1700 :post-affiliated post-affiliated)
1701 (cdr affiliated))))))
1703 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1704 "Interpret DIARY-SEXP as Org syntax.
1705 CONTENTS is nil."
1706 (org-element-property :value diary-sexp))
1709 ;;;; Example Block
1711 (defun org-element-example-block-parser (limit affiliated)
1712 "Parse an example block.
1714 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1715 the buffer position at the beginning of the first affiliated
1716 keyword and CDR is a plist of affiliated keywords along with
1717 their value.
1719 Return a list whose CAR is `example-block' and CDR is a plist
1720 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1721 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1722 `:value', `:post-blank' and `:post-affiliated' keywords."
1723 (let ((case-fold-search t))
1724 (if (not (save-excursion
1725 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1726 ;; Incomplete block: parse it as a paragraph.
1727 (org-element-paragraph-parser limit affiliated)
1728 (let ((contents-end (match-beginning 0)))
1729 (save-excursion
1730 (let* ((switches
1731 (progn
1732 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1733 (org-match-string-no-properties 1)))
1734 ;; Switches analysis
1735 (number-lines
1736 (cond ((not switches) nil)
1737 ((string-match "-n\\>" switches) 'new)
1738 ((string-match "+n\\>" switches) 'continued)))
1739 (preserve-indent
1740 (and switches (string-match "-i\\>" switches)))
1741 ;; Should labels be retained in (or stripped from) example
1742 ;; blocks?
1743 (retain-labels
1744 (or (not switches)
1745 (not (string-match "-r\\>" switches))
1746 (and number-lines (string-match "-k\\>" switches))))
1747 ;; What should code-references use - labels or
1748 ;; line-numbers?
1749 (use-labels
1750 (or (not switches)
1751 (and retain-labels
1752 (not (string-match "-k\\>" switches)))))
1753 (label-fmt
1754 (and switches
1755 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1756 (match-string 1 switches)))
1757 ;; Standard block parsing.
1758 (begin (car affiliated))
1759 (post-affiliated (point))
1760 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1761 (contents-begin (progn (forward-line) (point)))
1762 (value (org-element-remove-indentation
1763 (org-unescape-code-in-string
1764 (buffer-substring-no-properties
1765 contents-begin contents-end))
1766 block-ind))
1767 (pos-before-blank (progn (goto-char contents-end)
1768 (forward-line)
1769 (point)))
1770 (end (progn (skip-chars-forward " \r\t\n" limit)
1771 (skip-chars-backward " \t")
1772 (if (bolp) (point) (line-end-position)))))
1773 (list 'example-block
1774 (nconc
1775 (list :begin begin
1776 :end end
1777 :value value
1778 :switches switches
1779 :number-lines number-lines
1780 :preserve-indent preserve-indent
1781 :retain-labels retain-labels
1782 :use-labels use-labels
1783 :label-fmt label-fmt
1784 :post-blank (count-lines pos-before-blank end)
1785 :post-affiliated post-affiliated)
1786 (cdr affiliated)))))))))
1788 (defun org-element-example-block-interpreter (example-block contents)
1789 "Interpret EXAMPLE-BLOCK element as Org syntax.
1790 CONTENTS is nil."
1791 (let ((switches (org-element-property :switches example-block))
1792 (value (org-element-property :value example-block)))
1793 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1794 (org-escape-code-in-string
1795 (if (or org-src-preserve-indentation
1796 (org-element-property :preserve-indent example-block))
1797 value
1798 (org-element-remove-indentation value)))
1799 "#+END_EXAMPLE")))
1802 ;;;; Export Block
1804 (defun org-element-export-block-parser (limit affiliated)
1805 "Parse an export block.
1807 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1808 the buffer position at the beginning of the first affiliated
1809 keyword and CDR is a plist of affiliated keywords along with
1810 their value.
1812 Return a list whose CAR is `export-block' and CDR is a plist
1813 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1814 `:post-affiliated' keywords.
1816 Assume point is at export-block beginning."
1817 (let* ((case-fold-search t)
1818 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1819 (upcase (org-match-string-no-properties 1)))))
1820 (if (not (save-excursion
1821 (re-search-forward
1822 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1823 ;; Incomplete block: parse it as a paragraph.
1824 (org-element-paragraph-parser limit affiliated)
1825 (let ((contents-end (match-beginning 0)))
1826 (save-excursion
1827 (let* ((begin (car affiliated))
1828 (post-affiliated (point))
1829 (contents-begin (progn (forward-line) (point)))
1830 (pos-before-blank (progn (goto-char contents-end)
1831 (forward-line)
1832 (point)))
1833 (end (progn (skip-chars-forward " \r\t\n" limit)
1834 (skip-chars-backward " \t")
1835 (if (bolp) (point) (line-end-position))))
1836 (value (buffer-substring-no-properties contents-begin
1837 contents-end)))
1838 (list 'export-block
1839 (nconc
1840 (list :begin begin
1841 :end end
1842 :type type
1843 :value value
1844 :post-blank (count-lines pos-before-blank end)
1845 :post-affiliated post-affiliated)
1846 (cdr affiliated)))))))))
1848 (defun org-element-export-block-interpreter (export-block contents)
1849 "Interpret EXPORT-BLOCK element as Org syntax.
1850 CONTENTS is nil."
1851 (let ((type (org-element-property :type export-block)))
1852 (concat (format "#+BEGIN_%s\n" type)
1853 (org-element-property :value export-block)
1854 (format "#+END_%s" type))))
1857 ;;;; Fixed-width
1859 (defun org-element-fixed-width-parser (limit affiliated)
1860 "Parse a fixed-width section.
1862 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1863 the buffer position at the beginning of the first affiliated
1864 keyword and CDR is a plist of affiliated keywords along with
1865 their value.
1867 Return a list whose CAR is `fixed-width' and CDR is a plist
1868 containing `:begin', `:end', `:value', `:post-blank' and
1869 `:post-affiliated' keywords.
1871 Assume point is at the beginning of the fixed-width area."
1872 (save-excursion
1873 (let* ((begin (car affiliated))
1874 (post-affiliated (point))
1875 value
1876 (end-area
1877 (progn
1878 (while (and (< (point) limit)
1879 (looking-at "[ \t]*:\\( \\|$\\)"))
1880 ;; Accumulate text without starting colons.
1881 (setq value
1882 (concat value
1883 (buffer-substring-no-properties
1884 (match-end 0) (point-at-eol))
1885 "\n"))
1886 (forward-line))
1887 (point)))
1888 (end (progn (skip-chars-forward " \r\t\n" limit)
1889 (skip-chars-backward " \t")
1890 (if (bolp) (point) (line-end-position)))))
1891 (list 'fixed-width
1892 (nconc
1893 (list :begin begin
1894 :end end
1895 :value value
1896 :post-blank (count-lines end-area end)
1897 :post-affiliated post-affiliated)
1898 (cdr affiliated))))))
1900 (defun org-element-fixed-width-interpreter (fixed-width contents)
1901 "Interpret FIXED-WIDTH element as Org syntax.
1902 CONTENTS is nil."
1903 (let ((value (org-element-property :value fixed-width)))
1904 (and value
1905 (replace-regexp-in-string
1906 "^" ": "
1907 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1910 ;;;; Horizontal Rule
1912 (defun org-element-horizontal-rule-parser (limit affiliated)
1913 "Parse an horizontal rule.
1915 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1916 the buffer position at the beginning of the first affiliated
1917 keyword and CDR is a plist of affiliated keywords along with
1918 their value.
1920 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1921 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1922 keywords."
1923 (save-excursion
1924 (let ((begin (car affiliated))
1925 (post-affiliated (point))
1926 (post-hr (progn (forward-line) (point)))
1927 (end (progn (skip-chars-forward " \r\t\n" limit)
1928 (skip-chars-backward " \t")
1929 (if (bolp) (point) (line-end-position)))))
1930 (list 'horizontal-rule
1931 (nconc
1932 (list :begin begin
1933 :end end
1934 :post-blank (count-lines post-hr end)
1935 :post-affiliated post-affiliated)
1936 (cdr affiliated))))))
1938 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1939 "Interpret HORIZONTAL-RULE element as Org syntax.
1940 CONTENTS is nil."
1941 "-----")
1944 ;;;; Keyword
1946 (defun org-element-keyword-parser (limit affiliated)
1947 "Parse a keyword at point.
1949 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1950 the buffer position at the beginning of the first affiliated
1951 keyword and CDR is a plist of affiliated keywords along with
1952 their value.
1954 Return a list whose CAR is `keyword' and CDR is a plist
1955 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1956 `:post-affiliated' keywords."
1957 (save-excursion
1958 (let ((begin (car affiliated))
1959 (post-affiliated (point))
1960 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1961 (upcase (org-match-string-no-properties 1))))
1962 (value (org-trim (buffer-substring-no-properties
1963 (match-end 0) (point-at-eol))))
1964 (pos-before-blank (progn (forward-line) (point)))
1965 (end (progn (skip-chars-forward " \r\t\n" limit)
1966 (skip-chars-backward " \t")
1967 (if (bolp) (point) (line-end-position)))))
1968 (list 'keyword
1969 (nconc
1970 (list :key key
1971 :value value
1972 :begin begin
1973 :end end
1974 :post-blank (count-lines pos-before-blank end)
1975 :post-affiliated post-affiliated)
1976 (cdr affiliated))))))
1978 (defun org-element-keyword-interpreter (keyword contents)
1979 "Interpret KEYWORD element as Org syntax.
1980 CONTENTS is nil."
1981 (format "#+%s: %s"
1982 (org-element-property :key keyword)
1983 (org-element-property :value keyword)))
1986 ;;;; Latex Environment
1988 (defun org-element-latex-environment-parser (limit affiliated)
1989 "Parse a LaTeX environment.
1991 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1992 the buffer position at the beginning of the first affiliated
1993 keyword and CDR is a plist of affiliated keywords along with
1994 their value.
1996 Return a list whose CAR is `latex-environment' and CDR is a plist
1997 containing `:begin', `:end', `:value', `:post-blank' and
1998 `:post-affiliated' keywords.
2000 Assume point is at the beginning of the latex environment."
2001 (save-excursion
2002 (let ((case-fold-search t)
2003 (code-begin (point)))
2004 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2005 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2006 (regexp-quote (match-string 1)))
2007 limit t))
2008 ;; Incomplete latex environment: parse it as a paragraph.
2009 (org-element-paragraph-parser limit affiliated)
2010 (let* ((code-end (progn (forward-line) (point)))
2011 (begin (car affiliated))
2012 (value (buffer-substring-no-properties code-begin code-end))
2013 (end (progn (skip-chars-forward " \r\t\n" limit)
2014 (skip-chars-backward " \t")
2015 (if (bolp) (point) (line-end-position)))))
2016 (list 'latex-environment
2017 (nconc
2018 (list :begin begin
2019 :end end
2020 :value value
2021 :post-blank (count-lines code-end end)
2022 :post-affiliated code-begin)
2023 (cdr affiliated))))))))
2025 (defun org-element-latex-environment-interpreter (latex-environment contents)
2026 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2027 CONTENTS is nil."
2028 (org-element-property :value latex-environment))
2031 ;;;; Node Property
2033 (defun org-element-node-property-parser (limit)
2034 "Parse a node-property at point.
2036 LIMIT bounds the search.
2038 Return a list whose CAR is `node-property' and CDR is a plist
2039 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2040 keywords."
2041 (save-excursion
2042 (looking-at org-property-re)
2043 (let ((case-fold-search t)
2044 (begin (point))
2045 (key (org-match-string-no-properties 2))
2046 (value (org-match-string-no-properties 3))
2047 (pos-before-blank (progn (forward-line) (point)))
2048 (end (progn (skip-chars-forward " \r\t\n" limit)
2049 (if (eobp) (point) (point-at-bol)))))
2050 (list 'node-property
2051 (list :key key
2052 :value value
2053 :begin begin
2054 :end end
2055 :post-blank (count-lines pos-before-blank end))))))
2057 (defun org-element-node-property-interpreter (node-property contents)
2058 "Interpret NODE-PROPERTY element as Org syntax.
2059 CONTENTS is nil."
2060 (format org-property-format
2061 (format ":%s:" (org-element-property :key node-property))
2062 (org-element-property :value node-property)))
2065 ;;;; Paragraph
2067 (defun org-element-paragraph-parser (limit affiliated)
2068 "Parse a paragraph.
2070 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2071 the buffer position at the beginning of the first affiliated
2072 keyword and CDR is a plist of affiliated keywords along with
2073 their value.
2075 Return a list whose CAR is `paragraph' and CDR is a plist
2076 containing `:begin', `:end', `:contents-begin' and
2077 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2079 Assume point is at the beginning of the paragraph."
2080 (save-excursion
2081 (let* ((begin (car affiliated))
2082 (contents-begin (point))
2083 (before-blank
2084 (let ((case-fold-search t))
2085 (end-of-line)
2086 (if (not (re-search-forward
2087 org-element-paragraph-separate limit 'm))
2088 limit
2089 ;; A matching `org-element-paragraph-separate' is not
2090 ;; necessarily the end of the paragraph. In
2091 ;; particular, lines starting with # or : as a first
2092 ;; non-space character are ambiguous. We have check
2093 ;; if they are valid Org syntax (i.e. not an
2094 ;; incomplete keyword).
2095 (beginning-of-line)
2096 (while (not
2098 ;; There's no ambiguity for other symbols or
2099 ;; empty lines: stop here.
2100 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2101 ;; Stop at valid fixed-width areas.
2102 (looking-at "[ \t]*:\\(?: \\|$\\)")
2103 ;; Stop at drawers.
2104 (and (looking-at org-drawer-regexp)
2105 (save-excursion
2106 (re-search-forward
2107 "^[ \t]*:END:[ \t]*$" limit t)))
2108 ;; Stop at valid comments.
2109 (looking-at "[ \t]*#\\(?: \\|$\\)")
2110 ;; Stop at valid dynamic blocks.
2111 (and (looking-at org-dblock-start-re)
2112 (save-excursion
2113 (re-search-forward
2114 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2115 ;; Stop at valid blocks.
2116 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2117 (save-excursion
2118 (re-search-forward
2119 (format "^[ \t]*#\\+END_%s[ \t]*$"
2120 (regexp-quote
2121 (org-match-string-no-properties 1)))
2122 limit t)))
2123 ;; Stop at valid latex environments.
2124 (and (looking-at
2125 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2126 (save-excursion
2127 (re-search-forward
2128 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2129 (regexp-quote
2130 (org-match-string-no-properties 1)))
2131 limit t)))
2132 ;; Stop at valid keywords.
2133 (looking-at "[ \t]*#\\+\\S-+:")
2134 ;; Skip everything else.
2135 (not
2136 (progn
2137 (end-of-line)
2138 (re-search-forward org-element-paragraph-separate
2139 limit 'm)))))
2140 (beginning-of-line)))
2141 (if (= (point) limit) limit
2142 (goto-char (line-beginning-position)))))
2143 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2144 (forward-line)
2145 (point)))
2146 (end (progn (skip-chars-forward " \r\t\n" limit)
2147 (skip-chars-backward " \t")
2148 (if (bolp) (point) (line-end-position)))))
2149 (list 'paragraph
2150 (nconc
2151 (list :begin begin
2152 :end end
2153 :contents-begin contents-begin
2154 :contents-end contents-end
2155 :post-blank (count-lines before-blank end)
2156 :post-affiliated contents-begin)
2157 (cdr affiliated))))))
2159 (defun org-element-paragraph-interpreter (paragraph contents)
2160 "Interpret PARAGRAPH element as Org syntax.
2161 CONTENTS is the contents of the element."
2162 contents)
2165 ;;;; Planning
2167 (defun org-element-planning-parser (limit)
2168 "Parse a planning.
2170 LIMIT bounds the search.
2172 Return a list whose CAR is `planning' and CDR is a plist
2173 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2174 and `:post-blank' keywords."
2175 (save-excursion
2176 (let* ((case-fold-search nil)
2177 (begin (point))
2178 (post-blank (let ((before-blank (progn (forward-line) (point))))
2179 (skip-chars-forward " \r\t\n" limit)
2180 (skip-chars-backward " \t")
2181 (unless (bolp) (end-of-line))
2182 (count-lines before-blank (point))))
2183 (end (point))
2184 closed deadline scheduled)
2185 (goto-char begin)
2186 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2187 (goto-char (match-end 1))
2188 (skip-chars-forward " \t" end)
2189 (let ((keyword (match-string 1))
2190 (time (org-element-timestamp-parser)))
2191 (cond ((equal keyword org-closed-string) (setq closed time))
2192 ((equal keyword org-deadline-string) (setq deadline time))
2193 (t (setq scheduled time)))))
2194 (list 'planning
2195 (list :closed closed
2196 :deadline deadline
2197 :scheduled scheduled
2198 :begin begin
2199 :end end
2200 :post-blank post-blank)))))
2202 (defun org-element-planning-interpreter (planning contents)
2203 "Interpret PLANNING element as Org syntax.
2204 CONTENTS is nil."
2205 (mapconcat
2206 'identity
2207 (delq nil
2208 (list (let ((deadline (org-element-property :deadline planning)))
2209 (when deadline
2210 (concat org-deadline-string " "
2211 (org-element-timestamp-interpreter deadline nil))))
2212 (let ((scheduled (org-element-property :scheduled planning)))
2213 (when scheduled
2214 (concat org-scheduled-string " "
2215 (org-element-timestamp-interpreter scheduled nil))))
2216 (let ((closed (org-element-property :closed planning)))
2217 (when closed
2218 (concat org-closed-string " "
2219 (org-element-timestamp-interpreter closed nil))))))
2220 " "))
2223 ;;;; Quote Section
2225 (defun org-element-quote-section-parser (limit)
2226 "Parse a quote section.
2228 LIMIT bounds the search.
2230 Return a list whose CAR is `quote-section' and CDR is a plist
2231 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2233 Assume point is at beginning of the section."
2234 (save-excursion
2235 (let* ((begin (point))
2236 (end (progn (org-with-limited-levels (outline-next-heading))
2237 (point)))
2238 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2239 (forward-line)
2240 (point)))
2241 (value (buffer-substring-no-properties begin pos-before-blank)))
2242 (list 'quote-section
2243 (list :begin begin
2244 :end end
2245 :value value
2246 :post-blank (count-lines pos-before-blank end))))))
2248 (defun org-element-quote-section-interpreter (quote-section contents)
2249 "Interpret QUOTE-SECTION element as Org syntax.
2250 CONTENTS is nil."
2251 (org-element-property :value quote-section))
2254 ;;;; Src Block
2256 (defun org-element-src-block-parser (limit affiliated)
2257 "Parse a src block.
2259 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2260 the buffer position at the beginning of the first affiliated
2261 keyword and CDR is a plist of affiliated keywords along with
2262 their value.
2264 Return a list whose CAR is `src-block' and CDR is a plist
2265 containing `:language', `:switches', `:parameters', `:begin',
2266 `:end', `:number-lines', `:retain-labels', `:use-labels',
2267 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2268 `:post-affiliated' keywords.
2270 Assume point is at the beginning of the block."
2271 (let ((case-fold-search t))
2272 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2273 limit t)))
2274 ;; Incomplete block: parse it as a paragraph.
2275 (org-element-paragraph-parser limit affiliated)
2276 (let ((contents-end (match-beginning 0)))
2277 (save-excursion
2278 (let* ((begin (car affiliated))
2279 (post-affiliated (point))
2280 ;; Get language as a string.
2281 (language
2282 (progn
2283 (looking-at
2284 (concat "^[ \t]*#\\+BEGIN_SRC"
2285 "\\(?: +\\(\\S-+\\)\\)?"
2286 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2287 "\\(.*\\)[ \t]*$"))
2288 (org-match-string-no-properties 1)))
2289 ;; Get switches.
2290 (switches (org-match-string-no-properties 2))
2291 ;; Get parameters.
2292 (parameters (org-match-string-no-properties 3))
2293 ;; Switches analysis
2294 (number-lines
2295 (cond ((not switches) nil)
2296 ((string-match "-n\\>" switches) 'new)
2297 ((string-match "+n\\>" switches) 'continued)))
2298 (preserve-indent (and switches
2299 (string-match "-i\\>" switches)))
2300 (label-fmt
2301 (and switches
2302 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2303 (match-string 1 switches)))
2304 ;; Should labels be retained in (or stripped from)
2305 ;; src blocks?
2306 (retain-labels
2307 (or (not switches)
2308 (not (string-match "-r\\>" switches))
2309 (and number-lines (string-match "-k\\>" switches))))
2310 ;; What should code-references use - labels or
2311 ;; line-numbers?
2312 (use-labels
2313 (or (not switches)
2314 (and retain-labels
2315 (not (string-match "-k\\>" switches)))))
2316 ;; Indentation.
2317 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2318 ;; Retrieve code.
2319 (value (org-element-remove-indentation
2320 (org-unescape-code-in-string
2321 (buffer-substring-no-properties
2322 (progn (forward-line) (point)) contents-end))
2323 block-ind))
2324 (pos-before-blank (progn (goto-char contents-end)
2325 (forward-line)
2326 (point)))
2327 ;; Get position after ending blank lines.
2328 (end (progn (skip-chars-forward " \r\t\n" limit)
2329 (skip-chars-backward " \t")
2330 (if (bolp) (point) (line-end-position)))))
2331 (list 'src-block
2332 (nconc
2333 (list :language language
2334 :switches (and (org-string-nw-p switches)
2335 (org-trim switches))
2336 :parameters (and (org-string-nw-p parameters)
2337 (org-trim parameters))
2338 :begin begin
2339 :end end
2340 :number-lines number-lines
2341 :preserve-indent preserve-indent
2342 :retain-labels retain-labels
2343 :use-labels use-labels
2344 :label-fmt label-fmt
2345 :value value
2346 :post-blank (count-lines pos-before-blank end)
2347 :post-affiliated post-affiliated)
2348 (cdr affiliated)))))))))
2350 (defun org-element-src-block-interpreter (src-block contents)
2351 "Interpret SRC-BLOCK element as Org syntax.
2352 CONTENTS is nil."
2353 (let ((lang (org-element-property :language src-block))
2354 (switches (org-element-property :switches src-block))
2355 (params (org-element-property :parameters src-block))
2356 (value
2357 (let ((val (org-element-property :value src-block)))
2358 (cond
2359 ((or org-src-preserve-indentation
2360 (org-element-property :preserve-indent src-block))
2361 val)
2362 ((zerop org-edit-src-content-indentation) val)
2364 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2365 (replace-regexp-in-string
2366 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2367 (concat (format "#+BEGIN_SRC%s\n"
2368 (concat (and lang (concat " " lang))
2369 (and switches (concat " " switches))
2370 (and params (concat " " params))))
2371 (org-escape-code-in-string value)
2372 "#+END_SRC")))
2375 ;;;; Table
2377 (defun org-element-table-parser (limit affiliated)
2378 "Parse a table at point.
2380 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2381 the buffer position at the beginning of the first affiliated
2382 keyword and CDR is a plist of affiliated keywords along with
2383 their value.
2385 Return a list whose CAR is `table' and CDR is a plist containing
2386 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2387 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2388 keywords.
2390 Assume point is at the beginning of the table."
2391 (save-excursion
2392 (let* ((case-fold-search t)
2393 (table-begin (point))
2394 (type (if (org-at-table.el-p) 'table.el 'org))
2395 (begin (car affiliated))
2396 (table-end
2397 (if (re-search-forward org-table-any-border-regexp limit 'm)
2398 (goto-char (match-beginning 0))
2399 (point)))
2400 (tblfm (let (acc)
2401 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2402 (push (org-match-string-no-properties 1) acc)
2403 (forward-line))
2404 acc))
2405 (pos-before-blank (point))
2406 (end (progn (skip-chars-forward " \r\t\n" limit)
2407 (skip-chars-backward " \t")
2408 (if (bolp) (point) (line-end-position)))))
2409 (list 'table
2410 (nconc
2411 (list :begin begin
2412 :end end
2413 :type type
2414 :tblfm tblfm
2415 ;; Only `org' tables have contents. `table.el' tables
2416 ;; use a `:value' property to store raw table as
2417 ;; a string.
2418 :contents-begin (and (eq type 'org) table-begin)
2419 :contents-end (and (eq type 'org) table-end)
2420 :value (and (eq type 'table.el)
2421 (buffer-substring-no-properties
2422 table-begin table-end))
2423 :post-blank (count-lines pos-before-blank end)
2424 :post-affiliated table-begin)
2425 (cdr affiliated))))))
2427 (defun org-element-table-interpreter (table contents)
2428 "Interpret TABLE element as Org syntax.
2429 CONTENTS is nil."
2430 (if (eq (org-element-property :type table) 'table.el)
2431 (org-remove-indentation (org-element-property :value table))
2432 (concat (with-temp-buffer (insert contents)
2433 (org-table-align)
2434 (buffer-string))
2435 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2436 (reverse (org-element-property :tblfm table))
2437 "\n"))))
2440 ;;;; Table Row
2442 (defun org-element-table-row-parser (limit)
2443 "Parse table row at point.
2445 LIMIT bounds the search.
2447 Return a list whose CAR is `table-row' and CDR is a plist
2448 containing `:begin', `:end', `:contents-begin', `:contents-end',
2449 `:type' and `:post-blank' keywords."
2450 (save-excursion
2451 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2452 (begin (point))
2453 ;; A table rule has no contents. In that case, ensure
2454 ;; CONTENTS-BEGIN matches CONTENTS-END.
2455 (contents-begin (and (eq type 'standard)
2456 (search-forward "|")
2457 (point)))
2458 (contents-end (and (eq type 'standard)
2459 (progn
2460 (end-of-line)
2461 (skip-chars-backward " \t")
2462 (point))))
2463 (end (progn (forward-line) (point))))
2464 (list 'table-row
2465 (list :type type
2466 :begin begin
2467 :end end
2468 :contents-begin contents-begin
2469 :contents-end contents-end
2470 :post-blank 0)))))
2472 (defun org-element-table-row-interpreter (table-row contents)
2473 "Interpret TABLE-ROW element as Org syntax.
2474 CONTENTS is the contents of the table row."
2475 (if (eq (org-element-property :type table-row) 'rule) "|-"
2476 (concat "| " contents)))
2479 ;;;; Verse Block
2481 (defun org-element-verse-block-parser (limit affiliated)
2482 "Parse a verse block.
2484 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2485 the buffer position at the beginning of the first affiliated
2486 keyword and CDR is a plist of affiliated keywords along with
2487 their value.
2489 Return a list whose CAR is `verse-block' and CDR is a plist
2490 containing `:begin', `:end', `:contents-begin', `:contents-end',
2491 `:post-blank' and `:post-affiliated' keywords.
2493 Assume point is at beginning of the block."
2494 (let ((case-fold-search t))
2495 (if (not (save-excursion
2496 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2497 ;; Incomplete block: parse it as a paragraph.
2498 (org-element-paragraph-parser limit affiliated)
2499 (let ((contents-end (match-beginning 0)))
2500 (save-excursion
2501 (let* ((begin (car affiliated))
2502 (post-affiliated (point))
2503 (contents-begin (progn (forward-line) (point)))
2504 (pos-before-blank (progn (goto-char contents-end)
2505 (forward-line)
2506 (point)))
2507 (end (progn (skip-chars-forward " \r\t\n" limit)
2508 (skip-chars-backward " \t")
2509 (if (bolp) (point) (line-end-position)))))
2510 (list 'verse-block
2511 (nconc
2512 (list :begin begin
2513 :end end
2514 :contents-begin contents-begin
2515 :contents-end contents-end
2516 :post-blank (count-lines pos-before-blank end)
2517 :post-affiliated post-affiliated)
2518 (cdr affiliated)))))))))
2520 (defun org-element-verse-block-interpreter (verse-block contents)
2521 "Interpret VERSE-BLOCK element as Org syntax.
2522 CONTENTS is verse block contents."
2523 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2527 ;;; Objects
2529 ;; Unlike to elements, interstices can be found between objects.
2530 ;; That's why, along with the parser, successor functions are provided
2531 ;; for each object. Some objects share the same successor (i.e. `code'
2532 ;; and `verbatim' objects).
2534 ;; A successor must accept a single argument bounding the search. It
2535 ;; will return either a cons cell whose CAR is the object's type, as
2536 ;; a symbol, and CDR the position of its next occurrence, or nil.
2538 ;; Successors follow the naming convention:
2539 ;; org-element-NAME-successor, where NAME is the name of the
2540 ;; successor, as defined in `org-element-all-successors'.
2542 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2543 ;; object types they can contain will be specified in
2544 ;; `org-element-object-restrictions'.
2546 ;; Adding a new type of object is simple. Implement a successor,
2547 ;; a parser, and an interpreter for it, all following the naming
2548 ;; convention. Register type in `org-element-all-objects' and
2549 ;; successor in `org-element-all-successors'. Maybe tweak
2550 ;; restrictions about it, and that's it.
2553 ;;;; Bold
2555 (defun org-element-bold-parser ()
2556 "Parse bold object at point.
2558 Return a list whose CAR is `bold' and CDR is a plist with
2559 `:begin', `:end', `:contents-begin' and `:contents-end' and
2560 `:post-blank' keywords.
2562 Assume point is at the first star marker."
2563 (save-excursion
2564 (unless (bolp) (backward-char 1))
2565 (looking-at org-emph-re)
2566 (let ((begin (match-beginning 2))
2567 (contents-begin (match-beginning 4))
2568 (contents-end (match-end 4))
2569 (post-blank (progn (goto-char (match-end 2))
2570 (skip-chars-forward " \t")))
2571 (end (point)))
2572 (list 'bold
2573 (list :begin begin
2574 :end end
2575 :contents-begin contents-begin
2576 :contents-end contents-end
2577 :post-blank post-blank)))))
2579 (defun org-element-bold-interpreter (bold contents)
2580 "Interpret BOLD object as Org syntax.
2581 CONTENTS is the contents of the object."
2582 (format "*%s*" contents))
2584 (defun org-element-text-markup-successor ()
2585 "Search for the next text-markup object.
2587 Return value is a cons cell whose CAR is a symbol among `bold',
2588 `italic', `underline', `strike-through', `code' and `verbatim'
2589 and CDR is beginning position."
2590 (save-excursion
2591 (unless (bolp) (backward-char))
2592 (when (re-search-forward org-emph-re nil t)
2593 (let ((marker (match-string 3)))
2594 (cons (cond
2595 ((equal marker "*") 'bold)
2596 ((equal marker "/") 'italic)
2597 ((equal marker "_") 'underline)
2598 ((equal marker "+") 'strike-through)
2599 ((equal marker "~") 'code)
2600 ((equal marker "=") 'verbatim)
2601 (t (error "Unknown marker at %d" (match-beginning 3))))
2602 (match-beginning 2))))))
2605 ;;;; Code
2607 (defun org-element-code-parser ()
2608 "Parse code object at point.
2610 Return a list whose CAR is `code' and CDR is a plist with
2611 `:value', `:begin', `:end' and `:post-blank' keywords.
2613 Assume point is at the first tilde marker."
2614 (save-excursion
2615 (unless (bolp) (backward-char 1))
2616 (looking-at org-emph-re)
2617 (let ((begin (match-beginning 2))
2618 (value (org-match-string-no-properties 4))
2619 (post-blank (progn (goto-char (match-end 2))
2620 (skip-chars-forward " \t")))
2621 (end (point)))
2622 (list 'code
2623 (list :value value
2624 :begin begin
2625 :end end
2626 :post-blank post-blank)))))
2628 (defun org-element-code-interpreter (code contents)
2629 "Interpret CODE object as Org syntax.
2630 CONTENTS is nil."
2631 (format "~%s~" (org-element-property :value code)))
2634 ;;;; Entity
2636 (defun org-element-entity-parser ()
2637 "Parse entity at point.
2639 Return a list whose CAR is `entity' and CDR a plist with
2640 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2641 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2642 keywords.
2644 Assume point is at the beginning of the entity."
2645 (save-excursion
2646 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2647 (let* ((value (org-entity-get (match-string 1)))
2648 (begin (match-beginning 0))
2649 (bracketsp (string= (match-string 2) "{}"))
2650 (post-blank (progn (goto-char (match-end 1))
2651 (when bracketsp (forward-char 2))
2652 (skip-chars-forward " \t")))
2653 (end (point)))
2654 (list 'entity
2655 (list :name (car value)
2656 :latex (nth 1 value)
2657 :latex-math-p (nth 2 value)
2658 :html (nth 3 value)
2659 :ascii (nth 4 value)
2660 :latin1 (nth 5 value)
2661 :utf-8 (nth 6 value)
2662 :begin begin
2663 :end end
2664 :use-brackets-p bracketsp
2665 :post-blank post-blank)))))
2667 (defun org-element-entity-interpreter (entity contents)
2668 "Interpret ENTITY object as Org syntax.
2669 CONTENTS is nil."
2670 (concat "\\"
2671 (org-element-property :name entity)
2672 (when (org-element-property :use-brackets-p entity) "{}")))
2674 (defun org-element-latex-or-entity-successor ()
2675 "Search for the next latex-fragment or entity object.
2677 Return value is a cons cell whose CAR is `entity' or
2678 `latex-fragment' and CDR is beginning position."
2679 (save-excursion
2680 (unless (bolp) (backward-char))
2681 (let ((matchers (cdr org-latex-regexps))
2682 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2683 (entity-re
2684 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2685 (when (re-search-forward
2686 (concat (mapconcat #'cadr matchers "\\|") "\\|" entity-re) nil t)
2687 (goto-char (match-beginning 0))
2688 (if (looking-at entity-re)
2689 ;; Determine if it's a real entity or a LaTeX command.
2690 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2691 (match-beginning 0))
2692 ;; No entity nor command: point is at a LaTeX fragment.
2693 ;; Determine its type to get the correct beginning position.
2694 (cons 'latex-fragment
2695 (catch 'return
2696 (dolist (e matchers)
2697 (when (looking-at (nth 1 e))
2698 (throw 'return (match-beginning (nth 2 e)))))
2699 (point))))))))
2702 ;;;; Export Snippet
2704 (defun org-element-export-snippet-parser ()
2705 "Parse export snippet at point.
2707 Return a list whose CAR is `export-snippet' and CDR a plist with
2708 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2709 keywords.
2711 Assume point is at the beginning of the snippet."
2712 (save-excursion
2713 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2714 (let* ((begin (match-beginning 0))
2715 (back-end (org-match-string-no-properties 1))
2716 (value (buffer-substring-no-properties
2717 (point)
2718 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2719 (post-blank (skip-chars-forward " \t"))
2720 (end (point)))
2721 (list 'export-snippet
2722 (list :back-end back-end
2723 :value value
2724 :begin begin
2725 :end end
2726 :post-blank post-blank)))))
2728 (defun org-element-export-snippet-interpreter (export-snippet contents)
2729 "Interpret EXPORT-SNIPPET object as Org syntax.
2730 CONTENTS is nil."
2731 (format "@@%s:%s@@"
2732 (org-element-property :back-end export-snippet)
2733 (org-element-property :value export-snippet)))
2735 (defun org-element-export-snippet-successor ()
2736 "Search for the next export-snippet object.
2738 Return value is a cons cell whose CAR is `export-snippet' and CDR
2739 its beginning position."
2740 (save-excursion
2741 (let (beg)
2742 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2743 (setq beg (match-beginning 0))
2744 (search-forward "@@" nil t))
2745 (cons 'export-snippet beg)))))
2748 ;;;; Footnote Reference
2750 (defun org-element-footnote-reference-parser ()
2751 "Parse footnote reference at point.
2753 Return a list whose CAR is `footnote-reference' and CDR a plist
2754 with `:label', `:type', `:inline-definition', `:begin', `:end'
2755 and `:post-blank' as keywords."
2756 (save-excursion
2757 (looking-at org-footnote-re)
2758 (let* ((begin (point))
2759 (label (or (org-match-string-no-properties 2)
2760 (org-match-string-no-properties 3)
2761 (and (match-string 1)
2762 (concat "fn:" (org-match-string-no-properties 1)))))
2763 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2764 (inner-begin (match-end 0))
2765 (inner-end
2766 (let ((count 1))
2767 (forward-char)
2768 (while (and (> count 0) (re-search-forward "[][]" nil t))
2769 (if (equal (match-string 0) "[") (incf count) (decf count)))
2770 (1- (point))))
2771 (post-blank (progn (goto-char (1+ inner-end))
2772 (skip-chars-forward " \t")))
2773 (end (point))
2774 (footnote-reference
2775 (list 'footnote-reference
2776 (list :label label
2777 :type type
2778 :begin begin
2779 :end end
2780 :post-blank post-blank))))
2781 (org-element-put-property
2782 footnote-reference :inline-definition
2783 (and (eq type 'inline)
2784 (org-element-parse-secondary-string
2785 (buffer-substring inner-begin inner-end)
2786 (org-element-restriction 'footnote-reference)
2787 footnote-reference))))))
2789 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2790 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2791 CONTENTS is nil."
2792 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2793 (def
2794 (let ((inline-def
2795 (org-element-property :inline-definition footnote-reference)))
2796 (if (not inline-def) ""
2797 (concat ":" (org-element-interpret-data inline-def))))))
2798 (format "[%s]" (concat label def))))
2800 (defun org-element-footnote-reference-successor ()
2801 "Search for the next footnote-reference object.
2803 Return value is a cons cell whose CAR is `footnote-reference' and
2804 CDR is beginning position."
2805 (save-excursion
2806 (catch 'exit
2807 (while (re-search-forward org-footnote-re nil t)
2808 (save-excursion
2809 (let ((beg (match-beginning 0))
2810 (count 1))
2811 (backward-char)
2812 (while (re-search-forward "[][]" nil t)
2813 (if (equal (match-string 0) "[") (incf count) (decf count))
2814 (when (zerop count)
2815 (throw 'exit (cons 'footnote-reference beg))))))))))
2818 ;;;; Inline Babel Call
2820 (defun org-element-inline-babel-call-parser ()
2821 "Parse inline babel call at point.
2823 Return a list whose CAR is `inline-babel-call' and CDR a plist
2824 with `:begin', `:end', `:value' and `:post-blank' as keywords.
2826 Assume point is at the beginning of the babel call."
2827 (save-excursion
2828 (unless (bolp) (backward-char))
2829 (let ((case-fold-search t))
2830 (looking-at org-babel-inline-lob-one-liner-regexp))
2831 (let ((begin (match-end 1))
2832 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2833 (post-blank (progn (goto-char (match-end 0))
2834 (skip-chars-forward " \t")))
2835 (end (point)))
2836 (list 'inline-babel-call
2837 (list :begin begin
2838 :end end
2839 :value value
2840 :post-blank post-blank)))))
2842 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2843 "Interpret INLINE-BABEL-CALL object as Org syntax.
2844 CONTENTS is nil."
2845 (org-element-property :value inline-babel-call))
2847 (defun org-element-inline-babel-call-successor ()
2848 "Search for the next inline-babel-call object.
2850 Return value is a cons cell whose CAR is `inline-babel-call' and
2851 CDR is beginning position."
2852 (save-excursion
2853 ;; Use a simplified version of
2854 ;; `org-babel-inline-lob-one-liner-regexp'.
2855 (when (re-search-forward
2856 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2857 nil t)
2858 (cons 'inline-babel-call (match-beginning 0)))))
2861 ;;;; Inline Src Block
2863 (defun org-element-inline-src-block-parser ()
2864 "Parse inline source block at point.
2866 Return a list whose CAR is `inline-src-block' and CDR a plist
2867 with `:begin', `:end', `:language', `:value', `:parameters' and
2868 `:post-blank' as keywords.
2870 Assume point is at the beginning of the inline src block."
2871 (save-excursion
2872 (unless (bolp) (backward-char))
2873 (looking-at org-babel-inline-src-block-regexp)
2874 (let ((begin (match-beginning 1))
2875 (language (org-match-string-no-properties 2))
2876 (parameters (org-match-string-no-properties 4))
2877 (value (org-match-string-no-properties 5))
2878 (post-blank (progn (goto-char (match-end 0))
2879 (skip-chars-forward " \t")))
2880 (end (point)))
2881 (list 'inline-src-block
2882 (list :language language
2883 :value value
2884 :parameters parameters
2885 :begin begin
2886 :end end
2887 :post-blank post-blank)))))
2889 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2890 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2891 CONTENTS is nil."
2892 (let ((language (org-element-property :language inline-src-block))
2893 (arguments (org-element-property :parameters inline-src-block))
2894 (body (org-element-property :value inline-src-block)))
2895 (format "src_%s%s{%s}"
2896 language
2897 (if arguments (format "[%s]" arguments) "")
2898 body)))
2900 (defun org-element-inline-src-block-successor ()
2901 "Search for the next inline-babel-call element.
2903 Return value is a cons cell whose CAR is `inline-babel-call' and
2904 CDR is beginning position."
2905 (save-excursion
2906 (unless (bolp) (backward-char))
2907 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2908 (cons 'inline-src-block (match-beginning 1)))))
2910 ;;;; Italic
2912 (defun org-element-italic-parser ()
2913 "Parse italic object at point.
2915 Return a list whose CAR is `italic' and CDR is a plist with
2916 `:begin', `:end', `:contents-begin' and `:contents-end' and
2917 `:post-blank' keywords.
2919 Assume point is at the first slash marker."
2920 (save-excursion
2921 (unless (bolp) (backward-char 1))
2922 (looking-at org-emph-re)
2923 (let ((begin (match-beginning 2))
2924 (contents-begin (match-beginning 4))
2925 (contents-end (match-end 4))
2926 (post-blank (progn (goto-char (match-end 2))
2927 (skip-chars-forward " \t")))
2928 (end (point)))
2929 (list 'italic
2930 (list :begin begin
2931 :end end
2932 :contents-begin contents-begin
2933 :contents-end contents-end
2934 :post-blank post-blank)))))
2936 (defun org-element-italic-interpreter (italic contents)
2937 "Interpret ITALIC object as Org syntax.
2938 CONTENTS is the contents of the object."
2939 (format "/%s/" contents))
2942 ;;;; Latex Fragment
2944 (defun org-element-latex-fragment-parser ()
2945 "Parse LaTeX fragment at point.
2947 Return a list whose CAR is `latex-fragment' and CDR a plist with
2948 `:value', `:begin', `:end', and `:post-blank' as keywords.
2950 Assume point is at the beginning of the LaTeX fragment."
2951 (save-excursion
2952 (let* ((begin (point))
2953 (substring-match
2954 (catch 'exit
2955 (dolist (e (cdr org-latex-regexps))
2956 (let ((latex-regexp (nth 1 e)))
2957 (when (or (looking-at latex-regexp)
2958 (and (not (bobp))
2959 (save-excursion
2960 (backward-char)
2961 (looking-at latex-regexp))))
2962 (throw 'exit (nth 2 e)))))
2963 ;; None found: it's a macro.
2964 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2966 (value (org-match-string-no-properties substring-match))
2967 (post-blank (progn (goto-char (match-end substring-match))
2968 (skip-chars-forward " \t")))
2969 (end (point)))
2970 (list 'latex-fragment
2971 (list :value value
2972 :begin begin
2973 :end end
2974 :post-blank post-blank)))))
2976 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2977 "Interpret LATEX-FRAGMENT object as Org syntax.
2978 CONTENTS is nil."
2979 (org-element-property :value latex-fragment))
2981 ;;;; Line Break
2983 (defun org-element-line-break-parser ()
2984 "Parse line break at point.
2986 Return a list whose CAR is `line-break', and CDR a plist with
2987 `:begin', `:end' and `:post-blank' keywords.
2989 Assume point is at the beginning of the line break."
2990 (list 'line-break
2991 (list :begin (point)
2992 :end (progn (forward-line) (point))
2993 :post-blank 0)))
2995 (defun org-element-line-break-interpreter (line-break contents)
2996 "Interpret LINE-BREAK object as Org syntax.
2997 CONTENTS is nil."
2998 "\\\\\n")
3000 (defun org-element-line-break-successor ()
3001 "Search for the next line-break object.
3003 Return value is a cons cell whose CAR is `line-break' and CDR is
3004 beginning position."
3005 (save-excursion
3006 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
3007 (goto-char (match-beginning 1)))))
3008 ;; A line break can only happen on a non-empty line.
3009 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
3010 (cons 'line-break beg)))))
3013 ;;;; Link
3015 (defun org-element-link-parser ()
3016 "Parse link at point.
3018 Return a list whose CAR is `link' and CDR a plist with `:type',
3019 `:path', `:raw-link', `:application', `:search-option', `:begin',
3020 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3021 keywords.
3023 Assume point is at the beginning of the link."
3024 (save-excursion
3025 (let ((begin (point))
3026 end contents-begin contents-end link-end post-blank path type
3027 raw-link link search-option application)
3028 (cond
3029 ;; Type 1: Text targeted from a radio target.
3030 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3031 (setq type "radio"
3032 link-end (match-end 0)
3033 path (org-match-string-no-properties 0)))
3034 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3035 ((looking-at org-bracket-link-regexp)
3036 (setq contents-begin (match-beginning 3)
3037 contents-end (match-end 3)
3038 link-end (match-end 0)
3039 ;; RAW-LINK is the original link. Expand any
3040 ;; abbreviation in it.
3041 raw-link (org-translate-link
3042 (org-link-expand-abbrev
3043 (org-match-string-no-properties 1))))
3044 ;; Determine TYPE of link and set PATH accordingly.
3045 (cond
3046 ;; File type.
3047 ((or (file-name-absolute-p raw-link)
3048 (string-match "^\\.\\.?/" raw-link))
3049 (setq type "file" path raw-link))
3050 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3051 ((string-match org-link-re-with-space3 raw-link)
3052 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3053 ;; Id type: PATH is the id.
3054 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3055 (setq type "id" path (match-string 1 raw-link)))
3056 ;; Code-ref type: PATH is the name of the reference.
3057 ((string-match "^(\\(.*\\))$" raw-link)
3058 (setq type "coderef" path (match-string 1 raw-link)))
3059 ;; Custom-id type: PATH is the name of the custom id.
3060 ((= (aref raw-link 0) ?#)
3061 (setq type "custom-id" path (substring raw-link 1)))
3062 ;; Fuzzy type: Internal link either matches a target, an
3063 ;; headline name or nothing. PATH is the target or
3064 ;; headline's name.
3065 (t (setq type "fuzzy" path raw-link))))
3066 ;; Type 3: Plain link, i.e. http://orgmode.org
3067 ((looking-at org-plain-link-re)
3068 (setq raw-link (org-match-string-no-properties 0)
3069 type (org-match-string-no-properties 1)
3070 link-end (match-end 0)
3071 path (org-match-string-no-properties 2)))
3072 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3073 ((looking-at org-angle-link-re)
3074 (setq raw-link (buffer-substring-no-properties
3075 (match-beginning 1) (match-end 2))
3076 type (org-match-string-no-properties 1)
3077 link-end (match-end 0)
3078 path (org-match-string-no-properties 2))))
3079 ;; In any case, deduce end point after trailing white space from
3080 ;; LINK-END variable.
3081 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3082 end (point))
3083 ;; Extract search option and opening application out of
3084 ;; "file"-type links.
3085 (when (member type org-element-link-type-is-file)
3086 ;; Application.
3087 (cond ((string-match "^file\\+\\(.*\\)$" type)
3088 (setq application (match-string 1 type)))
3089 ((not (string-match "^file" type))
3090 (setq application type)))
3091 ;; Extract search option from PATH.
3092 (when (string-match "::\\(.*\\)$" path)
3093 (setq search-option (match-string 1 path)
3094 path (replace-match "" nil nil path)))
3095 ;; Make sure TYPE always reports "file".
3096 (setq type "file"))
3097 (list 'link
3098 (list :type type
3099 :path path
3100 :raw-link (or raw-link path)
3101 :application application
3102 :search-option search-option
3103 :begin begin
3104 :end end
3105 :contents-begin contents-begin
3106 :contents-end contents-end
3107 :post-blank post-blank)))))
3109 (defun org-element-link-interpreter (link contents)
3110 "Interpret LINK object as Org syntax.
3111 CONTENTS is the contents of the object, or nil."
3112 (let ((type (org-element-property :type link))
3113 (raw-link (org-element-property :raw-link link)))
3114 (if (string= type "radio") raw-link
3115 (format "[[%s]%s]"
3116 raw-link
3117 (if contents (format "[%s]" contents) "")))))
3119 (defun org-element-link-successor ()
3120 "Search for the next link object.
3122 Return value is a cons cell whose CAR is `link' and CDR is
3123 beginning position."
3124 (save-excursion
3125 (let ((link-regexp
3126 (if (not org-target-link-regexp) org-any-link-re
3127 (concat org-any-link-re "\\|" org-target-link-regexp))))
3128 (when (re-search-forward link-regexp nil t)
3129 (cons 'link (match-beginning 0))))))
3131 (defun org-element-plain-link-successor ()
3132 "Search for the next plain link object.
3134 Return value is a cons cell whose CAR is `link' and CDR is
3135 beginning position."
3136 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3137 (cons 'link (match-beginning 0))))
3140 ;;;; Macro
3142 (defun org-element-macro-parser ()
3143 "Parse macro at point.
3145 Return a list whose CAR is `macro' and CDR a plist with `:key',
3146 `:args', `:begin', `:end', `:value' and `:post-blank' as
3147 keywords.
3149 Assume point is at the macro."
3150 (save-excursion
3151 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3152 (let ((begin (point))
3153 (key (downcase (org-match-string-no-properties 1)))
3154 (value (org-match-string-no-properties 0))
3155 (post-blank (progn (goto-char (match-end 0))
3156 (skip-chars-forward " \t")))
3157 (end (point))
3158 (args (let ((args (org-match-string-no-properties 3)))
3159 (when args
3160 ;; Do not use `org-split-string' since empty
3161 ;; strings are meaningful here.
3162 (split-string
3163 (replace-regexp-in-string
3164 "\\(\\\\*\\)\\(,\\)"
3165 (lambda (str)
3166 (let ((len (length (match-string 1 str))))
3167 (concat (make-string (/ len 2) ?\\)
3168 (if (zerop (mod len 2)) "\000" ","))))
3169 args nil t)
3170 "\000")))))
3171 (list 'macro
3172 (list :key key
3173 :value value
3174 :args args
3175 :begin begin
3176 :end end
3177 :post-blank post-blank)))))
3179 (defun org-element-macro-interpreter (macro contents)
3180 "Interpret MACRO object as Org syntax.
3181 CONTENTS is nil."
3182 (org-element-property :value macro))
3184 (defun org-element-macro-successor ()
3185 "Search for the next macro object.
3187 Return value is cons cell whose CAR is `macro' and CDR is
3188 beginning position."
3189 (save-excursion
3190 (when (re-search-forward
3191 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3192 nil t)
3193 (cons 'macro (match-beginning 0)))))
3196 ;;;; Radio-target
3198 (defun org-element-radio-target-parser ()
3199 "Parse radio target at point.
3201 Return a list whose CAR is `radio-target' and CDR a plist with
3202 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3203 and `:post-blank' as keywords.
3205 Assume point is at the radio target."
3206 (save-excursion
3207 (looking-at org-radio-target-regexp)
3208 (let ((begin (point))
3209 (contents-begin (match-beginning 1))
3210 (contents-end (match-end 1))
3211 (value (org-match-string-no-properties 1))
3212 (post-blank (progn (goto-char (match-end 0))
3213 (skip-chars-forward " \t")))
3214 (end (point)))
3215 (list 'radio-target
3216 (list :begin begin
3217 :end end
3218 :contents-begin contents-begin
3219 :contents-end contents-end
3220 :post-blank post-blank
3221 :value value)))))
3223 (defun org-element-radio-target-interpreter (target contents)
3224 "Interpret TARGET object as Org syntax.
3225 CONTENTS is the contents of the object."
3226 (concat "<<<" contents ">>>"))
3228 (defun org-element-radio-target-successor ()
3229 "Search for the next radio-target object.
3231 Return value is a cons cell whose CAR is `radio-target' and CDR
3232 is beginning position."
3233 (save-excursion
3234 (when (re-search-forward org-radio-target-regexp nil t)
3235 (cons 'radio-target (match-beginning 0)))))
3238 ;;;; Statistics Cookie
3240 (defun org-element-statistics-cookie-parser ()
3241 "Parse statistics cookie at point.
3243 Return a list whose CAR is `statistics-cookie', and CDR a plist
3244 with `:begin', `:end', `:value' and `:post-blank' keywords.
3246 Assume point is at the beginning of the statistics-cookie."
3247 (save-excursion
3248 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3249 (let* ((begin (point))
3250 (value (buffer-substring-no-properties
3251 (match-beginning 0) (match-end 0)))
3252 (post-blank (progn (goto-char (match-end 0))
3253 (skip-chars-forward " \t")))
3254 (end (point)))
3255 (list 'statistics-cookie
3256 (list :begin begin
3257 :end end
3258 :value value
3259 :post-blank post-blank)))))
3261 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3262 "Interpret STATISTICS-COOKIE object as Org syntax.
3263 CONTENTS is nil."
3264 (org-element-property :value statistics-cookie))
3266 (defun org-element-statistics-cookie-successor ()
3267 "Search for the next statistics cookie object.
3269 Return value is a cons cell whose CAR is `statistics-cookie' and
3270 CDR is beginning position."
3271 (save-excursion
3272 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3273 (cons 'statistics-cookie (match-beginning 0)))))
3276 ;;;; Strike-Through
3278 (defun org-element-strike-through-parser ()
3279 "Parse strike-through object at point.
3281 Return a list whose CAR is `strike-through' and CDR is a plist
3282 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3283 `:post-blank' keywords.
3285 Assume point is at the first plus sign marker."
3286 (save-excursion
3287 (unless (bolp) (backward-char 1))
3288 (looking-at org-emph-re)
3289 (let ((begin (match-beginning 2))
3290 (contents-begin (match-beginning 4))
3291 (contents-end (match-end 4))
3292 (post-blank (progn (goto-char (match-end 2))
3293 (skip-chars-forward " \t")))
3294 (end (point)))
3295 (list 'strike-through
3296 (list :begin begin
3297 :end end
3298 :contents-begin contents-begin
3299 :contents-end contents-end
3300 :post-blank post-blank)))))
3302 (defun org-element-strike-through-interpreter (strike-through contents)
3303 "Interpret STRIKE-THROUGH object as Org syntax.
3304 CONTENTS is the contents of the object."
3305 (format "+%s+" contents))
3308 ;;;; Subscript
3310 (defun org-element-subscript-parser ()
3311 "Parse subscript at point.
3313 Return a list whose CAR is `subscript' and CDR a plist with
3314 `:begin', `:end', `:contents-begin', `:contents-end',
3315 `:use-brackets-p' and `:post-blank' as keywords.
3317 Assume point is at the underscore."
3318 (save-excursion
3319 (unless (bolp) (backward-char))
3320 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3322 (not (looking-at org-match-substring-regexp))))
3323 (begin (match-beginning 2))
3324 (contents-begin (or (match-beginning 5)
3325 (match-beginning 3)))
3326 (contents-end (or (match-end 5) (match-end 3)))
3327 (post-blank (progn (goto-char (match-end 0))
3328 (skip-chars-forward " \t")))
3329 (end (point)))
3330 (list 'subscript
3331 (list :begin begin
3332 :end end
3333 :use-brackets-p bracketsp
3334 :contents-begin contents-begin
3335 :contents-end contents-end
3336 :post-blank post-blank)))))
3338 (defun org-element-subscript-interpreter (subscript contents)
3339 "Interpret SUBSCRIPT object as Org syntax.
3340 CONTENTS is the contents of the object."
3341 (format
3342 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3343 contents))
3345 (defun org-element-sub/superscript-successor ()
3346 "Search for the next sub/superscript object.
3348 Return value is a cons cell whose CAR is either `subscript' or
3349 `superscript' and CDR is beginning position."
3350 (save-excursion
3351 (unless (bolp) (backward-char))
3352 (when (re-search-forward org-match-substring-regexp nil t)
3353 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3354 (match-beginning 2)))))
3357 ;;;; Superscript
3359 (defun org-element-superscript-parser ()
3360 "Parse superscript at point.
3362 Return a list whose CAR is `superscript' and CDR a plist with
3363 `:begin', `:end', `:contents-begin', `:contents-end',
3364 `:use-brackets-p' and `:post-blank' as keywords.
3366 Assume point is at the caret."
3367 (save-excursion
3368 (unless (bolp) (backward-char))
3369 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3370 (not (looking-at org-match-substring-regexp))))
3371 (begin (match-beginning 2))
3372 (contents-begin (or (match-beginning 5)
3373 (match-beginning 3)))
3374 (contents-end (or (match-end 5) (match-end 3)))
3375 (post-blank (progn (goto-char (match-end 0))
3376 (skip-chars-forward " \t")))
3377 (end (point)))
3378 (list 'superscript
3379 (list :begin begin
3380 :end end
3381 :use-brackets-p bracketsp
3382 :contents-begin contents-begin
3383 :contents-end contents-end
3384 :post-blank post-blank)))))
3386 (defun org-element-superscript-interpreter (superscript contents)
3387 "Interpret SUPERSCRIPT object as Org syntax.
3388 CONTENTS is the contents of the object."
3389 (format
3390 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3391 contents))
3394 ;;;; Table Cell
3396 (defun org-element-table-cell-parser ()
3397 "Parse table cell at point.
3399 Return a list whose CAR is `table-cell' and CDR is a plist
3400 containing `:begin', `:end', `:contents-begin', `:contents-end'
3401 and `:post-blank' keywords."
3402 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3403 (let* ((begin (match-beginning 0))
3404 (end (match-end 0))
3405 (contents-begin (match-beginning 1))
3406 (contents-end (match-end 1)))
3407 (list 'table-cell
3408 (list :begin begin
3409 :end end
3410 :contents-begin contents-begin
3411 :contents-end contents-end
3412 :post-blank 0))))
3414 (defun org-element-table-cell-interpreter (table-cell contents)
3415 "Interpret TABLE-CELL element as Org syntax.
3416 CONTENTS is the contents of the cell, or nil."
3417 (concat " " contents " |"))
3419 (defun org-element-table-cell-successor ()
3420 "Search for the next table-cell object.
3422 Return value is a cons cell whose CAR is `table-cell' and CDR is
3423 beginning position."
3424 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3427 ;;;; Target
3429 (defun org-element-target-parser ()
3430 "Parse target at point.
3432 Return a list whose CAR is `target' and CDR a plist with
3433 `:begin', `:end', `:value' and `:post-blank' as keywords.
3435 Assume point is at the target."
3436 (save-excursion
3437 (looking-at org-target-regexp)
3438 (let ((begin (point))
3439 (value (org-match-string-no-properties 1))
3440 (post-blank (progn (goto-char (match-end 0))
3441 (skip-chars-forward " \t")))
3442 (end (point)))
3443 (list 'target
3444 (list :begin begin
3445 :end end
3446 :value value
3447 :post-blank post-blank)))))
3449 (defun org-element-target-interpreter (target contents)
3450 "Interpret TARGET object as Org syntax.
3451 CONTENTS is nil."
3452 (format "<<%s>>" (org-element-property :value target)))
3454 (defun org-element-target-successor ()
3455 "Search for the next target object.
3457 Return value is a cons cell whose CAR is `target' and CDR is
3458 beginning position."
3459 (save-excursion
3460 (when (re-search-forward org-target-regexp nil t)
3461 (cons 'target (match-beginning 0)))))
3464 ;;;; Timestamp
3466 (defun org-element-timestamp-parser ()
3467 "Parse time stamp at point.
3469 Return a list whose CAR is `timestamp', and CDR a plist with
3470 `:type', `:raw-value', `:year-start', `:month-start',
3471 `:day-start', `:hour-start', `:minute-start', `:year-end',
3472 `:month-end', `:day-end', `:hour-end', `:minute-end',
3473 `:repeater-type', `:repeater-value', `:repeater-unit',
3474 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3475 `:end', `:value' and `:post-blank' keywords.
3477 Assume point is at the beginning of the timestamp."
3478 (save-excursion
3479 (let* ((begin (point))
3480 (activep (eq (char-after) ?<))
3481 (raw-value
3482 (progn
3483 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3484 (match-string-no-properties 0)))
3485 (date-start (match-string-no-properties 1))
3486 (date-end (match-string 3))
3487 (diaryp (match-beginning 2))
3488 (post-blank (progn (goto-char (match-end 0))
3489 (skip-chars-forward " \t")))
3490 (end (point))
3491 (time-range
3492 (and (not diaryp)
3493 (string-match
3494 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3495 date-start)
3496 (cons (string-to-number (match-string 2 date-start))
3497 (string-to-number (match-string 3 date-start)))))
3498 (type (cond (diaryp 'diary)
3499 ((and activep (or date-end time-range)) 'active-range)
3500 (activep 'active)
3501 ((or date-end time-range) 'inactive-range)
3502 (t 'inactive)))
3503 (repeater-props
3504 (and (not diaryp)
3505 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3506 raw-value)
3507 (list
3508 :repeater-type
3509 (let ((type (match-string 1 raw-value)))
3510 (cond ((equal "++" type) 'catch-up)
3511 ((equal ".+" type) 'restart)
3512 (t 'cumulate)))
3513 :repeater-value (string-to-number (match-string 2 raw-value))
3514 :repeater-unit
3515 (case (string-to-char (match-string 3 raw-value))
3516 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3517 (warning-props
3518 (and (not diaryp)
3519 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3520 (list
3521 :warning-type (if (match-string 1 raw-value) 'first 'all)
3522 :warning-value (string-to-number (match-string 2 raw-value))
3523 :warning-unit
3524 (case (string-to-char (match-string 3 raw-value))
3525 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3526 year-start month-start day-start hour-start minute-start year-end
3527 month-end day-end hour-end minute-end)
3528 ;; Parse date-start.
3529 (unless diaryp
3530 (let ((date (org-parse-time-string date-start t)))
3531 (setq year-start (nth 5 date)
3532 month-start (nth 4 date)
3533 day-start (nth 3 date)
3534 hour-start (nth 2 date)
3535 minute-start (nth 1 date))))
3536 ;; Compute date-end. It can be provided directly in time-stamp,
3537 ;; or extracted from time range. Otherwise, it defaults to the
3538 ;; same values as date-start.
3539 (unless diaryp
3540 (let ((date (and date-end (org-parse-time-string date-end t))))
3541 (setq year-end (or (nth 5 date) year-start)
3542 month-end (or (nth 4 date) month-start)
3543 day-end (or (nth 3 date) day-start)
3544 hour-end (or (nth 2 date) (car time-range) hour-start)
3545 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3546 (list 'timestamp
3547 (nconc (list :type type
3548 :raw-value raw-value
3549 :year-start year-start
3550 :month-start month-start
3551 :day-start day-start
3552 :hour-start hour-start
3553 :minute-start minute-start
3554 :year-end year-end
3555 :month-end month-end
3556 :day-end day-end
3557 :hour-end hour-end
3558 :minute-end minute-end
3559 :begin begin
3560 :end end
3561 :post-blank post-blank)
3562 repeater-props
3563 warning-props)))))
3565 (defun org-element-timestamp-interpreter (timestamp contents)
3566 "Interpret TIMESTAMP object as Org syntax.
3567 CONTENTS is nil."
3568 ;; Use `:raw-value' if specified.
3569 (or (org-element-property :raw-value timestamp)
3570 ;; Otherwise, build timestamp string.
3571 (let* ((repeat-string
3572 (concat
3573 (case (org-element-property :repeater-type timestamp)
3574 (cumulate "+") (catch-up "++") (restart ".+"))
3575 (let ((val (org-element-property :repeater-value timestamp)))
3576 (and val (number-to-string val)))
3577 (case (org-element-property :repeater-unit timestamp)
3578 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3579 (warning-string
3580 (concat
3581 (case (org-element-property :warning-type timestamp)
3582 (first "--")
3583 (all "-"))
3584 (let ((val (org-element-property :warning-value timestamp)))
3585 (and val (number-to-string val)))
3586 (case (org-element-property :warning-unit timestamp)
3587 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3588 (build-ts-string
3589 ;; Build an Org timestamp string from TIME. ACTIVEP is
3590 ;; non-nil when time stamp is active. If WITH-TIME-P is
3591 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3592 ;; specify a time range in the timestamp. REPEAT-STRING
3593 ;; is the repeater string, if any.
3594 (lambda (time activep &optional with-time-p hour-end minute-end)
3595 (let ((ts (format-time-string
3596 (funcall (if with-time-p 'cdr 'car)
3597 org-time-stamp-formats)
3598 time)))
3599 (when (and hour-end minute-end)
3600 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3601 (setq ts
3602 (replace-match
3603 (format "\\&-%02d:%02d" hour-end minute-end)
3604 nil nil ts)))
3605 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3606 (dolist (s (list repeat-string warning-string))
3607 (when (org-string-nw-p s)
3608 (setq ts (concat (substring ts 0 -1)
3611 (substring ts -1)))))
3612 ;; Return value.
3613 ts)))
3614 (type (org-element-property :type timestamp)))
3615 (case type
3616 ((active inactive)
3617 (let* ((minute-start (org-element-property :minute-start timestamp))
3618 (minute-end (org-element-property :minute-end timestamp))
3619 (hour-start (org-element-property :hour-start timestamp))
3620 (hour-end (org-element-property :hour-end timestamp))
3621 (time-range-p (and hour-start hour-end minute-start minute-end
3622 (or (/= hour-start hour-end)
3623 (/= minute-start minute-end)))))
3624 (funcall
3625 build-ts-string
3626 (encode-time 0
3627 (or minute-start 0)
3628 (or hour-start 0)
3629 (org-element-property :day-start timestamp)
3630 (org-element-property :month-start timestamp)
3631 (org-element-property :year-start timestamp))
3632 (eq type 'active)
3633 (and hour-start minute-start)
3634 (and time-range-p hour-end)
3635 (and time-range-p minute-end))))
3636 ((active-range inactive-range)
3637 (let ((minute-start (org-element-property :minute-start timestamp))
3638 (minute-end (org-element-property :minute-end timestamp))
3639 (hour-start (org-element-property :hour-start timestamp))
3640 (hour-end (org-element-property :hour-end timestamp)))
3641 (concat
3642 (funcall
3643 build-ts-string (encode-time
3645 (or minute-start 0)
3646 (or hour-start 0)
3647 (org-element-property :day-start timestamp)
3648 (org-element-property :month-start timestamp)
3649 (org-element-property :year-start timestamp))
3650 (eq type 'active-range)
3651 (and hour-start minute-start))
3652 "--"
3653 (funcall build-ts-string
3654 (encode-time 0
3655 (or minute-end 0)
3656 (or hour-end 0)
3657 (org-element-property :day-end timestamp)
3658 (org-element-property :month-end timestamp)
3659 (org-element-property :year-end timestamp))
3660 (eq type 'active-range)
3661 (and hour-end minute-end)))))))))
3663 (defun org-element-timestamp-successor ()
3664 "Search for the next timestamp object.
3666 Return value is a cons cell whose CAR is `timestamp' and CDR is
3667 beginning position."
3668 (save-excursion
3669 (when (re-search-forward
3670 (concat org-ts-regexp-both
3671 "\\|"
3672 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3673 "\\|"
3674 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3675 nil t)
3676 (cons 'timestamp (match-beginning 0)))))
3679 ;;;; Underline
3681 (defun org-element-underline-parser ()
3682 "Parse underline object at point.
3684 Return a list whose CAR is `underline' and CDR is a plist with
3685 `:begin', `:end', `:contents-begin' and `:contents-end' and
3686 `:post-blank' keywords.
3688 Assume point is at the first underscore marker."
3689 (save-excursion
3690 (unless (bolp) (backward-char 1))
3691 (looking-at org-emph-re)
3692 (let ((begin (match-beginning 2))
3693 (contents-begin (match-beginning 4))
3694 (contents-end (match-end 4))
3695 (post-blank (progn (goto-char (match-end 2))
3696 (skip-chars-forward " \t")))
3697 (end (point)))
3698 (list 'underline
3699 (list :begin begin
3700 :end end
3701 :contents-begin contents-begin
3702 :contents-end contents-end
3703 :post-blank post-blank)))))
3705 (defun org-element-underline-interpreter (underline contents)
3706 "Interpret UNDERLINE object as Org syntax.
3707 CONTENTS is the contents of the object."
3708 (format "_%s_" contents))
3711 ;;;; Verbatim
3713 (defun org-element-verbatim-parser ()
3714 "Parse verbatim object at point.
3716 Return a list whose CAR is `verbatim' and CDR is a plist with
3717 `:value', `:begin', `:end' and `:post-blank' keywords.
3719 Assume point is at the first equal sign marker."
3720 (save-excursion
3721 (unless (bolp) (backward-char 1))
3722 (looking-at org-emph-re)
3723 (let ((begin (match-beginning 2))
3724 (value (org-match-string-no-properties 4))
3725 (post-blank (progn (goto-char (match-end 2))
3726 (skip-chars-forward " \t")))
3727 (end (point)))
3728 (list 'verbatim
3729 (list :value value
3730 :begin begin
3731 :end end
3732 :post-blank post-blank)))))
3734 (defun org-element-verbatim-interpreter (verbatim contents)
3735 "Interpret VERBATIM object as Org syntax.
3736 CONTENTS is nil."
3737 (format "=%s=" (org-element-property :value verbatim)))
3741 ;;; Parsing Element Starting At Point
3743 ;; `org-element--current-element' is the core function of this section.
3744 ;; It returns the Lisp representation of the element starting at
3745 ;; point.
3747 ;; `org-element--current-element' makes use of special modes. They
3748 ;; are activated for fixed element chaining (i.e. `plain-list' >
3749 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3750 ;; `section'). Special modes are: `first-section', `item',
3751 ;; `node-property', `quote-section', `section' and `table-row'.
3753 (defun org-element--current-element
3754 (limit &optional granularity special structure)
3755 "Parse the element starting at point.
3757 Return value is a list like (TYPE PROPS) where TYPE is the type
3758 of the element and PROPS a plist of properties associated to the
3759 element.
3761 Possible types are defined in `org-element-all-elements'.
3763 LIMIT bounds the search.
3765 Optional argument GRANULARITY determines the depth of the
3766 recursion. Allowed values are `headline', `greater-element',
3767 `element', `object' or nil. When it is broader than `object' (or
3768 nil), secondary values will not be parsed, since they only
3769 contain objects.
3771 Optional argument SPECIAL, when non-nil, can be either
3772 `first-section', `item', `node-property', `quote-section',
3773 `section', and `table-row'.
3775 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3776 be computed.
3778 This function assumes point is always at the beginning of the
3779 element it has to parse."
3780 (save-excursion
3781 (let ((case-fold-search t)
3782 ;; Determine if parsing depth allows for secondary strings
3783 ;; parsing. It only applies to elements referenced in
3784 ;; `org-element-secondary-value-alist'.
3785 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3786 (cond
3787 ;; Item.
3788 ((eq special 'item)
3789 (org-element-item-parser limit structure raw-secondary-p))
3790 ;; Table Row.
3791 ((eq special 'table-row) (org-element-table-row-parser limit))
3792 ;; Node Property.
3793 ((eq special 'node-property) (org-element-node-property-parser limit))
3794 ;; Headline.
3795 ((org-with-limited-levels (org-at-heading-p))
3796 (org-element-headline-parser limit raw-secondary-p))
3797 ;; Sections (must be checked after headline).
3798 ((eq special 'section) (org-element-section-parser limit))
3799 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3800 ((eq special 'first-section)
3801 (org-element-section-parser
3802 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3803 limit)))
3804 ;; When not at bol, point is at the beginning of an item or
3805 ;; a footnote definition: next item is always a paragraph.
3806 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3807 ;; Planning and Clock.
3808 ((looking-at org-planning-or-clock-line-re)
3809 (if (equal (match-string 1) org-clock-string)
3810 (org-element-clock-parser limit)
3811 (org-element-planning-parser limit)))
3812 ;; Inlinetask.
3813 ((org-at-heading-p)
3814 (org-element-inlinetask-parser limit raw-secondary-p))
3815 ;; From there, elements can have affiliated keywords.
3816 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3817 (cond
3818 ;; Jumping over affiliated keywords put point off-limits.
3819 ;; Parse them as regular keywords.
3820 ((and (cdr affiliated) (>= (point) limit))
3821 (goto-char (car affiliated))
3822 (org-element-keyword-parser limit nil))
3823 ;; LaTeX Environment.
3824 ((looking-at
3825 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3826 (org-element-latex-environment-parser limit affiliated))
3827 ;; Drawer and Property Drawer.
3828 ((looking-at org-drawer-regexp)
3829 (if (equal (match-string 1) "PROPERTIES")
3830 (org-element-property-drawer-parser limit affiliated)
3831 (org-element-drawer-parser limit affiliated)))
3832 ;; Fixed Width
3833 ((looking-at "[ \t]*:\\( \\|$\\)")
3834 (org-element-fixed-width-parser limit affiliated))
3835 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3836 ;; Keywords.
3837 ((looking-at "[ \t]*#")
3838 (goto-char (match-end 0))
3839 (cond ((looking-at "\\(?: \\|$\\)")
3840 (beginning-of-line)
3841 (org-element-comment-parser limit affiliated))
3842 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3843 (beginning-of-line)
3844 (let ((parser (assoc (upcase (match-string 1))
3845 org-element-block-name-alist)))
3846 (if parser (funcall (cdr parser) limit affiliated)
3847 (org-element-special-block-parser limit affiliated))))
3848 ((looking-at "\\+CALL:")
3849 (beginning-of-line)
3850 (org-element-babel-call-parser limit affiliated))
3851 ((looking-at "\\+BEGIN:? ")
3852 (beginning-of-line)
3853 (org-element-dynamic-block-parser limit affiliated))
3854 ((looking-at "\\+\\S-+:")
3855 (beginning-of-line)
3856 (org-element-keyword-parser limit affiliated))
3858 (beginning-of-line)
3859 (org-element-paragraph-parser limit affiliated))))
3860 ;; Footnote Definition.
3861 ((looking-at org-footnote-definition-re)
3862 (org-element-footnote-definition-parser limit affiliated))
3863 ;; Horizontal Rule.
3864 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3865 (org-element-horizontal-rule-parser limit affiliated))
3866 ;; Diary Sexp.
3867 ((looking-at "%%(")
3868 (org-element-diary-sexp-parser limit affiliated))
3869 ;; Table.
3870 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3871 ;; List.
3872 ((looking-at (org-item-re))
3873 (org-element-plain-list-parser
3874 limit affiliated
3875 (or structure (org-element--list-struct limit))))
3876 ;; Default element: Paragraph.
3877 (t (org-element-paragraph-parser limit affiliated)))))))))
3880 ;; Most elements can have affiliated keywords. When looking for an
3881 ;; element beginning, we want to move before them, as they belong to
3882 ;; that element, and, in the meantime, collect information they give
3883 ;; into appropriate properties. Hence the following function.
3885 (defun org-element--collect-affiliated-keywords (limit)
3886 "Collect affiliated keywords from point down to LIMIT.
3888 Return a list whose CAR is the position at the first of them and
3889 CDR a plist of keywords and values and move point to the
3890 beginning of the first line after them.
3892 As a special case, if element doesn't start at the beginning of
3893 the line (i.e. a paragraph starting an item), CAR is current
3894 position of point and CDR is nil."
3895 (if (not (bolp)) (list (point))
3896 (let ((case-fold-search t)
3897 (origin (point))
3898 ;; RESTRICT is the list of objects allowed in parsed
3899 ;; keywords value.
3900 (restrict (org-element-restriction 'keyword))
3901 output)
3902 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3903 (let* ((raw-kwd (upcase (match-string 1)))
3904 ;; Apply translation to RAW-KWD. From there, KWD is
3905 ;; the official keyword.
3906 (kwd (or (cdr (assoc raw-kwd
3907 org-element-keyword-translation-alist))
3908 raw-kwd))
3909 ;; Find main value for any keyword.
3910 (value
3911 (save-match-data
3912 (org-trim
3913 (buffer-substring-no-properties
3914 (match-end 0) (point-at-eol)))))
3915 ;; PARSEDP is non-nil when keyword should have its
3916 ;; value parsed.
3917 (parsedp (member kwd org-element-parsed-keywords))
3918 ;; If KWD is a dual keyword, find its secondary
3919 ;; value. Maybe parse it.
3920 (dualp (member kwd org-element-dual-keywords))
3921 (dual-value
3922 (and dualp
3923 (let ((sec (org-match-string-no-properties 2)))
3924 (if (or (not sec) (not parsedp)) sec
3925 (org-element-parse-secondary-string sec restrict)))))
3926 ;; Attribute a property name to KWD.
3927 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3928 ;; Now set final shape for VALUE.
3929 (when parsedp
3930 (setq value (org-element-parse-secondary-string value restrict)))
3931 (when dualp
3932 (setq value (and (or value dual-value) (cons value dual-value))))
3933 (when (or (member kwd org-element-multiple-keywords)
3934 ;; Attributes can always appear on multiple lines.
3935 (string-match "^ATTR_" kwd))
3936 (setq value (cons value (plist-get output kwd-sym))))
3937 ;; Eventually store the new value in OUTPUT.
3938 (setq output (plist-put output kwd-sym value))
3939 ;; Move to next keyword.
3940 (forward-line)))
3941 ;; If affiliated keywords are orphaned: move back to first one.
3942 ;; They will be parsed as a paragraph.
3943 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3944 ;; Return value.
3945 (cons origin output))))
3949 ;;; The Org Parser
3951 ;; The two major functions here are `org-element-parse-buffer', which
3952 ;; parses Org syntax inside the current buffer, taking into account
3953 ;; region, narrowing, or even visibility if specified, and
3954 ;; `org-element-parse-secondary-string', which parses objects within
3955 ;; a given string.
3957 ;; The (almost) almighty `org-element-map' allows to apply a function
3958 ;; on elements or objects matching some type, and accumulate the
3959 ;; resulting values. In an export situation, it also skips unneeded
3960 ;; parts of the parse tree.
3962 (defun org-element-parse-buffer (&optional granularity visible-only)
3963 "Recursively parse the buffer and return structure.
3964 If narrowing is in effect, only parse the visible part of the
3965 buffer.
3967 Optional argument GRANULARITY determines the depth of the
3968 recursion. It can be set to the following symbols:
3970 `headline' Only parse headlines.
3971 `greater-element' Don't recurse into greater elements excepted
3972 headlines and sections. Thus, elements
3973 parsed are the top-level ones.
3974 `element' Parse everything but objects and plain text.
3975 `object' Parse the complete buffer (default).
3977 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3978 elements.
3980 An element or an objects is represented as a list with the
3981 pattern (TYPE PROPERTIES CONTENTS), where :
3983 TYPE is a symbol describing the element or object. See
3984 `org-element-all-elements' and `org-element-all-objects' for an
3985 exhaustive list of such symbols. One can retrieve it with
3986 `org-element-type' function.
3988 PROPERTIES is the list of attributes attached to the element or
3989 object, as a plist. Although most of them are specific to the
3990 element or object type, all types share `:begin', `:end',
3991 `:post-blank' and `:parent' properties, which respectively
3992 refer to buffer position where the element or object starts,
3993 ends, the number of white spaces or blank lines after it, and
3994 the element or object containing it. Properties values can be
3995 obtained by using `org-element-property' function.
3997 CONTENTS is a list of elements, objects or raw strings
3998 contained in the current element or object, when applicable.
3999 One can access them with `org-element-contents' function.
4001 The Org buffer has `org-data' as type and nil as properties.
4002 `org-element-map' function can be used to find specific elements
4003 or objects within the parse tree.
4005 This function assumes that current major mode is `org-mode'."
4006 (save-excursion
4007 (goto-char (point-min))
4008 (org-skip-whitespace)
4009 (org-element--parse-elements
4010 (point-at-bol) (point-max)
4011 ;; Start in `first-section' mode so text before the first
4012 ;; headline belongs to a section.
4013 'first-section nil granularity visible-only (list 'org-data nil))))
4015 (defun org-element-parse-secondary-string (string restriction &optional parent)
4016 "Recursively parse objects in STRING and return structure.
4018 RESTRICTION is a symbol limiting the object types that will be
4019 looked after.
4021 Optional argument PARENT, when non-nil, is the element or object
4022 containing the secondary string. It is used to set correctly
4023 `:parent' property within the string."
4024 ;; Copy buffer-local variables listed in
4025 ;; `org-element-object-variables' into temporary buffer. This is
4026 ;; required since object parsing is dependent on these variables.
4027 (let ((pairs (delq nil (mapcar (lambda (var)
4028 (when (boundp var)
4029 (cons var (symbol-value var))))
4030 org-element-object-variables))))
4031 (with-temp-buffer
4032 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4033 (insert string)
4034 (let ((secondary (org-element--parse-objects
4035 (point-min) (point-max) nil restriction)))
4036 (when parent
4037 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4038 secondary))
4039 secondary))))
4041 (defun org-element-map
4042 (data types fun &optional info first-match no-recursion with-affiliated)
4043 "Map a function on selected elements or objects.
4045 DATA is a parse tree, an element, an object, a string, or a list
4046 of such constructs. TYPES is a symbol or list of symbols of
4047 elements or objects types (see `org-element-all-elements' and
4048 `org-element-all-objects' for a complete list of types). FUN is
4049 the function called on the matching element or object. It has to
4050 accept one argument: the element or object itself.
4052 When optional argument INFO is non-nil, it should be a plist
4053 holding export options. In that case, parts of the parse tree
4054 not exportable according to that property list will be skipped.
4056 When optional argument FIRST-MATCH is non-nil, stop at the first
4057 match for which FUN doesn't return nil, and return that value.
4059 Optional argument NO-RECURSION is a symbol or a list of symbols
4060 representing elements or objects types. `org-element-map' won't
4061 enter any recursive element or object whose type belongs to that
4062 list. Though, FUN can still be applied on them.
4064 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4065 apply to matching objects within parsed affiliated keywords (see
4066 `org-element-parsed-keywords').
4068 Nil values returned from FUN do not appear in the results.
4071 Examples:
4072 ---------
4074 Assuming TREE is a variable containing an Org buffer parse tree,
4075 the following example will return a flat list of all `src-block'
4076 and `example-block' elements in it:
4078 \(org-element-map tree '(example-block src-block) 'identity)
4080 The following snippet will find the first headline with a level
4081 of 1 and a \"phone\" tag, and will return its beginning position:
4083 \(org-element-map tree 'headline
4084 \(lambda (hl)
4085 \(and (= (org-element-property :level hl) 1)
4086 \(member \"phone\" (org-element-property :tags hl))
4087 \(org-element-property :begin hl)))
4088 nil t)
4090 The next example will return a flat list of all `plain-list' type
4091 elements in TREE that are not a sub-list themselves:
4093 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4095 Eventually, this example will return a flat list of all `bold'
4096 type objects containing a `latex-snippet' type object, even
4097 looking into captions:
4099 \(org-element-map tree 'bold
4100 \(lambda (b)
4101 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4102 nil nil nil t)"
4103 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4104 (unless (listp types) (setq types (list types)))
4105 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4106 ;; Recursion depth is determined by --CATEGORY.
4107 (let* ((--category
4108 (catch 'found
4109 (let ((category 'greater-elements))
4110 (mapc (lambda (type)
4111 (cond ((or (memq type org-element-all-objects)
4112 (eq type 'plain-text))
4113 ;; If one object is found, the function
4114 ;; has to recurse into every object.
4115 (throw 'found 'objects))
4116 ((not (memq type org-element-greater-elements))
4117 ;; If one regular element is found, the
4118 ;; function has to recurse, at least,
4119 ;; into every element it encounters.
4120 (and (not (eq category 'elements))
4121 (setq category 'elements)))))
4122 types)
4123 category)))
4124 ;; Compute properties for affiliated keywords if necessary.
4125 (--affiliated-alist
4126 (and with-affiliated
4127 (mapcar (lambda (kwd)
4128 (cons kwd (intern (concat ":" (downcase kwd)))))
4129 org-element-affiliated-keywords)))
4130 --acc
4131 --walk-tree
4132 (--walk-tree
4133 (function
4134 (lambda (--data)
4135 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4136 ;; holding contextual information.
4137 (let ((--type (org-element-type --data)))
4138 (cond
4139 ((not --data))
4140 ;; Ignored element in an export context.
4141 ((and info (memq --data (plist-get info :ignore-list))))
4142 ;; List of elements or objects.
4143 ((not --type) (mapc --walk-tree --data))
4144 ;; Unconditionally enter parse trees.
4145 ((eq --type 'org-data)
4146 (mapc --walk-tree (org-element-contents --data)))
4148 ;; Check if TYPE is matching among TYPES. If so,
4149 ;; apply FUN to --DATA and accumulate return value
4150 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4151 (when (memq --type types)
4152 (let ((result (funcall fun --data)))
4153 (cond ((not result))
4154 (first-match (throw '--map-first-match result))
4155 (t (push result --acc)))))
4156 ;; If --DATA has a secondary string that can contain
4157 ;; objects with their type among TYPES, look into it.
4158 (when (and (eq --category 'objects) (not (stringp --data)))
4159 (let ((sec-prop
4160 (assq --type org-element-secondary-value-alist)))
4161 (when sec-prop
4162 (funcall --walk-tree
4163 (org-element-property (cdr sec-prop) --data)))))
4164 ;; If --DATA has any affiliated keywords and
4165 ;; WITH-AFFILIATED is non-nil, look for objects in
4166 ;; them.
4167 (when (and with-affiliated
4168 (eq --category 'objects)
4169 (memq --type org-element-all-elements))
4170 (mapc (lambda (kwd-pair)
4171 (let ((kwd (car kwd-pair))
4172 (value (org-element-property
4173 (cdr kwd-pair) --data)))
4174 ;; Pay attention to the type of value.
4175 ;; Preserve order for multiple keywords.
4176 (cond
4177 ((not value))
4178 ((and (member kwd org-element-multiple-keywords)
4179 (member kwd org-element-dual-keywords))
4180 (mapc (lambda (line)
4181 (funcall --walk-tree (cdr line))
4182 (funcall --walk-tree (car line)))
4183 (reverse value)))
4184 ((member kwd org-element-multiple-keywords)
4185 (mapc (lambda (line) (funcall --walk-tree line))
4186 (reverse value)))
4187 ((member kwd org-element-dual-keywords)
4188 (funcall --walk-tree (cdr value))
4189 (funcall --walk-tree (car value)))
4190 (t (funcall --walk-tree value)))))
4191 --affiliated-alist))
4192 ;; Determine if a recursion into --DATA is possible.
4193 (cond
4194 ;; --TYPE is explicitly removed from recursion.
4195 ((memq --type no-recursion))
4196 ;; --DATA has no contents.
4197 ((not (org-element-contents --data)))
4198 ;; Looking for greater elements but --DATA is simply
4199 ;; an element or an object.
4200 ((and (eq --category 'greater-elements)
4201 (not (memq --type org-element-greater-elements))))
4202 ;; Looking for elements but --DATA is an object.
4203 ((and (eq --category 'elements)
4204 (memq --type org-element-all-objects)))
4205 ;; In any other case, map contents.
4206 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4207 (catch '--map-first-match
4208 (funcall --walk-tree data)
4209 ;; Return value in a proper order.
4210 (nreverse --acc))))
4211 (put 'org-element-map 'lisp-indent-function 2)
4213 ;; The following functions are internal parts of the parser.
4215 ;; The first one, `org-element--parse-elements' acts at the element's
4216 ;; level.
4218 ;; The second one, `org-element--parse-objects' applies on all objects
4219 ;; of a paragraph or a secondary string. It uses
4220 ;; `org-element--get-next-object-candidates' to optimize the search of
4221 ;; the next object in the buffer.
4223 ;; More precisely, that function looks for every allowed object type
4224 ;; first. Then, it discards failed searches, keeps further matches,
4225 ;; and searches again types matched behind point, for subsequent
4226 ;; calls. Thus, searching for a given type fails only once, and every
4227 ;; object is searched only once at top level (but sometimes more for
4228 ;; nested types).
4230 (defun org-element--parse-elements
4231 (beg end special structure granularity visible-only acc)
4232 "Parse elements between BEG and END positions.
4234 SPECIAL prioritize some elements over the others. It can be set
4235 to `first-section', `quote-section', `section' `item' or
4236 `table-row'.
4238 When value is `item', STRUCTURE will be used as the current list
4239 structure.
4241 GRANULARITY determines the depth of the recursion. See
4242 `org-element-parse-buffer' for more information.
4244 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4245 elements.
4247 Elements are accumulated into ACC."
4248 (save-excursion
4249 (goto-char beg)
4250 ;; Visible only: skip invisible parts at the beginning of the
4251 ;; element.
4252 (when (and visible-only (org-invisible-p2))
4253 (goto-char (min (1+ (org-find-visible)) end)))
4254 ;; When parsing only headlines, skip any text before first one.
4255 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4256 (org-with-limited-levels (outline-next-heading)))
4257 ;; Main loop start.
4258 (while (< (point) end)
4259 ;; Find current element's type and parse it accordingly to
4260 ;; its category.
4261 (let* ((element (org-element--current-element
4262 end granularity special structure))
4263 (type (org-element-type element))
4264 (cbeg (org-element-property :contents-begin element)))
4265 (goto-char (org-element-property :end element))
4266 ;; Visible only: skip invisible parts between siblings.
4267 (when (and visible-only (org-invisible-p2))
4268 (goto-char (min (1+ (org-find-visible)) end)))
4269 ;; Fill ELEMENT contents by side-effect.
4270 (cond
4271 ;; If element has no contents, don't modify it.
4272 ((not cbeg))
4273 ;; Greater element: parse it between `contents-begin' and
4274 ;; `contents-end'. Make sure GRANULARITY allows the
4275 ;; recursion, or ELEMENT is a headline, in which case going
4276 ;; inside is mandatory, in order to get sub-level headings.
4277 ((and (memq type org-element-greater-elements)
4278 (or (memq granularity '(element object nil))
4279 (and (eq granularity 'greater-element)
4280 (eq type 'section))
4281 (eq type 'headline)))
4282 (org-element--parse-elements
4283 cbeg (org-element-property :contents-end element)
4284 ;; Possibly switch to a special mode.
4285 (case type
4286 (headline
4287 (if (org-element-property :quotedp element) 'quote-section
4288 'section))
4289 (plain-list 'item)
4290 (property-drawer 'node-property)
4291 (table 'table-row))
4292 (and (memq type '(item plain-list))
4293 (org-element-property :structure element))
4294 granularity visible-only element))
4295 ;; ELEMENT has contents. Parse objects inside, if
4296 ;; GRANULARITY allows it.
4297 ((memq granularity '(object nil))
4298 (org-element--parse-objects
4299 cbeg (org-element-property :contents-end element) element
4300 (org-element-restriction type))))
4301 (org-element-adopt-elements acc element)))
4302 ;; Return result.
4303 acc))
4305 (defun org-element--parse-objects (beg end acc restriction)
4306 "Parse objects between BEG and END and return recursive structure.
4308 Objects are accumulated in ACC.
4310 RESTRICTION is a list of object successors which are allowed in
4311 the current object."
4312 (let ((candidates 'initial))
4313 (save-excursion
4314 (save-restriction
4315 (narrow-to-region beg end)
4316 (goto-char (point-min))
4317 (while (and (not (eobp))
4318 (setq candidates
4319 (org-element--get-next-object-candidates
4320 restriction candidates)))
4321 (let ((next-object
4322 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4323 (save-excursion
4324 (goto-char pos)
4325 (funcall (intern (format "org-element-%s-parser"
4326 (car (rassq pos candidates)))))))))
4327 ;; 1. Text before any object. Untabify it.
4328 (let ((obj-beg (org-element-property :begin next-object)))
4329 (unless (= (point) obj-beg)
4330 (setq acc
4331 (org-element-adopt-elements
4333 (replace-regexp-in-string
4334 "\t" (make-string tab-width ? )
4335 (buffer-substring-no-properties (point) obj-beg))))))
4336 ;; 2. Object...
4337 (let ((obj-end (org-element-property :end next-object))
4338 (cont-beg (org-element-property :contents-begin next-object)))
4339 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4340 ;; a recursive type.
4341 (when (and cont-beg
4342 (memq (car next-object) org-element-recursive-objects))
4343 (org-element--parse-objects
4344 cont-beg (org-element-property :contents-end next-object)
4345 next-object (org-element-restriction next-object)))
4346 (setq acc (org-element-adopt-elements acc next-object))
4347 (goto-char obj-end))))
4348 ;; 3. Text after last object. Untabify it.
4349 (unless (eobp)
4350 (setq acc
4351 (org-element-adopt-elements
4353 (replace-regexp-in-string
4354 "\t" (make-string tab-width ? )
4355 (buffer-substring-no-properties (point) end)))))
4356 ;; Result.
4357 acc))))
4359 (defun org-element--get-next-object-candidates (restriction objects)
4360 "Return an alist of candidates for the next object.
4362 RESTRICTION is a list of object types, as symbols. Only
4363 candidates with such types are looked after.
4365 OBJECTS is the previous candidates alist. If it is set to
4366 `initial', no search has been done before, and all symbols in
4367 RESTRICTION should be looked after.
4369 Return value is an alist whose CAR is the object type and CDR its
4370 beginning position."
4371 (delq
4373 (if (eq objects 'initial)
4374 ;; When searching for the first time, look for every successor
4375 ;; allowed in RESTRICTION.
4376 (mapcar
4377 (lambda (res)
4378 (funcall (intern (format "org-element-%s-successor" res))))
4379 restriction)
4380 ;; Focus on objects returned during last search. Keep those
4381 ;; still after point. Search again objects before it.
4382 (mapcar
4383 (lambda (obj)
4384 (if (>= (cdr obj) (point)) obj
4385 (let* ((type (car obj))
4386 (succ (or (cdr (assq type org-element-object-successor-alist))
4387 type)))
4388 (and succ
4389 (funcall (intern (format "org-element-%s-successor" succ)))))))
4390 objects))))
4394 ;;; Towards A Bijective Process
4396 ;; The parse tree obtained with `org-element-parse-buffer' is really
4397 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4398 ;; interpreted and expanded into a string with canonical Org syntax.
4399 ;; Hence `org-element-interpret-data'.
4401 ;; The function relies internally on
4402 ;; `org-element--interpret-affiliated-keywords'.
4404 ;;;###autoload
4405 (defun org-element-interpret-data (data &optional parent)
4406 "Interpret DATA as Org syntax.
4408 DATA is a parse tree, an element, an object or a secondary string
4409 to interpret.
4411 Optional argument PARENT is used for recursive calls. It contains
4412 the element or object containing data, or nil.
4414 Return Org syntax as a string."
4415 (let* ((type (org-element-type data))
4416 (results
4417 (cond
4418 ;; Secondary string.
4419 ((not type)
4420 (mapconcat
4421 (lambda (obj) (org-element-interpret-data obj parent))
4422 data ""))
4423 ;; Full Org document.
4424 ((eq type 'org-data)
4425 (mapconcat
4426 (lambda (obj) (org-element-interpret-data obj parent))
4427 (org-element-contents data) ""))
4428 ;; Plain text: remove `:parent' text property from output.
4429 ((stringp data) (org-no-properties data))
4430 ;; Element/Object without contents.
4431 ((not (org-element-contents data))
4432 (funcall (intern (format "org-element-%s-interpreter" type))
4433 data nil))
4434 ;; Element/Object with contents.
4436 (let* ((greaterp (memq type org-element-greater-elements))
4437 (objectp (and (not greaterp)
4438 (memq type org-element-recursive-objects)))
4439 (contents
4440 (mapconcat
4441 (lambda (obj) (org-element-interpret-data obj data))
4442 (org-element-contents
4443 (if (or greaterp objectp) data
4444 ;; Elements directly containing objects must
4445 ;; have their indentation normalized first.
4446 (org-element-normalize-contents
4447 data
4448 ;; When normalizing first paragraph of an
4449 ;; item or a footnote-definition, ignore
4450 ;; first line's indentation.
4451 (and (eq type 'paragraph)
4452 (equal data (car (org-element-contents parent)))
4453 (memq (org-element-type parent)
4454 '(footnote-definition item))))))
4455 "")))
4456 (funcall (intern (format "org-element-%s-interpreter" type))
4457 data
4458 (if greaterp (org-element-normalize-contents contents)
4459 contents)))))))
4460 (if (memq type '(org-data plain-text nil)) results
4461 ;; Build white spaces. If no `:post-blank' property is
4462 ;; specified, assume its value is 0.
4463 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4464 (if (memq type org-element-all-objects)
4465 (concat results (make-string post-blank 32))
4466 (concat
4467 (org-element--interpret-affiliated-keywords data)
4468 (org-element-normalize-string results)
4469 (make-string post-blank 10)))))))
4471 (defun org-element--interpret-affiliated-keywords (element)
4472 "Return ELEMENT's affiliated keywords as Org syntax.
4473 If there is no affiliated keyword, return the empty string."
4474 (let ((keyword-to-org
4475 (function
4476 (lambda (key value)
4477 (let (dual)
4478 (when (member key org-element-dual-keywords)
4479 (setq dual (cdr value) value (car value)))
4480 (concat "#+" key
4481 (and dual
4482 (format "[%s]" (org-element-interpret-data dual)))
4483 ": "
4484 (if (member key org-element-parsed-keywords)
4485 (org-element-interpret-data value)
4486 value)
4487 "\n"))))))
4488 (mapconcat
4489 (lambda (prop)
4490 (let ((value (org-element-property prop element))
4491 (keyword (upcase (substring (symbol-name prop) 1))))
4492 (when value
4493 (if (or (member keyword org-element-multiple-keywords)
4494 ;; All attribute keywords can have multiple lines.
4495 (string-match "^ATTR_" keyword))
4496 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4497 (reverse value)
4499 (funcall keyword-to-org keyword value)))))
4500 ;; List all ELEMENT's properties matching an attribute line or an
4501 ;; affiliated keyword, but ignore translated keywords since they
4502 ;; cannot belong to the property list.
4503 (loop for prop in (nth 1 element) by 'cddr
4504 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4505 (or (string-match "^ATTR_" keyword)
4506 (and
4507 (member keyword org-element-affiliated-keywords)
4508 (not (assoc keyword
4509 org-element-keyword-translation-alist)))))
4510 collect prop)
4511 "")))
4513 ;; Because interpretation of the parse tree must return the same
4514 ;; number of blank lines between elements and the same number of white
4515 ;; space after objects, some special care must be given to white
4516 ;; spaces.
4518 ;; The first function, `org-element-normalize-string', ensures any
4519 ;; string different from the empty string will end with a single
4520 ;; newline character.
4522 ;; The second function, `org-element-normalize-contents', removes
4523 ;; global indentation from the contents of the current element.
4525 (defun org-element-normalize-string (s)
4526 "Ensure string S ends with a single newline character.
4528 If S isn't a string return it unchanged. If S is the empty
4529 string, return it. Otherwise, return a new string with a single
4530 newline character at its end."
4531 (cond
4532 ((not (stringp s)) s)
4533 ((string= "" s) "")
4534 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4535 (replace-match "\n" nil nil s)))))
4537 (defun org-element-normalize-contents (element &optional ignore-first)
4538 "Normalize plain text in ELEMENT's contents.
4540 ELEMENT must only contain plain text and objects.
4542 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4543 indentation to compute maximal common indentation.
4545 Return the normalized element that is element with global
4546 indentation removed from its contents. The function assumes that
4547 indentation is not done with TAB characters."
4548 (let* (ind-list ; for byte-compiler
4549 collect-inds ; for byte-compiler
4550 (collect-inds
4551 (function
4552 ;; Return list of indentations within BLOB. This is done by
4553 ;; walking recursively BLOB and updating IND-LIST along the
4554 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4555 ;; been seen yet. It is required as this string is the only
4556 ;; one whose indentation doesn't happen after a newline
4557 ;; character.
4558 (lambda (blob first-flag)
4559 (mapc
4560 (lambda (object)
4561 (when (and first-flag (stringp object))
4562 (setq first-flag nil)
4563 (string-match "\\`\\( *\\)" object)
4564 (let ((len (length (match-string 1 object))))
4565 ;; An indentation of zero means no string will be
4566 ;; modified. Quit the process.
4567 (if (zerop len) (throw 'zero (setq ind-list nil))
4568 (push len ind-list))))
4569 (cond
4570 ((stringp object)
4571 (let ((start 0))
4572 ;; Avoid matching blank or empty lines.
4573 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4574 (not (equal (match-string 2 object) " ")))
4575 (setq start (match-end 0))
4576 (push (length (match-string 1 object)) ind-list))))
4577 ((memq (org-element-type object) org-element-recursive-objects)
4578 (funcall collect-inds object first-flag))))
4579 (org-element-contents blob))))))
4580 ;; Collect indentation list in ELEMENT. Possibly remove first
4581 ;; value if IGNORE-FIRST is non-nil.
4582 (catch 'zero (funcall collect-inds element (not ignore-first)))
4583 (if (not ind-list) element
4584 ;; Build ELEMENT back, replacing each string with the same
4585 ;; string minus common indentation.
4586 (let* (build ; For byte compiler.
4587 (build
4588 (function
4589 (lambda (blob mci first-flag)
4590 ;; Return BLOB with all its strings indentation
4591 ;; shortened from MCI white spaces. FIRST-FLAG is
4592 ;; non-nil when the first string hasn't been seen
4593 ;; yet.
4594 (setcdr (cdr blob)
4595 (mapcar
4596 (lambda (object)
4597 (when (and first-flag (stringp object))
4598 (setq first-flag nil)
4599 (setq object
4600 (replace-regexp-in-string
4601 (format "\\` \\{%d\\}" mci) "" object)))
4602 (cond
4603 ((stringp object)
4604 (replace-regexp-in-string
4605 (format "\n \\{%d\\}" mci) "\n" object))
4606 ((memq (org-element-type object)
4607 org-element-recursive-objects)
4608 (funcall build object mci first-flag))
4609 (t object)))
4610 (org-element-contents blob)))
4611 blob))))
4612 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4616 ;;; The Toolbox
4618 ;; The first move is to implement a way to obtain the smallest element
4619 ;; containing point. This is the job of `org-element-at-point'. It
4620 ;; basically jumps back to the beginning of section containing point
4621 ;; and moves, element after element, with
4622 ;; `org-element--current-element' until the container is found. Note:
4623 ;; When using `org-element-at-point', secondary values are never
4624 ;; parsed since the function focuses on elements, not on objects.
4626 ;; At a deeper level, `org-element-context' lists all elements and
4627 ;; objects containing point.
4629 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4630 ;; internally by navigation and manipulation tools.
4632 ;;;###autoload
4633 (defun org-element-at-point (&optional keep-trail)
4634 "Determine closest element around point.
4636 Return value is a list like (TYPE PROPS) where TYPE is the type
4637 of the element and PROPS a plist of properties associated to the
4638 element.
4640 Possible types are defined in `org-element-all-elements'.
4641 Properties depend on element or object type, but always include
4642 `:begin', `:end', `:parent' and `:post-blank' properties.
4644 As a special case, if point is at the very beginning of a list or
4645 sub-list, returned element will be that list instead of the first
4646 item. In the same way, if point is at the beginning of the first
4647 row of a table, returned element will be the table instead of the
4648 first row.
4650 If optional argument KEEP-TRAIL is non-nil, the function returns
4651 a list of elements leading to element at point. The list's CAR
4652 is always the element at point. The following positions contain
4653 element's siblings, then parents, siblings of parents, until the
4654 first element of current section."
4655 (org-with-wide-buffer
4656 ;; If at a headline, parse it. It is the sole element that
4657 ;; doesn't require to know about context. Be sure to disallow
4658 ;; secondary string parsing, though.
4659 (if (org-with-limited-levels (org-at-heading-p))
4660 (progn
4661 (beginning-of-line)
4662 (if (not keep-trail) (org-element-headline-parser (point-max) t)
4663 (list (org-element-headline-parser (point-max) t))))
4664 ;; Otherwise move at the beginning of the section containing
4665 ;; point.
4666 (catch 'exit
4667 (let ((origin (point))
4668 (end (save-excursion
4669 (org-with-limited-levels (outline-next-heading)) (point)))
4670 element type special-flag trail struct prevs parent)
4671 (org-with-limited-levels
4672 (if (org-before-first-heading-p)
4673 ;; In empty lines at buffer's beginning, return nil.
4674 (progn (goto-char (point-min))
4675 (org-skip-whitespace)
4676 (when (or (eobp) (> (line-beginning-position) origin))
4677 (throw 'exit nil)))
4678 (org-back-to-heading)
4679 (forward-line)
4680 (org-skip-whitespace)
4681 (when (or (eobp) (> (line-beginning-position) origin))
4682 ;; In blank lines just after the headline, point still
4683 ;; belongs to the headline.
4684 (throw 'exit
4685 (progn (skip-chars-backward " \r\t\n")
4686 (beginning-of-line)
4687 (if (not keep-trail)
4688 (org-element-headline-parser (point-max) t)
4689 (list (org-element-headline-parser
4690 (point-max) t))))))))
4691 (beginning-of-line)
4692 ;; Parse successively each element, skipping those ending
4693 ;; before original position.
4694 (while t
4695 (setq element
4696 (org-element--current-element end 'element special-flag struct)
4697 type (car element))
4698 (org-element-put-property element :parent parent)
4699 (when keep-trail (push element trail))
4700 (cond
4701 ;; 1. Skip any element ending before point. Also skip
4702 ;; element ending at point when we're sure that another
4703 ;; element has started.
4704 ((let ((elem-end (org-element-property :end element)))
4705 (when (or (< elem-end origin)
4706 (and (= elem-end origin) (/= elem-end end)))
4707 (goto-char elem-end))))
4708 ;; 2. An element containing point is always the element at
4709 ;; point.
4710 ((not (memq type org-element-greater-elements))
4711 (throw 'exit (if keep-trail trail element)))
4712 ;; 3. At any other greater element type, if point is
4713 ;; within contents, move into it.
4715 (let ((cbeg (org-element-property :contents-begin element))
4716 (cend (org-element-property :contents-end element)))
4717 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
4718 ;; Create an anchor for tables and plain lists:
4719 ;; when point is at the very beginning of these
4720 ;; elements, ignoring affiliated keywords,
4721 ;; target them instead of their contents.
4722 (and (= cbeg origin) (memq type '(plain-list table)))
4723 ;; When point is at contents end, do not move
4724 ;; into elements with an explicit ending, but
4725 ;; return that element instead.
4726 (and (= cend origin)
4727 (or (memq type
4728 '(center-block
4729 drawer dynamic-block inlinetask
4730 property-drawer quote-block
4731 special-block))
4732 ;; Corner case: if a list ends at the
4733 ;; end of a buffer without a final new
4734 ;; line, return last element in last
4735 ;; item instead.
4736 (and (memq type '(item plain-list))
4737 (progn (goto-char cend)
4738 (or (bolp) (not (eobp))))))))
4739 (throw 'exit (if keep-trail trail element))
4740 (setq parent element)
4741 (case type
4742 (plain-list
4743 (setq special-flag 'item
4744 struct (org-element-property :structure element)))
4745 (item (setq special-flag nil))
4746 (property-drawer
4747 (setq special-flag 'node-property struct nil))
4748 (table (setq special-flag 'table-row struct nil))
4749 (otherwise (setq special-flag nil struct nil)))
4750 (setq end cend)
4751 (goto-char cbeg)))))))))))
4753 ;;;###autoload
4754 (defun org-element-context (&optional element)
4755 "Return closest element or object around point.
4757 Return value is a list like (TYPE PROPS) where TYPE is the type
4758 of the element or object and PROPS a plist of properties
4759 associated to it.
4761 Possible types are defined in `org-element-all-elements' and
4762 `org-element-all-objects'. Properties depend on element or
4763 object type, but always include `:begin', `:end', `:parent' and
4764 `:post-blank'.
4766 Optional argument ELEMENT, when non-nil, is the closest element
4767 containing point, as returned by `org-element-at-point'.
4768 Providing it allows for quicker computation."
4769 (catch 'objects-forbidden
4770 (org-with-wide-buffer
4771 (let* ((origin (point))
4772 (element (or element (org-element-at-point)))
4773 (type (org-element-type element))
4774 context)
4775 ;; Check if point is inside an element containing objects or at
4776 ;; a secondary string. In that case, narrow buffer to the
4777 ;; containing area. Otherwise, return ELEMENT.
4778 (cond
4779 ;; At a parsed affiliated keyword, check if we're inside main
4780 ;; or dual value.
4781 ((let ((post (org-element-property :post-affiliated element)))
4782 (and post (< origin post)))
4783 (beginning-of-line)
4784 (looking-at org-element--affiliated-re)
4785 (cond
4786 ((not (member (upcase (match-string 1)) org-element-parsed-keywords))
4787 (throw 'objects-forbidden element))
4788 ((< (match-end 0) origin)
4789 (narrow-to-region (match-end 0) (line-end-position)))
4790 ((and (match-beginning 2)
4791 (>= origin (match-beginning 2))
4792 (< origin (match-end 2)))
4793 (narrow-to-region (match-beginning 2) (match-end 2)))
4794 (t (throw 'objects-forbidden element)))
4795 ;; Also change type to retrieve correct restrictions.
4796 (setq type 'keyword))
4797 ;; At an item, objects can only be located within tag, if any.
4798 ((eq type 'item)
4799 (let ((tag (org-element-property :tag element)))
4800 (if (not tag) (throw 'objects-forbidden element)
4801 (beginning-of-line)
4802 (search-forward tag (line-end-position))
4803 (goto-char (match-beginning 0))
4804 (if (and (>= origin (point)) (< origin (match-end 0)))
4805 (narrow-to-region (point) (match-end 0))
4806 (throw 'objects-forbidden element)))))
4807 ;; At an headline or inlinetask, objects are located within
4808 ;; their title.
4809 ((memq type '(headline inlinetask))
4810 (goto-char (org-element-property :begin element))
4811 (skip-chars-forward "* ")
4812 (if (and (>= origin (point)) (< origin (line-end-position)))
4813 (narrow-to-region (point) (line-end-position))
4814 (throw 'objects-forbidden element)))
4815 ;; At a paragraph, a table-row or a verse block, objects are
4816 ;; located within their contents.
4817 ((memq type '(paragraph table-row verse-block))
4818 (let ((cbeg (org-element-property :contents-begin element))
4819 (cend (org-element-property :contents-end element)))
4820 ;; CBEG is nil for table rules.
4821 (if (and cbeg cend (>= origin cbeg) (< origin cend))
4822 (narrow-to-region cbeg cend)
4823 (throw 'objects-forbidden element))))
4824 ;; At a parsed keyword, objects are located within value.
4825 ((eq type 'keyword)
4826 (if (not (member (org-element-property :key element)
4827 org-element-document-properties))
4828 (throw 'objects-forbidden element)
4829 (beginning-of-line)
4830 (search-forward ":")
4831 (if (and (>= origin (point)) (< origin (line-end-position)))
4832 (narrow-to-region (point) (line-end-position))
4833 (throw 'objects-forbidden element))))
4834 (t (throw 'objects-forbidden element)))
4835 (goto-char (point-min))
4836 (let ((restriction (org-element-restriction type))
4837 (parent element)
4838 (candidates 'initial))
4839 (catch 'exit
4840 (while (setq candidates
4841 (org-element--get-next-object-candidates
4842 restriction candidates))
4843 (let ((closest-cand (rassq (apply 'min (mapcar 'cdr candidates))
4844 candidates)))
4845 ;; If ORIGIN is before next object in element, there's
4846 ;; no point in looking further.
4847 (if (> (cdr closest-cand) origin) (throw 'exit parent)
4848 (let* ((object
4849 (progn (goto-char (cdr closest-cand))
4850 (funcall (intern (format "org-element-%s-parser"
4851 (car closest-cand))))))
4852 (cbeg (org-element-property :contents-begin object))
4853 (cend (org-element-property :contents-end object))
4854 (obj-end (org-element-property :end object)))
4855 (cond
4856 ;; ORIGIN is after OBJECT, so skip it.
4857 ((<= obj-end origin) (goto-char obj-end))
4858 ;; ORIGIN is within a non-recursive object or at
4859 ;; an object boundaries: Return that object.
4860 ((or (not cbeg) (< origin cbeg) (>= origin cend))
4861 (throw 'exit
4862 (org-element-put-property object :parent parent)))
4863 ;; Otherwise, move within current object and
4864 ;; restrict search to the end of its contents.
4865 (t (goto-char cbeg)
4866 (narrow-to-region (point) cend)
4867 (org-element-put-property object :parent parent)
4868 (setq parent object
4869 restriction (org-element-restriction object)
4870 candidates 'initial)))))))
4871 parent))))))
4873 (defun org-element-nested-p (elem-A elem-B)
4874 "Non-nil when elements ELEM-A and ELEM-B are nested."
4875 (let ((beg-A (org-element-property :begin elem-A))
4876 (beg-B (org-element-property :begin elem-B))
4877 (end-A (org-element-property :end elem-A))
4878 (end-B (org-element-property :end elem-B)))
4879 (or (and (>= beg-A beg-B) (<= end-A end-B))
4880 (and (>= beg-B beg-A) (<= end-B end-A)))))
4882 (defun org-element-swap-A-B (elem-A elem-B)
4883 "Swap elements ELEM-A and ELEM-B.
4884 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
4885 end of ELEM-A."
4886 (goto-char (org-element-property :begin elem-A))
4887 ;; There are two special cases when an element doesn't start at bol:
4888 ;; the first paragraph in an item or in a footnote definition.
4889 (let ((specialp (not (bolp))))
4890 ;; Only a paragraph without any affiliated keyword can be moved at
4891 ;; ELEM-A position in such a situation. Note that the case of
4892 ;; a footnote definition is impossible: it cannot contain two
4893 ;; paragraphs in a row because it cannot contain a blank line.
4894 (if (and specialp
4895 (or (not (eq (org-element-type elem-B) 'paragraph))
4896 (/= (org-element-property :begin elem-B)
4897 (org-element-property :contents-begin elem-B))))
4898 (error "Cannot swap elements"))
4899 ;; In a special situation, ELEM-A will have no indentation. We'll
4900 ;; give it ELEM-B's (which will in, in turn, have no indentation).
4901 (let* ((ind-B (when specialp
4902 (goto-char (org-element-property :begin elem-B))
4903 (org-get-indentation)))
4904 (beg-A (org-element-property :begin elem-A))
4905 (end-A (save-excursion
4906 (goto-char (org-element-property :end elem-A))
4907 (skip-chars-backward " \r\t\n")
4908 (point-at-eol)))
4909 (beg-B (org-element-property :begin elem-B))
4910 (end-B (save-excursion
4911 (goto-char (org-element-property :end elem-B))
4912 (skip-chars-backward " \r\t\n")
4913 (point-at-eol)))
4914 ;; Store overlays responsible for visibility status. We
4915 ;; also need to store their boundaries as they will be
4916 ;; removed from buffer.
4917 (overlays
4918 (cons
4919 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4920 (overlays-in beg-A end-A))
4921 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4922 (overlays-in beg-B end-B))))
4923 ;; Get contents.
4924 (body-A (buffer-substring beg-A end-A))
4925 (body-B (delete-and-extract-region beg-B end-B)))
4926 (goto-char beg-B)
4927 (when specialp
4928 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
4929 (org-indent-to-column ind-B))
4930 (insert body-A)
4931 ;; Restore ex ELEM-A overlays.
4932 (let ((offset (- beg-B beg-A)))
4933 (mapc (lambda (ov)
4934 (move-overlay
4935 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
4936 (car overlays))
4937 (goto-char beg-A)
4938 (delete-region beg-A end-A)
4939 (insert body-B)
4940 ;; Restore ex ELEM-B overlays.
4941 (mapc (lambda (ov)
4942 (move-overlay
4943 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
4944 (cdr overlays)))
4945 (goto-char (org-element-property :end elem-B)))))
4947 (defun org-element-remove-indentation (s &optional n)
4948 "Remove maximum common indentation in string S and return it.
4949 When optional argument N is a positive integer, remove exactly
4950 that much characters from indentation, if possible, or return
4951 S as-is otherwise. Unlike to `org-remove-indentation', this
4952 function doesn't call `untabify' on S."
4953 (catch 'exit
4954 (with-temp-buffer
4955 (insert s)
4956 (goto-char (point-min))
4957 ;; Find maximum common indentation, if not specified.
4958 (setq n (or n
4959 (let ((min-ind (point-max)))
4960 (save-excursion
4961 (while (re-search-forward "^[ \t]*\\S-" nil t)
4962 (let ((ind (1- (current-column))))
4963 (if (zerop ind) (throw 'exit s)
4964 (setq min-ind (min min-ind ind))))))
4965 min-ind)))
4966 (if (zerop n) s
4967 ;; Remove exactly N indentation, but give up if not possible.
4968 (while (not (eobp))
4969 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
4970 (cond ((eolp) (delete-region (line-beginning-position) (point)))
4971 ((< ind n) (throw 'exit s))
4972 (t (org-indent-line-to (- ind n))))
4973 (forward-line)))
4974 (buffer-string)))))
4977 (provide 'org-element)
4979 ;; Local variables:
4980 ;; generated-autoload-file: "org-loaddefs.el"
4981 ;; End:
4983 ;;; org-element.el ends here