org-element: Small change to src block indentation
[org-mode.git] / lisp / org-element.el
blob254af3c6975b286bbf88992d000442a06d33c94c
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 (drawers-re (concat ":\\("
1150 (mapconcat 'regexp-quote org-drawers "\\|")
1151 "\\):[ \t]*$"))
1152 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1153 items struct)
1154 (save-excursion
1155 (catch 'exit
1156 (while t
1157 (cond
1158 ;; At limit: end all items.
1159 ((>= (point) limit)
1160 (throw 'exit
1161 (let ((end (progn (skip-chars-backward " \r\t\n")
1162 (forward-line)
1163 (point))))
1164 (dolist (item items (sort (nconc items struct)
1165 'car-less-than-car))
1166 (setcar (nthcdr 6 item) end)))))
1167 ;; At list end: end all items.
1168 ((looking-at org-list-end-re)
1169 (throw 'exit (dolist (item items (sort (nconc items struct)
1170 'car-less-than-car))
1171 (setcar (nthcdr 6 item) (point)))))
1172 ;; At a new item: end previous sibling.
1173 ((looking-at item-re)
1174 (let ((ind (save-excursion (skip-chars-forward " \t")
1175 (current-column))))
1176 (setq top-ind (min top-ind ind))
1177 (while (and items (<= ind (nth 1 (car items))))
1178 (let ((item (pop items)))
1179 (setcar (nthcdr 6 item) (point))
1180 (push item struct)))
1181 (push (progn (looking-at org-list-full-item-re)
1182 (let ((bullet (match-string-no-properties 1)))
1183 (list (point)
1185 bullet
1186 (match-string-no-properties 2) ; counter
1187 (match-string-no-properties 3) ; checkbox
1188 ;; Description tag.
1189 (and (save-match-data
1190 (string-match "[-+*]" bullet))
1191 (match-string-no-properties 4))
1192 ;; Ending position, unknown so far.
1193 nil)))
1194 items))
1195 (forward-line 1))
1196 ;; Skip empty lines.
1197 ((looking-at "^[ \t]*$") (forward-line))
1198 ;; Skip inline tasks and blank lines along the way.
1199 ((and inlinetask-re (looking-at inlinetask-re))
1200 (forward-line)
1201 (let ((origin (point)))
1202 (when (re-search-forward inlinetask-re limit t)
1203 (if (looking-at "^\\*+ END[ \t]*$") (forward-line)
1204 (goto-char origin)))))
1205 ;; At some text line. Check if it ends any previous item.
1207 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1208 (when (<= ind top-ind)
1209 (skip-chars-backward " \r\t\n")
1210 (forward-line))
1211 (while (<= ind (nth 1 (car items)))
1212 (let ((item (pop items)))
1213 (setcar (nthcdr 6 item) (line-beginning-position))
1214 (push item struct)
1215 (unless items
1216 (throw 'exit (sort struct 'car-less-than-car))))))
1217 ;; Skip blocks (any type) and drawers contents.
1218 (cond
1219 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1220 (re-search-forward
1221 (format "^[ \t]*#\\+END%s[ \t]*$"
1222 (org-match-string-no-properties 1))
1223 limit t)))
1224 ((and (looking-at drawers-re)
1225 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1226 (forward-line))))))))
1228 (defun org-element-plain-list-parser (limit affiliated structure)
1229 "Parse a plain list.
1231 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1232 the buffer position at the beginning of the first affiliated
1233 keyword and CDR is a plist of affiliated keywords along with
1234 their value. STRUCTURE is the structure of the plain list being
1235 parsed.
1237 Return a list whose CAR is `plain-list' and CDR is a plist
1238 containing `:type', `:begin', `:end', `:contents-begin' and
1239 `:contents-end', `:structure', `:post-blank' and
1240 `:post-affiliated' keywords.
1242 Assume point is at the beginning of the list."
1243 (save-excursion
1244 (let* ((struct (or structure (org-element--list-struct limit)))
1245 (prevs (org-list-prevs-alist struct))
1246 (type (org-list-get-list-type (point) struct prevs))
1247 (contents-begin (point))
1248 (begin (car affiliated))
1249 (contents-end
1250 (progn (goto-char (org-list-get-list-end (point) struct prevs))
1251 (unless (bolp) (forward-line))
1252 (point)))
1253 (end (progn (skip-chars-forward " \r\t\n" limit)
1254 (if (= (point) limit) limit (line-beginning-position)))))
1255 ;; Return value.
1256 (list 'plain-list
1257 (nconc
1258 (list :type type
1259 :begin begin
1260 :end end
1261 :contents-begin contents-begin
1262 :contents-end contents-end
1263 :structure struct
1264 :post-blank (count-lines contents-end end)
1265 :post-affiliated contents-begin)
1266 (cdr affiliated))))))
1268 (defun org-element-plain-list-interpreter (plain-list contents)
1269 "Interpret PLAIN-LIST element as Org syntax.
1270 CONTENTS is the contents of the element."
1271 (with-temp-buffer
1272 (insert contents)
1273 (goto-char (point-min))
1274 (org-list-repair)
1275 (buffer-string)))
1278 ;;;; Property Drawer
1280 (defun org-element-property-drawer-parser (limit affiliated)
1281 "Parse a property drawer.
1283 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1284 the buffer position at the beginning of the first affiliated
1285 keyword and CDR is a plist of affiliated keywords along with
1286 their value.
1288 Return a list whose CAR is `property-drawer' and CDR is a plist
1289 containing `:begin', `:end', `:contents-begin', `:contents-end',
1290 `:post-blank' and `:post-affiliated' keywords.
1292 Assume point is at the beginning of the property drawer."
1293 (save-excursion
1294 (let ((case-fold-search t))
1295 (if (not (save-excursion
1296 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1297 ;; Incomplete drawer: parse it as a paragraph.
1298 (org-element-paragraph-parser limit affiliated)
1299 (save-excursion
1300 (let* ((drawer-end-line (match-beginning 0))
1301 (begin (car affiliated))
1302 (post-affiliated (point))
1303 (contents-begin (progn (forward-line)
1304 (and (< (point) drawer-end-line)
1305 (point))))
1306 (contents-end (and contents-begin drawer-end-line))
1307 (pos-before-blank (progn (goto-char drawer-end-line)
1308 (forward-line)
1309 (point)))
1310 (end (progn (skip-chars-forward " \r\t\n" limit)
1311 (skip-chars-backward " \t")
1312 (if (bolp) (point) (line-end-position)))))
1313 (list 'property-drawer
1314 (nconc
1315 (list :begin begin
1316 :end end
1317 :contents-begin contents-begin
1318 :contents-end contents-end
1319 :post-blank (count-lines pos-before-blank end)
1320 :post-affiliated post-affiliated)
1321 (cdr affiliated)))))))))
1323 (defun org-element-property-drawer-interpreter (property-drawer contents)
1324 "Interpret PROPERTY-DRAWER element as Org syntax.
1325 CONTENTS is the properties within the drawer."
1326 (format ":PROPERTIES:\n%s:END:" contents))
1329 ;;;; Quote Block
1331 (defun org-element-quote-block-parser (limit affiliated)
1332 "Parse a quote block.
1334 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1335 the buffer position at the beginning of the first affiliated
1336 keyword and CDR is a plist of affiliated keywords along with
1337 their value.
1339 Return a list whose CAR is `quote-block' and CDR is a plist
1340 containing `:begin', `:end', `:contents-begin', `:contents-end',
1341 `:post-blank' and `:post-affiliated' keywords.
1343 Assume point is at the beginning of the block."
1344 (let ((case-fold-search t))
1345 (if (not (save-excursion
1346 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1347 ;; Incomplete block: parse it as a paragraph.
1348 (org-element-paragraph-parser limit affiliated)
1349 (let ((block-end-line (match-beginning 0)))
1350 (save-excursion
1351 (let* ((begin (car affiliated))
1352 (post-affiliated (point))
1353 ;; Empty blocks have no contents.
1354 (contents-begin (progn (forward-line)
1355 (and (< (point) block-end-line)
1356 (point))))
1357 (contents-end (and contents-begin block-end-line))
1358 (pos-before-blank (progn (goto-char block-end-line)
1359 (forward-line)
1360 (point)))
1361 (end (progn (skip-chars-forward " \r\t\n" limit)
1362 (skip-chars-backward " \t")
1363 (if (bolp) (point) (line-end-position)))))
1364 (list 'quote-block
1365 (nconc
1366 (list :begin begin
1367 :end end
1368 :contents-begin contents-begin
1369 :contents-end contents-end
1370 :post-blank (count-lines pos-before-blank end)
1371 :post-affiliated post-affiliated)
1372 (cdr affiliated)))))))))
1374 (defun org-element-quote-block-interpreter (quote-block contents)
1375 "Interpret QUOTE-BLOCK element as Org syntax.
1376 CONTENTS is the contents of the element."
1377 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1380 ;;;; Section
1382 (defun org-element-section-parser (limit)
1383 "Parse a section.
1385 LIMIT bounds the search.
1387 Return a list whose CAR is `section' and CDR is a plist
1388 containing `:begin', `:end', `:contents-begin', `contents-end'
1389 and `:post-blank' keywords."
1390 (save-excursion
1391 ;; Beginning of section is the beginning of the first non-blank
1392 ;; line after previous headline.
1393 (let ((begin (point))
1394 (end (progn (org-with-limited-levels (outline-next-heading))
1395 (point)))
1396 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1397 (forward-line)
1398 (point))))
1399 (list 'section
1400 (list :begin begin
1401 :end end
1402 :contents-begin begin
1403 :contents-end pos-before-blank
1404 :post-blank (count-lines pos-before-blank end))))))
1406 (defun org-element-section-interpreter (section contents)
1407 "Interpret SECTION element as Org syntax.
1408 CONTENTS is the contents of the element."
1409 contents)
1412 ;;;; Special Block
1414 (defun org-element-special-block-parser (limit affiliated)
1415 "Parse a special block.
1417 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1418 the buffer position at the beginning of the first affiliated
1419 keyword and CDR is a plist of affiliated keywords along with
1420 their value.
1422 Return a list whose CAR is `special-block' and CDR is a plist
1423 containing `:type', `:begin', `:end', `:contents-begin',
1424 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1426 Assume point is at the beginning of the block."
1427 (let* ((case-fold-search t)
1428 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1429 (upcase (match-string-no-properties 1)))))
1430 (if (not (save-excursion
1431 (re-search-forward
1432 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1433 limit t)))
1434 ;; Incomplete block: parse it as a paragraph.
1435 (org-element-paragraph-parser limit affiliated)
1436 (let ((block-end-line (match-beginning 0)))
1437 (save-excursion
1438 (let* ((begin (car affiliated))
1439 (post-affiliated (point))
1440 ;; Empty blocks have no contents.
1441 (contents-begin (progn (forward-line)
1442 (and (< (point) block-end-line)
1443 (point))))
1444 (contents-end (and contents-begin block-end-line))
1445 (pos-before-blank (progn (goto-char block-end-line)
1446 (forward-line)
1447 (point)))
1448 (end (progn (skip-chars-forward " \r\t\n" limit)
1449 (skip-chars-backward " \t")
1450 (if (bolp) (point) (line-end-position)))))
1451 (list 'special-block
1452 (nconc
1453 (list :type type
1454 :begin begin
1455 :end end
1456 :contents-begin contents-begin
1457 :contents-end contents-end
1458 :post-blank (count-lines pos-before-blank end)
1459 :post-affiliated post-affiliated)
1460 (cdr affiliated)))))))))
1462 (defun org-element-special-block-interpreter (special-block contents)
1463 "Interpret SPECIAL-BLOCK element as Org syntax.
1464 CONTENTS is the contents of the element."
1465 (let ((block-type (org-element-property :type special-block)))
1466 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1470 ;;; Elements
1472 ;; For each element, a parser and an interpreter are also defined.
1473 ;; Both follow the same naming convention used for greater elements.
1475 ;; Also, as for greater elements, adding a new element type is done
1476 ;; through the following steps: implement a parser and an interpreter,
1477 ;; tweak `org-element--current-element' so that it recognizes the new
1478 ;; type and add that new type to `org-element-all-elements'.
1480 ;; As a special case, when the newly defined type is a block type,
1481 ;; `org-element-block-name-alist' has to be modified accordingly.
1484 ;;;; Babel Call
1486 (defun org-element-babel-call-parser (limit affiliated)
1487 "Parse a babel call.
1489 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1490 the buffer position at the beginning of the first affiliated
1491 keyword and CDR is a plist of affiliated keywords along with
1492 their value.
1494 Return a list whose CAR is `babel-call' and CDR is a plist
1495 containing `:begin', `:end', `:value', `:post-blank' and
1496 `:post-affiliated' as keywords."
1497 (save-excursion
1498 (let ((begin (car affiliated))
1499 (post-affiliated (point))
1500 (value (progn (let ((case-fold-search t))
1501 (re-search-forward "call:[ \t]*" nil t))
1502 (buffer-substring-no-properties (point)
1503 (line-end-position))))
1504 (pos-before-blank (progn (forward-line) (point)))
1505 (end (progn (skip-chars-forward " \r\t\n" limit)
1506 (skip-chars-backward " \t")
1507 (if (bolp) (point) (line-end-position)))))
1508 (list 'babel-call
1509 (nconc
1510 (list :begin begin
1511 :end end
1512 :value value
1513 :post-blank (count-lines pos-before-blank end)
1514 :post-affiliated post-affiliated)
1515 (cdr affiliated))))))
1517 (defun org-element-babel-call-interpreter (babel-call contents)
1518 "Interpret BABEL-CALL element as Org syntax.
1519 CONTENTS is nil."
1520 (concat "#+CALL: " (org-element-property :value babel-call)))
1523 ;;;; Clock
1525 (defun org-element-clock-parser (limit)
1526 "Parse a clock.
1528 LIMIT bounds the search.
1530 Return a list whose CAR is `clock' and CDR is a plist containing
1531 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1532 as keywords."
1533 (save-excursion
1534 (let* ((case-fold-search nil)
1535 (begin (point))
1536 (value (progn (search-forward org-clock-string (line-end-position) t)
1537 (skip-chars-forward " \t")
1538 (org-element-timestamp-parser)))
1539 (duration (and (search-forward " => " (line-end-position) t)
1540 (progn (skip-chars-forward " \t")
1541 (looking-at "\\(\\S-+\\)[ \t]*$"))
1542 (org-match-string-no-properties 1)))
1543 (status (if duration 'closed 'running))
1544 (post-blank (let ((before-blank (progn (forward-line) (point))))
1545 (skip-chars-forward " \r\t\n" limit)
1546 (skip-chars-backward " \t")
1547 (unless (bolp) (end-of-line))
1548 (count-lines before-blank (point))))
1549 (end (point)))
1550 (list 'clock
1551 (list :status status
1552 :value value
1553 :duration duration
1554 :begin begin
1555 :end end
1556 :post-blank post-blank)))))
1558 (defun org-element-clock-interpreter (clock contents)
1559 "Interpret CLOCK element as Org syntax.
1560 CONTENTS is nil."
1561 (concat org-clock-string " "
1562 (org-element-timestamp-interpreter
1563 (org-element-property :value clock) nil)
1564 (let ((duration (org-element-property :duration clock)))
1565 (and duration
1566 (concat " => "
1567 (apply 'format
1568 "%2s:%02s"
1569 (org-split-string duration ":")))))))
1572 ;;;; Comment
1574 (defun org-element-comment-parser (limit affiliated)
1575 "Parse a comment.
1577 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1578 the buffer position at the beginning of the first affiliated
1579 keyword and CDR is a plist of affiliated keywords along with
1580 their value.
1582 Return a list whose CAR is `comment' and CDR is a plist
1583 containing `:begin', `:end', `:value', `:post-blank',
1584 `:post-affiliated' keywords.
1586 Assume point is at comment beginning."
1587 (save-excursion
1588 (let* ((begin (car affiliated))
1589 (post-affiliated (point))
1590 (value (prog2 (looking-at "[ \t]*# ?")
1591 (buffer-substring-no-properties
1592 (match-end 0) (line-end-position))
1593 (forward-line)))
1594 (com-end
1595 ;; Get comments ending.
1596 (progn
1597 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1598 ;; Accumulate lines without leading hash and first
1599 ;; whitespace.
1600 (setq value
1601 (concat value
1602 "\n"
1603 (buffer-substring-no-properties
1604 (match-end 0) (line-end-position))))
1605 (forward-line))
1606 (point)))
1607 (end (progn (goto-char com-end)
1608 (skip-chars-forward " \r\t\n" limit)
1609 (skip-chars-backward " \t")
1610 (if (bolp) (point) (line-end-position)))))
1611 (list 'comment
1612 (nconc
1613 (list :begin begin
1614 :end end
1615 :value value
1616 :post-blank (count-lines com-end end)
1617 :post-affiliated post-affiliated)
1618 (cdr affiliated))))))
1620 (defun org-element-comment-interpreter (comment contents)
1621 "Interpret COMMENT element as Org syntax.
1622 CONTENTS is nil."
1623 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1626 ;;;; Comment Block
1628 (defun org-element-comment-block-parser (limit affiliated)
1629 "Parse an export block.
1631 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1632 the buffer position at the beginning of the first affiliated
1633 keyword and CDR is a plist of affiliated keywords along with
1634 their value.
1636 Return a list whose CAR is `comment-block' and CDR is a plist
1637 containing `:begin', `:end', `:value', `:post-blank' and
1638 `:post-affiliated' keywords.
1640 Assume point is at comment block beginning."
1641 (let ((case-fold-search t))
1642 (if (not (save-excursion
1643 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1644 ;; Incomplete block: parse it as a paragraph.
1645 (org-element-paragraph-parser limit affiliated)
1646 (let ((contents-end (match-beginning 0)))
1647 (save-excursion
1648 (let* ((begin (car affiliated))
1649 (post-affiliated (point))
1650 (contents-begin (progn (forward-line) (point)))
1651 (pos-before-blank (progn (goto-char contents-end)
1652 (forward-line)
1653 (point)))
1654 (end (progn (skip-chars-forward " \r\t\n" limit)
1655 (skip-chars-backward " \t")
1656 (if (bolp) (point) (line-end-position))))
1657 (value (buffer-substring-no-properties
1658 contents-begin contents-end)))
1659 (list 'comment-block
1660 (nconc
1661 (list :begin begin
1662 :end end
1663 :value value
1664 :post-blank (count-lines pos-before-blank end)
1665 :post-affiliated post-affiliated)
1666 (cdr affiliated)))))))))
1668 (defun org-element-comment-block-interpreter (comment-block contents)
1669 "Interpret COMMENT-BLOCK element as Org syntax.
1670 CONTENTS is nil."
1671 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1672 (org-remove-indentation (org-element-property :value comment-block))))
1675 ;;;; Diary Sexp
1677 (defun org-element-diary-sexp-parser (limit affiliated)
1678 "Parse a diary sexp.
1680 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1681 the buffer position at the beginning of the first affiliated
1682 keyword and CDR is a plist of affiliated keywords along with
1683 their value.
1685 Return a list whose CAR is `diary-sexp' and CDR is a plist
1686 containing `:begin', `:end', `:value', `:post-blank' and
1687 `:post-affiliated' keywords."
1688 (save-excursion
1689 (let ((begin (car affiliated))
1690 (post-affiliated (point))
1691 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1692 (org-match-string-no-properties 1)))
1693 (pos-before-blank (progn (forward-line) (point)))
1694 (end (progn (skip-chars-forward " \r\t\n" limit)
1695 (skip-chars-backward " \t")
1696 (if (bolp) (point) (line-end-position)))))
1697 (list 'diary-sexp
1698 (nconc
1699 (list :value value
1700 :begin begin
1701 :end end
1702 :post-blank (count-lines pos-before-blank end)
1703 :post-affiliated post-affiliated)
1704 (cdr affiliated))))))
1706 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1707 "Interpret DIARY-SEXP as Org syntax.
1708 CONTENTS is nil."
1709 (org-element-property :value diary-sexp))
1712 ;;;; Example Block
1714 (defun org-element-example-block-parser (limit affiliated)
1715 "Parse an example block.
1717 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1718 the buffer position at the beginning of the first affiliated
1719 keyword and CDR is a plist of affiliated keywords along with
1720 their value.
1722 Return a list whose CAR is `example-block' and CDR is a plist
1723 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1724 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1725 `:value', `:post-blank' and `:post-affiliated' keywords."
1726 (let ((case-fold-search t))
1727 (if (not (save-excursion
1728 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1729 ;; Incomplete block: parse it as a paragraph.
1730 (org-element-paragraph-parser limit affiliated)
1731 (let ((contents-end (match-beginning 0)))
1732 (save-excursion
1733 (let* ((switches
1734 (progn
1735 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1736 (org-match-string-no-properties 1)))
1737 ;; Switches analysis
1738 (number-lines
1739 (cond ((not switches) nil)
1740 ((string-match "-n\\>" switches) 'new)
1741 ((string-match "+n\\>" switches) 'continued)))
1742 (preserve-indent
1743 (and switches (string-match "-i\\>" switches)))
1744 ;; Should labels be retained in (or stripped from) example
1745 ;; blocks?
1746 (retain-labels
1747 (or (not switches)
1748 (not (string-match "-r\\>" switches))
1749 (and number-lines (string-match "-k\\>" switches))))
1750 ;; What should code-references use - labels or
1751 ;; line-numbers?
1752 (use-labels
1753 (or (not switches)
1754 (and retain-labels
1755 (not (string-match "-k\\>" switches)))))
1756 (label-fmt
1757 (and switches
1758 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1759 (match-string 1 switches)))
1760 ;; Standard block parsing.
1761 (begin (car affiliated))
1762 (post-affiliated (point))
1763 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1764 (contents-begin (progn (forward-line) (point)))
1765 (value (org-element-remove-indentation
1766 (org-unescape-code-in-string
1767 (buffer-substring-no-properties
1768 contents-begin contents-end))
1769 block-ind))
1770 (pos-before-blank (progn (goto-char contents-end)
1771 (forward-line)
1772 (point)))
1773 (end (progn (skip-chars-forward " \r\t\n" limit)
1774 (skip-chars-backward " \t")
1775 (if (bolp) (point) (line-end-position)))))
1776 (list 'example-block
1777 (nconc
1778 (list :begin begin
1779 :end end
1780 :value value
1781 :switches switches
1782 :number-lines number-lines
1783 :preserve-indent preserve-indent
1784 :retain-labels retain-labels
1785 :use-labels use-labels
1786 :label-fmt label-fmt
1787 :post-blank (count-lines pos-before-blank end)
1788 :post-affiliated post-affiliated)
1789 (cdr affiliated)))))))))
1791 (defun org-element-example-block-interpreter (example-block contents)
1792 "Interpret EXAMPLE-BLOCK element as Org syntax.
1793 CONTENTS is nil."
1794 (let ((switches (org-element-property :switches example-block))
1795 (value (org-element-property :value example-block)))
1796 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1797 (org-escape-code-in-string
1798 (if (or org-src-preserve-indentation
1799 (org-element-property :preserve-indent example-block))
1800 value
1801 (org-element-remove-indentation value)))
1802 "#+END_EXAMPLE")))
1805 ;;;; Export Block
1807 (defun org-element-export-block-parser (limit affiliated)
1808 "Parse an export block.
1810 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1811 the buffer position at the beginning of the first affiliated
1812 keyword and CDR is a plist of affiliated keywords along with
1813 their value.
1815 Return a list whose CAR is `export-block' and CDR is a plist
1816 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1817 `:post-affiliated' keywords.
1819 Assume point is at export-block beginning."
1820 (let* ((case-fold-search t)
1821 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1822 (upcase (org-match-string-no-properties 1)))))
1823 (if (not (save-excursion
1824 (re-search-forward
1825 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1826 ;; Incomplete block: parse it as a paragraph.
1827 (org-element-paragraph-parser limit affiliated)
1828 (let ((contents-end (match-beginning 0)))
1829 (save-excursion
1830 (let* ((begin (car affiliated))
1831 (post-affiliated (point))
1832 (contents-begin (progn (forward-line) (point)))
1833 (pos-before-blank (progn (goto-char contents-end)
1834 (forward-line)
1835 (point)))
1836 (end (progn (skip-chars-forward " \r\t\n" limit)
1837 (skip-chars-backward " \t")
1838 (if (bolp) (point) (line-end-position))))
1839 (value (buffer-substring-no-properties contents-begin
1840 contents-end)))
1841 (list 'export-block
1842 (nconc
1843 (list :begin begin
1844 :end end
1845 :type type
1846 :value value
1847 :post-blank (count-lines pos-before-blank end)
1848 :post-affiliated post-affiliated)
1849 (cdr affiliated)))))))))
1851 (defun org-element-export-block-interpreter (export-block contents)
1852 "Interpret EXPORT-BLOCK element as Org syntax.
1853 CONTENTS is nil."
1854 (let ((type (org-element-property :type export-block)))
1855 (concat (format "#+BEGIN_%s\n" type)
1856 (org-element-property :value export-block)
1857 (format "#+END_%s" type))))
1860 ;;;; Fixed-width
1862 (defun org-element-fixed-width-parser (limit affiliated)
1863 "Parse a fixed-width section.
1865 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1866 the buffer position at the beginning of the first affiliated
1867 keyword and CDR is a plist of affiliated keywords along with
1868 their value.
1870 Return a list whose CAR is `fixed-width' and CDR is a plist
1871 containing `:begin', `:end', `:value', `:post-blank' and
1872 `:post-affiliated' keywords.
1874 Assume point is at the beginning of the fixed-width area."
1875 (save-excursion
1876 (let* ((begin (car affiliated))
1877 (post-affiliated (point))
1878 value
1879 (end-area
1880 (progn
1881 (while (and (< (point) limit)
1882 (looking-at "[ \t]*:\\( \\|$\\)"))
1883 ;; Accumulate text without starting colons.
1884 (setq value
1885 (concat value
1886 (buffer-substring-no-properties
1887 (match-end 0) (point-at-eol))
1888 "\n"))
1889 (forward-line))
1890 (point)))
1891 (end (progn (skip-chars-forward " \r\t\n" limit)
1892 (skip-chars-backward " \t")
1893 (if (bolp) (point) (line-end-position)))))
1894 (list 'fixed-width
1895 (nconc
1896 (list :begin begin
1897 :end end
1898 :value value
1899 :post-blank (count-lines end-area end)
1900 :post-affiliated post-affiliated)
1901 (cdr affiliated))))))
1903 (defun org-element-fixed-width-interpreter (fixed-width contents)
1904 "Interpret FIXED-WIDTH element as Org syntax.
1905 CONTENTS is nil."
1906 (let ((value (org-element-property :value fixed-width)))
1907 (and value
1908 (replace-regexp-in-string
1909 "^" ": "
1910 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1913 ;;;; Horizontal Rule
1915 (defun org-element-horizontal-rule-parser (limit affiliated)
1916 "Parse an horizontal rule.
1918 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1919 the buffer position at the beginning of the first affiliated
1920 keyword and CDR is a plist of affiliated keywords along with
1921 their value.
1923 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1924 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1925 keywords."
1926 (save-excursion
1927 (let ((begin (car affiliated))
1928 (post-affiliated (point))
1929 (post-hr (progn (forward-line) (point)))
1930 (end (progn (skip-chars-forward " \r\t\n" limit)
1931 (skip-chars-backward " \t")
1932 (if (bolp) (point) (line-end-position)))))
1933 (list 'horizontal-rule
1934 (nconc
1935 (list :begin begin
1936 :end end
1937 :post-blank (count-lines post-hr end)
1938 :post-affiliated post-affiliated)
1939 (cdr affiliated))))))
1941 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1942 "Interpret HORIZONTAL-RULE element as Org syntax.
1943 CONTENTS is nil."
1944 "-----")
1947 ;;;; Keyword
1949 (defun org-element-keyword-parser (limit affiliated)
1950 "Parse a keyword at point.
1952 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1953 the buffer position at the beginning of the first affiliated
1954 keyword and CDR is a plist of affiliated keywords along with
1955 their value.
1957 Return a list whose CAR is `keyword' and CDR is a plist
1958 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1959 `:post-affiliated' keywords."
1960 (save-excursion
1961 (let ((begin (car affiliated))
1962 (post-affiliated (point))
1963 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1964 (upcase (org-match-string-no-properties 1))))
1965 (value (org-trim (buffer-substring-no-properties
1966 (match-end 0) (point-at-eol))))
1967 (pos-before-blank (progn (forward-line) (point)))
1968 (end (progn (skip-chars-forward " \r\t\n" limit)
1969 (skip-chars-backward " \t")
1970 (if (bolp) (point) (line-end-position)))))
1971 (list 'keyword
1972 (nconc
1973 (list :key key
1974 :value value
1975 :begin begin
1976 :end end
1977 :post-blank (count-lines pos-before-blank end)
1978 :post-affiliated post-affiliated)
1979 (cdr affiliated))))))
1981 (defun org-element-keyword-interpreter (keyword contents)
1982 "Interpret KEYWORD element as Org syntax.
1983 CONTENTS is nil."
1984 (format "#+%s: %s"
1985 (org-element-property :key keyword)
1986 (org-element-property :value keyword)))
1989 ;;;; Latex Environment
1991 (defun org-element-latex-environment-parser (limit affiliated)
1992 "Parse a LaTeX environment.
1994 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1995 the buffer position at the beginning of the first affiliated
1996 keyword and CDR is a plist of affiliated keywords along with
1997 their value.
1999 Return a list whose CAR is `latex-environment' and CDR is a plist
2000 containing `:begin', `:end', `:value', `:post-blank' and
2001 `:post-affiliated' keywords.
2003 Assume point is at the beginning of the latex environment."
2004 (save-excursion
2005 (let ((case-fold-search t)
2006 (code-begin (point)))
2007 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2008 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2009 (regexp-quote (match-string 1)))
2010 limit t))
2011 ;; Incomplete latex environment: parse it as a paragraph.
2012 (org-element-paragraph-parser limit affiliated)
2013 (let* ((code-end (progn (forward-line) (point)))
2014 (begin (car affiliated))
2015 (value (buffer-substring-no-properties code-begin code-end))
2016 (end (progn (skip-chars-forward " \r\t\n" limit)
2017 (skip-chars-backward " \t")
2018 (if (bolp) (point) (line-end-position)))))
2019 (list 'latex-environment
2020 (nconc
2021 (list :begin begin
2022 :end end
2023 :value value
2024 :post-blank (count-lines code-end end)
2025 :post-affiliated code-begin)
2026 (cdr affiliated))))))))
2028 (defun org-element-latex-environment-interpreter (latex-environment contents)
2029 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2030 CONTENTS is nil."
2031 (org-element-property :value latex-environment))
2034 ;;;; Node Property
2036 (defun org-element-node-property-parser (limit)
2037 "Parse a node-property at point.
2039 LIMIT bounds the search.
2041 Return a list whose CAR is `node-property' and CDR is a plist
2042 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2043 keywords."
2044 (save-excursion
2045 (looking-at org-property-re)
2046 (let ((case-fold-search t)
2047 (begin (point))
2048 (key (org-match-string-no-properties 2))
2049 (value (org-match-string-no-properties 3))
2050 (pos-before-blank (progn (forward-line) (point)))
2051 (end (progn (skip-chars-forward " \r\t\n" limit)
2052 (if (eobp) (point) (point-at-bol)))))
2053 (list 'node-property
2054 (list :key key
2055 :value value
2056 :begin begin
2057 :end end
2058 :post-blank (count-lines pos-before-blank end))))))
2060 (defun org-element-node-property-interpreter (node-property contents)
2061 "Interpret NODE-PROPERTY element as Org syntax.
2062 CONTENTS is nil."
2063 (format org-property-format
2064 (format ":%s:" (org-element-property :key node-property))
2065 (org-element-property :value node-property)))
2068 ;;;; Paragraph
2070 (defun org-element-paragraph-parser (limit affiliated)
2071 "Parse a paragraph.
2073 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2074 the buffer position at the beginning of the first affiliated
2075 keyword and CDR is a plist of affiliated keywords along with
2076 their value.
2078 Return a list whose CAR is `paragraph' and CDR is a plist
2079 containing `:begin', `:end', `:contents-begin' and
2080 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2082 Assume point is at the beginning of the paragraph."
2083 (save-excursion
2084 (let* ((begin (car affiliated))
2085 (contents-begin (point))
2086 (before-blank
2087 (let ((case-fold-search t))
2088 (end-of-line)
2089 (if (not (re-search-forward
2090 org-element-paragraph-separate limit 'm))
2091 limit
2092 ;; A matching `org-element-paragraph-separate' is not
2093 ;; necessarily the end of the paragraph. In
2094 ;; particular, lines starting with # or : as a first
2095 ;; non-space character are ambiguous. We have check
2096 ;; if they are valid Org syntax (i.e. not an
2097 ;; incomplete keyword).
2098 (beginning-of-line)
2099 (while (not
2101 ;; There's no ambiguity for other symbols or
2102 ;; empty lines: stop here.
2103 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2104 ;; Stop at valid fixed-width areas.
2105 (looking-at "[ \t]*:\\(?: \\|$\\)")
2106 ;; Stop at drawers.
2107 (and (looking-at org-drawer-regexp)
2108 (save-excursion
2109 (re-search-forward
2110 "^[ \t]*:END:[ \t]*$" limit t)))
2111 ;; Stop at valid comments.
2112 (looking-at "[ \t]*#\\(?: \\|$\\)")
2113 ;; Stop at valid dynamic blocks.
2114 (and (looking-at org-dblock-start-re)
2115 (save-excursion
2116 (re-search-forward
2117 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2118 ;; Stop at valid blocks.
2119 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2120 (save-excursion
2121 (re-search-forward
2122 (format "^[ \t]*#\\+END_%s[ \t]*$"
2123 (regexp-quote
2124 (org-match-string-no-properties 1)))
2125 limit t)))
2126 ;; Stop at valid latex environments.
2127 (and (looking-at
2128 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2129 (save-excursion
2130 (re-search-forward
2131 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2132 (regexp-quote
2133 (org-match-string-no-properties 1)))
2134 limit t)))
2135 ;; Stop at valid keywords.
2136 (looking-at "[ \t]*#\\+\\S-+:")
2137 ;; Skip everything else.
2138 (not
2139 (progn
2140 (end-of-line)
2141 (re-search-forward org-element-paragraph-separate
2142 limit 'm)))))
2143 (beginning-of-line)))
2144 (if (= (point) limit) limit
2145 (goto-char (line-beginning-position)))))
2146 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2147 (forward-line)
2148 (point)))
2149 (end (progn (skip-chars-forward " \r\t\n" limit)
2150 (skip-chars-backward " \t")
2151 (if (bolp) (point) (line-end-position)))))
2152 (list 'paragraph
2153 (nconc
2154 (list :begin begin
2155 :end end
2156 :contents-begin contents-begin
2157 :contents-end contents-end
2158 :post-blank (count-lines before-blank end)
2159 :post-affiliated contents-begin)
2160 (cdr affiliated))))))
2162 (defun org-element-paragraph-interpreter (paragraph contents)
2163 "Interpret PARAGRAPH element as Org syntax.
2164 CONTENTS is the contents of the element."
2165 contents)
2168 ;;;; Planning
2170 (defun org-element-planning-parser (limit)
2171 "Parse a planning.
2173 LIMIT bounds the search.
2175 Return a list whose CAR is `planning' and CDR is a plist
2176 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2177 and `:post-blank' keywords."
2178 (save-excursion
2179 (let* ((case-fold-search nil)
2180 (begin (point))
2181 (post-blank (let ((before-blank (progn (forward-line) (point))))
2182 (skip-chars-forward " \r\t\n" limit)
2183 (skip-chars-backward " \t")
2184 (unless (bolp) (end-of-line))
2185 (count-lines before-blank (point))))
2186 (end (point))
2187 closed deadline scheduled)
2188 (goto-char begin)
2189 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2190 (goto-char (match-end 1))
2191 (skip-chars-forward " \t" end)
2192 (let ((keyword (match-string 1))
2193 (time (org-element-timestamp-parser)))
2194 (cond ((equal keyword org-closed-string) (setq closed time))
2195 ((equal keyword org-deadline-string) (setq deadline time))
2196 (t (setq scheduled time)))))
2197 (list 'planning
2198 (list :closed closed
2199 :deadline deadline
2200 :scheduled scheduled
2201 :begin begin
2202 :end end
2203 :post-blank post-blank)))))
2205 (defun org-element-planning-interpreter (planning contents)
2206 "Interpret PLANNING element as Org syntax.
2207 CONTENTS is nil."
2208 (mapconcat
2209 'identity
2210 (delq nil
2211 (list (let ((deadline (org-element-property :deadline planning)))
2212 (when deadline
2213 (concat org-deadline-string " "
2214 (org-element-timestamp-interpreter deadline nil))))
2215 (let ((scheduled (org-element-property :scheduled planning)))
2216 (when scheduled
2217 (concat org-scheduled-string " "
2218 (org-element-timestamp-interpreter scheduled nil))))
2219 (let ((closed (org-element-property :closed planning)))
2220 (when closed
2221 (concat org-closed-string " "
2222 (org-element-timestamp-interpreter closed nil))))))
2223 " "))
2226 ;;;; Quote Section
2228 (defun org-element-quote-section-parser (limit)
2229 "Parse a quote section.
2231 LIMIT bounds the search.
2233 Return a list whose CAR is `quote-section' and CDR is a plist
2234 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2236 Assume point is at beginning of the section."
2237 (save-excursion
2238 (let* ((begin (point))
2239 (end (progn (org-with-limited-levels (outline-next-heading))
2240 (point)))
2241 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2242 (forward-line)
2243 (point)))
2244 (value (buffer-substring-no-properties begin pos-before-blank)))
2245 (list 'quote-section
2246 (list :begin begin
2247 :end end
2248 :value value
2249 :post-blank (count-lines pos-before-blank end))))))
2251 (defun org-element-quote-section-interpreter (quote-section contents)
2252 "Interpret QUOTE-SECTION element as Org syntax.
2253 CONTENTS is nil."
2254 (org-element-property :value quote-section))
2257 ;;;; Src Block
2259 (defun org-element-src-block-parser (limit affiliated)
2260 "Parse a src block.
2262 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2263 the buffer position at the beginning of the first affiliated
2264 keyword and CDR is a plist of affiliated keywords along with
2265 their value.
2267 Return a list whose CAR is `src-block' and CDR is a plist
2268 containing `:language', `:switches', `:parameters', `:begin',
2269 `:end', `:number-lines', `:retain-labels', `:use-labels',
2270 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2271 `:post-affiliated' keywords.
2273 Assume point is at the beginning of the block."
2274 (let ((case-fold-search t))
2275 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2276 limit t)))
2277 ;; Incomplete block: parse it as a paragraph.
2278 (org-element-paragraph-parser limit affiliated)
2279 (let ((contents-end (match-beginning 0)))
2280 (save-excursion
2281 (let* ((begin (car affiliated))
2282 (post-affiliated (point))
2283 ;; Get language as a string.
2284 (language
2285 (progn
2286 (looking-at
2287 (concat "^[ \t]*#\\+BEGIN_SRC"
2288 "\\(?: +\\(\\S-+\\)\\)?"
2289 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2290 "\\(.*\\)[ \t]*$"))
2291 (org-match-string-no-properties 1)))
2292 ;; Get switches.
2293 (switches (org-match-string-no-properties 2))
2294 ;; Get parameters.
2295 (parameters (org-match-string-no-properties 3))
2296 ;; Switches analysis
2297 (number-lines
2298 (cond ((not switches) nil)
2299 ((string-match "-n\\>" switches) 'new)
2300 ((string-match "+n\\>" switches) 'continued)))
2301 (preserve-indent (and switches
2302 (string-match "-i\\>" switches)))
2303 (label-fmt
2304 (and switches
2305 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2306 (match-string 1 switches)))
2307 ;; Should labels be retained in (or stripped from)
2308 ;; src blocks?
2309 (retain-labels
2310 (or (not switches)
2311 (not (string-match "-r\\>" switches))
2312 (and number-lines (string-match "-k\\>" switches))))
2313 ;; What should code-references use - labels or
2314 ;; line-numbers?
2315 (use-labels
2316 (or (not switches)
2317 (and retain-labels
2318 (not (string-match "-k\\>" switches)))))
2319 ;; Indentation.
2320 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2321 ;; Retrieve code.
2322 (value (org-element-remove-indentation
2323 (org-unescape-code-in-string
2324 (buffer-substring-no-properties
2325 (progn (forward-line) (point)) contents-end))
2326 block-ind))
2327 (pos-before-blank (progn (goto-char contents-end)
2328 (forward-line)
2329 (point)))
2330 ;; Get position after ending blank lines.
2331 (end (progn (skip-chars-forward " \r\t\n" limit)
2332 (skip-chars-backward " \t")
2333 (if (bolp) (point) (line-end-position)))))
2334 (list 'src-block
2335 (nconc
2336 (list :language language
2337 :switches (and (org-string-nw-p switches)
2338 (org-trim switches))
2339 :parameters (and (org-string-nw-p parameters)
2340 (org-trim parameters))
2341 :begin begin
2342 :end end
2343 :number-lines number-lines
2344 :preserve-indent preserve-indent
2345 :retain-labels retain-labels
2346 :use-labels use-labels
2347 :label-fmt label-fmt
2348 :value value
2349 :post-blank (count-lines pos-before-blank end)
2350 :post-affiliated post-affiliated)
2351 (cdr affiliated)))))))))
2353 (defun org-element-src-block-interpreter (src-block contents)
2354 "Interpret SRC-BLOCK element as Org syntax.
2355 CONTENTS is nil."
2356 (let ((lang (org-element-property :language src-block))
2357 (switches (org-element-property :switches src-block))
2358 (params (org-element-property :parameters src-block))
2359 (value
2360 (let ((val (org-element-property :value src-block)))
2361 (cond
2362 ((or org-src-preserve-indentation
2363 (org-element-property :preserve-indent src-block))
2364 val)
2365 ((zerop org-edit-src-content-indentation) val)
2367 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2368 (replace-regexp-in-string
2369 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2370 (concat (format "#+BEGIN_SRC%s\n"
2371 (concat (and lang (concat " " lang))
2372 (and switches (concat " " switches))
2373 (and params (concat " " params))))
2374 (org-escape-code-in-string value)
2375 "#+END_SRC")))
2378 ;;;; Table
2380 (defun org-element-table-parser (limit affiliated)
2381 "Parse a table at point.
2383 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2384 the buffer position at the beginning of the first affiliated
2385 keyword and CDR is a plist of affiliated keywords along with
2386 their value.
2388 Return a list whose CAR is `table' and CDR is a plist containing
2389 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2390 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2391 keywords.
2393 Assume point is at the beginning of the table."
2394 (save-excursion
2395 (let* ((case-fold-search t)
2396 (table-begin (point))
2397 (type (if (org-at-table.el-p) 'table.el 'org))
2398 (begin (car affiliated))
2399 (table-end
2400 (if (re-search-forward org-table-any-border-regexp limit 'm)
2401 (goto-char (match-beginning 0))
2402 (point)))
2403 (tblfm (let (acc)
2404 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2405 (push (org-match-string-no-properties 1) acc)
2406 (forward-line))
2407 acc))
2408 (pos-before-blank (point))
2409 (end (progn (skip-chars-forward " \r\t\n" limit)
2410 (skip-chars-backward " \t")
2411 (if (bolp) (point) (line-end-position)))))
2412 (list 'table
2413 (nconc
2414 (list :begin begin
2415 :end end
2416 :type type
2417 :tblfm tblfm
2418 ;; Only `org' tables have contents. `table.el' tables
2419 ;; use a `:value' property to store raw table as
2420 ;; a string.
2421 :contents-begin (and (eq type 'org) table-begin)
2422 :contents-end (and (eq type 'org) table-end)
2423 :value (and (eq type 'table.el)
2424 (buffer-substring-no-properties
2425 table-begin table-end))
2426 :post-blank (count-lines pos-before-blank end)
2427 :post-affiliated table-begin)
2428 (cdr affiliated))))))
2430 (defun org-element-table-interpreter (table contents)
2431 "Interpret TABLE element as Org syntax.
2432 CONTENTS is nil."
2433 (if (eq (org-element-property :type table) 'table.el)
2434 (org-remove-indentation (org-element-property :value table))
2435 (concat (with-temp-buffer (insert contents)
2436 (org-table-align)
2437 (buffer-string))
2438 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2439 (reverse (org-element-property :tblfm table))
2440 "\n"))))
2443 ;;;; Table Row
2445 (defun org-element-table-row-parser (limit)
2446 "Parse table row at point.
2448 LIMIT bounds the search.
2450 Return a list whose CAR is `table-row' and CDR is a plist
2451 containing `:begin', `:end', `:contents-begin', `:contents-end',
2452 `:type' and `:post-blank' keywords."
2453 (save-excursion
2454 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2455 (begin (point))
2456 ;; A table rule has no contents. In that case, ensure
2457 ;; CONTENTS-BEGIN matches CONTENTS-END.
2458 (contents-begin (and (eq type 'standard)
2459 (search-forward "|")
2460 (point)))
2461 (contents-end (and (eq type 'standard)
2462 (progn
2463 (end-of-line)
2464 (skip-chars-backward " \t")
2465 (point))))
2466 (end (progn (forward-line) (point))))
2467 (list 'table-row
2468 (list :type type
2469 :begin begin
2470 :end end
2471 :contents-begin contents-begin
2472 :contents-end contents-end
2473 :post-blank 0)))))
2475 (defun org-element-table-row-interpreter (table-row contents)
2476 "Interpret TABLE-ROW element as Org syntax.
2477 CONTENTS is the contents of the table row."
2478 (if (eq (org-element-property :type table-row) 'rule) "|-"
2479 (concat "| " contents)))
2482 ;;;; Verse Block
2484 (defun org-element-verse-block-parser (limit affiliated)
2485 "Parse a verse block.
2487 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2488 the buffer position at the beginning of the first affiliated
2489 keyword and CDR is a plist of affiliated keywords along with
2490 their value.
2492 Return a list whose CAR is `verse-block' and CDR is a plist
2493 containing `:begin', `:end', `:contents-begin', `:contents-end',
2494 `:post-blank' and `:post-affiliated' keywords.
2496 Assume point is at beginning of the block."
2497 (let ((case-fold-search t))
2498 (if (not (save-excursion
2499 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2500 ;; Incomplete block: parse it as a paragraph.
2501 (org-element-paragraph-parser limit affiliated)
2502 (let ((contents-end (match-beginning 0)))
2503 (save-excursion
2504 (let* ((begin (car affiliated))
2505 (post-affiliated (point))
2506 (contents-begin (progn (forward-line) (point)))
2507 (pos-before-blank (progn (goto-char contents-end)
2508 (forward-line)
2509 (point)))
2510 (end (progn (skip-chars-forward " \r\t\n" limit)
2511 (skip-chars-backward " \t")
2512 (if (bolp) (point) (line-end-position)))))
2513 (list 'verse-block
2514 (nconc
2515 (list :begin begin
2516 :end end
2517 :contents-begin contents-begin
2518 :contents-end contents-end
2519 :post-blank (count-lines pos-before-blank end)
2520 :post-affiliated post-affiliated)
2521 (cdr affiliated)))))))))
2523 (defun org-element-verse-block-interpreter (verse-block contents)
2524 "Interpret VERSE-BLOCK element as Org syntax.
2525 CONTENTS is verse block contents."
2526 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2530 ;;; Objects
2532 ;; Unlike to elements, interstices can be found between objects.
2533 ;; That's why, along with the parser, successor functions are provided
2534 ;; for each object. Some objects share the same successor (i.e. `code'
2535 ;; and `verbatim' objects).
2537 ;; A successor must accept a single argument bounding the search. It
2538 ;; will return either a cons cell whose CAR is the object's type, as
2539 ;; a symbol, and CDR the position of its next occurrence, or nil.
2541 ;; Successors follow the naming convention:
2542 ;; org-element-NAME-successor, where NAME is the name of the
2543 ;; successor, as defined in `org-element-all-successors'.
2545 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2546 ;; object types they can contain will be specified in
2547 ;; `org-element-object-restrictions'.
2549 ;; Adding a new type of object is simple. Implement a successor,
2550 ;; a parser, and an interpreter for it, all following the naming
2551 ;; convention. Register type in `org-element-all-objects' and
2552 ;; successor in `org-element-all-successors'. Maybe tweak
2553 ;; restrictions about it, and that's it.
2556 ;;;; Bold
2558 (defun org-element-bold-parser ()
2559 "Parse bold object at point.
2561 Return a list whose CAR is `bold' and CDR is a plist with
2562 `:begin', `:end', `:contents-begin' and `:contents-end' and
2563 `:post-blank' keywords.
2565 Assume point is at the first star marker."
2566 (save-excursion
2567 (unless (bolp) (backward-char 1))
2568 (looking-at org-emph-re)
2569 (let ((begin (match-beginning 2))
2570 (contents-begin (match-beginning 4))
2571 (contents-end (match-end 4))
2572 (post-blank (progn (goto-char (match-end 2))
2573 (skip-chars-forward " \t")))
2574 (end (point)))
2575 (list 'bold
2576 (list :begin begin
2577 :end end
2578 :contents-begin contents-begin
2579 :contents-end contents-end
2580 :post-blank post-blank)))))
2582 (defun org-element-bold-interpreter (bold contents)
2583 "Interpret BOLD object as Org syntax.
2584 CONTENTS is the contents of the object."
2585 (format "*%s*" contents))
2587 (defun org-element-text-markup-successor ()
2588 "Search for the next text-markup object.
2590 Return value is a cons cell whose CAR is a symbol among `bold',
2591 `italic', `underline', `strike-through', `code' and `verbatim'
2592 and CDR is beginning position."
2593 (save-excursion
2594 (unless (bolp) (backward-char))
2595 (when (re-search-forward org-emph-re nil t)
2596 (let ((marker (match-string 3)))
2597 (cons (cond
2598 ((equal marker "*") 'bold)
2599 ((equal marker "/") 'italic)
2600 ((equal marker "_") 'underline)
2601 ((equal marker "+") 'strike-through)
2602 ((equal marker "~") 'code)
2603 ((equal marker "=") 'verbatim)
2604 (t (error "Unknown marker at %d" (match-beginning 3))))
2605 (match-beginning 2))))))
2608 ;;;; Code
2610 (defun org-element-code-parser ()
2611 "Parse code object at point.
2613 Return a list whose CAR is `code' and CDR is a plist with
2614 `:value', `:begin', `:end' and `:post-blank' keywords.
2616 Assume point is at the first tilde marker."
2617 (save-excursion
2618 (unless (bolp) (backward-char 1))
2619 (looking-at org-emph-re)
2620 (let ((begin (match-beginning 2))
2621 (value (org-match-string-no-properties 4))
2622 (post-blank (progn (goto-char (match-end 2))
2623 (skip-chars-forward " \t")))
2624 (end (point)))
2625 (list 'code
2626 (list :value value
2627 :begin begin
2628 :end end
2629 :post-blank post-blank)))))
2631 (defun org-element-code-interpreter (code contents)
2632 "Interpret CODE object as Org syntax.
2633 CONTENTS is nil."
2634 (format "~%s~" (org-element-property :value code)))
2637 ;;;; Entity
2639 (defun org-element-entity-parser ()
2640 "Parse entity at point.
2642 Return a list whose CAR is `entity' and CDR a plist with
2643 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2644 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2645 keywords.
2647 Assume point is at the beginning of the entity."
2648 (save-excursion
2649 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2650 (let* ((value (org-entity-get (match-string 1)))
2651 (begin (match-beginning 0))
2652 (bracketsp (string= (match-string 2) "{}"))
2653 (post-blank (progn (goto-char (match-end 1))
2654 (when bracketsp (forward-char 2))
2655 (skip-chars-forward " \t")))
2656 (end (point)))
2657 (list 'entity
2658 (list :name (car value)
2659 :latex (nth 1 value)
2660 :latex-math-p (nth 2 value)
2661 :html (nth 3 value)
2662 :ascii (nth 4 value)
2663 :latin1 (nth 5 value)
2664 :utf-8 (nth 6 value)
2665 :begin begin
2666 :end end
2667 :use-brackets-p bracketsp
2668 :post-blank post-blank)))))
2670 (defun org-element-entity-interpreter (entity contents)
2671 "Interpret ENTITY object as Org syntax.
2672 CONTENTS is nil."
2673 (concat "\\"
2674 (org-element-property :name entity)
2675 (when (org-element-property :use-brackets-p entity) "{}")))
2677 (defun org-element-latex-or-entity-successor ()
2678 "Search for the next latex-fragment or entity object.
2680 Return value is a cons cell whose CAR is `entity' or
2681 `latex-fragment' and CDR is beginning position."
2682 (save-excursion
2683 (unless (bolp) (backward-char))
2684 (let ((matchers (cdr org-latex-regexps))
2685 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2686 (entity-re
2687 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2688 (when (re-search-forward
2689 (concat (mapconcat #'cadr matchers "\\|") "\\|" entity-re) nil t)
2690 (goto-char (match-beginning 0))
2691 (if (looking-at entity-re)
2692 ;; Determine if it's a real entity or a LaTeX command.
2693 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2694 (match-beginning 0))
2695 ;; No entity nor command: point is at a LaTeX fragment.
2696 ;; Determine its type to get the correct beginning position.
2697 (cons 'latex-fragment
2698 (catch 'return
2699 (dolist (e matchers)
2700 (when (looking-at (nth 1 e))
2701 (throw 'return (match-beginning (nth 2 e)))))
2702 (point))))))))
2705 ;;;; Export Snippet
2707 (defun org-element-export-snippet-parser ()
2708 "Parse export snippet at point.
2710 Return a list whose CAR is `export-snippet' and CDR a plist with
2711 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2712 keywords.
2714 Assume point is at the beginning of the snippet."
2715 (save-excursion
2716 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2717 (let* ((begin (match-beginning 0))
2718 (back-end (org-match-string-no-properties 1))
2719 (value (buffer-substring-no-properties
2720 (point)
2721 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2722 (post-blank (skip-chars-forward " \t"))
2723 (end (point)))
2724 (list 'export-snippet
2725 (list :back-end back-end
2726 :value value
2727 :begin begin
2728 :end end
2729 :post-blank post-blank)))))
2731 (defun org-element-export-snippet-interpreter (export-snippet contents)
2732 "Interpret EXPORT-SNIPPET object as Org syntax.
2733 CONTENTS is nil."
2734 (format "@@%s:%s@@"
2735 (org-element-property :back-end export-snippet)
2736 (org-element-property :value export-snippet)))
2738 (defun org-element-export-snippet-successor ()
2739 "Search for the next export-snippet object.
2741 Return value is a cons cell whose CAR is `export-snippet' and CDR
2742 its beginning position."
2743 (save-excursion
2744 (let (beg)
2745 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2746 (setq beg (match-beginning 0))
2747 (search-forward "@@" nil t))
2748 (cons 'export-snippet beg)))))
2751 ;;;; Footnote Reference
2753 (defun org-element-footnote-reference-parser ()
2754 "Parse footnote reference at point.
2756 Return a list whose CAR is `footnote-reference' and CDR a plist
2757 with `:label', `:type', `:inline-definition', `:begin', `:end'
2758 and `:post-blank' as keywords."
2759 (save-excursion
2760 (looking-at org-footnote-re)
2761 (let* ((begin (point))
2762 (label (or (org-match-string-no-properties 2)
2763 (org-match-string-no-properties 3)
2764 (and (match-string 1)
2765 (concat "fn:" (org-match-string-no-properties 1)))))
2766 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2767 (inner-begin (match-end 0))
2768 (inner-end
2769 (let ((count 1))
2770 (forward-char)
2771 (while (and (> count 0) (re-search-forward "[][]" nil t))
2772 (if (equal (match-string 0) "[") (incf count) (decf count)))
2773 (1- (point))))
2774 (post-blank (progn (goto-char (1+ inner-end))
2775 (skip-chars-forward " \t")))
2776 (end (point))
2777 (footnote-reference
2778 (list 'footnote-reference
2779 (list :label label
2780 :type type
2781 :begin begin
2782 :end end
2783 :post-blank post-blank))))
2784 (org-element-put-property
2785 footnote-reference :inline-definition
2786 (and (eq type 'inline)
2787 (org-element-parse-secondary-string
2788 (buffer-substring inner-begin inner-end)
2789 (org-element-restriction 'footnote-reference)
2790 footnote-reference))))))
2792 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2793 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2794 CONTENTS is nil."
2795 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2796 (def
2797 (let ((inline-def
2798 (org-element-property :inline-definition footnote-reference)))
2799 (if (not inline-def) ""
2800 (concat ":" (org-element-interpret-data inline-def))))))
2801 (format "[%s]" (concat label def))))
2803 (defun org-element-footnote-reference-successor ()
2804 "Search for the next footnote-reference object.
2806 Return value is a cons cell whose CAR is `footnote-reference' and
2807 CDR is beginning position."
2808 (save-excursion
2809 (catch 'exit
2810 (while (re-search-forward org-footnote-re nil t)
2811 (save-excursion
2812 (let ((beg (match-beginning 0))
2813 (count 1))
2814 (backward-char)
2815 (while (re-search-forward "[][]" nil t)
2816 (if (equal (match-string 0) "[") (incf count) (decf count))
2817 (when (zerop count)
2818 (throw 'exit (cons 'footnote-reference beg))))))))))
2821 ;;;; Inline Babel Call
2823 (defun org-element-inline-babel-call-parser ()
2824 "Parse inline babel call at point.
2826 Return a list whose CAR is `inline-babel-call' and CDR a plist
2827 with `:begin', `:end', `:value' and `:post-blank' as keywords.
2829 Assume point is at the beginning of the babel call."
2830 (save-excursion
2831 (unless (bolp) (backward-char))
2832 (let ((case-fold-search t))
2833 (looking-at org-babel-inline-lob-one-liner-regexp))
2834 (let ((begin (match-end 1))
2835 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2836 (post-blank (progn (goto-char (match-end 0))
2837 (skip-chars-forward " \t")))
2838 (end (point)))
2839 (list 'inline-babel-call
2840 (list :begin begin
2841 :end end
2842 :value value
2843 :post-blank post-blank)))))
2845 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2846 "Interpret INLINE-BABEL-CALL object as Org syntax.
2847 CONTENTS is nil."
2848 (org-element-property :value inline-babel-call))
2850 (defun org-element-inline-babel-call-successor ()
2851 "Search for the next inline-babel-call object.
2853 Return value is a cons cell whose CAR is `inline-babel-call' and
2854 CDR is beginning position."
2855 (save-excursion
2856 ;; Use a simplified version of
2857 ;; `org-babel-inline-lob-one-liner-regexp'.
2858 (when (re-search-forward
2859 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2860 nil t)
2861 (cons 'inline-babel-call (match-beginning 0)))))
2864 ;;;; Inline Src Block
2866 (defun org-element-inline-src-block-parser ()
2867 "Parse inline source block at point.
2869 Return a list whose CAR is `inline-src-block' and CDR a plist
2870 with `:begin', `:end', `:language', `:value', `:parameters' and
2871 `:post-blank' as keywords.
2873 Assume point is at the beginning of the inline src block."
2874 (save-excursion
2875 (unless (bolp) (backward-char))
2876 (looking-at org-babel-inline-src-block-regexp)
2877 (let ((begin (match-beginning 1))
2878 (language (org-match-string-no-properties 2))
2879 (parameters (org-match-string-no-properties 4))
2880 (value (org-match-string-no-properties 5))
2881 (post-blank (progn (goto-char (match-end 0))
2882 (skip-chars-forward " \t")))
2883 (end (point)))
2884 (list 'inline-src-block
2885 (list :language language
2886 :value value
2887 :parameters parameters
2888 :begin begin
2889 :end end
2890 :post-blank post-blank)))))
2892 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2893 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2894 CONTENTS is nil."
2895 (let ((language (org-element-property :language inline-src-block))
2896 (arguments (org-element-property :parameters inline-src-block))
2897 (body (org-element-property :value inline-src-block)))
2898 (format "src_%s%s{%s}"
2899 language
2900 (if arguments (format "[%s]" arguments) "")
2901 body)))
2903 (defun org-element-inline-src-block-successor ()
2904 "Search for the next inline-babel-call element.
2906 Return value is a cons cell whose CAR is `inline-babel-call' and
2907 CDR is beginning position."
2908 (save-excursion
2909 (unless (bolp) (backward-char))
2910 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2911 (cons 'inline-src-block (match-beginning 1)))))
2913 ;;;; Italic
2915 (defun org-element-italic-parser ()
2916 "Parse italic object at point.
2918 Return a list whose CAR is `italic' and CDR is a plist with
2919 `:begin', `:end', `:contents-begin' and `:contents-end' and
2920 `:post-blank' keywords.
2922 Assume point is at the first slash marker."
2923 (save-excursion
2924 (unless (bolp) (backward-char 1))
2925 (looking-at org-emph-re)
2926 (let ((begin (match-beginning 2))
2927 (contents-begin (match-beginning 4))
2928 (contents-end (match-end 4))
2929 (post-blank (progn (goto-char (match-end 2))
2930 (skip-chars-forward " \t")))
2931 (end (point)))
2932 (list 'italic
2933 (list :begin begin
2934 :end end
2935 :contents-begin contents-begin
2936 :contents-end contents-end
2937 :post-blank post-blank)))))
2939 (defun org-element-italic-interpreter (italic contents)
2940 "Interpret ITALIC object as Org syntax.
2941 CONTENTS is the contents of the object."
2942 (format "/%s/" contents))
2945 ;;;; Latex Fragment
2947 (defun org-element-latex-fragment-parser ()
2948 "Parse LaTeX fragment at point.
2950 Return a list whose CAR is `latex-fragment' and CDR a plist with
2951 `:value', `:begin', `:end', and `:post-blank' as keywords.
2953 Assume point is at the beginning of the LaTeX fragment."
2954 (save-excursion
2955 (let* ((begin (point))
2956 (substring-match
2957 (catch 'exit
2958 (dolist (e (cdr org-latex-regexps))
2959 (let ((latex-regexp (nth 1 e)))
2960 (when (or (looking-at latex-regexp)
2961 (and (not (bobp))
2962 (save-excursion
2963 (backward-char)
2964 (looking-at latex-regexp))))
2965 (throw 'exit (nth 2 e)))))
2966 ;; None found: it's a macro.
2967 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2969 (value (org-match-string-no-properties substring-match))
2970 (post-blank (progn (goto-char (match-end substring-match))
2971 (skip-chars-forward " \t")))
2972 (end (point)))
2973 (list 'latex-fragment
2974 (list :value value
2975 :begin begin
2976 :end end
2977 :post-blank post-blank)))))
2979 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2980 "Interpret LATEX-FRAGMENT object as Org syntax.
2981 CONTENTS is nil."
2982 (org-element-property :value latex-fragment))
2984 ;;;; Line Break
2986 (defun org-element-line-break-parser ()
2987 "Parse line break at point.
2989 Return a list whose CAR is `line-break', and CDR a plist with
2990 `:begin', `:end' and `:post-blank' keywords.
2992 Assume point is at the beginning of the line break."
2993 (list 'line-break
2994 (list :begin (point)
2995 :end (progn (forward-line) (point))
2996 :post-blank 0)))
2998 (defun org-element-line-break-interpreter (line-break contents)
2999 "Interpret LINE-BREAK object as Org syntax.
3000 CONTENTS is nil."
3001 "\\\\\n")
3003 (defun org-element-line-break-successor ()
3004 "Search for the next line-break object.
3006 Return value is a cons cell whose CAR is `line-break' and CDR is
3007 beginning position."
3008 (save-excursion
3009 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
3010 (goto-char (match-beginning 1)))))
3011 ;; A line break can only happen on a non-empty line.
3012 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
3013 (cons 'line-break beg)))))
3016 ;;;; Link
3018 (defun org-element-link-parser ()
3019 "Parse link at point.
3021 Return a list whose CAR is `link' and CDR a plist with `:type',
3022 `:path', `:raw-link', `:application', `:search-option', `:begin',
3023 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3024 keywords.
3026 Assume point is at the beginning of the link."
3027 (save-excursion
3028 (let ((begin (point))
3029 end contents-begin contents-end link-end post-blank path type
3030 raw-link link search-option application)
3031 (cond
3032 ;; Type 1: Text targeted from a radio target.
3033 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3034 (setq type "radio"
3035 link-end (match-end 0)
3036 path (org-match-string-no-properties 0)))
3037 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3038 ((looking-at org-bracket-link-regexp)
3039 (setq contents-begin (match-beginning 3)
3040 contents-end (match-end 3)
3041 link-end (match-end 0)
3042 ;; RAW-LINK is the original link. Expand any
3043 ;; abbreviation in it.
3044 raw-link (org-translate-link
3045 (org-link-expand-abbrev
3046 (org-match-string-no-properties 1))))
3047 ;; Determine TYPE of link and set PATH accordingly.
3048 (cond
3049 ;; File type.
3050 ((or (file-name-absolute-p raw-link)
3051 (string-match "^\\.\\.?/" raw-link))
3052 (setq type "file" path raw-link))
3053 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3054 ((string-match org-link-re-with-space3 raw-link)
3055 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3056 ;; Id type: PATH is the id.
3057 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3058 (setq type "id" path (match-string 1 raw-link)))
3059 ;; Code-ref type: PATH is the name of the reference.
3060 ((string-match "^(\\(.*\\))$" raw-link)
3061 (setq type "coderef" path (match-string 1 raw-link)))
3062 ;; Custom-id type: PATH is the name of the custom id.
3063 ((= (aref raw-link 0) ?#)
3064 (setq type "custom-id" path (substring raw-link 1)))
3065 ;; Fuzzy type: Internal link either matches a target, an
3066 ;; headline name or nothing. PATH is the target or
3067 ;; headline's name.
3068 (t (setq type "fuzzy" path raw-link))))
3069 ;; Type 3: Plain link, i.e. http://orgmode.org
3070 ((looking-at org-plain-link-re)
3071 (setq raw-link (org-match-string-no-properties 0)
3072 type (org-match-string-no-properties 1)
3073 link-end (match-end 0)
3074 path (org-match-string-no-properties 2)))
3075 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3076 ((looking-at org-angle-link-re)
3077 (setq raw-link (buffer-substring-no-properties
3078 (match-beginning 1) (match-end 2))
3079 type (org-match-string-no-properties 1)
3080 link-end (match-end 0)
3081 path (org-match-string-no-properties 2))))
3082 ;; In any case, deduce end point after trailing white space from
3083 ;; LINK-END variable.
3084 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3085 end (point))
3086 ;; Extract search option and opening application out of
3087 ;; "file"-type links.
3088 (when (member type org-element-link-type-is-file)
3089 ;; Application.
3090 (cond ((string-match "^file\\+\\(.*\\)$" type)
3091 (setq application (match-string 1 type)))
3092 ((not (string-match "^file" type))
3093 (setq application type)))
3094 ;; Extract search option from PATH.
3095 (when (string-match "::\\(.*\\)$" path)
3096 (setq search-option (match-string 1 path)
3097 path (replace-match "" nil nil path)))
3098 ;; Make sure TYPE always reports "file".
3099 (setq type "file"))
3100 (list 'link
3101 (list :type type
3102 :path path
3103 :raw-link (or raw-link path)
3104 :application application
3105 :search-option search-option
3106 :begin begin
3107 :end end
3108 :contents-begin contents-begin
3109 :contents-end contents-end
3110 :post-blank post-blank)))))
3112 (defun org-element-link-interpreter (link contents)
3113 "Interpret LINK object as Org syntax.
3114 CONTENTS is the contents of the object, or nil."
3115 (let ((type (org-element-property :type link))
3116 (raw-link (org-element-property :raw-link link)))
3117 (if (string= type "radio") raw-link
3118 (format "[[%s]%s]"
3119 raw-link
3120 (if contents (format "[%s]" contents) "")))))
3122 (defun org-element-link-successor ()
3123 "Search for the next link object.
3125 Return value is a cons cell whose CAR is `link' and CDR is
3126 beginning position."
3127 (save-excursion
3128 (let ((link-regexp
3129 (if (not org-target-link-regexp) org-any-link-re
3130 (concat org-any-link-re "\\|" org-target-link-regexp))))
3131 (when (re-search-forward link-regexp nil t)
3132 (cons 'link (match-beginning 0))))))
3134 (defun org-element-plain-link-successor ()
3135 "Search for the next plain link object.
3137 Return value is a cons cell whose CAR is `link' and CDR is
3138 beginning position."
3139 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3140 (cons 'link (match-beginning 0))))
3143 ;;;; Macro
3145 (defun org-element-macro-parser ()
3146 "Parse macro at point.
3148 Return a list whose CAR is `macro' and CDR a plist with `:key',
3149 `:args', `:begin', `:end', `:value' and `:post-blank' as
3150 keywords.
3152 Assume point is at the macro."
3153 (save-excursion
3154 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3155 (let ((begin (point))
3156 (key (downcase (org-match-string-no-properties 1)))
3157 (value (org-match-string-no-properties 0))
3158 (post-blank (progn (goto-char (match-end 0))
3159 (skip-chars-forward " \t")))
3160 (end (point))
3161 (args (let ((args (org-match-string-no-properties 3)))
3162 (when args
3163 ;; Do not use `org-split-string' since empty
3164 ;; strings are meaningful here.
3165 (split-string
3166 (replace-regexp-in-string
3167 "\\(\\\\*\\)\\(,\\)"
3168 (lambda (str)
3169 (let ((len (length (match-string 1 str))))
3170 (concat (make-string (/ len 2) ?\\)
3171 (if (zerop (mod len 2)) "\000" ","))))
3172 args nil t)
3173 "\000")))))
3174 (list 'macro
3175 (list :key key
3176 :value value
3177 :args args
3178 :begin begin
3179 :end end
3180 :post-blank post-blank)))))
3182 (defun org-element-macro-interpreter (macro contents)
3183 "Interpret MACRO object as Org syntax.
3184 CONTENTS is nil."
3185 (org-element-property :value macro))
3187 (defun org-element-macro-successor ()
3188 "Search for the next macro object.
3190 Return value is cons cell whose CAR is `macro' and CDR is
3191 beginning position."
3192 (save-excursion
3193 (when (re-search-forward
3194 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3195 nil t)
3196 (cons 'macro (match-beginning 0)))))
3199 ;;;; Radio-target
3201 (defun org-element-radio-target-parser ()
3202 "Parse radio target at point.
3204 Return a list whose CAR is `radio-target' and CDR a plist with
3205 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3206 and `:post-blank' as keywords.
3208 Assume point is at the radio target."
3209 (save-excursion
3210 (looking-at org-radio-target-regexp)
3211 (let ((begin (point))
3212 (contents-begin (match-beginning 1))
3213 (contents-end (match-end 1))
3214 (value (org-match-string-no-properties 1))
3215 (post-blank (progn (goto-char (match-end 0))
3216 (skip-chars-forward " \t")))
3217 (end (point)))
3218 (list 'radio-target
3219 (list :begin begin
3220 :end end
3221 :contents-begin contents-begin
3222 :contents-end contents-end
3223 :post-blank post-blank
3224 :value value)))))
3226 (defun org-element-radio-target-interpreter (target contents)
3227 "Interpret TARGET object as Org syntax.
3228 CONTENTS is the contents of the object."
3229 (concat "<<<" contents ">>>"))
3231 (defun org-element-radio-target-successor ()
3232 "Search for the next radio-target object.
3234 Return value is a cons cell whose CAR is `radio-target' and CDR
3235 is beginning position."
3236 (save-excursion
3237 (when (re-search-forward org-radio-target-regexp nil t)
3238 (cons 'radio-target (match-beginning 0)))))
3241 ;;;; Statistics Cookie
3243 (defun org-element-statistics-cookie-parser ()
3244 "Parse statistics cookie at point.
3246 Return a list whose CAR is `statistics-cookie', and CDR a plist
3247 with `:begin', `:end', `:value' and `:post-blank' keywords.
3249 Assume point is at the beginning of the statistics-cookie."
3250 (save-excursion
3251 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3252 (let* ((begin (point))
3253 (value (buffer-substring-no-properties
3254 (match-beginning 0) (match-end 0)))
3255 (post-blank (progn (goto-char (match-end 0))
3256 (skip-chars-forward " \t")))
3257 (end (point)))
3258 (list 'statistics-cookie
3259 (list :begin begin
3260 :end end
3261 :value value
3262 :post-blank post-blank)))))
3264 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3265 "Interpret STATISTICS-COOKIE object as Org syntax.
3266 CONTENTS is nil."
3267 (org-element-property :value statistics-cookie))
3269 (defun org-element-statistics-cookie-successor ()
3270 "Search for the next statistics cookie object.
3272 Return value is a cons cell whose CAR is `statistics-cookie' and
3273 CDR is beginning position."
3274 (save-excursion
3275 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3276 (cons 'statistics-cookie (match-beginning 0)))))
3279 ;;;; Strike-Through
3281 (defun org-element-strike-through-parser ()
3282 "Parse strike-through object at point.
3284 Return a list whose CAR is `strike-through' and CDR is a plist
3285 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3286 `:post-blank' keywords.
3288 Assume point is at the first plus sign marker."
3289 (save-excursion
3290 (unless (bolp) (backward-char 1))
3291 (looking-at org-emph-re)
3292 (let ((begin (match-beginning 2))
3293 (contents-begin (match-beginning 4))
3294 (contents-end (match-end 4))
3295 (post-blank (progn (goto-char (match-end 2))
3296 (skip-chars-forward " \t")))
3297 (end (point)))
3298 (list 'strike-through
3299 (list :begin begin
3300 :end end
3301 :contents-begin contents-begin
3302 :contents-end contents-end
3303 :post-blank post-blank)))))
3305 (defun org-element-strike-through-interpreter (strike-through contents)
3306 "Interpret STRIKE-THROUGH object as Org syntax.
3307 CONTENTS is the contents of the object."
3308 (format "+%s+" contents))
3311 ;;;; Subscript
3313 (defun org-element-subscript-parser ()
3314 "Parse subscript at point.
3316 Return a list whose CAR is `subscript' and CDR a plist with
3317 `:begin', `:end', `:contents-begin', `:contents-end',
3318 `:use-brackets-p' and `:post-blank' as keywords.
3320 Assume point is at the underscore."
3321 (save-excursion
3322 (unless (bolp) (backward-char))
3323 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3325 (not (looking-at org-match-substring-regexp))))
3326 (begin (match-beginning 2))
3327 (contents-begin (or (match-beginning 5)
3328 (match-beginning 3)))
3329 (contents-end (or (match-end 5) (match-end 3)))
3330 (post-blank (progn (goto-char (match-end 0))
3331 (skip-chars-forward " \t")))
3332 (end (point)))
3333 (list 'subscript
3334 (list :begin begin
3335 :end end
3336 :use-brackets-p bracketsp
3337 :contents-begin contents-begin
3338 :contents-end contents-end
3339 :post-blank post-blank)))))
3341 (defun org-element-subscript-interpreter (subscript contents)
3342 "Interpret SUBSCRIPT object as Org syntax.
3343 CONTENTS is the contents of the object."
3344 (format
3345 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3346 contents))
3348 (defun org-element-sub/superscript-successor ()
3349 "Search for the next sub/superscript object.
3351 Return value is a cons cell whose CAR is either `subscript' or
3352 `superscript' and CDR is beginning position."
3353 (save-excursion
3354 (unless (bolp) (backward-char))
3355 (when (re-search-forward org-match-substring-regexp nil t)
3356 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3357 (match-beginning 2)))))
3360 ;;;; Superscript
3362 (defun org-element-superscript-parser ()
3363 "Parse superscript at point.
3365 Return a list whose CAR is `superscript' and CDR a plist with
3366 `:begin', `:end', `:contents-begin', `:contents-end',
3367 `:use-brackets-p' and `:post-blank' as keywords.
3369 Assume point is at the caret."
3370 (save-excursion
3371 (unless (bolp) (backward-char))
3372 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3373 (not (looking-at org-match-substring-regexp))))
3374 (begin (match-beginning 2))
3375 (contents-begin (or (match-beginning 5)
3376 (match-beginning 3)))
3377 (contents-end (or (match-end 5) (match-end 3)))
3378 (post-blank (progn (goto-char (match-end 0))
3379 (skip-chars-forward " \t")))
3380 (end (point)))
3381 (list 'superscript
3382 (list :begin begin
3383 :end end
3384 :use-brackets-p bracketsp
3385 :contents-begin contents-begin
3386 :contents-end contents-end
3387 :post-blank post-blank)))))
3389 (defun org-element-superscript-interpreter (superscript contents)
3390 "Interpret SUPERSCRIPT object as Org syntax.
3391 CONTENTS is the contents of the object."
3392 (format
3393 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3394 contents))
3397 ;;;; Table Cell
3399 (defun org-element-table-cell-parser ()
3400 "Parse table cell at point.
3402 Return a list whose CAR is `table-cell' and CDR is a plist
3403 containing `:begin', `:end', `:contents-begin', `:contents-end'
3404 and `:post-blank' keywords."
3405 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3406 (let* ((begin (match-beginning 0))
3407 (end (match-end 0))
3408 (contents-begin (match-beginning 1))
3409 (contents-end (match-end 1)))
3410 (list 'table-cell
3411 (list :begin begin
3412 :end end
3413 :contents-begin contents-begin
3414 :contents-end contents-end
3415 :post-blank 0))))
3417 (defun org-element-table-cell-interpreter (table-cell contents)
3418 "Interpret TABLE-CELL element as Org syntax.
3419 CONTENTS is the contents of the cell, or nil."
3420 (concat " " contents " |"))
3422 (defun org-element-table-cell-successor ()
3423 "Search for the next table-cell object.
3425 Return value is a cons cell whose CAR is `table-cell' and CDR is
3426 beginning position."
3427 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3430 ;;;; Target
3432 (defun org-element-target-parser ()
3433 "Parse target at point.
3435 Return a list whose CAR is `target' and CDR a plist with
3436 `:begin', `:end', `:value' and `:post-blank' as keywords.
3438 Assume point is at the target."
3439 (save-excursion
3440 (looking-at org-target-regexp)
3441 (let ((begin (point))
3442 (value (org-match-string-no-properties 1))
3443 (post-blank (progn (goto-char (match-end 0))
3444 (skip-chars-forward " \t")))
3445 (end (point)))
3446 (list 'target
3447 (list :begin begin
3448 :end end
3449 :value value
3450 :post-blank post-blank)))))
3452 (defun org-element-target-interpreter (target contents)
3453 "Interpret TARGET object as Org syntax.
3454 CONTENTS is nil."
3455 (format "<<%s>>" (org-element-property :value target)))
3457 (defun org-element-target-successor ()
3458 "Search for the next target object.
3460 Return value is a cons cell whose CAR is `target' and CDR is
3461 beginning position."
3462 (save-excursion
3463 (when (re-search-forward org-target-regexp nil t)
3464 (cons 'target (match-beginning 0)))))
3467 ;;;; Timestamp
3469 (defun org-element-timestamp-parser ()
3470 "Parse time stamp at point.
3472 Return a list whose CAR is `timestamp', and CDR a plist with
3473 `:type', `:raw-value', `:year-start', `:month-start',
3474 `:day-start', `:hour-start', `:minute-start', `:year-end',
3475 `:month-end', `:day-end', `:hour-end', `:minute-end',
3476 `:repeater-type', `:repeater-value', `:repeater-unit',
3477 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3478 `:end', `:value' and `:post-blank' keywords.
3480 Assume point is at the beginning of the timestamp."
3481 (save-excursion
3482 (let* ((begin (point))
3483 (activep (eq (char-after) ?<))
3484 (raw-value
3485 (progn
3486 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3487 (match-string-no-properties 0)))
3488 (date-start (match-string-no-properties 1))
3489 (date-end (match-string 3))
3490 (diaryp (match-beginning 2))
3491 (post-blank (progn (goto-char (match-end 0))
3492 (skip-chars-forward " \t")))
3493 (end (point))
3494 (time-range
3495 (and (not diaryp)
3496 (string-match
3497 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3498 date-start)
3499 (cons (string-to-number (match-string 2 date-start))
3500 (string-to-number (match-string 3 date-start)))))
3501 (type (cond (diaryp 'diary)
3502 ((and activep (or date-end time-range)) 'active-range)
3503 (activep 'active)
3504 ((or date-end time-range) 'inactive-range)
3505 (t 'inactive)))
3506 (repeater-props
3507 (and (not diaryp)
3508 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3509 raw-value)
3510 (list
3511 :repeater-type
3512 (let ((type (match-string 1 raw-value)))
3513 (cond ((equal "++" type) 'catch-up)
3514 ((equal ".+" type) 'restart)
3515 (t 'cumulate)))
3516 :repeater-value (string-to-number (match-string 2 raw-value))
3517 :repeater-unit
3518 (case (string-to-char (match-string 3 raw-value))
3519 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3520 (warning-props
3521 (and (not diaryp)
3522 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3523 (list
3524 :warning-type (if (match-string 1 raw-value) 'first 'all)
3525 :warning-value (string-to-number (match-string 2 raw-value))
3526 :warning-unit
3527 (case (string-to-char (match-string 3 raw-value))
3528 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3529 year-start month-start day-start hour-start minute-start year-end
3530 month-end day-end hour-end minute-end)
3531 ;; Parse date-start.
3532 (unless diaryp
3533 (let ((date (org-parse-time-string date-start t)))
3534 (setq year-start (nth 5 date)
3535 month-start (nth 4 date)
3536 day-start (nth 3 date)
3537 hour-start (nth 2 date)
3538 minute-start (nth 1 date))))
3539 ;; Compute date-end. It can be provided directly in time-stamp,
3540 ;; or extracted from time range. Otherwise, it defaults to the
3541 ;; same values as date-start.
3542 (unless diaryp
3543 (let ((date (and date-end (org-parse-time-string date-end t))))
3544 (setq year-end (or (nth 5 date) year-start)
3545 month-end (or (nth 4 date) month-start)
3546 day-end (or (nth 3 date) day-start)
3547 hour-end (or (nth 2 date) (car time-range) hour-start)
3548 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3549 (list 'timestamp
3550 (nconc (list :type type
3551 :raw-value raw-value
3552 :year-start year-start
3553 :month-start month-start
3554 :day-start day-start
3555 :hour-start hour-start
3556 :minute-start minute-start
3557 :year-end year-end
3558 :month-end month-end
3559 :day-end day-end
3560 :hour-end hour-end
3561 :minute-end minute-end
3562 :begin begin
3563 :end end
3564 :post-blank post-blank)
3565 repeater-props
3566 warning-props)))))
3568 (defun org-element-timestamp-interpreter (timestamp contents)
3569 "Interpret TIMESTAMP object as Org syntax.
3570 CONTENTS is nil."
3571 ;; Use `:raw-value' if specified.
3572 (or (org-element-property :raw-value timestamp)
3573 ;; Otherwise, build timestamp string.
3574 (let* ((repeat-string
3575 (concat
3576 (case (org-element-property :repeater-type timestamp)
3577 (cumulate "+") (catch-up "++") (restart ".+"))
3578 (let ((val (org-element-property :repeater-value timestamp)))
3579 (and val (number-to-string val)))
3580 (case (org-element-property :repeater-unit timestamp)
3581 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3582 (warning-string
3583 (concat
3584 (case (org-element-property :warning-type timestamp)
3585 (first "--")
3586 (all "-"))
3587 (let ((val (org-element-property :warning-value timestamp)))
3588 (and val (number-to-string val)))
3589 (case (org-element-property :warning-unit timestamp)
3590 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3591 (build-ts-string
3592 ;; Build an Org timestamp string from TIME. ACTIVEP is
3593 ;; non-nil when time stamp is active. If WITH-TIME-P is
3594 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3595 ;; specify a time range in the timestamp. REPEAT-STRING
3596 ;; is the repeater string, if any.
3597 (lambda (time activep &optional with-time-p hour-end minute-end)
3598 (let ((ts (format-time-string
3599 (funcall (if with-time-p 'cdr 'car)
3600 org-time-stamp-formats)
3601 time)))
3602 (when (and hour-end minute-end)
3603 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3604 (setq ts
3605 (replace-match
3606 (format "\\&-%02d:%02d" hour-end minute-end)
3607 nil nil ts)))
3608 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3609 (dolist (s (list repeat-string warning-string))
3610 (when (org-string-nw-p s)
3611 (setq ts (concat (substring ts 0 -1)
3614 (substring ts -1)))))
3615 ;; Return value.
3616 ts)))
3617 (type (org-element-property :type timestamp)))
3618 (case type
3619 ((active inactive)
3620 (let* ((minute-start (org-element-property :minute-start timestamp))
3621 (minute-end (org-element-property :minute-end timestamp))
3622 (hour-start (org-element-property :hour-start timestamp))
3623 (hour-end (org-element-property :hour-end timestamp))
3624 (time-range-p (and hour-start hour-end minute-start minute-end
3625 (or (/= hour-start hour-end)
3626 (/= minute-start minute-end)))))
3627 (funcall
3628 build-ts-string
3629 (encode-time 0
3630 (or minute-start 0)
3631 (or hour-start 0)
3632 (org-element-property :day-start timestamp)
3633 (org-element-property :month-start timestamp)
3634 (org-element-property :year-start timestamp))
3635 (eq type 'active)
3636 (and hour-start minute-start)
3637 (and time-range-p hour-end)
3638 (and time-range-p minute-end))))
3639 ((active-range inactive-range)
3640 (let ((minute-start (org-element-property :minute-start timestamp))
3641 (minute-end (org-element-property :minute-end timestamp))
3642 (hour-start (org-element-property :hour-start timestamp))
3643 (hour-end (org-element-property :hour-end timestamp)))
3644 (concat
3645 (funcall
3646 build-ts-string (encode-time
3648 (or minute-start 0)
3649 (or hour-start 0)
3650 (org-element-property :day-start timestamp)
3651 (org-element-property :month-start timestamp)
3652 (org-element-property :year-start timestamp))
3653 (eq type 'active-range)
3654 (and hour-start minute-start))
3655 "--"
3656 (funcall build-ts-string
3657 (encode-time 0
3658 (or minute-end 0)
3659 (or hour-end 0)
3660 (org-element-property :day-end timestamp)
3661 (org-element-property :month-end timestamp)
3662 (org-element-property :year-end timestamp))
3663 (eq type 'active-range)
3664 (and hour-end minute-end)))))))))
3666 (defun org-element-timestamp-successor ()
3667 "Search for the next timestamp object.
3669 Return value is a cons cell whose CAR is `timestamp' and CDR is
3670 beginning position."
3671 (save-excursion
3672 (when (re-search-forward
3673 (concat org-ts-regexp-both
3674 "\\|"
3675 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3676 "\\|"
3677 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3678 nil t)
3679 (cons 'timestamp (match-beginning 0)))))
3682 ;;;; Underline
3684 (defun org-element-underline-parser ()
3685 "Parse underline object at point.
3687 Return a list whose CAR is `underline' and CDR is a plist with
3688 `:begin', `:end', `:contents-begin' and `:contents-end' and
3689 `:post-blank' keywords.
3691 Assume point is at the first underscore marker."
3692 (save-excursion
3693 (unless (bolp) (backward-char 1))
3694 (looking-at org-emph-re)
3695 (let ((begin (match-beginning 2))
3696 (contents-begin (match-beginning 4))
3697 (contents-end (match-end 4))
3698 (post-blank (progn (goto-char (match-end 2))
3699 (skip-chars-forward " \t")))
3700 (end (point)))
3701 (list 'underline
3702 (list :begin begin
3703 :end end
3704 :contents-begin contents-begin
3705 :contents-end contents-end
3706 :post-blank post-blank)))))
3708 (defun org-element-underline-interpreter (underline contents)
3709 "Interpret UNDERLINE object as Org syntax.
3710 CONTENTS is the contents of the object."
3711 (format "_%s_" contents))
3714 ;;;; Verbatim
3716 (defun org-element-verbatim-parser ()
3717 "Parse verbatim object at point.
3719 Return a list whose CAR is `verbatim' and CDR is a plist with
3720 `:value', `:begin', `:end' and `:post-blank' keywords.
3722 Assume point is at the first equal sign marker."
3723 (save-excursion
3724 (unless (bolp) (backward-char 1))
3725 (looking-at org-emph-re)
3726 (let ((begin (match-beginning 2))
3727 (value (org-match-string-no-properties 4))
3728 (post-blank (progn (goto-char (match-end 2))
3729 (skip-chars-forward " \t")))
3730 (end (point)))
3731 (list 'verbatim
3732 (list :value value
3733 :begin begin
3734 :end end
3735 :post-blank post-blank)))))
3737 (defun org-element-verbatim-interpreter (verbatim contents)
3738 "Interpret VERBATIM object as Org syntax.
3739 CONTENTS is nil."
3740 (format "=%s=" (org-element-property :value verbatim)))
3744 ;;; Parsing Element Starting At Point
3746 ;; `org-element--current-element' is the core function of this section.
3747 ;; It returns the Lisp representation of the element starting at
3748 ;; point.
3750 ;; `org-element--current-element' makes use of special modes. They
3751 ;; are activated for fixed element chaining (i.e. `plain-list' >
3752 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3753 ;; `section'). Special modes are: `first-section', `item',
3754 ;; `node-property', `quote-section', `section' and `table-row'.
3756 (defun org-element--current-element
3757 (limit &optional granularity special structure)
3758 "Parse the element starting at point.
3760 Return value is a list like (TYPE PROPS) where TYPE is the type
3761 of the element and PROPS a plist of properties associated to the
3762 element.
3764 Possible types are defined in `org-element-all-elements'.
3766 LIMIT bounds the search.
3768 Optional argument GRANULARITY determines the depth of the
3769 recursion. Allowed values are `headline', `greater-element',
3770 `element', `object' or nil. When it is broader than `object' (or
3771 nil), secondary values will not be parsed, since they only
3772 contain objects.
3774 Optional argument SPECIAL, when non-nil, can be either
3775 `first-section', `item', `node-property', `quote-section',
3776 `section', and `table-row'.
3778 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3779 be computed.
3781 This function assumes point is always at the beginning of the
3782 element it has to parse."
3783 (save-excursion
3784 (let ((case-fold-search t)
3785 ;; Determine if parsing depth allows for secondary strings
3786 ;; parsing. It only applies to elements referenced in
3787 ;; `org-element-secondary-value-alist'.
3788 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3789 (cond
3790 ;; Item.
3791 ((eq special 'item)
3792 (org-element-item-parser limit structure raw-secondary-p))
3793 ;; Table Row.
3794 ((eq special 'table-row) (org-element-table-row-parser limit))
3795 ;; Node Property.
3796 ((eq special 'node-property) (org-element-node-property-parser limit))
3797 ;; Headline.
3798 ((org-with-limited-levels (org-at-heading-p))
3799 (org-element-headline-parser limit raw-secondary-p))
3800 ;; Sections (must be checked after headline).
3801 ((eq special 'section) (org-element-section-parser limit))
3802 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3803 ((eq special 'first-section)
3804 (org-element-section-parser
3805 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3806 limit)))
3807 ;; When not at bol, point is at the beginning of an item or
3808 ;; a footnote definition: next item is always a paragraph.
3809 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3810 ;; Planning and Clock.
3811 ((looking-at org-planning-or-clock-line-re)
3812 (if (equal (match-string 1) org-clock-string)
3813 (org-element-clock-parser limit)
3814 (org-element-planning-parser limit)))
3815 ;; Inlinetask.
3816 ((org-at-heading-p)
3817 (org-element-inlinetask-parser limit raw-secondary-p))
3818 ;; From there, elements can have affiliated keywords.
3819 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3820 (cond
3821 ;; Jumping over affiliated keywords put point off-limits.
3822 ;; Parse them as regular keywords.
3823 ((and (cdr affiliated) (>= (point) limit))
3824 (goto-char (car affiliated))
3825 (org-element-keyword-parser limit nil))
3826 ;; LaTeX Environment.
3827 ((looking-at
3828 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3829 (org-element-latex-environment-parser limit affiliated))
3830 ;; Drawer and Property Drawer.
3831 ((looking-at org-drawer-regexp)
3832 (if (equal (match-string 1) "PROPERTIES")
3833 (org-element-property-drawer-parser limit affiliated)
3834 (org-element-drawer-parser limit affiliated)))
3835 ;; Fixed Width
3836 ((looking-at "[ \t]*:\\( \\|$\\)")
3837 (org-element-fixed-width-parser limit affiliated))
3838 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3839 ;; Keywords.
3840 ((looking-at "[ \t]*#")
3841 (goto-char (match-end 0))
3842 (cond ((looking-at "\\(?: \\|$\\)")
3843 (beginning-of-line)
3844 (org-element-comment-parser limit affiliated))
3845 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3846 (beginning-of-line)
3847 (let ((parser (assoc (upcase (match-string 1))
3848 org-element-block-name-alist)))
3849 (if parser (funcall (cdr parser) limit affiliated)
3850 (org-element-special-block-parser limit affiliated))))
3851 ((looking-at "\\+CALL:")
3852 (beginning-of-line)
3853 (org-element-babel-call-parser limit affiliated))
3854 ((looking-at "\\+BEGIN:? ")
3855 (beginning-of-line)
3856 (org-element-dynamic-block-parser limit affiliated))
3857 ((looking-at "\\+\\S-+:")
3858 (beginning-of-line)
3859 (org-element-keyword-parser limit affiliated))
3861 (beginning-of-line)
3862 (org-element-paragraph-parser limit affiliated))))
3863 ;; Footnote Definition.
3864 ((looking-at org-footnote-definition-re)
3865 (org-element-footnote-definition-parser limit affiliated))
3866 ;; Horizontal Rule.
3867 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3868 (org-element-horizontal-rule-parser limit affiliated))
3869 ;; Diary Sexp.
3870 ((looking-at "%%(")
3871 (org-element-diary-sexp-parser limit affiliated))
3872 ;; Table.
3873 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3874 ;; List.
3875 ((looking-at (org-item-re))
3876 (org-element-plain-list-parser
3877 limit affiliated
3878 (or structure (org-element--list-struct limit))))
3879 ;; Default element: Paragraph.
3880 (t (org-element-paragraph-parser limit affiliated)))))))))
3883 ;; Most elements can have affiliated keywords. When looking for an
3884 ;; element beginning, we want to move before them, as they belong to
3885 ;; that element, and, in the meantime, collect information they give
3886 ;; into appropriate properties. Hence the following function.
3888 (defun org-element--collect-affiliated-keywords (limit)
3889 "Collect affiliated keywords from point down to LIMIT.
3891 Return a list whose CAR is the position at the first of them and
3892 CDR a plist of keywords and values and move point to the
3893 beginning of the first line after them.
3895 As a special case, if element doesn't start at the beginning of
3896 the line (i.e. a paragraph starting an item), CAR is current
3897 position of point and CDR is nil."
3898 (if (not (bolp)) (list (point))
3899 (let ((case-fold-search t)
3900 (origin (point))
3901 ;; RESTRICT is the list of objects allowed in parsed
3902 ;; keywords value.
3903 (restrict (org-element-restriction 'keyword))
3904 output)
3905 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3906 (let* ((raw-kwd (upcase (match-string 1)))
3907 ;; Apply translation to RAW-KWD. From there, KWD is
3908 ;; the official keyword.
3909 (kwd (or (cdr (assoc raw-kwd
3910 org-element-keyword-translation-alist))
3911 raw-kwd))
3912 ;; Find main value for any keyword.
3913 (value
3914 (save-match-data
3915 (org-trim
3916 (buffer-substring-no-properties
3917 (match-end 0) (point-at-eol)))))
3918 ;; PARSEDP is non-nil when keyword should have its
3919 ;; value parsed.
3920 (parsedp (member kwd org-element-parsed-keywords))
3921 ;; If KWD is a dual keyword, find its secondary
3922 ;; value. Maybe parse it.
3923 (dualp (member kwd org-element-dual-keywords))
3924 (dual-value
3925 (and dualp
3926 (let ((sec (org-match-string-no-properties 2)))
3927 (if (or (not sec) (not parsedp)) sec
3928 (org-element-parse-secondary-string sec restrict)))))
3929 ;; Attribute a property name to KWD.
3930 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3931 ;; Now set final shape for VALUE.
3932 (when parsedp
3933 (setq value (org-element-parse-secondary-string value restrict)))
3934 (when dualp
3935 (setq value (and (or value dual-value) (cons value dual-value))))
3936 (when (or (member kwd org-element-multiple-keywords)
3937 ;; Attributes can always appear on multiple lines.
3938 (string-match "^ATTR_" kwd))
3939 (setq value (cons value (plist-get output kwd-sym))))
3940 ;; Eventually store the new value in OUTPUT.
3941 (setq output (plist-put output kwd-sym value))
3942 ;; Move to next keyword.
3943 (forward-line)))
3944 ;; If affiliated keywords are orphaned: move back to first one.
3945 ;; They will be parsed as a paragraph.
3946 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3947 ;; Return value.
3948 (cons origin output))))
3952 ;;; The Org Parser
3954 ;; The two major functions here are `org-element-parse-buffer', which
3955 ;; parses Org syntax inside the current buffer, taking into account
3956 ;; region, narrowing, or even visibility if specified, and
3957 ;; `org-element-parse-secondary-string', which parses objects within
3958 ;; a given string.
3960 ;; The (almost) almighty `org-element-map' allows to apply a function
3961 ;; on elements or objects matching some type, and accumulate the
3962 ;; resulting values. In an export situation, it also skips unneeded
3963 ;; parts of the parse tree.
3965 (defun org-element-parse-buffer (&optional granularity visible-only)
3966 "Recursively parse the buffer and return structure.
3967 If narrowing is in effect, only parse the visible part of the
3968 buffer.
3970 Optional argument GRANULARITY determines the depth of the
3971 recursion. It can be set to the following symbols:
3973 `headline' Only parse headlines.
3974 `greater-element' Don't recurse into greater elements excepted
3975 headlines and sections. Thus, elements
3976 parsed are the top-level ones.
3977 `element' Parse everything but objects and plain text.
3978 `object' Parse the complete buffer (default).
3980 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3981 elements.
3983 An element or an objects is represented as a list with the
3984 pattern (TYPE PROPERTIES CONTENTS), where :
3986 TYPE is a symbol describing the element or object. See
3987 `org-element-all-elements' and `org-element-all-objects' for an
3988 exhaustive list of such symbols. One can retrieve it with
3989 `org-element-type' function.
3991 PROPERTIES is the list of attributes attached to the element or
3992 object, as a plist. Although most of them are specific to the
3993 element or object type, all types share `:begin', `:end',
3994 `:post-blank' and `:parent' properties, which respectively
3995 refer to buffer position where the element or object starts,
3996 ends, the number of white spaces or blank lines after it, and
3997 the element or object containing it. Properties values can be
3998 obtained by using `org-element-property' function.
4000 CONTENTS is a list of elements, objects or raw strings
4001 contained in the current element or object, when applicable.
4002 One can access them with `org-element-contents' function.
4004 The Org buffer has `org-data' as type and nil as properties.
4005 `org-element-map' function can be used to find specific elements
4006 or objects within the parse tree.
4008 This function assumes that current major mode is `org-mode'."
4009 (save-excursion
4010 (goto-char (point-min))
4011 (org-skip-whitespace)
4012 (org-element--parse-elements
4013 (point-at-bol) (point-max)
4014 ;; Start in `first-section' mode so text before the first
4015 ;; headline belongs to a section.
4016 'first-section nil granularity visible-only (list 'org-data nil))))
4018 (defun org-element-parse-secondary-string (string restriction &optional parent)
4019 "Recursively parse objects in STRING and return structure.
4021 RESTRICTION is a symbol limiting the object types that will be
4022 looked after.
4024 Optional argument PARENT, when non-nil, is the element or object
4025 containing the secondary string. It is used to set correctly
4026 `:parent' property within the string."
4027 ;; Copy buffer-local variables listed in
4028 ;; `org-element-object-variables' into temporary buffer. This is
4029 ;; required since object parsing is dependent on these variables.
4030 (let ((pairs (delq nil (mapcar (lambda (var)
4031 (when (boundp var)
4032 (cons var (symbol-value var))))
4033 org-element-object-variables))))
4034 (with-temp-buffer
4035 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4036 (insert string)
4037 (let ((secondary (org-element--parse-objects
4038 (point-min) (point-max) nil restriction)))
4039 (when parent
4040 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4041 secondary))
4042 secondary))))
4044 (defun org-element-map
4045 (data types fun &optional info first-match no-recursion with-affiliated)
4046 "Map a function on selected elements or objects.
4048 DATA is a parse tree, an element, an object, a string, or a list
4049 of such constructs. TYPES is a symbol or list of symbols of
4050 elements or objects types (see `org-element-all-elements' and
4051 `org-element-all-objects' for a complete list of types). FUN is
4052 the function called on the matching element or object. It has to
4053 accept one argument: the element or object itself.
4055 When optional argument INFO is non-nil, it should be a plist
4056 holding export options. In that case, parts of the parse tree
4057 not exportable according to that property list will be skipped.
4059 When optional argument FIRST-MATCH is non-nil, stop at the first
4060 match for which FUN doesn't return nil, and return that value.
4062 Optional argument NO-RECURSION is a symbol or a list of symbols
4063 representing elements or objects types. `org-element-map' won't
4064 enter any recursive element or object whose type belongs to that
4065 list. Though, FUN can still be applied on them.
4067 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4068 apply to matching objects within parsed affiliated keywords (see
4069 `org-element-parsed-keywords').
4071 Nil values returned from FUN do not appear in the results.
4074 Examples:
4075 ---------
4077 Assuming TREE is a variable containing an Org buffer parse tree,
4078 the following example will return a flat list of all `src-block'
4079 and `example-block' elements in it:
4081 \(org-element-map tree '(example-block src-block) 'identity)
4083 The following snippet will find the first headline with a level
4084 of 1 and a \"phone\" tag, and will return its beginning position:
4086 \(org-element-map tree 'headline
4087 \(lambda (hl)
4088 \(and (= (org-element-property :level hl) 1)
4089 \(member \"phone\" (org-element-property :tags hl))
4090 \(org-element-property :begin hl)))
4091 nil t)
4093 The next example will return a flat list of all `plain-list' type
4094 elements in TREE that are not a sub-list themselves:
4096 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4098 Eventually, this example will return a flat list of all `bold'
4099 type objects containing a `latex-snippet' type object, even
4100 looking into captions:
4102 \(org-element-map tree 'bold
4103 \(lambda (b)
4104 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4105 nil nil nil t)"
4106 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4107 (unless (listp types) (setq types (list types)))
4108 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4109 ;; Recursion depth is determined by --CATEGORY.
4110 (let* ((--category
4111 (catch 'found
4112 (let ((category 'greater-elements))
4113 (mapc (lambda (type)
4114 (cond ((or (memq type org-element-all-objects)
4115 (eq type 'plain-text))
4116 ;; If one object is found, the function
4117 ;; has to recurse into every object.
4118 (throw 'found 'objects))
4119 ((not (memq type org-element-greater-elements))
4120 ;; If one regular element is found, the
4121 ;; function has to recurse, at least,
4122 ;; into every element it encounters.
4123 (and (not (eq category 'elements))
4124 (setq category 'elements)))))
4125 types)
4126 category)))
4127 ;; Compute properties for affiliated keywords if necessary.
4128 (--affiliated-alist
4129 (and with-affiliated
4130 (mapcar (lambda (kwd)
4131 (cons kwd (intern (concat ":" (downcase kwd)))))
4132 org-element-affiliated-keywords)))
4133 --acc
4134 --walk-tree
4135 (--walk-tree
4136 (function
4137 (lambda (--data)
4138 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4139 ;; holding contextual information.
4140 (let ((--type (org-element-type --data)))
4141 (cond
4142 ((not --data))
4143 ;; Ignored element in an export context.
4144 ((and info (memq --data (plist-get info :ignore-list))))
4145 ;; List of elements or objects.
4146 ((not --type) (mapc --walk-tree --data))
4147 ;; Unconditionally enter parse trees.
4148 ((eq --type 'org-data)
4149 (mapc --walk-tree (org-element-contents --data)))
4151 ;; Check if TYPE is matching among TYPES. If so,
4152 ;; apply FUN to --DATA and accumulate return value
4153 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4154 (when (memq --type types)
4155 (let ((result (funcall fun --data)))
4156 (cond ((not result))
4157 (first-match (throw '--map-first-match result))
4158 (t (push result --acc)))))
4159 ;; If --DATA has a secondary string that can contain
4160 ;; objects with their type among TYPES, look into it.
4161 (when (and (eq --category 'objects) (not (stringp --data)))
4162 (let ((sec-prop
4163 (assq --type org-element-secondary-value-alist)))
4164 (when sec-prop
4165 (funcall --walk-tree
4166 (org-element-property (cdr sec-prop) --data)))))
4167 ;; If --DATA has any affiliated keywords and
4168 ;; WITH-AFFILIATED is non-nil, look for objects in
4169 ;; them.
4170 (when (and with-affiliated
4171 (eq --category 'objects)
4172 (memq --type org-element-all-elements))
4173 (mapc (lambda (kwd-pair)
4174 (let ((kwd (car kwd-pair))
4175 (value (org-element-property
4176 (cdr kwd-pair) --data)))
4177 ;; Pay attention to the type of value.
4178 ;; Preserve order for multiple keywords.
4179 (cond
4180 ((not value))
4181 ((and (member kwd org-element-multiple-keywords)
4182 (member kwd org-element-dual-keywords))
4183 (mapc (lambda (line)
4184 (funcall --walk-tree (cdr line))
4185 (funcall --walk-tree (car line)))
4186 (reverse value)))
4187 ((member kwd org-element-multiple-keywords)
4188 (mapc (lambda (line) (funcall --walk-tree line))
4189 (reverse value)))
4190 ((member kwd org-element-dual-keywords)
4191 (funcall --walk-tree (cdr value))
4192 (funcall --walk-tree (car value)))
4193 (t (funcall --walk-tree value)))))
4194 --affiliated-alist))
4195 ;; Determine if a recursion into --DATA is possible.
4196 (cond
4197 ;; --TYPE is explicitly removed from recursion.
4198 ((memq --type no-recursion))
4199 ;; --DATA has no contents.
4200 ((not (org-element-contents --data)))
4201 ;; Looking for greater elements but --DATA is simply
4202 ;; an element or an object.
4203 ((and (eq --category 'greater-elements)
4204 (not (memq --type org-element-greater-elements))))
4205 ;; Looking for elements but --DATA is an object.
4206 ((and (eq --category 'elements)
4207 (memq --type org-element-all-objects)))
4208 ;; In any other case, map contents.
4209 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4210 (catch '--map-first-match
4211 (funcall --walk-tree data)
4212 ;; Return value in a proper order.
4213 (nreverse --acc))))
4214 (put 'org-element-map 'lisp-indent-function 2)
4216 ;; The following functions are internal parts of the parser.
4218 ;; The first one, `org-element--parse-elements' acts at the element's
4219 ;; level.
4221 ;; The second one, `org-element--parse-objects' applies on all objects
4222 ;; of a paragraph or a secondary string. It uses
4223 ;; `org-element--get-next-object-candidates' to optimize the search of
4224 ;; the next object in the buffer.
4226 ;; More precisely, that function looks for every allowed object type
4227 ;; first. Then, it discards failed searches, keeps further matches,
4228 ;; and searches again types matched behind point, for subsequent
4229 ;; calls. Thus, searching for a given type fails only once, and every
4230 ;; object is searched only once at top level (but sometimes more for
4231 ;; nested types).
4233 (defun org-element--parse-elements
4234 (beg end special structure granularity visible-only acc)
4235 "Parse elements between BEG and END positions.
4237 SPECIAL prioritize some elements over the others. It can be set
4238 to `first-section', `quote-section', `section' `item' or
4239 `table-row'.
4241 When value is `item', STRUCTURE will be used as the current list
4242 structure.
4244 GRANULARITY determines the depth of the recursion. See
4245 `org-element-parse-buffer' for more information.
4247 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4248 elements.
4250 Elements are accumulated into ACC."
4251 (save-excursion
4252 (goto-char beg)
4253 ;; Visible only: skip invisible parts at the beginning of the
4254 ;; element.
4255 (when (and visible-only (org-invisible-p2))
4256 (goto-char (min (1+ (org-find-visible)) end)))
4257 ;; When parsing only headlines, skip any text before first one.
4258 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4259 (org-with-limited-levels (outline-next-heading)))
4260 ;; Main loop start.
4261 (while (< (point) end)
4262 ;; Find current element's type and parse it accordingly to
4263 ;; its category.
4264 (let* ((element (org-element--current-element
4265 end granularity special structure))
4266 (type (org-element-type element))
4267 (cbeg (org-element-property :contents-begin element)))
4268 (goto-char (org-element-property :end element))
4269 ;; Visible only: skip invisible parts between siblings.
4270 (when (and visible-only (org-invisible-p2))
4271 (goto-char (min (1+ (org-find-visible)) end)))
4272 ;; Fill ELEMENT contents by side-effect.
4273 (cond
4274 ;; If element has no contents, don't modify it.
4275 ((not cbeg))
4276 ;; Greater element: parse it between `contents-begin' and
4277 ;; `contents-end'. Make sure GRANULARITY allows the
4278 ;; recursion, or ELEMENT is a headline, in which case going
4279 ;; inside is mandatory, in order to get sub-level headings.
4280 ((and (memq type org-element-greater-elements)
4281 (or (memq granularity '(element object nil))
4282 (and (eq granularity 'greater-element)
4283 (eq type 'section))
4284 (eq type 'headline)))
4285 (org-element--parse-elements
4286 cbeg (org-element-property :contents-end element)
4287 ;; Possibly switch to a special mode.
4288 (case type
4289 (headline
4290 (if (org-element-property :quotedp element) 'quote-section
4291 'section))
4292 (plain-list 'item)
4293 (property-drawer 'node-property)
4294 (table 'table-row))
4295 (and (memq type '(item plain-list))
4296 (org-element-property :structure element))
4297 granularity visible-only element))
4298 ;; ELEMENT has contents. Parse objects inside, if
4299 ;; GRANULARITY allows it.
4300 ((memq granularity '(object nil))
4301 (org-element--parse-objects
4302 cbeg (org-element-property :contents-end element) element
4303 (org-element-restriction type))))
4304 (org-element-adopt-elements acc element)))
4305 ;; Return result.
4306 acc))
4308 (defun org-element--parse-objects (beg end acc restriction)
4309 "Parse objects between BEG and END and return recursive structure.
4311 Objects are accumulated in ACC.
4313 RESTRICTION is a list of object successors which are allowed in
4314 the current object."
4315 (let ((candidates 'initial))
4316 (save-excursion
4317 (save-restriction
4318 (narrow-to-region beg end)
4319 (goto-char (point-min))
4320 (while (and (not (eobp))
4321 (setq candidates
4322 (org-element--get-next-object-candidates
4323 restriction candidates)))
4324 (let ((next-object
4325 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4326 (save-excursion
4327 (goto-char pos)
4328 (funcall (intern (format "org-element-%s-parser"
4329 (car (rassq pos candidates)))))))))
4330 ;; 1. Text before any object. Untabify it.
4331 (let ((obj-beg (org-element-property :begin next-object)))
4332 (unless (= (point) obj-beg)
4333 (setq acc
4334 (org-element-adopt-elements
4336 (replace-regexp-in-string
4337 "\t" (make-string tab-width ? )
4338 (buffer-substring-no-properties (point) obj-beg))))))
4339 ;; 2. Object...
4340 (let ((obj-end (org-element-property :end next-object))
4341 (cont-beg (org-element-property :contents-begin next-object)))
4342 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4343 ;; a recursive type.
4344 (when (and cont-beg
4345 (memq (car next-object) org-element-recursive-objects))
4346 (org-element--parse-objects
4347 cont-beg (org-element-property :contents-end next-object)
4348 next-object (org-element-restriction next-object)))
4349 (setq acc (org-element-adopt-elements acc next-object))
4350 (goto-char obj-end))))
4351 ;; 3. Text after last object. Untabify it.
4352 (unless (eobp)
4353 (setq acc
4354 (org-element-adopt-elements
4356 (replace-regexp-in-string
4357 "\t" (make-string tab-width ? )
4358 (buffer-substring-no-properties (point) end)))))
4359 ;; Result.
4360 acc))))
4362 (defun org-element--get-next-object-candidates (restriction objects)
4363 "Return an alist of candidates for the next object.
4365 RESTRICTION is a list of object types, as symbols. Only
4366 candidates with such types are looked after.
4368 OBJECTS is the previous candidates alist. If it is set to
4369 `initial', no search has been done before, and all symbols in
4370 RESTRICTION should be looked after.
4372 Return value is an alist whose CAR is the object type and CDR its
4373 beginning position."
4374 (delq
4376 (if (eq objects 'initial)
4377 ;; When searching for the first time, look for every successor
4378 ;; allowed in RESTRICTION.
4379 (mapcar
4380 (lambda (res)
4381 (funcall (intern (format "org-element-%s-successor" res))))
4382 restriction)
4383 ;; Focus on objects returned during last search. Keep those
4384 ;; still after point. Search again objects before it.
4385 (mapcar
4386 (lambda (obj)
4387 (if (>= (cdr obj) (point)) obj
4388 (let* ((type (car obj))
4389 (succ (or (cdr (assq type org-element-object-successor-alist))
4390 type)))
4391 (and succ
4392 (funcall (intern (format "org-element-%s-successor" succ)))))))
4393 objects))))
4397 ;;; Towards A Bijective Process
4399 ;; The parse tree obtained with `org-element-parse-buffer' is really
4400 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4401 ;; interpreted and expanded into a string with canonical Org syntax.
4402 ;; Hence `org-element-interpret-data'.
4404 ;; The function relies internally on
4405 ;; `org-element--interpret-affiliated-keywords'.
4407 ;;;###autoload
4408 (defun org-element-interpret-data (data &optional parent)
4409 "Interpret DATA as Org syntax.
4411 DATA is a parse tree, an element, an object or a secondary string
4412 to interpret.
4414 Optional argument PARENT is used for recursive calls. It contains
4415 the element or object containing data, or nil.
4417 Return Org syntax as a string."
4418 (let* ((type (org-element-type data))
4419 (results
4420 (cond
4421 ;; Secondary string.
4422 ((not type)
4423 (mapconcat
4424 (lambda (obj) (org-element-interpret-data obj parent))
4425 data ""))
4426 ;; Full Org document.
4427 ((eq type 'org-data)
4428 (mapconcat
4429 (lambda (obj) (org-element-interpret-data obj parent))
4430 (org-element-contents data) ""))
4431 ;; Plain text: remove `:parent' text property from output.
4432 ((stringp data) (org-no-properties data))
4433 ;; Element/Object without contents.
4434 ((not (org-element-contents data))
4435 (funcall (intern (format "org-element-%s-interpreter" type))
4436 data nil))
4437 ;; Element/Object with contents.
4439 (let* ((greaterp (memq type org-element-greater-elements))
4440 (objectp (and (not greaterp)
4441 (memq type org-element-recursive-objects)))
4442 (contents
4443 (mapconcat
4444 (lambda (obj) (org-element-interpret-data obj data))
4445 (org-element-contents
4446 (if (or greaterp objectp) data
4447 ;; Elements directly containing objects must
4448 ;; have their indentation normalized first.
4449 (org-element-normalize-contents
4450 data
4451 ;; When normalizing first paragraph of an
4452 ;; item or a footnote-definition, ignore
4453 ;; first line's indentation.
4454 (and (eq type 'paragraph)
4455 (equal data (car (org-element-contents parent)))
4456 (memq (org-element-type parent)
4457 '(footnote-definition item))))))
4458 "")))
4459 (funcall (intern (format "org-element-%s-interpreter" type))
4460 data
4461 (if greaterp (org-element-normalize-contents contents)
4462 contents)))))))
4463 (if (memq type '(org-data plain-text nil)) results
4464 ;; Build white spaces. If no `:post-blank' property is
4465 ;; specified, assume its value is 0.
4466 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4467 (if (memq type org-element-all-objects)
4468 (concat results (make-string post-blank 32))
4469 (concat
4470 (org-element--interpret-affiliated-keywords data)
4471 (org-element-normalize-string results)
4472 (make-string post-blank 10)))))))
4474 (defun org-element--interpret-affiliated-keywords (element)
4475 "Return ELEMENT's affiliated keywords as Org syntax.
4476 If there is no affiliated keyword, return the empty string."
4477 (let ((keyword-to-org
4478 (function
4479 (lambda (key value)
4480 (let (dual)
4481 (when (member key org-element-dual-keywords)
4482 (setq dual (cdr value) value (car value)))
4483 (concat "#+" key
4484 (and dual
4485 (format "[%s]" (org-element-interpret-data dual)))
4486 ": "
4487 (if (member key org-element-parsed-keywords)
4488 (org-element-interpret-data value)
4489 value)
4490 "\n"))))))
4491 (mapconcat
4492 (lambda (prop)
4493 (let ((value (org-element-property prop element))
4494 (keyword (upcase (substring (symbol-name prop) 1))))
4495 (when value
4496 (if (or (member keyword org-element-multiple-keywords)
4497 ;; All attribute keywords can have multiple lines.
4498 (string-match "^ATTR_" keyword))
4499 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4500 (reverse value)
4502 (funcall keyword-to-org keyword value)))))
4503 ;; List all ELEMENT's properties matching an attribute line or an
4504 ;; affiliated keyword, but ignore translated keywords since they
4505 ;; cannot belong to the property list.
4506 (loop for prop in (nth 1 element) by 'cddr
4507 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4508 (or (string-match "^ATTR_" keyword)
4509 (and
4510 (member keyword org-element-affiliated-keywords)
4511 (not (assoc keyword
4512 org-element-keyword-translation-alist)))))
4513 collect prop)
4514 "")))
4516 ;; Because interpretation of the parse tree must return the same
4517 ;; number of blank lines between elements and the same number of white
4518 ;; space after objects, some special care must be given to white
4519 ;; spaces.
4521 ;; The first function, `org-element-normalize-string', ensures any
4522 ;; string different from the empty string will end with a single
4523 ;; newline character.
4525 ;; The second function, `org-element-normalize-contents', removes
4526 ;; global indentation from the contents of the current element.
4528 (defun org-element-normalize-string (s)
4529 "Ensure string S ends with a single newline character.
4531 If S isn't a string return it unchanged. If S is the empty
4532 string, return it. Otherwise, return a new string with a single
4533 newline character at its end."
4534 (cond
4535 ((not (stringp s)) s)
4536 ((string= "" s) "")
4537 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4538 (replace-match "\n" nil nil s)))))
4540 (defun org-element-normalize-contents (element &optional ignore-first)
4541 "Normalize plain text in ELEMENT's contents.
4543 ELEMENT must only contain plain text and objects.
4545 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4546 indentation to compute maximal common indentation.
4548 Return the normalized element that is element with global
4549 indentation removed from its contents. The function assumes that
4550 indentation is not done with TAB characters."
4551 (let* (ind-list ; for byte-compiler
4552 collect-inds ; for byte-compiler
4553 (collect-inds
4554 (function
4555 ;; Return list of indentations within BLOB. This is done by
4556 ;; walking recursively BLOB and updating IND-LIST along the
4557 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4558 ;; been seen yet. It is required as this string is the only
4559 ;; one whose indentation doesn't happen after a newline
4560 ;; character.
4561 (lambda (blob first-flag)
4562 (mapc
4563 (lambda (object)
4564 (when (and first-flag (stringp object))
4565 (setq first-flag nil)
4566 (string-match "\\`\\( *\\)" object)
4567 (let ((len (length (match-string 1 object))))
4568 ;; An indentation of zero means no string will be
4569 ;; modified. Quit the process.
4570 (if (zerop len) (throw 'zero (setq ind-list nil))
4571 (push len ind-list))))
4572 (cond
4573 ((stringp object)
4574 (let ((start 0))
4575 ;; Avoid matching blank or empty lines.
4576 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4577 (not (equal (match-string 2 object) " ")))
4578 (setq start (match-end 0))
4579 (push (length (match-string 1 object)) ind-list))))
4580 ((memq (org-element-type object) org-element-recursive-objects)
4581 (funcall collect-inds object first-flag))))
4582 (org-element-contents blob))))))
4583 ;; Collect indentation list in ELEMENT. Possibly remove first
4584 ;; value if IGNORE-FIRST is non-nil.
4585 (catch 'zero (funcall collect-inds element (not ignore-first)))
4586 (if (not ind-list) element
4587 ;; Build ELEMENT back, replacing each string with the same
4588 ;; string minus common indentation.
4589 (let* (build ; For byte compiler.
4590 (build
4591 (function
4592 (lambda (blob mci first-flag)
4593 ;; Return BLOB with all its strings indentation
4594 ;; shortened from MCI white spaces. FIRST-FLAG is
4595 ;; non-nil when the first string hasn't been seen
4596 ;; yet.
4597 (setcdr (cdr blob)
4598 (mapcar
4599 (lambda (object)
4600 (when (and first-flag (stringp object))
4601 (setq first-flag nil)
4602 (setq object
4603 (replace-regexp-in-string
4604 (format "\\` \\{%d\\}" mci) "" object)))
4605 (cond
4606 ((stringp object)
4607 (replace-regexp-in-string
4608 (format "\n \\{%d\\}" mci) "\n" object))
4609 ((memq (org-element-type object)
4610 org-element-recursive-objects)
4611 (funcall build object mci first-flag))
4612 (t object)))
4613 (org-element-contents blob)))
4614 blob))))
4615 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4619 ;;; The Toolbox
4621 ;; The first move is to implement a way to obtain the smallest element
4622 ;; containing point. This is the job of `org-element-at-point'. It
4623 ;; basically jumps back to the beginning of section containing point
4624 ;; and moves, element after element, with
4625 ;; `org-element--current-element' until the container is found. Note:
4626 ;; When using `org-element-at-point', secondary values are never
4627 ;; parsed since the function focuses on elements, not on objects.
4629 ;; At a deeper level, `org-element-context' lists all elements and
4630 ;; objects containing point.
4632 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4633 ;; internally by navigation and manipulation tools.
4635 ;;;###autoload
4636 (defun org-element-at-point (&optional keep-trail)
4637 "Determine closest element around point.
4639 Return value is a list like (TYPE PROPS) where TYPE is the type
4640 of the element and PROPS a plist of properties associated to the
4641 element.
4643 Possible types are defined in `org-element-all-elements'.
4644 Properties depend on element or object type, but always include
4645 `:begin', `:end', `:parent' and `:post-blank' properties.
4647 As a special case, if point is at the very beginning of a list or
4648 sub-list, returned element will be that list instead of the first
4649 item. In the same way, if point is at the beginning of the first
4650 row of a table, returned element will be the table instead of the
4651 first row.
4653 If optional argument KEEP-TRAIL is non-nil, the function returns
4654 a list of elements leading to element at point. The list's CAR
4655 is always the element at point. The following positions contain
4656 element's siblings, then parents, siblings of parents, until the
4657 first element of current section."
4658 (org-with-wide-buffer
4659 ;; If at a headline, parse it. It is the sole element that
4660 ;; doesn't require to know about context. Be sure to disallow
4661 ;; secondary string parsing, though.
4662 (if (org-with-limited-levels (org-at-heading-p))
4663 (progn
4664 (beginning-of-line)
4665 (if (not keep-trail) (org-element-headline-parser (point-max) t)
4666 (list (org-element-headline-parser (point-max) t))))
4667 ;; Otherwise move at the beginning of the section containing
4668 ;; point.
4669 (catch 'exit
4670 (let ((origin (point))
4671 (end (save-excursion
4672 (org-with-limited-levels (outline-next-heading)) (point)))
4673 element type special-flag trail struct prevs parent)
4674 (org-with-limited-levels
4675 (if (org-before-first-heading-p)
4676 ;; In empty lines at buffer's beginning, return nil.
4677 (progn (goto-char (point-min))
4678 (org-skip-whitespace)
4679 (when (or (eobp) (> (line-beginning-position) origin))
4680 (throw 'exit nil)))
4681 (org-back-to-heading)
4682 (forward-line)
4683 (org-skip-whitespace)
4684 (when (or (eobp) (> (line-beginning-position) origin))
4685 ;; In blank lines just after the headline, point still
4686 ;; belongs to the headline.
4687 (throw 'exit
4688 (progn (skip-chars-backward " \r\t\n")
4689 (beginning-of-line)
4690 (if (not keep-trail)
4691 (org-element-headline-parser (point-max) t)
4692 (list (org-element-headline-parser
4693 (point-max) t))))))))
4694 (beginning-of-line)
4695 ;; Parse successively each element, skipping those ending
4696 ;; before original position.
4697 (while t
4698 (setq element
4699 (org-element--current-element end 'element special-flag struct)
4700 type (car element))
4701 (org-element-put-property element :parent parent)
4702 (when keep-trail (push element trail))
4703 (cond
4704 ;; 1. Skip any element ending before point. Also skip
4705 ;; element ending at point when we're sure that another
4706 ;; element has started.
4707 ((let ((elem-end (org-element-property :end element)))
4708 (when (or (< elem-end origin)
4709 (and (= elem-end origin) (/= elem-end end)))
4710 (goto-char elem-end))))
4711 ;; 2. An element containing point is always the element at
4712 ;; point.
4713 ((not (memq type org-element-greater-elements))
4714 (throw 'exit (if keep-trail trail element)))
4715 ;; 3. At any other greater element type, if point is
4716 ;; within contents, move into it.
4718 (let ((cbeg (org-element-property :contents-begin element))
4719 (cend (org-element-property :contents-end element)))
4720 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
4721 ;; Create an anchor for tables and plain lists:
4722 ;; when point is at the very beginning of these
4723 ;; elements, ignoring affiliated keywords,
4724 ;; target them instead of their contents.
4725 (and (= cbeg origin) (memq type '(plain-list table)))
4726 ;; When point is at contents end, do not move
4727 ;; into elements with an explicit ending, but
4728 ;; return that element instead.
4729 (and (= cend origin)
4730 (or (memq type
4731 '(center-block
4732 drawer dynamic-block inlinetask
4733 property-drawer quote-block
4734 special-block))
4735 ;; Corner case: if a list ends at the
4736 ;; end of a buffer without a final new
4737 ;; line, return last element in last
4738 ;; item instead.
4739 (and (memq type '(item plain-list))
4740 (progn (goto-char cend)
4741 (or (bolp) (not (eobp))))))))
4742 (throw 'exit (if keep-trail trail element))
4743 (setq parent element)
4744 (case type
4745 (plain-list
4746 (setq special-flag 'item
4747 struct (org-element-property :structure element)))
4748 (item (setq special-flag nil))
4749 (property-drawer
4750 (setq special-flag 'node-property struct nil))
4751 (table (setq special-flag 'table-row struct nil))
4752 (otherwise (setq special-flag nil struct nil)))
4753 (setq end cend)
4754 (goto-char cbeg)))))))))))
4756 ;;;###autoload
4757 (defun org-element-context (&optional element)
4758 "Return closest element or object around point.
4760 Return value is a list like (TYPE PROPS) where TYPE is the type
4761 of the element or object and PROPS a plist of properties
4762 associated to it.
4764 Possible types are defined in `org-element-all-elements' and
4765 `org-element-all-objects'. Properties depend on element or
4766 object type, but always include `:begin', `:end', `:parent' and
4767 `:post-blank'.
4769 Optional argument ELEMENT, when non-nil, is the closest element
4770 containing point, as returned by `org-element-at-point'.
4771 Providing it allows for quicker computation."
4772 (catch 'objects-forbidden
4773 (org-with-wide-buffer
4774 (let* ((origin (point))
4775 (element (or element (org-element-at-point)))
4776 (type (org-element-type element))
4777 context)
4778 ;; Check if point is inside an element containing objects or at
4779 ;; a secondary string. In that case, narrow buffer to the
4780 ;; containing area. Otherwise, return ELEMENT.
4781 (cond
4782 ;; At a parsed affiliated keyword, check if we're inside main
4783 ;; or dual value.
4784 ((let ((post (org-element-property :post-affiliated element)))
4785 (and post (< origin post)))
4786 (beginning-of-line)
4787 (looking-at org-element--affiliated-re)
4788 (cond
4789 ((not (member (upcase (match-string 1)) org-element-parsed-keywords))
4790 (throw 'objects-forbidden element))
4791 ((< (match-end 0) origin)
4792 (narrow-to-region (match-end 0) (line-end-position)))
4793 ((and (match-beginning 2)
4794 (>= origin (match-beginning 2))
4795 (< origin (match-end 2)))
4796 (narrow-to-region (match-beginning 2) (match-end 2)))
4797 (t (throw 'objects-forbidden element)))
4798 ;; Also change type to retrieve correct restrictions.
4799 (setq type 'keyword))
4800 ;; At an item, objects can only be located within tag, if any.
4801 ((eq type 'item)
4802 (let ((tag (org-element-property :tag element)))
4803 (if (not tag) (throw 'objects-forbidden element)
4804 (beginning-of-line)
4805 (search-forward tag (line-end-position))
4806 (goto-char (match-beginning 0))
4807 (if (and (>= origin (point)) (< origin (match-end 0)))
4808 (narrow-to-region (point) (match-end 0))
4809 (throw 'objects-forbidden element)))))
4810 ;; At an headline or inlinetask, objects are located within
4811 ;; their title.
4812 ((memq type '(headline inlinetask))
4813 (goto-char (org-element-property :begin element))
4814 (skip-chars-forward "* ")
4815 (if (and (>= origin (point)) (< origin (line-end-position)))
4816 (narrow-to-region (point) (line-end-position))
4817 (throw 'objects-forbidden element)))
4818 ;; At a paragraph, a table-row or a verse block, objects are
4819 ;; located within their contents.
4820 ((memq type '(paragraph table-row verse-block))
4821 (let ((cbeg (org-element-property :contents-begin element))
4822 (cend (org-element-property :contents-end element)))
4823 ;; CBEG is nil for table rules.
4824 (if (and cbeg cend (>= origin cbeg) (< origin cend))
4825 (narrow-to-region cbeg cend)
4826 (throw 'objects-forbidden element))))
4827 ;; At a parsed keyword, objects are located within value.
4828 ((eq type 'keyword)
4829 (if (not (member (org-element-property :key element)
4830 org-element-document-properties))
4831 (throw 'objects-forbidden element)
4832 (beginning-of-line)
4833 (search-forward ":")
4834 (if (and (>= origin (point)) (< origin (line-end-position)))
4835 (narrow-to-region (point) (line-end-position))
4836 (throw 'objects-forbidden element))))
4837 (t (throw 'objects-forbidden element)))
4838 (goto-char (point-min))
4839 (let ((restriction (org-element-restriction type))
4840 (parent element)
4841 (candidates 'initial))
4842 (catch 'exit
4843 (while (setq candidates
4844 (org-element--get-next-object-candidates
4845 restriction candidates))
4846 (let ((closest-cand (rassq (apply 'min (mapcar 'cdr candidates))
4847 candidates)))
4848 ;; If ORIGIN is before next object in element, there's
4849 ;; no point in looking further.
4850 (if (> (cdr closest-cand) origin) (throw 'exit parent)
4851 (let* ((object
4852 (progn (goto-char (cdr closest-cand))
4853 (funcall (intern (format "org-element-%s-parser"
4854 (car closest-cand))))))
4855 (cbeg (org-element-property :contents-begin object))
4856 (cend (org-element-property :contents-end object))
4857 (obj-end (org-element-property :end object)))
4858 (cond
4859 ;; ORIGIN is after OBJECT, so skip it.
4860 ((<= obj-end origin) (goto-char obj-end))
4861 ;; ORIGIN is within a non-recursive object or at
4862 ;; an object boundaries: Return that object.
4863 ((or (not cbeg) (< origin cbeg) (>= origin cend))
4864 (throw 'exit
4865 (org-element-put-property object :parent parent)))
4866 ;; Otherwise, move within current object and
4867 ;; restrict search to the end of its contents.
4868 (t (goto-char cbeg)
4869 (narrow-to-region (point) cend)
4870 (org-element-put-property object :parent parent)
4871 (setq parent object
4872 restriction (org-element-restriction object)
4873 candidates 'initial)))))))
4874 parent))))))
4876 (defun org-element-nested-p (elem-A elem-B)
4877 "Non-nil when elements ELEM-A and ELEM-B are nested."
4878 (let ((beg-A (org-element-property :begin elem-A))
4879 (beg-B (org-element-property :begin elem-B))
4880 (end-A (org-element-property :end elem-A))
4881 (end-B (org-element-property :end elem-B)))
4882 (or (and (>= beg-A beg-B) (<= end-A end-B))
4883 (and (>= beg-B beg-A) (<= end-B end-A)))))
4885 (defun org-element-swap-A-B (elem-A elem-B)
4886 "Swap elements ELEM-A and ELEM-B.
4887 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
4888 end of ELEM-A."
4889 (goto-char (org-element-property :begin elem-A))
4890 ;; There are two special cases when an element doesn't start at bol:
4891 ;; the first paragraph in an item or in a footnote definition.
4892 (let ((specialp (not (bolp))))
4893 ;; Only a paragraph without any affiliated keyword can be moved at
4894 ;; ELEM-A position in such a situation. Note that the case of
4895 ;; a footnote definition is impossible: it cannot contain two
4896 ;; paragraphs in a row because it cannot contain a blank line.
4897 (if (and specialp
4898 (or (not (eq (org-element-type elem-B) 'paragraph))
4899 (/= (org-element-property :begin elem-B)
4900 (org-element-property :contents-begin elem-B))))
4901 (error "Cannot swap elements"))
4902 ;; In a special situation, ELEM-A will have no indentation. We'll
4903 ;; give it ELEM-B's (which will in, in turn, have no indentation).
4904 (let* ((ind-B (when specialp
4905 (goto-char (org-element-property :begin elem-B))
4906 (org-get-indentation)))
4907 (beg-A (org-element-property :begin elem-A))
4908 (end-A (save-excursion
4909 (goto-char (org-element-property :end elem-A))
4910 (skip-chars-backward " \r\t\n")
4911 (point-at-eol)))
4912 (beg-B (org-element-property :begin elem-B))
4913 (end-B (save-excursion
4914 (goto-char (org-element-property :end elem-B))
4915 (skip-chars-backward " \r\t\n")
4916 (point-at-eol)))
4917 ;; Store overlays responsible for visibility status. We
4918 ;; also need to store their boundaries as they will be
4919 ;; removed from buffer.
4920 (overlays
4921 (cons
4922 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4923 (overlays-in beg-A end-A))
4924 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4925 (overlays-in beg-B end-B))))
4926 ;; Get contents.
4927 (body-A (buffer-substring beg-A end-A))
4928 (body-B (delete-and-extract-region beg-B end-B)))
4929 (goto-char beg-B)
4930 (when specialp
4931 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
4932 (org-indent-to-column ind-B))
4933 (insert body-A)
4934 ;; Restore ex ELEM-A overlays.
4935 (let ((offset (- beg-B beg-A)))
4936 (mapc (lambda (ov)
4937 (move-overlay
4938 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
4939 (car overlays))
4940 (goto-char beg-A)
4941 (delete-region beg-A end-A)
4942 (insert body-B)
4943 ;; Restore ex ELEM-B overlays.
4944 (mapc (lambda (ov)
4945 (move-overlay
4946 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
4947 (cdr overlays)))
4948 (goto-char (org-element-property :end elem-B)))))
4950 (defun org-element-remove-indentation (s &optional n)
4951 "Remove maximum common indentation in string S and return it.
4952 When optional argument N is a positive integer, remove exactly
4953 that much characters from indentation, if possible, or return
4954 S as-is otherwise. Unlike to `org-remove-indentation', this
4955 function doesn't call `untabify' on S."
4956 (catch 'exit
4957 (with-temp-buffer
4958 (insert s)
4959 (goto-char (point-min))
4960 ;; Find maximum common indentation, if not specified.
4961 (setq n (or n
4962 (let ((min-ind (point-max)))
4963 (save-excursion
4964 (while (re-search-forward "^[ \t]*\\S-" nil t)
4965 (let ((ind (1- (current-column))))
4966 (if (zerop ind) (throw 'exit s)
4967 (setq min-ind (min min-ind ind))))))
4968 min-ind)))
4969 (if (zerop n) s
4970 ;; Remove exactly N indentation, but give up if not possible.
4971 (while (not (eobp))
4972 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
4973 (cond ((eolp) (delete-region (line-beginning-position) (point)))
4974 ((< ind n) (throw 'exit s))
4975 (t (org-indent-line-to (- ind n))))
4976 (forward-line)))
4977 (buffer-string)))))
4980 (provide 'org-element)
4982 ;; Local variables:
4983 ;; generated-autoload-file: "org-loaddefs.el"
4984 ;; End:
4986 ;;; org-element.el ends here