Merge branch 'maint'
[org-mode.git] / lisp / org-element.el
blob1fc26f7ca572e11ab320aa02ab51dfe9e23f77c8
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', `:info', `:post-blank' and
1496 `:post-affiliated' as keywords."
1497 (save-excursion
1498 (let ((case-fold-search t)
1499 (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
1500 (org-babel-lob-get-info)))
1501 (begin (car affiliated))
1502 (post-affiliated (point))
1503 (pos-before-blank (progn (forward-line) (point)))
1504 (end (progn (skip-chars-forward " \r\t\n" limit)
1505 (skip-chars-backward " \t")
1506 (if (bolp) (point) (line-end-position)))))
1507 (list 'babel-call
1508 (nconc
1509 (list :begin begin
1510 :end end
1511 :info info
1512 :post-blank (count-lines pos-before-blank end)
1513 :post-affiliated post-affiliated)
1514 (cdr affiliated))))))
1516 (defun org-element-babel-call-interpreter (babel-call contents)
1517 "Interpret BABEL-CALL element as Org syntax.
1518 CONTENTS is nil."
1519 (let* ((babel-info (org-element-property :info babel-call))
1520 (main (car babel-info))
1521 (post-options (nth 1 babel-info)))
1522 (concat "#+CALL: "
1523 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
1524 ;; Remove redundant square brackets.
1525 (replace-match (match-string 1 main) nil nil main))
1526 (and post-options (format "[%s]" post-options)))))
1529 ;;;; Clock
1531 (defun org-element-clock-parser (limit)
1532 "Parse a clock.
1534 LIMIT bounds the search.
1536 Return a list whose CAR is `clock' and CDR is a plist containing
1537 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1538 as keywords."
1539 (save-excursion
1540 (let* ((case-fold-search nil)
1541 (begin (point))
1542 (value (progn (search-forward org-clock-string (line-end-position) t)
1543 (skip-chars-forward " \t")
1544 (org-element-timestamp-parser)))
1545 (duration (and (search-forward " => " (line-end-position) t)
1546 (progn (skip-chars-forward " \t")
1547 (looking-at "\\(\\S-+\\)[ \t]*$"))
1548 (org-match-string-no-properties 1)))
1549 (status (if duration 'closed 'running))
1550 (post-blank (let ((before-blank (progn (forward-line) (point))))
1551 (skip-chars-forward " \r\t\n" limit)
1552 (skip-chars-backward " \t")
1553 (unless (bolp) (end-of-line))
1554 (count-lines before-blank (point))))
1555 (end (point)))
1556 (list 'clock
1557 (list :status status
1558 :value value
1559 :duration duration
1560 :begin begin
1561 :end end
1562 :post-blank post-blank)))))
1564 (defun org-element-clock-interpreter (clock contents)
1565 "Interpret CLOCK element as Org syntax.
1566 CONTENTS is nil."
1567 (concat org-clock-string " "
1568 (org-element-timestamp-interpreter
1569 (org-element-property :value clock) nil)
1570 (let ((duration (org-element-property :duration clock)))
1571 (and duration
1572 (concat " => "
1573 (apply 'format
1574 "%2s:%02s"
1575 (org-split-string duration ":")))))))
1578 ;;;; Comment
1580 (defun org-element-comment-parser (limit affiliated)
1581 "Parse a comment.
1583 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1584 the buffer position at the beginning of the first affiliated
1585 keyword and CDR is a plist of affiliated keywords along with
1586 their value.
1588 Return a list whose CAR is `comment' and CDR is a plist
1589 containing `:begin', `:end', `:value', `:post-blank',
1590 `:post-affiliated' keywords.
1592 Assume point is at comment beginning."
1593 (save-excursion
1594 (let* ((begin (car affiliated))
1595 (post-affiliated (point))
1596 (value (prog2 (looking-at "[ \t]*# ?")
1597 (buffer-substring-no-properties
1598 (match-end 0) (line-end-position))
1599 (forward-line)))
1600 (com-end
1601 ;; Get comments ending.
1602 (progn
1603 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1604 ;; Accumulate lines without leading hash and first
1605 ;; whitespace.
1606 (setq value
1607 (concat value
1608 "\n"
1609 (buffer-substring-no-properties
1610 (match-end 0) (line-end-position))))
1611 (forward-line))
1612 (point)))
1613 (end (progn (goto-char com-end)
1614 (skip-chars-forward " \r\t\n" limit)
1615 (skip-chars-backward " \t")
1616 (if (bolp) (point) (line-end-position)))))
1617 (list 'comment
1618 (nconc
1619 (list :begin begin
1620 :end end
1621 :value value
1622 :post-blank (count-lines com-end end)
1623 :post-affiliated post-affiliated)
1624 (cdr affiliated))))))
1626 (defun org-element-comment-interpreter (comment contents)
1627 "Interpret COMMENT element as Org syntax.
1628 CONTENTS is nil."
1629 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1632 ;;;; Comment Block
1634 (defun org-element-comment-block-parser (limit affiliated)
1635 "Parse an export block.
1637 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1638 the buffer position at the beginning of the first affiliated
1639 keyword and CDR is a plist of affiliated keywords along with
1640 their value.
1642 Return a list whose CAR is `comment-block' and CDR is a plist
1643 containing `:begin', `:end', `:value', `:post-blank' and
1644 `:post-affiliated' keywords.
1646 Assume point is at comment block beginning."
1647 (let ((case-fold-search t))
1648 (if (not (save-excursion
1649 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1650 ;; Incomplete block: parse it as a paragraph.
1651 (org-element-paragraph-parser limit affiliated)
1652 (let ((contents-end (match-beginning 0)))
1653 (save-excursion
1654 (let* ((begin (car affiliated))
1655 (post-affiliated (point))
1656 (contents-begin (progn (forward-line) (point)))
1657 (pos-before-blank (progn (goto-char contents-end)
1658 (forward-line)
1659 (point)))
1660 (end (progn (skip-chars-forward " \r\t\n" limit)
1661 (skip-chars-backward " \t")
1662 (if (bolp) (point) (line-end-position))))
1663 (value (buffer-substring-no-properties
1664 contents-begin contents-end)))
1665 (list 'comment-block
1666 (nconc
1667 (list :begin begin
1668 :end end
1669 :value value
1670 :post-blank (count-lines pos-before-blank end)
1671 :post-affiliated post-affiliated)
1672 (cdr affiliated)))))))))
1674 (defun org-element-comment-block-interpreter (comment-block contents)
1675 "Interpret COMMENT-BLOCK element as Org syntax.
1676 CONTENTS is nil."
1677 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1678 (org-remove-indentation (org-element-property :value comment-block))))
1681 ;;;; Diary Sexp
1683 (defun org-element-diary-sexp-parser (limit affiliated)
1684 "Parse a diary sexp.
1686 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1687 the buffer position at the beginning of the first affiliated
1688 keyword and CDR is a plist of affiliated keywords along with
1689 their value.
1691 Return a list whose CAR is `diary-sexp' and CDR is a plist
1692 containing `:begin', `:end', `:value', `:post-blank' and
1693 `:post-affiliated' keywords."
1694 (save-excursion
1695 (let ((begin (car affiliated))
1696 (post-affiliated (point))
1697 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1698 (org-match-string-no-properties 1)))
1699 (pos-before-blank (progn (forward-line) (point)))
1700 (end (progn (skip-chars-forward " \r\t\n" limit)
1701 (skip-chars-backward " \t")
1702 (if (bolp) (point) (line-end-position)))))
1703 (list 'diary-sexp
1704 (nconc
1705 (list :value value
1706 :begin begin
1707 :end end
1708 :post-blank (count-lines pos-before-blank end)
1709 :post-affiliated post-affiliated)
1710 (cdr affiliated))))))
1712 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1713 "Interpret DIARY-SEXP as Org syntax.
1714 CONTENTS is nil."
1715 (org-element-property :value diary-sexp))
1718 ;;;; Example Block
1720 (defun org-element--remove-indentation (s &optional n)
1721 "Remove maximum common indentation in string S and return it.
1722 When optional argument N is a positive integer, remove exactly
1723 that much characters from indentation, if possible, or return
1724 S as-is otherwise. Unlike to `org-remove-indentation', this
1725 function doesn't call `untabify' on S."
1726 (catch 'exit
1727 (with-temp-buffer
1728 (insert s)
1729 (goto-char (point-min))
1730 ;; Find maximum common indentation, if not specified.
1731 (setq n (or n
1732 (let ((min-ind (point-max)))
1733 (save-excursion
1734 (while (re-search-forward "^[ \t]*\\S-" nil t)
1735 (let ((ind (1- (current-column))))
1736 (if (zerop ind) (throw 'exit s)
1737 (setq min-ind (min min-ind ind))))))
1738 min-ind)))
1739 (if (zerop n) s
1740 ;; Remove exactly N indentation, but give up if not possible.
1741 (while (not (eobp))
1742 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1743 (cond ((eolp) (delete-region (line-beginning-position) (point)))
1744 ((< ind n) (throw 'exit s))
1745 (t (org-indent-line-to (- ind n))))
1746 (forward-line)))
1747 (buffer-string)))))
1749 (defun org-element-example-block-parser (limit affiliated)
1750 "Parse an example block.
1752 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1753 the buffer position at the beginning of the first affiliated
1754 keyword and CDR is a plist of affiliated keywords along with
1755 their value.
1757 Return a list whose CAR is `example-block' and CDR is a plist
1758 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1759 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1760 `:value', `:post-blank' and `:post-affiliated' keywords."
1761 (let ((case-fold-search t))
1762 (if (not (save-excursion
1763 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1764 ;; Incomplete block: parse it as a paragraph.
1765 (org-element-paragraph-parser limit affiliated)
1766 (let ((contents-end (match-beginning 0)))
1767 (save-excursion
1768 (let* ((switches
1769 (progn
1770 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1771 (org-match-string-no-properties 1)))
1772 ;; Switches analysis
1773 (number-lines
1774 (cond ((not switches) nil)
1775 ((string-match "-n\\>" switches) 'new)
1776 ((string-match "+n\\>" switches) 'continued)))
1777 (preserve-indent
1778 (or org-src-preserve-indentation
1779 (and switches (string-match "-i\\>" switches))))
1780 ;; Should labels be retained in (or stripped from) example
1781 ;; blocks?
1782 (retain-labels
1783 (or (not switches)
1784 (not (string-match "-r\\>" switches))
1785 (and number-lines (string-match "-k\\>" switches))))
1786 ;; What should code-references use - labels or
1787 ;; line-numbers?
1788 (use-labels
1789 (or (not switches)
1790 (and retain-labels
1791 (not (string-match "-k\\>" switches)))))
1792 (label-fmt
1793 (and switches
1794 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1795 (match-string 1 switches)))
1796 ;; Standard block parsing.
1797 (begin (car affiliated))
1798 (post-affiliated (point))
1799 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1800 (contents-begin (progn (forward-line) (point)))
1801 (value (org-element--remove-indentation
1802 (org-unescape-code-in-string
1803 (buffer-substring-no-properties
1804 contents-begin contents-end))
1805 (and preserve-indent block-ind)))
1806 (pos-before-blank (progn (goto-char contents-end)
1807 (forward-line)
1808 (point)))
1809 (end (progn (skip-chars-forward " \r\t\n" limit)
1810 (skip-chars-backward " \t")
1811 (if (bolp) (point) (line-end-position)))))
1812 (list 'example-block
1813 (nconc
1814 (list :begin begin
1815 :end end
1816 :value value
1817 :switches switches
1818 :number-lines number-lines
1819 :preserve-indent preserve-indent
1820 :retain-labels retain-labels
1821 :use-labels use-labels
1822 :label-fmt label-fmt
1823 :post-blank (count-lines pos-before-blank end)
1824 :post-affiliated post-affiliated)
1825 (cdr affiliated)))))))))
1827 (defun org-element-example-block-interpreter (example-block contents)
1828 "Interpret EXAMPLE-BLOCK element as Org syntax.
1829 CONTENTS is nil."
1830 (let ((switches (org-element-property :switches example-block)))
1831 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1832 (org-escape-code-in-string
1833 (org-element-property :value example-block))
1834 "#+END_EXAMPLE")))
1837 ;;;; Export Block
1839 (defun org-element-export-block-parser (limit affiliated)
1840 "Parse an export block.
1842 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1843 the buffer position at the beginning of the first affiliated
1844 keyword and CDR is a plist of affiliated keywords along with
1845 their value.
1847 Return a list whose CAR is `export-block' and CDR is a plist
1848 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1849 `:post-affiliated' keywords.
1851 Assume point is at export-block beginning."
1852 (let* ((case-fold-search t)
1853 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1854 (upcase (org-match-string-no-properties 1)))))
1855 (if (not (save-excursion
1856 (re-search-forward
1857 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1858 ;; Incomplete block: parse it as a paragraph.
1859 (org-element-paragraph-parser limit affiliated)
1860 (let ((contents-end (match-beginning 0)))
1861 (save-excursion
1862 (let* ((begin (car affiliated))
1863 (post-affiliated (point))
1864 (contents-begin (progn (forward-line) (point)))
1865 (pos-before-blank (progn (goto-char contents-end)
1866 (forward-line)
1867 (point)))
1868 (end (progn (skip-chars-forward " \r\t\n" limit)
1869 (skip-chars-backward " \t")
1870 (if (bolp) (point) (line-end-position))))
1871 (value (buffer-substring-no-properties contents-begin
1872 contents-end)))
1873 (list 'export-block
1874 (nconc
1875 (list :begin begin
1876 :end end
1877 :type type
1878 :value value
1879 :post-blank (count-lines pos-before-blank end)
1880 :post-affiliated post-affiliated)
1881 (cdr affiliated)))))))))
1883 (defun org-element-export-block-interpreter (export-block contents)
1884 "Interpret EXPORT-BLOCK element as Org syntax.
1885 CONTENTS is nil."
1886 (let ((type (org-element-property :type export-block)))
1887 (concat (format "#+BEGIN_%s\n" type)
1888 (org-element-property :value export-block)
1889 (format "#+END_%s" type))))
1892 ;;;; Fixed-width
1894 (defun org-element-fixed-width-parser (limit affiliated)
1895 "Parse a fixed-width section.
1897 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1898 the buffer position at the beginning of the first affiliated
1899 keyword and CDR is a plist of affiliated keywords along with
1900 their value.
1902 Return a list whose CAR is `fixed-width' and CDR is a plist
1903 containing `:begin', `:end', `:value', `:post-blank' and
1904 `:post-affiliated' keywords.
1906 Assume point is at the beginning of the fixed-width area."
1907 (save-excursion
1908 (let* ((begin (car affiliated))
1909 (post-affiliated (point))
1910 value
1911 (end-area
1912 (progn
1913 (while (and (< (point) limit)
1914 (looking-at "[ \t]*:\\( \\|$\\)"))
1915 ;; Accumulate text without starting colons.
1916 (setq value
1917 (concat value
1918 (buffer-substring-no-properties
1919 (match-end 0) (point-at-eol))
1920 "\n"))
1921 (forward-line))
1922 (point)))
1923 (end (progn (skip-chars-forward " \r\t\n" limit)
1924 (skip-chars-backward " \t")
1925 (if (bolp) (point) (line-end-position)))))
1926 (list 'fixed-width
1927 (nconc
1928 (list :begin begin
1929 :end end
1930 :value value
1931 :post-blank (count-lines end-area end)
1932 :post-affiliated post-affiliated)
1933 (cdr affiliated))))))
1935 (defun org-element-fixed-width-interpreter (fixed-width contents)
1936 "Interpret FIXED-WIDTH element as Org syntax.
1937 CONTENTS is nil."
1938 (let ((value (org-element-property :value fixed-width)))
1939 (and value
1940 (replace-regexp-in-string
1941 "^" ": "
1942 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1945 ;;;; Horizontal Rule
1947 (defun org-element-horizontal-rule-parser (limit affiliated)
1948 "Parse an horizontal rule.
1950 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1951 the buffer position at the beginning of the first affiliated
1952 keyword and CDR is a plist of affiliated keywords along with
1953 their value.
1955 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1956 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1957 keywords."
1958 (save-excursion
1959 (let ((begin (car affiliated))
1960 (post-affiliated (point))
1961 (post-hr (progn (forward-line) (point)))
1962 (end (progn (skip-chars-forward " \r\t\n" limit)
1963 (skip-chars-backward " \t")
1964 (if (bolp) (point) (line-end-position)))))
1965 (list 'horizontal-rule
1966 (nconc
1967 (list :begin begin
1968 :end end
1969 :post-blank (count-lines post-hr end)
1970 :post-affiliated post-affiliated)
1971 (cdr affiliated))))))
1973 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1974 "Interpret HORIZONTAL-RULE element as Org syntax.
1975 CONTENTS is nil."
1976 "-----")
1979 ;;;; Keyword
1981 (defun org-element-keyword-parser (limit affiliated)
1982 "Parse a keyword at point.
1984 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1985 the buffer position at the beginning of the first affiliated
1986 keyword and CDR is a plist of affiliated keywords along with
1987 their value.
1989 Return a list whose CAR is `keyword' and CDR is a plist
1990 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1991 `:post-affiliated' keywords."
1992 (save-excursion
1993 (let ((begin (car affiliated))
1994 (post-affiliated (point))
1995 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1996 (upcase (org-match-string-no-properties 1))))
1997 (value (org-trim (buffer-substring-no-properties
1998 (match-end 0) (point-at-eol))))
1999 (pos-before-blank (progn (forward-line) (point)))
2000 (end (progn (skip-chars-forward " \r\t\n" limit)
2001 (skip-chars-backward " \t")
2002 (if (bolp) (point) (line-end-position)))))
2003 (list 'keyword
2004 (nconc
2005 (list :key key
2006 :value value
2007 :begin begin
2008 :end end
2009 :post-blank (count-lines pos-before-blank end)
2010 :post-affiliated post-affiliated)
2011 (cdr affiliated))))))
2013 (defun org-element-keyword-interpreter (keyword contents)
2014 "Interpret KEYWORD element as Org syntax.
2015 CONTENTS is nil."
2016 (format "#+%s: %s"
2017 (org-element-property :key keyword)
2018 (org-element-property :value keyword)))
2021 ;;;; Latex Environment
2023 (defun org-element-latex-environment-parser (limit affiliated)
2024 "Parse a LaTeX environment.
2026 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2027 the buffer position at the beginning of the first affiliated
2028 keyword and CDR is a plist of affiliated keywords along with
2029 their value.
2031 Return a list whose CAR is `latex-environment' and CDR is a plist
2032 containing `:begin', `:end', `:value', `:post-blank' and
2033 `:post-affiliated' keywords.
2035 Assume point is at the beginning of the latex environment."
2036 (save-excursion
2037 (let ((case-fold-search t)
2038 (code-begin (point)))
2039 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2040 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
2041 (regexp-quote (match-string 1)))
2042 limit t))
2043 ;; Incomplete latex environment: parse it as a paragraph.
2044 (org-element-paragraph-parser limit affiliated)
2045 (let* ((code-end (progn (forward-line) (point)))
2046 (begin (car affiliated))
2047 (value (buffer-substring-no-properties code-begin code-end))
2048 (end (progn (skip-chars-forward " \r\t\n" limit)
2049 (skip-chars-backward " \t")
2050 (if (bolp) (point) (line-end-position)))))
2051 (list 'latex-environment
2052 (nconc
2053 (list :begin begin
2054 :end end
2055 :value value
2056 :post-blank (count-lines code-end end)
2057 :post-affiliated code-begin)
2058 (cdr affiliated))))))))
2060 (defun org-element-latex-environment-interpreter (latex-environment contents)
2061 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2062 CONTENTS is nil."
2063 (org-element-property :value latex-environment))
2066 ;;;; Node Property
2068 (defun org-element-node-property-parser (limit)
2069 "Parse a node-property at point.
2071 LIMIT bounds the search.
2073 Return a list whose CAR is `node-property' and CDR is a plist
2074 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2075 keywords."
2076 (save-excursion
2077 (looking-at org-property-re)
2078 (let ((case-fold-search t)
2079 (begin (point))
2080 (key (org-match-string-no-properties 2))
2081 (value (org-match-string-no-properties 3))
2082 (pos-before-blank (progn (forward-line) (point)))
2083 (end (progn (skip-chars-forward " \r\t\n" limit)
2084 (if (eobp) (point) (point-at-bol)))))
2085 (list 'node-property
2086 (list :key key
2087 :value value
2088 :begin begin
2089 :end end
2090 :post-blank (count-lines pos-before-blank end))))))
2092 (defun org-element-node-property-interpreter (node-property contents)
2093 "Interpret NODE-PROPERTY element as Org syntax.
2094 CONTENTS is nil."
2095 (format org-property-format
2096 (format ":%s:" (org-element-property :key node-property))
2097 (org-element-property :value node-property)))
2100 ;;;; Paragraph
2102 (defun org-element-paragraph-parser (limit affiliated)
2103 "Parse a paragraph.
2105 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2106 the buffer position at the beginning of the first affiliated
2107 keyword and CDR is a plist of affiliated keywords along with
2108 their value.
2110 Return a list whose CAR is `paragraph' and CDR is a plist
2111 containing `:begin', `:end', `:contents-begin' and
2112 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2114 Assume point is at the beginning of the paragraph."
2115 (save-excursion
2116 (let* ((begin (car affiliated))
2117 (contents-begin (point))
2118 (before-blank
2119 (let ((case-fold-search t))
2120 (end-of-line)
2121 (if (not (re-search-forward
2122 org-element-paragraph-separate limit 'm))
2123 limit
2124 ;; A matching `org-element-paragraph-separate' is not
2125 ;; necessarily the end of the paragraph. In
2126 ;; particular, lines starting with # or : as a first
2127 ;; non-space character are ambiguous. We have check
2128 ;; if they are valid Org syntax (i.e. not an
2129 ;; incomplete keyword).
2130 (beginning-of-line)
2131 (while (not
2133 ;; There's no ambiguity for other symbols or
2134 ;; empty lines: stop here.
2135 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2136 ;; Stop at valid fixed-width areas.
2137 (looking-at "[ \t]*:\\(?: \\|$\\)")
2138 ;; Stop at drawers.
2139 (and (looking-at org-drawer-regexp)
2140 (save-excursion
2141 (re-search-forward
2142 "^[ \t]*:END:[ \t]*$" limit t)))
2143 ;; Stop at valid comments.
2144 (looking-at "[ \t]*#\\(?: \\|$\\)")
2145 ;; Stop at valid dynamic blocks.
2146 (and (looking-at org-dblock-start-re)
2147 (save-excursion
2148 (re-search-forward
2149 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2150 ;; Stop at valid blocks.
2151 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2152 (save-excursion
2153 (re-search-forward
2154 (format "^[ \t]*#\\+END_%s[ \t]*$"
2155 (regexp-quote
2156 (org-match-string-no-properties 1)))
2157 limit t)))
2158 ;; Stop at valid latex environments.
2159 (and (looking-at
2160 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2161 (save-excursion
2162 (re-search-forward
2163 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2164 (regexp-quote
2165 (org-match-string-no-properties 1)))
2166 limit t)))
2167 ;; Stop at valid keywords.
2168 (looking-at "[ \t]*#\\+\\S-+:")
2169 ;; Skip everything else.
2170 (not
2171 (progn
2172 (end-of-line)
2173 (re-search-forward org-element-paragraph-separate
2174 limit 'm)))))
2175 (beginning-of-line)))
2176 (if (= (point) limit) limit
2177 (goto-char (line-beginning-position)))))
2178 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2179 (forward-line)
2180 (point)))
2181 (end (progn (skip-chars-forward " \r\t\n" limit)
2182 (skip-chars-backward " \t")
2183 (if (bolp) (point) (line-end-position)))))
2184 (list 'paragraph
2185 (nconc
2186 (list :begin begin
2187 :end end
2188 :contents-begin contents-begin
2189 :contents-end contents-end
2190 :post-blank (count-lines before-blank end)
2191 :post-affiliated contents-begin)
2192 (cdr affiliated))))))
2194 (defun org-element-paragraph-interpreter (paragraph contents)
2195 "Interpret PARAGRAPH element as Org syntax.
2196 CONTENTS is the contents of the element."
2197 contents)
2200 ;;;; Planning
2202 (defun org-element-planning-parser (limit)
2203 "Parse a planning.
2205 LIMIT bounds the search.
2207 Return a list whose CAR is `planning' and CDR is a plist
2208 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2209 and `:post-blank' keywords."
2210 (save-excursion
2211 (let* ((case-fold-search nil)
2212 (begin (point))
2213 (post-blank (let ((before-blank (progn (forward-line) (point))))
2214 (skip-chars-forward " \r\t\n" limit)
2215 (skip-chars-backward " \t")
2216 (unless (bolp) (end-of-line))
2217 (count-lines before-blank (point))))
2218 (end (point))
2219 closed deadline scheduled)
2220 (goto-char begin)
2221 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2222 (goto-char (match-end 1))
2223 (skip-chars-forward " \t" end)
2224 (let ((keyword (match-string 1))
2225 (time (org-element-timestamp-parser)))
2226 (cond ((equal keyword org-closed-string) (setq closed time))
2227 ((equal keyword org-deadline-string) (setq deadline time))
2228 (t (setq scheduled time)))))
2229 (list 'planning
2230 (list :closed closed
2231 :deadline deadline
2232 :scheduled scheduled
2233 :begin begin
2234 :end end
2235 :post-blank post-blank)))))
2237 (defun org-element-planning-interpreter (planning contents)
2238 "Interpret PLANNING element as Org syntax.
2239 CONTENTS is nil."
2240 (mapconcat
2241 'identity
2242 (delq nil
2243 (list (let ((deadline (org-element-property :deadline planning)))
2244 (when deadline
2245 (concat org-deadline-string " "
2246 (org-element-timestamp-interpreter deadline nil))))
2247 (let ((scheduled (org-element-property :scheduled planning)))
2248 (when scheduled
2249 (concat org-scheduled-string " "
2250 (org-element-timestamp-interpreter scheduled nil))))
2251 (let ((closed (org-element-property :closed planning)))
2252 (when closed
2253 (concat org-closed-string " "
2254 (org-element-timestamp-interpreter closed nil))))))
2255 " "))
2258 ;;;; Quote Section
2260 (defun org-element-quote-section-parser (limit)
2261 "Parse a quote section.
2263 LIMIT bounds the search.
2265 Return a list whose CAR is `quote-section' and CDR is a plist
2266 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2268 Assume point is at beginning of the section."
2269 (save-excursion
2270 (let* ((begin (point))
2271 (end (progn (org-with-limited-levels (outline-next-heading))
2272 (point)))
2273 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2274 (forward-line)
2275 (point)))
2276 (value (buffer-substring-no-properties begin pos-before-blank)))
2277 (list 'quote-section
2278 (list :begin begin
2279 :end end
2280 :value value
2281 :post-blank (count-lines pos-before-blank end))))))
2283 (defun org-element-quote-section-interpreter (quote-section contents)
2284 "Interpret QUOTE-SECTION element as Org syntax.
2285 CONTENTS is nil."
2286 (org-element-property :value quote-section))
2289 ;;;; Src Block
2291 (defun org-element-src-block-parser (limit affiliated)
2292 "Parse a src block.
2294 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2295 the buffer position at the beginning of the first affiliated
2296 keyword and CDR is a plist of affiliated keywords along with
2297 their value.
2299 Return a list whose CAR is `src-block' and CDR is a plist
2300 containing `:language', `:switches', `:parameters', `:begin',
2301 `:end', `:number-lines', `:retain-labels', `:use-labels',
2302 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2303 `:post-affiliated' keywords.
2305 Assume point is at the beginning of the block."
2306 (let ((case-fold-search t))
2307 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2308 limit t)))
2309 ;; Incomplete block: parse it as a paragraph.
2310 (org-element-paragraph-parser limit affiliated)
2311 (let ((contents-end (match-beginning 0)))
2312 (save-excursion
2313 (let* ((begin (car affiliated))
2314 (post-affiliated (point))
2315 ;; Get language as a string.
2316 (language
2317 (progn
2318 (looking-at
2319 (concat "^[ \t]*#\\+BEGIN_SRC"
2320 "\\(?: +\\(\\S-+\\)\\)?"
2321 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2322 "\\(.*\\)[ \t]*$"))
2323 (org-match-string-no-properties 1)))
2324 ;; Get switches.
2325 (switches (org-match-string-no-properties 2))
2326 ;; Get parameters.
2327 (parameters (org-match-string-no-properties 3))
2328 ;; Switches analysis
2329 (number-lines
2330 (cond ((not switches) nil)
2331 ((string-match "-n\\>" switches) 'new)
2332 ((string-match "+n\\>" switches) 'continued)))
2333 (preserve-indent (or org-src-preserve-indentation
2334 (and switches
2335 (string-match "-i\\>" switches))))
2336 (label-fmt
2337 (and switches
2338 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2339 (match-string 1 switches)))
2340 ;; Should labels be retained in (or stripped from)
2341 ;; src blocks?
2342 (retain-labels
2343 (or (not switches)
2344 (not (string-match "-r\\>" switches))
2345 (and number-lines (string-match "-k\\>" switches))))
2346 ;; What should code-references use - labels or
2347 ;; line-numbers?
2348 (use-labels
2349 (or (not switches)
2350 (and retain-labels
2351 (not (string-match "-k\\>" switches)))))
2352 ;; Indentation.
2353 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2354 ;; Retrieve code.
2355 (value (org-element--remove-indentation
2356 (org-unescape-code-in-string
2357 (buffer-substring-no-properties
2358 (progn (forward-line) (point)) contents-end))
2359 (and preserve-indent block-ind)))
2360 (pos-before-blank (progn (goto-char contents-end)
2361 (forward-line)
2362 (point)))
2363 ;; Get position after ending blank lines.
2364 (end (progn (skip-chars-forward " \r\t\n" limit)
2365 (skip-chars-backward " \t")
2366 (if (bolp) (point) (line-end-position)))))
2367 (list 'src-block
2368 (nconc
2369 (list :language language
2370 :switches (and (org-string-nw-p switches)
2371 (org-trim switches))
2372 :parameters (and (org-string-nw-p parameters)
2373 (org-trim parameters))
2374 :begin begin
2375 :end end
2376 :number-lines number-lines
2377 :preserve-indent preserve-indent
2378 :retain-labels retain-labels
2379 :use-labels use-labels
2380 :label-fmt label-fmt
2381 :value value
2382 :post-blank (count-lines pos-before-blank end)
2383 :post-affiliated post-affiliated)
2384 (cdr affiliated)))))))))
2386 (defun org-element-src-block-interpreter (src-block contents)
2387 "Interpret SRC-BLOCK element as Org syntax.
2388 CONTENTS is nil."
2389 (let ((lang (org-element-property :language src-block))
2390 (switches (org-element-property :switches src-block))
2391 (params (org-element-property :parameters src-block))
2392 (value (let ((val (org-element-property :value src-block)))
2393 (cond
2394 ((org-element-property :preserve-indent src-block) val)
2395 ((zerop org-edit-src-content-indentation) val)
2397 (let ((ind (make-string
2398 org-edit-src-content-indentation 32)))
2399 (replace-regexp-in-string
2400 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2401 (concat (format "#+BEGIN_SRC%s\n"
2402 (concat (and lang (concat " " lang))
2403 (and switches (concat " " switches))
2404 (and params (concat " " params))))
2405 (org-escape-code-in-string value)
2406 "#+END_SRC")))
2409 ;;;; Table
2411 (defun org-element-table-parser (limit affiliated)
2412 "Parse a table at point.
2414 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2415 the buffer position at the beginning of the first affiliated
2416 keyword and CDR is a plist of affiliated keywords along with
2417 their value.
2419 Return a list whose CAR is `table' and CDR is a plist containing
2420 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2421 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2422 keywords.
2424 Assume point is at the beginning of the table."
2425 (save-excursion
2426 (let* ((case-fold-search t)
2427 (table-begin (point))
2428 (type (if (org-at-table.el-p) 'table.el 'org))
2429 (begin (car affiliated))
2430 (table-end
2431 (if (re-search-forward org-table-any-border-regexp limit 'm)
2432 (goto-char (match-beginning 0))
2433 (point)))
2434 (tblfm (let (acc)
2435 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2436 (push (org-match-string-no-properties 1) acc)
2437 (forward-line))
2438 acc))
2439 (pos-before-blank (point))
2440 (end (progn (skip-chars-forward " \r\t\n" limit)
2441 (skip-chars-backward " \t")
2442 (if (bolp) (point) (line-end-position)))))
2443 (list 'table
2444 (nconc
2445 (list :begin begin
2446 :end end
2447 :type type
2448 :tblfm tblfm
2449 ;; Only `org' tables have contents. `table.el' tables
2450 ;; use a `:value' property to store raw table as
2451 ;; a string.
2452 :contents-begin (and (eq type 'org) table-begin)
2453 :contents-end (and (eq type 'org) table-end)
2454 :value (and (eq type 'table.el)
2455 (buffer-substring-no-properties
2456 table-begin table-end))
2457 :post-blank (count-lines pos-before-blank end)
2458 :post-affiliated table-begin)
2459 (cdr affiliated))))))
2461 (defun org-element-table-interpreter (table contents)
2462 "Interpret TABLE element as Org syntax.
2463 CONTENTS is nil."
2464 (if (eq (org-element-property :type table) 'table.el)
2465 (org-remove-indentation (org-element-property :value table))
2466 (concat (with-temp-buffer (insert contents)
2467 (org-table-align)
2468 (buffer-string))
2469 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2470 (reverse (org-element-property :tblfm table))
2471 "\n"))))
2474 ;;;; Table Row
2476 (defun org-element-table-row-parser (limit)
2477 "Parse table row at point.
2479 LIMIT bounds the search.
2481 Return a list whose CAR is `table-row' and CDR is a plist
2482 containing `:begin', `:end', `:contents-begin', `:contents-end',
2483 `:type' and `:post-blank' keywords."
2484 (save-excursion
2485 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2486 (begin (point))
2487 ;; A table rule has no contents. In that case, ensure
2488 ;; CONTENTS-BEGIN matches CONTENTS-END.
2489 (contents-begin (and (eq type 'standard)
2490 (search-forward "|")
2491 (point)))
2492 (contents-end (and (eq type 'standard)
2493 (progn
2494 (end-of-line)
2495 (skip-chars-backward " \t")
2496 (point))))
2497 (end (progn (forward-line) (point))))
2498 (list 'table-row
2499 (list :type type
2500 :begin begin
2501 :end end
2502 :contents-begin contents-begin
2503 :contents-end contents-end
2504 :post-blank 0)))))
2506 (defun org-element-table-row-interpreter (table-row contents)
2507 "Interpret TABLE-ROW element as Org syntax.
2508 CONTENTS is the contents of the table row."
2509 (if (eq (org-element-property :type table-row) 'rule) "|-"
2510 (concat "| " contents)))
2513 ;;;; Verse Block
2515 (defun org-element-verse-block-parser (limit affiliated)
2516 "Parse a verse block.
2518 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2519 the buffer position at the beginning of the first affiliated
2520 keyword and CDR is a plist of affiliated keywords along with
2521 their value.
2523 Return a list whose CAR is `verse-block' and CDR is a plist
2524 containing `:begin', `:end', `:contents-begin', `:contents-end',
2525 `:post-blank' and `:post-affiliated' keywords.
2527 Assume point is at beginning of the block."
2528 (let ((case-fold-search t))
2529 (if (not (save-excursion
2530 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2531 ;; Incomplete block: parse it as a paragraph.
2532 (org-element-paragraph-parser limit affiliated)
2533 (let ((contents-end (match-beginning 0)))
2534 (save-excursion
2535 (let* ((begin (car affiliated))
2536 (post-affiliated (point))
2537 (contents-begin (progn (forward-line) (point)))
2538 (pos-before-blank (progn (goto-char contents-end)
2539 (forward-line)
2540 (point)))
2541 (end (progn (skip-chars-forward " \r\t\n" limit)
2542 (skip-chars-backward " \t")
2543 (if (bolp) (point) (line-end-position)))))
2544 (list 'verse-block
2545 (nconc
2546 (list :begin begin
2547 :end end
2548 :contents-begin contents-begin
2549 :contents-end contents-end
2550 :post-blank (count-lines pos-before-blank end)
2551 :post-affiliated post-affiliated)
2552 (cdr affiliated)))))))))
2554 (defun org-element-verse-block-interpreter (verse-block contents)
2555 "Interpret VERSE-BLOCK element as Org syntax.
2556 CONTENTS is verse block contents."
2557 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2561 ;;; Objects
2563 ;; Unlike to elements, interstices can be found between objects.
2564 ;; That's why, along with the parser, successor functions are provided
2565 ;; for each object. Some objects share the same successor (i.e. `code'
2566 ;; and `verbatim' objects).
2568 ;; A successor must accept a single argument bounding the search. It
2569 ;; will return either a cons cell whose CAR is the object's type, as
2570 ;; a symbol, and CDR the position of its next occurrence, or nil.
2572 ;; Successors follow the naming convention:
2573 ;; org-element-NAME-successor, where NAME is the name of the
2574 ;; successor, as defined in `org-element-all-successors'.
2576 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2577 ;; object types they can contain will be specified in
2578 ;; `org-element-object-restrictions'.
2580 ;; Adding a new type of object is simple. Implement a successor,
2581 ;; a parser, and an interpreter for it, all following the naming
2582 ;; convention. Register type in `org-element-all-objects' and
2583 ;; successor in `org-element-all-successors'. Maybe tweak
2584 ;; restrictions about it, and that's it.
2587 ;;;; Bold
2589 (defun org-element-bold-parser ()
2590 "Parse bold object at point.
2592 Return a list whose CAR is `bold' and CDR is a plist with
2593 `:begin', `:end', `:contents-begin' and `:contents-end' and
2594 `:post-blank' keywords.
2596 Assume point is at the first star marker."
2597 (save-excursion
2598 (unless (bolp) (backward-char 1))
2599 (looking-at org-emph-re)
2600 (let ((begin (match-beginning 2))
2601 (contents-begin (match-beginning 4))
2602 (contents-end (match-end 4))
2603 (post-blank (progn (goto-char (match-end 2))
2604 (skip-chars-forward " \t")))
2605 (end (point)))
2606 (list 'bold
2607 (list :begin begin
2608 :end end
2609 :contents-begin contents-begin
2610 :contents-end contents-end
2611 :post-blank post-blank)))))
2613 (defun org-element-bold-interpreter (bold contents)
2614 "Interpret BOLD object as Org syntax.
2615 CONTENTS is the contents of the object."
2616 (format "*%s*" contents))
2618 (defun org-element-text-markup-successor ()
2619 "Search for the next text-markup object.
2621 Return value is a cons cell whose CAR is a symbol among `bold',
2622 `italic', `underline', `strike-through', `code' and `verbatim'
2623 and CDR is beginning position."
2624 (save-excursion
2625 (unless (bolp) (backward-char))
2626 (when (re-search-forward org-emph-re nil t)
2627 (let ((marker (match-string 3)))
2628 (cons (cond
2629 ((equal marker "*") 'bold)
2630 ((equal marker "/") 'italic)
2631 ((equal marker "_") 'underline)
2632 ((equal marker "+") 'strike-through)
2633 ((equal marker "~") 'code)
2634 ((equal marker "=") 'verbatim)
2635 (t (error "Unknown marker at %d" (match-beginning 3))))
2636 (match-beginning 2))))))
2639 ;;;; Code
2641 (defun org-element-code-parser ()
2642 "Parse code object at point.
2644 Return a list whose CAR is `code' and CDR is a plist with
2645 `:value', `:begin', `:end' and `:post-blank' keywords.
2647 Assume point is at the first tilde marker."
2648 (save-excursion
2649 (unless (bolp) (backward-char 1))
2650 (looking-at org-emph-re)
2651 (let ((begin (match-beginning 2))
2652 (value (org-match-string-no-properties 4))
2653 (post-blank (progn (goto-char (match-end 2))
2654 (skip-chars-forward " \t")))
2655 (end (point)))
2656 (list 'code
2657 (list :value value
2658 :begin begin
2659 :end end
2660 :post-blank post-blank)))))
2662 (defun org-element-code-interpreter (code contents)
2663 "Interpret CODE object as Org syntax.
2664 CONTENTS is nil."
2665 (format "~%s~" (org-element-property :value code)))
2668 ;;;; Entity
2670 (defun org-element-entity-parser ()
2671 "Parse entity at point.
2673 Return a list whose CAR is `entity' and CDR a plist with
2674 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2675 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2676 keywords.
2678 Assume point is at the beginning of the entity."
2679 (save-excursion
2680 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2681 (let* ((value (org-entity-get (match-string 1)))
2682 (begin (match-beginning 0))
2683 (bracketsp (string= (match-string 2) "{}"))
2684 (post-blank (progn (goto-char (match-end 1))
2685 (when bracketsp (forward-char 2))
2686 (skip-chars-forward " \t")))
2687 (end (point)))
2688 (list 'entity
2689 (list :name (car value)
2690 :latex (nth 1 value)
2691 :latex-math-p (nth 2 value)
2692 :html (nth 3 value)
2693 :ascii (nth 4 value)
2694 :latin1 (nth 5 value)
2695 :utf-8 (nth 6 value)
2696 :begin begin
2697 :end end
2698 :use-brackets-p bracketsp
2699 :post-blank post-blank)))))
2701 (defun org-element-entity-interpreter (entity contents)
2702 "Interpret ENTITY object as Org syntax.
2703 CONTENTS is nil."
2704 (concat "\\"
2705 (org-element-property :name entity)
2706 (when (org-element-property :use-brackets-p entity) "{}")))
2708 (defun org-element-latex-or-entity-successor ()
2709 "Search for the next latex-fragment or entity object.
2711 Return value is a cons cell whose CAR is `entity' or
2712 `latex-fragment' and CDR is beginning position."
2713 (save-excursion
2714 (unless (bolp) (backward-char))
2715 (let ((matchers
2716 (remove "begin" (plist-get org-format-latex-options :matchers)))
2717 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2718 (entity-re
2719 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2720 (when (re-search-forward
2721 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
2722 matchers "\\|")
2723 "\\|" entity-re)
2724 nil t)
2725 (goto-char (match-beginning 0))
2726 (if (looking-at entity-re)
2727 ;; Determine if it's a real entity or a LaTeX command.
2728 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2729 (match-beginning 0))
2730 ;; No entity nor command: point is at a LaTeX fragment.
2731 ;; Determine its type to get the correct beginning position.
2732 (cons 'latex-fragment
2733 (catch 'return
2734 (mapc (lambda (e)
2735 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
2736 (throw 'return
2737 (match-beginning
2738 (nth 2 (assoc e org-latex-regexps))))))
2739 matchers)
2740 (point))))))))
2743 ;;;; Export Snippet
2745 (defun org-element-export-snippet-parser ()
2746 "Parse export snippet at point.
2748 Return a list whose CAR is `export-snippet' and CDR a plist with
2749 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2750 keywords.
2752 Assume point is at the beginning of the snippet."
2753 (save-excursion
2754 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2755 (let* ((begin (match-beginning 0))
2756 (back-end (org-match-string-no-properties 1))
2757 (value (buffer-substring-no-properties
2758 (point)
2759 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2760 (post-blank (skip-chars-forward " \t"))
2761 (end (point)))
2762 (list 'export-snippet
2763 (list :back-end back-end
2764 :value value
2765 :begin begin
2766 :end end
2767 :post-blank post-blank)))))
2769 (defun org-element-export-snippet-interpreter (export-snippet contents)
2770 "Interpret EXPORT-SNIPPET object as Org syntax.
2771 CONTENTS is nil."
2772 (format "@@%s:%s@@"
2773 (org-element-property :back-end export-snippet)
2774 (org-element-property :value export-snippet)))
2776 (defun org-element-export-snippet-successor ()
2777 "Search for the next export-snippet object.
2779 Return value is a cons cell whose CAR is `export-snippet' and CDR
2780 its beginning position."
2781 (save-excursion
2782 (let (beg)
2783 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2784 (setq beg (match-beginning 0))
2785 (search-forward "@@" nil t))
2786 (cons 'export-snippet beg)))))
2789 ;;;; Footnote Reference
2791 (defun org-element-footnote-reference-parser ()
2792 "Parse footnote reference at point.
2794 Return a list whose CAR is `footnote-reference' and CDR a plist
2795 with `:label', `:type', `:inline-definition', `:begin', `:end'
2796 and `:post-blank' as keywords."
2797 (save-excursion
2798 (looking-at org-footnote-re)
2799 (let* ((begin (point))
2800 (label (or (org-match-string-no-properties 2)
2801 (org-match-string-no-properties 3)
2802 (and (match-string 1)
2803 (concat "fn:" (org-match-string-no-properties 1)))))
2804 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2805 (inner-begin (match-end 0))
2806 (inner-end
2807 (let ((count 1))
2808 (forward-char)
2809 (while (and (> count 0) (re-search-forward "[][]" nil t))
2810 (if (equal (match-string 0) "[") (incf count) (decf count)))
2811 (1- (point))))
2812 (post-blank (progn (goto-char (1+ inner-end))
2813 (skip-chars-forward " \t")))
2814 (end (point))
2815 (footnote-reference
2816 (list 'footnote-reference
2817 (list :label label
2818 :type type
2819 :begin begin
2820 :end end
2821 :post-blank post-blank))))
2822 (org-element-put-property
2823 footnote-reference :inline-definition
2824 (and (eq type 'inline)
2825 (org-element-parse-secondary-string
2826 (buffer-substring inner-begin inner-end)
2827 (org-element-restriction 'footnote-reference)
2828 footnote-reference))))))
2830 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2831 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2832 CONTENTS is nil."
2833 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2834 (def
2835 (let ((inline-def
2836 (org-element-property :inline-definition footnote-reference)))
2837 (if (not inline-def) ""
2838 (concat ":" (org-element-interpret-data inline-def))))))
2839 (format "[%s]" (concat label def))))
2841 (defun org-element-footnote-reference-successor ()
2842 "Search for the next footnote-reference object.
2844 Return value is a cons cell whose CAR is `footnote-reference' and
2845 CDR is beginning position."
2846 (save-excursion
2847 (catch 'exit
2848 (while (re-search-forward org-footnote-re nil t)
2849 (save-excursion
2850 (let ((beg (match-beginning 0))
2851 (count 1))
2852 (backward-char)
2853 (while (re-search-forward "[][]" nil t)
2854 (if (equal (match-string 0) "[") (incf count) (decf count))
2855 (when (zerop count)
2856 (throw 'exit (cons 'footnote-reference beg))))))))))
2859 ;;;; Inline Babel Call
2861 (defun org-element-inline-babel-call-parser ()
2862 "Parse inline babel call at point.
2864 Return a list whose CAR is `inline-babel-call' and CDR a plist
2865 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2867 Assume point is at the beginning of the babel call."
2868 (save-excursion
2869 (unless (bolp) (backward-char))
2870 (looking-at org-babel-inline-lob-one-liner-regexp)
2871 (let ((info (save-match-data (org-babel-lob-get-info)))
2872 (begin (match-end 1))
2873 (post-blank (progn (goto-char (match-end 0))
2874 (skip-chars-forward " \t")))
2875 (end (point)))
2876 (list 'inline-babel-call
2877 (list :begin begin
2878 :end end
2879 :info info
2880 :post-blank post-blank)))))
2882 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2883 "Interpret INLINE-BABEL-CALL object as Org syntax.
2884 CONTENTS is nil."
2885 (let* ((babel-info (org-element-property :info inline-babel-call))
2886 (main-source (car babel-info))
2887 (post-options (nth 1 babel-info)))
2888 (concat "call_"
2889 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2890 ;; Remove redundant square brackets.
2891 (replace-match
2892 (match-string 1 main-source) nil nil main-source)
2893 main-source)
2894 (and post-options (format "[%s]" post-options)))))
2896 (defun org-element-inline-babel-call-successor ()
2897 "Search for the next inline-babel-call object.
2899 Return value is a cons cell whose CAR is `inline-babel-call' and
2900 CDR is beginning position."
2901 (save-excursion
2902 ;; Use a simplified version of
2903 ;; `org-babel-inline-lob-one-liner-regexp'.
2904 (when (re-search-forward
2905 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2906 nil t)
2907 (cons 'inline-babel-call (match-beginning 0)))))
2910 ;;;; Inline Src Block
2912 (defun org-element-inline-src-block-parser ()
2913 "Parse inline source block at point.
2915 Return a list whose CAR is `inline-src-block' and CDR a plist
2916 with `:begin', `:end', `:language', `:value', `:parameters' and
2917 `:post-blank' as keywords.
2919 Assume point is at the beginning of the inline src block."
2920 (save-excursion
2921 (unless (bolp) (backward-char))
2922 (looking-at org-babel-inline-src-block-regexp)
2923 (let ((begin (match-beginning 1))
2924 (language (org-match-string-no-properties 2))
2925 (parameters (org-match-string-no-properties 4))
2926 (value (org-match-string-no-properties 5))
2927 (post-blank (progn (goto-char (match-end 0))
2928 (skip-chars-forward " \t")))
2929 (end (point)))
2930 (list 'inline-src-block
2931 (list :language language
2932 :value value
2933 :parameters parameters
2934 :begin begin
2935 :end end
2936 :post-blank post-blank)))))
2938 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2939 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2940 CONTENTS is nil."
2941 (let ((language (org-element-property :language inline-src-block))
2942 (arguments (org-element-property :parameters inline-src-block))
2943 (body (org-element-property :value inline-src-block)))
2944 (format "src_%s%s{%s}"
2945 language
2946 (if arguments (format "[%s]" arguments) "")
2947 body)))
2949 (defun org-element-inline-src-block-successor ()
2950 "Search for the next inline-babel-call element.
2952 Return value is a cons cell whose CAR is `inline-babel-call' and
2953 CDR is beginning position."
2954 (save-excursion
2955 (unless (bolp) (backward-char))
2956 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2957 (cons 'inline-src-block (match-beginning 1)))))
2959 ;;;; Italic
2961 (defun org-element-italic-parser ()
2962 "Parse italic object at point.
2964 Return a list whose CAR is `italic' and CDR is a plist with
2965 `:begin', `:end', `:contents-begin' and `:contents-end' and
2966 `:post-blank' keywords.
2968 Assume point is at the first slash marker."
2969 (save-excursion
2970 (unless (bolp) (backward-char 1))
2971 (looking-at org-emph-re)
2972 (let ((begin (match-beginning 2))
2973 (contents-begin (match-beginning 4))
2974 (contents-end (match-end 4))
2975 (post-blank (progn (goto-char (match-end 2))
2976 (skip-chars-forward " \t")))
2977 (end (point)))
2978 (list 'italic
2979 (list :begin begin
2980 :end end
2981 :contents-begin contents-begin
2982 :contents-end contents-end
2983 :post-blank post-blank)))))
2985 (defun org-element-italic-interpreter (italic contents)
2986 "Interpret ITALIC object as Org syntax.
2987 CONTENTS is the contents of the object."
2988 (format "/%s/" contents))
2991 ;;;; Latex Fragment
2993 (defun org-element-latex-fragment-parser ()
2994 "Parse latex fragment at point.
2996 Return a list whose CAR is `latex-fragment' and CDR a plist with
2997 `:value', `:begin', `:end', and `:post-blank' as keywords.
2999 Assume point is at the beginning of the latex fragment."
3000 (save-excursion
3001 (let* ((begin (point))
3002 (substring-match
3003 (catch 'exit
3004 (mapc (lambda (e)
3005 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
3006 (when (or (looking-at latex-regexp)
3007 (and (not (bobp))
3008 (save-excursion
3009 (backward-char)
3010 (looking-at latex-regexp))))
3011 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
3012 (plist-get org-format-latex-options :matchers))
3013 ;; None found: it's a macro.
3014 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
3016 (value (match-string-no-properties substring-match))
3017 (post-blank (progn (goto-char (match-end substring-match))
3018 (skip-chars-forward " \t")))
3019 (end (point)))
3020 (list 'latex-fragment
3021 (list :value value
3022 :begin begin
3023 :end end
3024 :post-blank post-blank)))))
3026 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
3027 "Interpret LATEX-FRAGMENT object as Org syntax.
3028 CONTENTS is nil."
3029 (org-element-property :value latex-fragment))
3031 ;;;; Line Break
3033 (defun org-element-line-break-parser ()
3034 "Parse line break at point.
3036 Return a list whose CAR is `line-break', and CDR a plist with
3037 `:begin', `:end' and `:post-blank' keywords.
3039 Assume point is at the beginning of the line break."
3040 (list 'line-break
3041 (list :begin (point)
3042 :end (progn (forward-line) (point))
3043 :post-blank 0)))
3045 (defun org-element-line-break-interpreter (line-break contents)
3046 "Interpret LINE-BREAK object as Org syntax.
3047 CONTENTS is nil."
3048 "\\\\\n")
3050 (defun org-element-line-break-successor ()
3051 "Search for the next line-break object.
3053 Return value is a cons cell whose CAR is `line-break' and CDR is
3054 beginning position."
3055 (save-excursion
3056 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
3057 (goto-char (match-beginning 1)))))
3058 ;; A line break can only happen on a non-empty line.
3059 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
3060 (cons 'line-break beg)))))
3063 ;;;; Link
3065 (defun org-element-link-parser ()
3066 "Parse link at point.
3068 Return a list whose CAR is `link' and CDR a plist with `:type',
3069 `:path', `:raw-link', `:application', `:search-option', `:begin',
3070 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3071 keywords.
3073 Assume point is at the beginning of the link."
3074 (save-excursion
3075 (let ((begin (point))
3076 end contents-begin contents-end link-end post-blank path type
3077 raw-link link search-option application)
3078 (cond
3079 ;; Type 1: Text targeted from a radio target.
3080 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3081 (setq type "radio"
3082 link-end (match-end 0)
3083 path (org-match-string-no-properties 0)))
3084 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3085 ((looking-at org-bracket-link-regexp)
3086 (setq contents-begin (match-beginning 3)
3087 contents-end (match-end 3)
3088 link-end (match-end 0)
3089 ;; RAW-LINK is the original link. Expand any
3090 ;; abbreviation in it.
3091 raw-link (org-translate-link
3092 (org-link-expand-abbrev
3093 (org-match-string-no-properties 1))))
3094 ;; Determine TYPE of link and set PATH accordingly.
3095 (cond
3096 ;; File type.
3097 ((or (file-name-absolute-p raw-link)
3098 (string-match "^\\.\\.?/" raw-link))
3099 (setq type "file" path raw-link))
3100 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3101 ((string-match org-link-re-with-space3 raw-link)
3102 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3103 ;; Id type: PATH is the id.
3104 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3105 (setq type "id" path (match-string 1 raw-link)))
3106 ;; Code-ref type: PATH is the name of the reference.
3107 ((string-match "^(\\(.*\\))$" raw-link)
3108 (setq type "coderef" path (match-string 1 raw-link)))
3109 ;; Custom-id type: PATH is the name of the custom id.
3110 ((= (aref raw-link 0) ?#)
3111 (setq type "custom-id" path (substring raw-link 1)))
3112 ;; Fuzzy type: Internal link either matches a target, an
3113 ;; headline name or nothing. PATH is the target or
3114 ;; headline's name.
3115 (t (setq type "fuzzy" path raw-link))))
3116 ;; Type 3: Plain link, i.e. http://orgmode.org
3117 ((looking-at org-plain-link-re)
3118 (setq raw-link (org-match-string-no-properties 0)
3119 type (org-match-string-no-properties 1)
3120 link-end (match-end 0)
3121 path (org-match-string-no-properties 2)))
3122 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3123 ((looking-at org-angle-link-re)
3124 (setq raw-link (buffer-substring-no-properties
3125 (match-beginning 1) (match-end 2))
3126 type (org-match-string-no-properties 1)
3127 link-end (match-end 0)
3128 path (org-match-string-no-properties 2))))
3129 ;; In any case, deduce end point after trailing white space from
3130 ;; LINK-END variable.
3131 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3132 end (point))
3133 ;; Extract search option and opening application out of
3134 ;; "file"-type links.
3135 (when (member type org-element-link-type-is-file)
3136 ;; Application.
3137 (cond ((string-match "^file\\+\\(.*\\)$" type)
3138 (setq application (match-string 1 type)))
3139 ((not (string-match "^file" type))
3140 (setq application type)))
3141 ;; Extract search option from PATH.
3142 (when (string-match "::\\(.*\\)$" path)
3143 (setq search-option (match-string 1 path)
3144 path (replace-match "" nil nil path)))
3145 ;; Make sure TYPE always reports "file".
3146 (setq type "file"))
3147 (list 'link
3148 (list :type type
3149 :path path
3150 :raw-link (or raw-link path)
3151 :application application
3152 :search-option search-option
3153 :begin begin
3154 :end end
3155 :contents-begin contents-begin
3156 :contents-end contents-end
3157 :post-blank post-blank)))))
3159 (defun org-element-link-interpreter (link contents)
3160 "Interpret LINK object as Org syntax.
3161 CONTENTS is the contents of the object, or nil."
3162 (let ((type (org-element-property :type link))
3163 (raw-link (org-element-property :raw-link link)))
3164 (if (string= type "radio") raw-link
3165 (format "[[%s]%s]"
3166 raw-link
3167 (if contents (format "[%s]" contents) "")))))
3169 (defun org-element-link-successor ()
3170 "Search for the next link object.
3172 Return value is a cons cell whose CAR is `link' and CDR is
3173 beginning position."
3174 (save-excursion
3175 (let ((link-regexp
3176 (if (not org-target-link-regexp) org-any-link-re
3177 (concat org-any-link-re "\\|" org-target-link-regexp))))
3178 (when (re-search-forward link-regexp nil t)
3179 (cons 'link (match-beginning 0))))))
3181 (defun org-element-plain-link-successor ()
3182 "Search for the next plain link object.
3184 Return value is a cons cell whose CAR is `link' and CDR is
3185 beginning position."
3186 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3187 (cons 'link (match-beginning 0))))
3190 ;;;; Macro
3192 (defun org-element-macro-parser ()
3193 "Parse macro at point.
3195 Return a list whose CAR is `macro' and CDR a plist with `:key',
3196 `:args', `:begin', `:end', `:value' and `:post-blank' as
3197 keywords.
3199 Assume point is at the macro."
3200 (save-excursion
3201 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3202 (let ((begin (point))
3203 (key (downcase (org-match-string-no-properties 1)))
3204 (value (org-match-string-no-properties 0))
3205 (post-blank (progn (goto-char (match-end 0))
3206 (skip-chars-forward " \t")))
3207 (end (point))
3208 (args (let ((args (org-match-string-no-properties 3)))
3209 (when args
3210 ;; Do not use `org-split-string' since empty
3211 ;; strings are meaningful here.
3212 (split-string
3213 (replace-regexp-in-string
3214 "\\(\\\\*\\)\\(,\\)"
3215 (lambda (str)
3216 (let ((len (length (match-string 1 str))))
3217 (concat (make-string (/ len 2) ?\\)
3218 (if (zerop (mod len 2)) "\000" ","))))
3219 args nil t)
3220 "\000")))))
3221 (list 'macro
3222 (list :key key
3223 :value value
3224 :args args
3225 :begin begin
3226 :end end
3227 :post-blank post-blank)))))
3229 (defun org-element-macro-interpreter (macro contents)
3230 "Interpret MACRO object as Org syntax.
3231 CONTENTS is nil."
3232 (org-element-property :value macro))
3234 (defun org-element-macro-successor ()
3235 "Search for the next macro object.
3237 Return value is cons cell whose CAR is `macro' and CDR is
3238 beginning position."
3239 (save-excursion
3240 (when (re-search-forward
3241 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3242 nil t)
3243 (cons 'macro (match-beginning 0)))))
3246 ;;;; Radio-target
3248 (defun org-element-radio-target-parser ()
3249 "Parse radio target at point.
3251 Return a list whose CAR is `radio-target' and CDR a plist with
3252 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3253 and `:post-blank' as keywords.
3255 Assume point is at the radio target."
3256 (save-excursion
3257 (looking-at org-radio-target-regexp)
3258 (let ((begin (point))
3259 (contents-begin (match-beginning 1))
3260 (contents-end (match-end 1))
3261 (value (org-match-string-no-properties 1))
3262 (post-blank (progn (goto-char (match-end 0))
3263 (skip-chars-forward " \t")))
3264 (end (point)))
3265 (list 'radio-target
3266 (list :begin begin
3267 :end end
3268 :contents-begin contents-begin
3269 :contents-end contents-end
3270 :post-blank post-blank
3271 :value value)))))
3273 (defun org-element-radio-target-interpreter (target contents)
3274 "Interpret TARGET object as Org syntax.
3275 CONTENTS is the contents of the object."
3276 (concat "<<<" contents ">>>"))
3278 (defun org-element-radio-target-successor ()
3279 "Search for the next radio-target object.
3281 Return value is a cons cell whose CAR is `radio-target' and CDR
3282 is beginning position."
3283 (save-excursion
3284 (when (re-search-forward org-radio-target-regexp nil t)
3285 (cons 'radio-target (match-beginning 0)))))
3288 ;;;; Statistics Cookie
3290 (defun org-element-statistics-cookie-parser ()
3291 "Parse statistics cookie at point.
3293 Return a list whose CAR is `statistics-cookie', and CDR a plist
3294 with `:begin', `:end', `:value' and `:post-blank' keywords.
3296 Assume point is at the beginning of the statistics-cookie."
3297 (save-excursion
3298 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3299 (let* ((begin (point))
3300 (value (buffer-substring-no-properties
3301 (match-beginning 0) (match-end 0)))
3302 (post-blank (progn (goto-char (match-end 0))
3303 (skip-chars-forward " \t")))
3304 (end (point)))
3305 (list 'statistics-cookie
3306 (list :begin begin
3307 :end end
3308 :value value
3309 :post-blank post-blank)))))
3311 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3312 "Interpret STATISTICS-COOKIE object as Org syntax.
3313 CONTENTS is nil."
3314 (org-element-property :value statistics-cookie))
3316 (defun org-element-statistics-cookie-successor ()
3317 "Search for the next statistics cookie object.
3319 Return value is a cons cell whose CAR is `statistics-cookie' and
3320 CDR is beginning position."
3321 (save-excursion
3322 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3323 (cons 'statistics-cookie (match-beginning 0)))))
3326 ;;;; Strike-Through
3328 (defun org-element-strike-through-parser ()
3329 "Parse strike-through object at point.
3331 Return a list whose CAR is `strike-through' and CDR is a plist
3332 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3333 `:post-blank' keywords.
3335 Assume point is at the first plus sign marker."
3336 (save-excursion
3337 (unless (bolp) (backward-char 1))
3338 (looking-at org-emph-re)
3339 (let ((begin (match-beginning 2))
3340 (contents-begin (match-beginning 4))
3341 (contents-end (match-end 4))
3342 (post-blank (progn (goto-char (match-end 2))
3343 (skip-chars-forward " \t")))
3344 (end (point)))
3345 (list 'strike-through
3346 (list :begin begin
3347 :end end
3348 :contents-begin contents-begin
3349 :contents-end contents-end
3350 :post-blank post-blank)))))
3352 (defun org-element-strike-through-interpreter (strike-through contents)
3353 "Interpret STRIKE-THROUGH object as Org syntax.
3354 CONTENTS is the contents of the object."
3355 (format "+%s+" contents))
3358 ;;;; Subscript
3360 (defun org-element-subscript-parser ()
3361 "Parse subscript at point.
3363 Return a list whose CAR is `subscript' and CDR a plist with
3364 `:begin', `:end', `:contents-begin', `:contents-end',
3365 `:use-brackets-p' and `:post-blank' as keywords.
3367 Assume point is at the underscore."
3368 (save-excursion
3369 (unless (bolp) (backward-char))
3370 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3372 (not (looking-at org-match-substring-regexp))))
3373 (begin (match-beginning 2))
3374 (contents-begin (or (match-beginning 5)
3375 (match-beginning 3)))
3376 (contents-end (or (match-end 5) (match-end 3)))
3377 (post-blank (progn (goto-char (match-end 0))
3378 (skip-chars-forward " \t")))
3379 (end (point)))
3380 (list 'subscript
3381 (list :begin begin
3382 :end end
3383 :use-brackets-p bracketsp
3384 :contents-begin contents-begin
3385 :contents-end contents-end
3386 :post-blank post-blank)))))
3388 (defun org-element-subscript-interpreter (subscript contents)
3389 "Interpret SUBSCRIPT object as Org syntax.
3390 CONTENTS is the contents of the object."
3391 (format
3392 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3393 contents))
3395 (defun org-element-sub/superscript-successor ()
3396 "Search for the next sub/superscript object.
3398 Return value is a cons cell whose CAR is either `subscript' or
3399 `superscript' and CDR is beginning position."
3400 (save-excursion
3401 (unless (bolp) (backward-char))
3402 (when (re-search-forward org-match-substring-regexp nil t)
3403 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3404 (match-beginning 2)))))
3407 ;;;; Superscript
3409 (defun org-element-superscript-parser ()
3410 "Parse superscript at point.
3412 Return a list whose CAR is `superscript' and CDR a plist with
3413 `:begin', `:end', `:contents-begin', `:contents-end',
3414 `:use-brackets-p' and `:post-blank' as keywords.
3416 Assume point is at the caret."
3417 (save-excursion
3418 (unless (bolp) (backward-char))
3419 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3420 (not (looking-at org-match-substring-regexp))))
3421 (begin (match-beginning 2))
3422 (contents-begin (or (match-beginning 5)
3423 (match-beginning 3)))
3424 (contents-end (or (match-end 5) (match-end 3)))
3425 (post-blank (progn (goto-char (match-end 0))
3426 (skip-chars-forward " \t")))
3427 (end (point)))
3428 (list 'superscript
3429 (list :begin begin
3430 :end end
3431 :use-brackets-p bracketsp
3432 :contents-begin contents-begin
3433 :contents-end contents-end
3434 :post-blank post-blank)))))
3436 (defun org-element-superscript-interpreter (superscript contents)
3437 "Interpret SUPERSCRIPT object as Org syntax.
3438 CONTENTS is the contents of the object."
3439 (format
3440 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3441 contents))
3444 ;;;; Table Cell
3446 (defun org-element-table-cell-parser ()
3447 "Parse table cell at point.
3449 Return a list whose CAR is `table-cell' and CDR is a plist
3450 containing `:begin', `:end', `:contents-begin', `:contents-end'
3451 and `:post-blank' keywords."
3452 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3453 (let* ((begin (match-beginning 0))
3454 (end (match-end 0))
3455 (contents-begin (match-beginning 1))
3456 (contents-end (match-end 1)))
3457 (list 'table-cell
3458 (list :begin begin
3459 :end end
3460 :contents-begin contents-begin
3461 :contents-end contents-end
3462 :post-blank 0))))
3464 (defun org-element-table-cell-interpreter (table-cell contents)
3465 "Interpret TABLE-CELL element as Org syntax.
3466 CONTENTS is the contents of the cell, or nil."
3467 (concat " " contents " |"))
3469 (defun org-element-table-cell-successor ()
3470 "Search for the next table-cell object.
3472 Return value is a cons cell whose CAR is `table-cell' and CDR is
3473 beginning position."
3474 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3477 ;;;; Target
3479 (defun org-element-target-parser ()
3480 "Parse target at point.
3482 Return a list whose CAR is `target' and CDR a plist with
3483 `:begin', `:end', `:value' and `:post-blank' as keywords.
3485 Assume point is at the target."
3486 (save-excursion
3487 (looking-at org-target-regexp)
3488 (let ((begin (point))
3489 (value (org-match-string-no-properties 1))
3490 (post-blank (progn (goto-char (match-end 0))
3491 (skip-chars-forward " \t")))
3492 (end (point)))
3493 (list 'target
3494 (list :begin begin
3495 :end end
3496 :value value
3497 :post-blank post-blank)))))
3499 (defun org-element-target-interpreter (target contents)
3500 "Interpret TARGET object as Org syntax.
3501 CONTENTS is nil."
3502 (format "<<%s>>" (org-element-property :value target)))
3504 (defun org-element-target-successor ()
3505 "Search for the next target object.
3507 Return value is a cons cell whose CAR is `target' and CDR is
3508 beginning position."
3509 (save-excursion
3510 (when (re-search-forward org-target-regexp nil t)
3511 (cons 'target (match-beginning 0)))))
3514 ;;;; Timestamp
3516 (defun org-element-timestamp-parser ()
3517 "Parse time stamp at point.
3519 Return a list whose CAR is `timestamp', and CDR a plist with
3520 `:type', `:raw-value', `:year-start', `:month-start',
3521 `:day-start', `:hour-start', `:minute-start', `:year-end',
3522 `:month-end', `:day-end', `:hour-end', `:minute-end',
3523 `:repeater-type', `:repeater-value', `:repeater-unit',
3524 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3525 `:end', `:value' and `:post-blank' keywords.
3527 Assume point is at the beginning of the timestamp."
3528 (save-excursion
3529 (let* ((begin (point))
3530 (activep (eq (char-after) ?<))
3531 (raw-value
3532 (progn
3533 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3534 (match-string-no-properties 0)))
3535 (date-start (match-string-no-properties 1))
3536 (date-end (match-string 3))
3537 (diaryp (match-beginning 2))
3538 (post-blank (progn (goto-char (match-end 0))
3539 (skip-chars-forward " \t")))
3540 (end (point))
3541 (time-range
3542 (and (not diaryp)
3543 (string-match
3544 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3545 date-start)
3546 (cons (string-to-number (match-string 2 date-start))
3547 (string-to-number (match-string 3 date-start)))))
3548 (type (cond (diaryp 'diary)
3549 ((and activep (or date-end time-range)) 'active-range)
3550 (activep 'active)
3551 ((or date-end time-range) 'inactive-range)
3552 (t 'inactive)))
3553 (repeater-props
3554 (and (not diaryp)
3555 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3556 raw-value)
3557 (list
3558 :repeater-type
3559 (let ((type (match-string 1 raw-value)))
3560 (cond ((equal "++" type) 'catch-up)
3561 ((equal ".+" type) 'restart)
3562 (t 'cumulate)))
3563 :repeater-value (string-to-number (match-string 2 raw-value))
3564 :repeater-unit
3565 (case (string-to-char (match-string 3 raw-value))
3566 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3567 (warning-props
3568 (and (not diaryp)
3569 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3570 (list
3571 :warning-type (if (match-string 1 raw-value) 'first 'all)
3572 :warning-value (string-to-number (match-string 2 raw-value))
3573 :warning-unit
3574 (case (string-to-char (match-string 3 raw-value))
3575 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3576 year-start month-start day-start hour-start minute-start year-end
3577 month-end day-end hour-end minute-end)
3578 ;; Parse date-start.
3579 (unless diaryp
3580 (let ((date (org-parse-time-string date-start t)))
3581 (setq year-start (nth 5 date)
3582 month-start (nth 4 date)
3583 day-start (nth 3 date)
3584 hour-start (nth 2 date)
3585 minute-start (nth 1 date))))
3586 ;; Compute date-end. It can be provided directly in time-stamp,
3587 ;; or extracted from time range. Otherwise, it defaults to the
3588 ;; same values as date-start.
3589 (unless diaryp
3590 (let ((date (and date-end (org-parse-time-string date-end t))))
3591 (setq year-end (or (nth 5 date) year-start)
3592 month-end (or (nth 4 date) month-start)
3593 day-end (or (nth 3 date) day-start)
3594 hour-end (or (nth 2 date) (car time-range) hour-start)
3595 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3596 (list 'timestamp
3597 (nconc (list :type type
3598 :raw-value raw-value
3599 :year-start year-start
3600 :month-start month-start
3601 :day-start day-start
3602 :hour-start hour-start
3603 :minute-start minute-start
3604 :year-end year-end
3605 :month-end month-end
3606 :day-end day-end
3607 :hour-end hour-end
3608 :minute-end minute-end
3609 :begin begin
3610 :end end
3611 :post-blank post-blank)
3612 repeater-props
3613 warning-props)))))
3615 (defun org-element-timestamp-interpreter (timestamp contents)
3616 "Interpret TIMESTAMP object as Org syntax.
3617 CONTENTS is nil."
3618 ;; Use `:raw-value' if specified.
3619 (or (org-element-property :raw-value timestamp)
3620 ;; Otherwise, build timestamp string.
3621 (let* ((repeat-string
3622 (concat
3623 (case (org-element-property :repeater-type timestamp)
3624 (cumulate "+") (catch-up "++") (restart ".+"))
3625 (let ((val (org-element-property :repeater-value timestamp)))
3626 (and val (number-to-string val)))
3627 (case (org-element-property :repeater-unit timestamp)
3628 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3629 (warning-string
3630 (concat
3631 (case (org-element-property :warning-type timestamp)
3632 (first "--")
3633 (all "-"))
3634 (let ((val (org-element-property :warning-value timestamp)))
3635 (and val (number-to-string val)))
3636 (case (org-element-property :warning-unit timestamp)
3637 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3638 (build-ts-string
3639 ;; Build an Org timestamp string from TIME. ACTIVEP is
3640 ;; non-nil when time stamp is active. If WITH-TIME-P is
3641 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3642 ;; specify a time range in the timestamp. REPEAT-STRING
3643 ;; is the repeater string, if any.
3644 (lambda (time activep &optional with-time-p hour-end minute-end)
3645 (let ((ts (format-time-string
3646 (funcall (if with-time-p 'cdr 'car)
3647 org-time-stamp-formats)
3648 time)))
3649 (when (and hour-end minute-end)
3650 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3651 (setq ts
3652 (replace-match
3653 (format "\\&-%02d:%02d" hour-end minute-end)
3654 nil nil ts)))
3655 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3656 (dolist (s (list repeat-string warning-string))
3657 (when (org-string-nw-p s)
3658 (setq ts (concat (substring ts 0 -1)
3661 (substring ts -1)))))
3662 ;; Return value.
3663 ts)))
3664 (type (org-element-property :type timestamp)))
3665 (case type
3666 ((active inactive)
3667 (let* ((minute-start (org-element-property :minute-start timestamp))
3668 (minute-end (org-element-property :minute-end timestamp))
3669 (hour-start (org-element-property :hour-start timestamp))
3670 (hour-end (org-element-property :hour-end timestamp))
3671 (time-range-p (and hour-start hour-end minute-start minute-end
3672 (or (/= hour-start hour-end)
3673 (/= minute-start minute-end)))))
3674 (funcall
3675 build-ts-string
3676 (encode-time 0
3677 (or minute-start 0)
3678 (or hour-start 0)
3679 (org-element-property :day-start timestamp)
3680 (org-element-property :month-start timestamp)
3681 (org-element-property :year-start timestamp))
3682 (eq type 'active)
3683 (and hour-start minute-start)
3684 (and time-range-p hour-end)
3685 (and time-range-p minute-end))))
3686 ((active-range inactive-range)
3687 (let ((minute-start (org-element-property :minute-start timestamp))
3688 (minute-end (org-element-property :minute-end timestamp))
3689 (hour-start (org-element-property :hour-start timestamp))
3690 (hour-end (org-element-property :hour-end timestamp)))
3691 (concat
3692 (funcall
3693 build-ts-string (encode-time
3695 (or minute-start 0)
3696 (or hour-start 0)
3697 (org-element-property :day-start timestamp)
3698 (org-element-property :month-start timestamp)
3699 (org-element-property :year-start timestamp))
3700 (eq type 'active-range)
3701 (and hour-start minute-start))
3702 "--"
3703 (funcall build-ts-string
3704 (encode-time 0
3705 (or minute-end 0)
3706 (or hour-end 0)
3707 (org-element-property :day-end timestamp)
3708 (org-element-property :month-end timestamp)
3709 (org-element-property :year-end timestamp))
3710 (eq type 'active-range)
3711 (and hour-end minute-end)))))))))
3713 (defun org-element-timestamp-successor ()
3714 "Search for the next timestamp object.
3716 Return value is a cons cell whose CAR is `timestamp' and CDR is
3717 beginning position."
3718 (save-excursion
3719 (when (re-search-forward
3720 (concat org-ts-regexp-both
3721 "\\|"
3722 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3723 "\\|"
3724 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3725 nil t)
3726 (cons 'timestamp (match-beginning 0)))))
3729 ;;;; Underline
3731 (defun org-element-underline-parser ()
3732 "Parse underline object at point.
3734 Return a list whose CAR is `underline' and CDR is a plist with
3735 `:begin', `:end', `:contents-begin' and `:contents-end' and
3736 `:post-blank' keywords.
3738 Assume point is at the first underscore marker."
3739 (save-excursion
3740 (unless (bolp) (backward-char 1))
3741 (looking-at org-emph-re)
3742 (let ((begin (match-beginning 2))
3743 (contents-begin (match-beginning 4))
3744 (contents-end (match-end 4))
3745 (post-blank (progn (goto-char (match-end 2))
3746 (skip-chars-forward " \t")))
3747 (end (point)))
3748 (list 'underline
3749 (list :begin begin
3750 :end end
3751 :contents-begin contents-begin
3752 :contents-end contents-end
3753 :post-blank post-blank)))))
3755 (defun org-element-underline-interpreter (underline contents)
3756 "Interpret UNDERLINE object as Org syntax.
3757 CONTENTS is the contents of the object."
3758 (format "_%s_" contents))
3761 ;;;; Verbatim
3763 (defun org-element-verbatim-parser ()
3764 "Parse verbatim object at point.
3766 Return a list whose CAR is `verbatim' and CDR is a plist with
3767 `:value', `:begin', `:end' and `:post-blank' keywords.
3769 Assume point is at the first equal sign marker."
3770 (save-excursion
3771 (unless (bolp) (backward-char 1))
3772 (looking-at org-emph-re)
3773 (let ((begin (match-beginning 2))
3774 (value (org-match-string-no-properties 4))
3775 (post-blank (progn (goto-char (match-end 2))
3776 (skip-chars-forward " \t")))
3777 (end (point)))
3778 (list 'verbatim
3779 (list :value value
3780 :begin begin
3781 :end end
3782 :post-blank post-blank)))))
3784 (defun org-element-verbatim-interpreter (verbatim contents)
3785 "Interpret VERBATIM object as Org syntax.
3786 CONTENTS is nil."
3787 (format "=%s=" (org-element-property :value verbatim)))
3791 ;;; Parsing Element Starting At Point
3793 ;; `org-element--current-element' is the core function of this section.
3794 ;; It returns the Lisp representation of the element starting at
3795 ;; point.
3797 ;; `org-element--current-element' makes use of special modes. They
3798 ;; are activated for fixed element chaining (i.e. `plain-list' >
3799 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3800 ;; `section'). Special modes are: `first-section', `item',
3801 ;; `node-property', `quote-section', `section' and `table-row'.
3803 (defun org-element--current-element
3804 (limit &optional granularity special structure)
3805 "Parse the element starting at point.
3807 Return value is a list like (TYPE PROPS) where TYPE is the type
3808 of the element and PROPS a plist of properties associated to the
3809 element.
3811 Possible types are defined in `org-element-all-elements'.
3813 LIMIT bounds the search.
3815 Optional argument GRANULARITY determines the depth of the
3816 recursion. Allowed values are `headline', `greater-element',
3817 `element', `object' or nil. When it is broader than `object' (or
3818 nil), secondary values will not be parsed, since they only
3819 contain objects.
3821 Optional argument SPECIAL, when non-nil, can be either
3822 `first-section', `item', `node-property', `quote-section',
3823 `section', and `table-row'.
3825 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3826 be computed.
3828 This function assumes point is always at the beginning of the
3829 element it has to parse."
3830 (save-excursion
3831 (let ((case-fold-search t)
3832 ;; Determine if parsing depth allows for secondary strings
3833 ;; parsing. It only applies to elements referenced in
3834 ;; `org-element-secondary-value-alist'.
3835 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3836 (cond
3837 ;; Item.
3838 ((eq special 'item)
3839 (org-element-item-parser limit structure raw-secondary-p))
3840 ;; Table Row.
3841 ((eq special 'table-row) (org-element-table-row-parser limit))
3842 ;; Node Property.
3843 ((eq special 'node-property) (org-element-node-property-parser limit))
3844 ;; Headline.
3845 ((org-with-limited-levels (org-at-heading-p))
3846 (org-element-headline-parser limit raw-secondary-p))
3847 ;; Sections (must be checked after headline).
3848 ((eq special 'section) (org-element-section-parser limit))
3849 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3850 ((eq special 'first-section)
3851 (org-element-section-parser
3852 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3853 limit)))
3854 ;; When not at bol, point is at the beginning of an item or
3855 ;; a footnote definition: next item is always a paragraph.
3856 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3857 ;; Planning and Clock.
3858 ((looking-at org-planning-or-clock-line-re)
3859 (if (equal (match-string 1) org-clock-string)
3860 (org-element-clock-parser limit)
3861 (org-element-planning-parser limit)))
3862 ;; Inlinetask.
3863 ((org-at-heading-p)
3864 (org-element-inlinetask-parser limit raw-secondary-p))
3865 ;; From there, elements can have affiliated keywords.
3866 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3867 (cond
3868 ;; Jumping over affiliated keywords put point off-limits.
3869 ;; Parse them as regular keywords.
3870 ((and (cdr affiliated) (>= (point) limit))
3871 (goto-char (car affiliated))
3872 (org-element-keyword-parser limit nil))
3873 ;; LaTeX Environment.
3874 ((looking-at
3875 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3876 (org-element-latex-environment-parser limit affiliated))
3877 ;; Drawer and Property Drawer.
3878 ((looking-at org-drawer-regexp)
3879 (if (equal (match-string 1) "PROPERTIES")
3880 (org-element-property-drawer-parser limit affiliated)
3881 (org-element-drawer-parser limit affiliated)))
3882 ;; Fixed Width
3883 ((looking-at "[ \t]*:\\( \\|$\\)")
3884 (org-element-fixed-width-parser limit affiliated))
3885 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3886 ;; Keywords.
3887 ((looking-at "[ \t]*#")
3888 (goto-char (match-end 0))
3889 (cond ((looking-at "\\(?: \\|$\\)")
3890 (beginning-of-line)
3891 (org-element-comment-parser limit affiliated))
3892 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3893 (beginning-of-line)
3894 (let ((parser (assoc (upcase (match-string 1))
3895 org-element-block-name-alist)))
3896 (if parser (funcall (cdr parser) limit affiliated)
3897 (org-element-special-block-parser limit affiliated))))
3898 ((looking-at "\\+CALL:")
3899 (beginning-of-line)
3900 (org-element-babel-call-parser limit affiliated))
3901 ((looking-at "\\+BEGIN:? ")
3902 (beginning-of-line)
3903 (org-element-dynamic-block-parser limit affiliated))
3904 ((looking-at "\\+\\S-+:")
3905 (beginning-of-line)
3906 (org-element-keyword-parser limit affiliated))
3908 (beginning-of-line)
3909 (org-element-paragraph-parser limit affiliated))))
3910 ;; Footnote Definition.
3911 ((looking-at org-footnote-definition-re)
3912 (org-element-footnote-definition-parser limit affiliated))
3913 ;; Horizontal Rule.
3914 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3915 (org-element-horizontal-rule-parser limit affiliated))
3916 ;; Diary Sexp.
3917 ((looking-at "%%(")
3918 (org-element-diary-sexp-parser limit affiliated))
3919 ;; Table.
3920 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3921 ;; List.
3922 ((looking-at (org-item-re))
3923 (org-element-plain-list-parser
3924 limit affiliated
3925 (or structure (org-element--list-struct limit))))
3926 ;; Default element: Paragraph.
3927 (t (org-element-paragraph-parser limit affiliated)))))))))
3930 ;; Most elements can have affiliated keywords. When looking for an
3931 ;; element beginning, we want to move before them, as they belong to
3932 ;; that element, and, in the meantime, collect information they give
3933 ;; into appropriate properties. Hence the following function.
3935 (defun org-element--collect-affiliated-keywords (limit)
3936 "Collect affiliated keywords from point down to LIMIT.
3938 Return a list whose CAR is the position at the first of them and
3939 CDR a plist of keywords and values and move point to the
3940 beginning of the first line after them.
3942 As a special case, if element doesn't start at the beginning of
3943 the line (i.e. a paragraph starting an item), CAR is current
3944 position of point and CDR is nil."
3945 (if (not (bolp)) (list (point))
3946 (let ((case-fold-search t)
3947 (origin (point))
3948 ;; RESTRICT is the list of objects allowed in parsed
3949 ;; keywords value.
3950 (restrict (org-element-restriction 'keyword))
3951 output)
3952 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3953 (let* ((raw-kwd (upcase (match-string 1)))
3954 ;; Apply translation to RAW-KWD. From there, KWD is
3955 ;; the official keyword.
3956 (kwd (or (cdr (assoc raw-kwd
3957 org-element-keyword-translation-alist))
3958 raw-kwd))
3959 ;; Find main value for any keyword.
3960 (value
3961 (save-match-data
3962 (org-trim
3963 (buffer-substring-no-properties
3964 (match-end 0) (point-at-eol)))))
3965 ;; PARSEDP is non-nil when keyword should have its
3966 ;; value parsed.
3967 (parsedp (member kwd org-element-parsed-keywords))
3968 ;; If KWD is a dual keyword, find its secondary
3969 ;; value. Maybe parse it.
3970 (dualp (member kwd org-element-dual-keywords))
3971 (dual-value
3972 (and dualp
3973 (let ((sec (org-match-string-no-properties 2)))
3974 (if (or (not sec) (not parsedp)) sec
3975 (org-element-parse-secondary-string sec restrict)))))
3976 ;; Attribute a property name to KWD.
3977 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3978 ;; Now set final shape for VALUE.
3979 (when parsedp
3980 (setq value (org-element-parse-secondary-string value restrict)))
3981 (when dualp
3982 (setq value (and (or value dual-value) (cons value dual-value))))
3983 (when (or (member kwd org-element-multiple-keywords)
3984 ;; Attributes can always appear on multiple lines.
3985 (string-match "^ATTR_" kwd))
3986 (setq value (cons value (plist-get output kwd-sym))))
3987 ;; Eventually store the new value in OUTPUT.
3988 (setq output (plist-put output kwd-sym value))
3989 ;; Move to next keyword.
3990 (forward-line)))
3991 ;; If affiliated keywords are orphaned: move back to first one.
3992 ;; They will be parsed as a paragraph.
3993 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3994 ;; Return value.
3995 (cons origin output))))
3999 ;;; The Org Parser
4001 ;; The two major functions here are `org-element-parse-buffer', which
4002 ;; parses Org syntax inside the current buffer, taking into account
4003 ;; region, narrowing, or even visibility if specified, and
4004 ;; `org-element-parse-secondary-string', which parses objects within
4005 ;; a given string.
4007 ;; The (almost) almighty `org-element-map' allows to apply a function
4008 ;; on elements or objects matching some type, and accumulate the
4009 ;; resulting values. In an export situation, it also skips unneeded
4010 ;; parts of the parse tree.
4012 (defun org-element-parse-buffer (&optional granularity visible-only)
4013 "Recursively parse the buffer and return structure.
4014 If narrowing is in effect, only parse the visible part of the
4015 buffer.
4017 Optional argument GRANULARITY determines the depth of the
4018 recursion. It can be set to the following symbols:
4020 `headline' Only parse headlines.
4021 `greater-element' Don't recurse into greater elements excepted
4022 headlines and sections. Thus, elements
4023 parsed are the top-level ones.
4024 `element' Parse everything but objects and plain text.
4025 `object' Parse the complete buffer (default).
4027 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4028 elements.
4030 An element or an objects is represented as a list with the
4031 pattern (TYPE PROPERTIES CONTENTS), where :
4033 TYPE is a symbol describing the element or object. See
4034 `org-element-all-elements' and `org-element-all-objects' for an
4035 exhaustive list of such symbols. One can retrieve it with
4036 `org-element-type' function.
4038 PROPERTIES is the list of attributes attached to the element or
4039 object, as a plist. Although most of them are specific to the
4040 element or object type, all types share `:begin', `:end',
4041 `:post-blank' and `:parent' properties, which respectively
4042 refer to buffer position where the element or object starts,
4043 ends, the number of white spaces or blank lines after it, and
4044 the element or object containing it. Properties values can be
4045 obtained by using `org-element-property' function.
4047 CONTENTS is a list of elements, objects or raw strings
4048 contained in the current element or object, when applicable.
4049 One can access them with `org-element-contents' function.
4051 The Org buffer has `org-data' as type and nil as properties.
4052 `org-element-map' function can be used to find specific elements
4053 or objects within the parse tree.
4055 This function assumes that current major mode is `org-mode'."
4056 (save-excursion
4057 (goto-char (point-min))
4058 (org-skip-whitespace)
4059 (org-element--parse-elements
4060 (point-at-bol) (point-max)
4061 ;; Start in `first-section' mode so text before the first
4062 ;; headline belongs to a section.
4063 'first-section nil granularity visible-only (list 'org-data nil))))
4065 (defun org-element-parse-secondary-string (string restriction &optional parent)
4066 "Recursively parse objects in STRING and return structure.
4068 RESTRICTION is a symbol limiting the object types that will be
4069 looked after.
4071 Optional argument PARENT, when non-nil, is the element or object
4072 containing the secondary string. It is used to set correctly
4073 `:parent' property within the string."
4074 ;; Copy buffer-local variables listed in
4075 ;; `org-element-object-variables' into temporary buffer. This is
4076 ;; required since object parsing is dependent on these variables.
4077 (let ((pairs (delq nil (mapcar (lambda (var)
4078 (when (boundp var)
4079 (cons var (symbol-value var))))
4080 org-element-object-variables))))
4081 (with-temp-buffer
4082 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4083 (insert string)
4084 (let ((secondary (org-element--parse-objects
4085 (point-min) (point-max) nil restriction)))
4086 (when parent
4087 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4088 secondary))
4089 secondary))))
4091 (defun org-element-map
4092 (data types fun &optional info first-match no-recursion with-affiliated)
4093 "Map a function on selected elements or objects.
4095 DATA is a parse tree, an element, an object, a string, or a list
4096 of such constructs. TYPES is a symbol or list of symbols of
4097 elements or objects types (see `org-element-all-elements' and
4098 `org-element-all-objects' for a complete list of types). FUN is
4099 the function called on the matching element or object. It has to
4100 accept one argument: the element or object itself.
4102 When optional argument INFO is non-nil, it should be a plist
4103 holding export options. In that case, parts of the parse tree
4104 not exportable according to that property list will be skipped.
4106 When optional argument FIRST-MATCH is non-nil, stop at the first
4107 match for which FUN doesn't return nil, and return that value.
4109 Optional argument NO-RECURSION is a symbol or a list of symbols
4110 representing elements or objects types. `org-element-map' won't
4111 enter any recursive element or object whose type belongs to that
4112 list. Though, FUN can still be applied on them.
4114 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4115 apply to matching objects within parsed affiliated keywords (see
4116 `org-element-parsed-keywords').
4118 Nil values returned from FUN do not appear in the results.
4121 Examples:
4122 ---------
4124 Assuming TREE is a variable containing an Org buffer parse tree,
4125 the following example will return a flat list of all `src-block'
4126 and `example-block' elements in it:
4128 \(org-element-map tree '(example-block src-block) 'identity)
4130 The following snippet will find the first headline with a level
4131 of 1 and a \"phone\" tag, and will return its beginning position:
4133 \(org-element-map tree 'headline
4134 \(lambda (hl)
4135 \(and (= (org-element-property :level hl) 1)
4136 \(member \"phone\" (org-element-property :tags hl))
4137 \(org-element-property :begin hl)))
4138 nil t)
4140 The next example will return a flat list of all `plain-list' type
4141 elements in TREE that are not a sub-list themselves:
4143 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4145 Eventually, this example will return a flat list of all `bold'
4146 type objects containing a `latex-snippet' type object, even
4147 looking into captions:
4149 \(org-element-map tree 'bold
4150 \(lambda (b)
4151 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4152 nil nil nil t)"
4153 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4154 (unless (listp types) (setq types (list types)))
4155 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4156 ;; Recursion depth is determined by --CATEGORY.
4157 (let* ((--category
4158 (catch 'found
4159 (let ((category 'greater-elements))
4160 (mapc (lambda (type)
4161 (cond ((or (memq type org-element-all-objects)
4162 (eq type 'plain-text))
4163 ;; If one object is found, the function
4164 ;; has to recurse into every object.
4165 (throw 'found 'objects))
4166 ((not (memq type org-element-greater-elements))
4167 ;; If one regular element is found, the
4168 ;; function has to recurse, at least,
4169 ;; into every element it encounters.
4170 (and (not (eq category 'elements))
4171 (setq category 'elements)))))
4172 types)
4173 category)))
4174 ;; Compute properties for affiliated keywords if necessary.
4175 (--affiliated-alist
4176 (and with-affiliated
4177 (mapcar (lambda (kwd)
4178 (cons kwd (intern (concat ":" (downcase kwd)))))
4179 org-element-affiliated-keywords)))
4180 --acc
4181 --walk-tree
4182 (--walk-tree
4183 (function
4184 (lambda (--data)
4185 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4186 ;; holding contextual information.
4187 (let ((--type (org-element-type --data)))
4188 (cond
4189 ((not --data))
4190 ;; Ignored element in an export context.
4191 ((and info (memq --data (plist-get info :ignore-list))))
4192 ;; List of elements or objects.
4193 ((not --type) (mapc --walk-tree --data))
4194 ;; Unconditionally enter parse trees.
4195 ((eq --type 'org-data)
4196 (mapc --walk-tree (org-element-contents --data)))
4198 ;; Check if TYPE is matching among TYPES. If so,
4199 ;; apply FUN to --DATA and accumulate return value
4200 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4201 (when (memq --type types)
4202 (let ((result (funcall fun --data)))
4203 (cond ((not result))
4204 (first-match (throw '--map-first-match result))
4205 (t (push result --acc)))))
4206 ;; If --DATA has a secondary string that can contain
4207 ;; objects with their type among TYPES, look into it.
4208 (when (and (eq --category 'objects) (not (stringp --data)))
4209 (let ((sec-prop
4210 (assq --type org-element-secondary-value-alist)))
4211 (when sec-prop
4212 (funcall --walk-tree
4213 (org-element-property (cdr sec-prop) --data)))))
4214 ;; If --DATA has any affiliated keywords and
4215 ;; WITH-AFFILIATED is non-nil, look for objects in
4216 ;; them.
4217 (when (and with-affiliated
4218 (eq --category 'objects)
4219 (memq --type org-element-all-elements))
4220 (mapc (lambda (kwd-pair)
4221 (let ((kwd (car kwd-pair))
4222 (value (org-element-property
4223 (cdr kwd-pair) --data)))
4224 ;; Pay attention to the type of value.
4225 ;; Preserve order for multiple keywords.
4226 (cond
4227 ((not value))
4228 ((and (member kwd org-element-multiple-keywords)
4229 (member kwd org-element-dual-keywords))
4230 (mapc (lambda (line)
4231 (funcall --walk-tree (cdr line))
4232 (funcall --walk-tree (car line)))
4233 (reverse value)))
4234 ((member kwd org-element-multiple-keywords)
4235 (mapc (lambda (line) (funcall --walk-tree line))
4236 (reverse value)))
4237 ((member kwd org-element-dual-keywords)
4238 (funcall --walk-tree (cdr value))
4239 (funcall --walk-tree (car value)))
4240 (t (funcall --walk-tree value)))))
4241 --affiliated-alist))
4242 ;; Determine if a recursion into --DATA is possible.
4243 (cond
4244 ;; --TYPE is explicitly removed from recursion.
4245 ((memq --type no-recursion))
4246 ;; --DATA has no contents.
4247 ((not (org-element-contents --data)))
4248 ;; Looking for greater elements but --DATA is simply
4249 ;; an element or an object.
4250 ((and (eq --category 'greater-elements)
4251 (not (memq --type org-element-greater-elements))))
4252 ;; Looking for elements but --DATA is an object.
4253 ((and (eq --category 'elements)
4254 (memq --type org-element-all-objects)))
4255 ;; In any other case, map contents.
4256 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4257 (catch '--map-first-match
4258 (funcall --walk-tree data)
4259 ;; Return value in a proper order.
4260 (nreverse --acc))))
4261 (put 'org-element-map 'lisp-indent-function 2)
4263 ;; The following functions are internal parts of the parser.
4265 ;; The first one, `org-element--parse-elements' acts at the element's
4266 ;; level.
4268 ;; The second one, `org-element--parse-objects' applies on all objects
4269 ;; of a paragraph or a secondary string. It uses
4270 ;; `org-element--get-next-object-candidates' to optimize the search of
4271 ;; the next object in the buffer.
4273 ;; More precisely, that function looks for every allowed object type
4274 ;; first. Then, it discards failed searches, keeps further matches,
4275 ;; and searches again types matched behind point, for subsequent
4276 ;; calls. Thus, searching for a given type fails only once, and every
4277 ;; object is searched only once at top level (but sometimes more for
4278 ;; nested types).
4280 (defun org-element--parse-elements
4281 (beg end special structure granularity visible-only acc)
4282 "Parse elements between BEG and END positions.
4284 SPECIAL prioritize some elements over the others. It can be set
4285 to `first-section', `quote-section', `section' `item' or
4286 `table-row'.
4288 When value is `item', STRUCTURE will be used as the current list
4289 structure.
4291 GRANULARITY determines the depth of the recursion. See
4292 `org-element-parse-buffer' for more information.
4294 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4295 elements.
4297 Elements are accumulated into ACC."
4298 (save-excursion
4299 (goto-char beg)
4300 ;; Visible only: skip invisible parts at the beginning of the
4301 ;; element.
4302 (when (and visible-only (org-invisible-p2))
4303 (goto-char (min (1+ (org-find-visible)) end)))
4304 ;; When parsing only headlines, skip any text before first one.
4305 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4306 (org-with-limited-levels (outline-next-heading)))
4307 ;; Main loop start.
4308 (while (< (point) end)
4309 ;; Find current element's type and parse it accordingly to
4310 ;; its category.
4311 (let* ((element (org-element--current-element
4312 end granularity special structure))
4313 (type (org-element-type element))
4314 (cbeg (org-element-property :contents-begin element)))
4315 (goto-char (org-element-property :end element))
4316 ;; Visible only: skip invisible parts between siblings.
4317 (when (and visible-only (org-invisible-p2))
4318 (goto-char (min (1+ (org-find-visible)) end)))
4319 ;; Fill ELEMENT contents by side-effect.
4320 (cond
4321 ;; If element has no contents, don't modify it.
4322 ((not cbeg))
4323 ;; Greater element: parse it between `contents-begin' and
4324 ;; `contents-end'. Make sure GRANULARITY allows the
4325 ;; recursion, or ELEMENT is a headline, in which case going
4326 ;; inside is mandatory, in order to get sub-level headings.
4327 ((and (memq type org-element-greater-elements)
4328 (or (memq granularity '(element object nil))
4329 (and (eq granularity 'greater-element)
4330 (eq type 'section))
4331 (eq type 'headline)))
4332 (org-element--parse-elements
4333 cbeg (org-element-property :contents-end element)
4334 ;; Possibly switch to a special mode.
4335 (case type
4336 (headline
4337 (if (org-element-property :quotedp element) 'quote-section
4338 'section))
4339 (plain-list 'item)
4340 (property-drawer 'node-property)
4341 (table 'table-row))
4342 (and (memq type '(item plain-list))
4343 (org-element-property :structure element))
4344 granularity visible-only element))
4345 ;; ELEMENT has contents. Parse objects inside, if
4346 ;; GRANULARITY allows it.
4347 ((memq granularity '(object nil))
4348 (org-element--parse-objects
4349 cbeg (org-element-property :contents-end element) element
4350 (org-element-restriction type))))
4351 (org-element-adopt-elements acc element)))
4352 ;; Return result.
4353 acc))
4355 (defun org-element--parse-objects (beg end acc restriction)
4356 "Parse objects between BEG and END and return recursive structure.
4358 Objects are accumulated in ACC.
4360 RESTRICTION is a list of object successors which are allowed in
4361 the current object."
4362 (let ((candidates 'initial))
4363 (save-excursion
4364 (save-restriction
4365 (narrow-to-region beg end)
4366 (goto-char (point-min))
4367 (while (and (not (eobp))
4368 (setq candidates
4369 (org-element--get-next-object-candidates
4370 restriction candidates)))
4371 (let ((next-object
4372 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4373 (save-excursion
4374 (goto-char pos)
4375 (funcall (intern (format "org-element-%s-parser"
4376 (car (rassq pos candidates)))))))))
4377 ;; 1. Text before any object. Untabify it.
4378 (let ((obj-beg (org-element-property :begin next-object)))
4379 (unless (= (point) obj-beg)
4380 (setq acc
4381 (org-element-adopt-elements
4383 (replace-regexp-in-string
4384 "\t" (make-string tab-width ? )
4385 (buffer-substring-no-properties (point) obj-beg))))))
4386 ;; 2. Object...
4387 (let ((obj-end (org-element-property :end next-object))
4388 (cont-beg (org-element-property :contents-begin next-object)))
4389 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4390 ;; a recursive type.
4391 (when (and cont-beg
4392 (memq (car next-object) org-element-recursive-objects))
4393 (org-element--parse-objects
4394 cont-beg (org-element-property :contents-end next-object)
4395 next-object (org-element-restriction next-object)))
4396 (setq acc (org-element-adopt-elements acc next-object))
4397 (goto-char obj-end))))
4398 ;; 3. Text after last object. Untabify it.
4399 (unless (eobp)
4400 (setq acc
4401 (org-element-adopt-elements
4403 (replace-regexp-in-string
4404 "\t" (make-string tab-width ? )
4405 (buffer-substring-no-properties (point) end)))))
4406 ;; Result.
4407 acc))))
4409 (defun org-element--get-next-object-candidates (restriction objects)
4410 "Return an alist of candidates for the next object.
4412 RESTRICTION is a list of object types, as symbols. Only
4413 candidates with such types are looked after.
4415 OBJECTS is the previous candidates alist. If it is set to
4416 `initial', no search has been done before, and all symbols in
4417 RESTRICTION should be looked after.
4419 Return value is an alist whose CAR is the object type and CDR its
4420 beginning position."
4421 (delq
4423 (if (eq objects 'initial)
4424 ;; When searching for the first time, look for every successor
4425 ;; allowed in RESTRICTION.
4426 (mapcar
4427 (lambda (res)
4428 (funcall (intern (format "org-element-%s-successor" res))))
4429 restriction)
4430 ;; Focus on objects returned during last search. Keep those
4431 ;; still after point. Search again objects before it.
4432 (mapcar
4433 (lambda (obj)
4434 (if (>= (cdr obj) (point)) obj
4435 (let* ((type (car obj))
4436 (succ (or (cdr (assq type org-element-object-successor-alist))
4437 type)))
4438 (and succ
4439 (funcall (intern (format "org-element-%s-successor" succ)))))))
4440 objects))))
4444 ;;; Towards A Bijective Process
4446 ;; The parse tree obtained with `org-element-parse-buffer' is really
4447 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4448 ;; interpreted and expanded into a string with canonical Org syntax.
4449 ;; Hence `org-element-interpret-data'.
4451 ;; The function relies internally on
4452 ;; `org-element--interpret-affiliated-keywords'.
4454 ;;;###autoload
4455 (defun org-element-interpret-data (data &optional parent)
4456 "Interpret DATA as Org syntax.
4458 DATA is a parse tree, an element, an object or a secondary string
4459 to interpret.
4461 Optional argument PARENT is used for recursive calls. It contains
4462 the element or object containing data, or nil.
4464 Return Org syntax as a string."
4465 (let* ((type (org-element-type data))
4466 (results
4467 (cond
4468 ;; Secondary string.
4469 ((not type)
4470 (mapconcat
4471 (lambda (obj) (org-element-interpret-data obj parent))
4472 data ""))
4473 ;; Full Org document.
4474 ((eq type 'org-data)
4475 (mapconcat
4476 (lambda (obj) (org-element-interpret-data obj parent))
4477 (org-element-contents data) ""))
4478 ;; Plain text: remove `:parent' text property from output.
4479 ((stringp data) (org-no-properties data))
4480 ;; Element/Object without contents.
4481 ((not (org-element-contents data))
4482 (funcall (intern (format "org-element-%s-interpreter" type))
4483 data nil))
4484 ;; Element/Object with contents.
4486 (let* ((greaterp (memq type org-element-greater-elements))
4487 (objectp (and (not greaterp)
4488 (memq type org-element-recursive-objects)))
4489 (contents
4490 (mapconcat
4491 (lambda (obj) (org-element-interpret-data obj data))
4492 (org-element-contents
4493 (if (or greaterp objectp) data
4494 ;; Elements directly containing objects must
4495 ;; have their indentation normalized first.
4496 (org-element-normalize-contents
4497 data
4498 ;; When normalizing first paragraph of an
4499 ;; item or a footnote-definition, ignore
4500 ;; first line's indentation.
4501 (and (eq type 'paragraph)
4502 (equal data (car (org-element-contents parent)))
4503 (memq (org-element-type parent)
4504 '(footnote-definition item))))))
4505 "")))
4506 (funcall (intern (format "org-element-%s-interpreter" type))
4507 data
4508 (if greaterp (org-element-normalize-contents contents)
4509 contents)))))))
4510 (if (memq type '(org-data plain-text nil)) results
4511 ;; Build white spaces. If no `:post-blank' property is
4512 ;; specified, assume its value is 0.
4513 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4514 (if (memq type org-element-all-objects)
4515 (concat results (make-string post-blank 32))
4516 (concat
4517 (org-element--interpret-affiliated-keywords data)
4518 (org-element-normalize-string results)
4519 (make-string post-blank 10)))))))
4521 (defun org-element--interpret-affiliated-keywords (element)
4522 "Return ELEMENT's affiliated keywords as Org syntax.
4523 If there is no affiliated keyword, return the empty string."
4524 (let ((keyword-to-org
4525 (function
4526 (lambda (key value)
4527 (let (dual)
4528 (when (member key org-element-dual-keywords)
4529 (setq dual (cdr value) value (car value)))
4530 (concat "#+" key
4531 (and dual
4532 (format "[%s]" (org-element-interpret-data dual)))
4533 ": "
4534 (if (member key org-element-parsed-keywords)
4535 (org-element-interpret-data value)
4536 value)
4537 "\n"))))))
4538 (mapconcat
4539 (lambda (prop)
4540 (let ((value (org-element-property prop element))
4541 (keyword (upcase (substring (symbol-name prop) 1))))
4542 (when value
4543 (if (or (member keyword org-element-multiple-keywords)
4544 ;; All attribute keywords can have multiple lines.
4545 (string-match "^ATTR_" keyword))
4546 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4547 (reverse value)
4549 (funcall keyword-to-org keyword value)))))
4550 ;; List all ELEMENT's properties matching an attribute line or an
4551 ;; affiliated keyword, but ignore translated keywords since they
4552 ;; cannot belong to the property list.
4553 (loop for prop in (nth 1 element) by 'cddr
4554 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4555 (or (string-match "^ATTR_" keyword)
4556 (and
4557 (member keyword org-element-affiliated-keywords)
4558 (not (assoc keyword
4559 org-element-keyword-translation-alist)))))
4560 collect prop)
4561 "")))
4563 ;; Because interpretation of the parse tree must return the same
4564 ;; number of blank lines between elements and the same number of white
4565 ;; space after objects, some special care must be given to white
4566 ;; spaces.
4568 ;; The first function, `org-element-normalize-string', ensures any
4569 ;; string different from the empty string will end with a single
4570 ;; newline character.
4572 ;; The second function, `org-element-normalize-contents', removes
4573 ;; global indentation from the contents of the current element.
4575 (defun org-element-normalize-string (s)
4576 "Ensure string S ends with a single newline character.
4578 If S isn't a string return it unchanged. If S is the empty
4579 string, return it. Otherwise, return a new string with a single
4580 newline character at its end."
4581 (cond
4582 ((not (stringp s)) s)
4583 ((string= "" s) "")
4584 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4585 (replace-match "\n" nil nil s)))))
4587 (defun org-element-normalize-contents (element &optional ignore-first)
4588 "Normalize plain text in ELEMENT's contents.
4590 ELEMENT must only contain plain text and objects.
4592 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4593 indentation to compute maximal common indentation.
4595 Return the normalized element that is element with global
4596 indentation removed from its contents. The function assumes that
4597 indentation is not done with TAB characters."
4598 (let* (ind-list ; for byte-compiler
4599 collect-inds ; for byte-compiler
4600 (collect-inds
4601 (function
4602 ;; Return list of indentations within BLOB. This is done by
4603 ;; walking recursively BLOB and updating IND-LIST along the
4604 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4605 ;; been seen yet. It is required as this string is the only
4606 ;; one whose indentation doesn't happen after a newline
4607 ;; character.
4608 (lambda (blob first-flag)
4609 (mapc
4610 (lambda (object)
4611 (when (and first-flag (stringp object))
4612 (setq first-flag nil)
4613 (string-match "\\`\\( *\\)" object)
4614 (let ((len (length (match-string 1 object))))
4615 ;; An indentation of zero means no string will be
4616 ;; modified. Quit the process.
4617 (if (zerop len) (throw 'zero (setq ind-list nil))
4618 (push len ind-list))))
4619 (cond
4620 ((stringp object)
4621 (let ((start 0))
4622 ;; Avoid matching blank or empty lines.
4623 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4624 (not (equal (match-string 2 object) " ")))
4625 (setq start (match-end 0))
4626 (push (length (match-string 1 object)) ind-list))))
4627 ((memq (org-element-type object) org-element-recursive-objects)
4628 (funcall collect-inds object first-flag))))
4629 (org-element-contents blob))))))
4630 ;; Collect indentation list in ELEMENT. Possibly remove first
4631 ;; value if IGNORE-FIRST is non-nil.
4632 (catch 'zero (funcall collect-inds element (not ignore-first)))
4633 (if (not ind-list) element
4634 ;; Build ELEMENT back, replacing each string with the same
4635 ;; string minus common indentation.
4636 (let* (build ; For byte compiler.
4637 (build
4638 (function
4639 (lambda (blob mci first-flag)
4640 ;; Return BLOB with all its strings indentation
4641 ;; shortened from MCI white spaces. FIRST-FLAG is
4642 ;; non-nil when the first string hasn't been seen
4643 ;; yet.
4644 (setcdr (cdr blob)
4645 (mapcar
4646 (lambda (object)
4647 (when (and first-flag (stringp object))
4648 (setq first-flag nil)
4649 (setq object
4650 (replace-regexp-in-string
4651 (format "\\` \\{%d\\}" mci) "" object)))
4652 (cond
4653 ((stringp object)
4654 (replace-regexp-in-string
4655 (format "\n \\{%d\\}" mci) "\n" object))
4656 ((memq (org-element-type object)
4657 org-element-recursive-objects)
4658 (funcall build object mci first-flag))
4659 (t object)))
4660 (org-element-contents blob)))
4661 blob))))
4662 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4666 ;;; The Toolbox
4668 ;; The first move is to implement a way to obtain the smallest element
4669 ;; containing point. This is the job of `org-element-at-point'. It
4670 ;; basically jumps back to the beginning of section containing point
4671 ;; and moves, element after element, with
4672 ;; `org-element--current-element' until the container is found. Note:
4673 ;; When using `org-element-at-point', secondary values are never
4674 ;; parsed since the function focuses on elements, not on objects.
4676 ;; At a deeper level, `org-element-context' lists all elements and
4677 ;; objects containing point.
4679 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4680 ;; internally by navigation and manipulation tools.
4682 ;;;###autoload
4683 (defun org-element-at-point (&optional keep-trail)
4684 "Determine closest element around point.
4686 Return value is a list like (TYPE PROPS) where TYPE is the type
4687 of the element and PROPS a plist of properties associated to the
4688 element.
4690 Possible types are defined in `org-element-all-elements'.
4691 Properties depend on element or object type, but always include
4692 `:begin', `:end', `:parent' and `:post-blank' properties.
4694 As a special case, if point is at the very beginning of a list or
4695 sub-list, returned element will be that list instead of the first
4696 item. In the same way, if point is at the beginning of the first
4697 row of a table, returned element will be the table instead of the
4698 first row.
4700 If optional argument KEEP-TRAIL is non-nil, the function returns
4701 a list of elements leading to element at point. The list's CAR
4702 is always the element at point. The following positions contain
4703 element's siblings, then parents, siblings of parents, until the
4704 first element of current section."
4705 (org-with-wide-buffer
4706 ;; If at a headline, parse it. It is the sole element that
4707 ;; doesn't require to know about context. Be sure to disallow
4708 ;; secondary string parsing, though.
4709 (if (org-with-limited-levels (org-at-heading-p))
4710 (progn
4711 (beginning-of-line)
4712 (if (not keep-trail) (org-element-headline-parser (point-max) t)
4713 (list (org-element-headline-parser (point-max) t))))
4714 ;; Otherwise move at the beginning of the section containing
4715 ;; point.
4716 (catch 'exit
4717 (let ((origin (point))
4718 (end (save-excursion
4719 (org-with-limited-levels (outline-next-heading)) (point)))
4720 element type special-flag trail struct prevs parent)
4721 (org-with-limited-levels
4722 (if (org-before-first-heading-p)
4723 ;; In empty lines at buffer's beginning, return nil.
4724 (progn (goto-char (point-min))
4725 (org-skip-whitespace)
4726 (when (or (eobp) (> (line-beginning-position) origin))
4727 (throw 'exit nil)))
4728 (org-back-to-heading)
4729 (forward-line)
4730 (org-skip-whitespace)
4731 (when (or (eobp) (> (line-beginning-position) origin))
4732 ;; In blank lines just after the headline, point still
4733 ;; belongs to the headline.
4734 (throw 'exit
4735 (progn (skip-chars-backward " \r\t\n")
4736 (beginning-of-line)
4737 (if (not keep-trail)
4738 (org-element-headline-parser (point-max) t)
4739 (list (org-element-headline-parser
4740 (point-max) t))))))))
4741 (beginning-of-line)
4742 ;; Parse successively each element, skipping those ending
4743 ;; before original position.
4744 (while t
4745 (setq element
4746 (org-element--current-element end 'element special-flag struct)
4747 type (car element))
4748 (org-element-put-property element :parent parent)
4749 (when keep-trail (push element trail))
4750 (cond
4751 ;; 1. Skip any element ending before point. Also skip
4752 ;; element ending at point when we're sure that another
4753 ;; element has started.
4754 ((let ((elem-end (org-element-property :end element)))
4755 (when (or (< elem-end origin)
4756 (and (= elem-end origin) (/= elem-end end)))
4757 (goto-char elem-end))))
4758 ;; 2. An element containing point is always the element at
4759 ;; point.
4760 ((not (memq type org-element-greater-elements))
4761 (throw 'exit (if keep-trail trail element)))
4762 ;; 3. At any other greater element type, if point is
4763 ;; within contents, move into it.
4765 (let ((cbeg (org-element-property :contents-begin element))
4766 (cend (org-element-property :contents-end element)))
4767 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
4768 ;; Create an anchor for tables and plain lists:
4769 ;; when point is at the very beginning of these
4770 ;; elements, ignoring affiliated keywords,
4771 ;; target them instead of their contents.
4772 (and (= cbeg origin) (memq type '(plain-list table)))
4773 ;; When point is at contents end, do not move
4774 ;; into elements with an explicit ending, but
4775 ;; return that element instead.
4776 (and (= cend origin)
4777 (or (memq type
4778 '(center-block
4779 drawer dynamic-block inlinetask
4780 property-drawer quote-block
4781 special-block))
4782 ;; Corner case: if a list ends at the
4783 ;; end of a buffer without a final new
4784 ;; line, return last element in last
4785 ;; item instead.
4786 (and (memq type '(item plain-list))
4787 (progn (goto-char cend)
4788 (or (bolp) (not (eobp))))))))
4789 (throw 'exit (if keep-trail trail element))
4790 (setq parent element)
4791 (case type
4792 (plain-list
4793 (setq special-flag 'item
4794 struct (org-element-property :structure element)))
4795 (item (setq special-flag nil))
4796 (property-drawer
4797 (setq special-flag 'node-property struct nil))
4798 (table (setq special-flag 'table-row struct nil))
4799 (otherwise (setq special-flag nil struct nil)))
4800 (setq end cend)
4801 (goto-char cbeg)))))))))))
4803 ;;;###autoload
4804 (defun org-element-context (&optional element)
4805 "Return closest element or object around point.
4807 Return value is a list like (TYPE PROPS) where TYPE is the type
4808 of the element or object and PROPS a plist of properties
4809 associated to it.
4811 Possible types are defined in `org-element-all-elements' and
4812 `org-element-all-objects'. Properties depend on element or
4813 object type, but always include `:begin', `:end', `:parent' and
4814 `:post-blank'.
4816 Optional argument ELEMENT, when non-nil, is the closest element
4817 containing point, as returned by `org-element-at-point'.
4818 Providing it allows for quicker computation."
4819 (catch 'objects-forbidden
4820 (org-with-wide-buffer
4821 (let* ((origin (point))
4822 (element (or element (org-element-at-point)))
4823 (type (org-element-type element))
4824 context)
4825 ;; Check if point is inside an element containing objects or at
4826 ;; a secondary string. In that case, narrow buffer to the
4827 ;; containing area. Otherwise, return ELEMENT.
4828 (cond
4829 ;; At a parsed affiliated keyword, check if we're inside main
4830 ;; or dual value.
4831 ((let ((post (org-element-property :post-affiliated element)))
4832 (and post (< origin post)))
4833 (beginning-of-line)
4834 (looking-at org-element--affiliated-re)
4835 (cond
4836 ((not (member (upcase (match-string 1)) org-element-parsed-keywords))
4837 (throw 'objects-forbidden element))
4838 ((< (match-end 0) origin)
4839 (narrow-to-region (match-end 0) (line-end-position)))
4840 ((and (match-beginning 2)
4841 (>= origin (match-beginning 2))
4842 (< origin (match-end 2)))
4843 (narrow-to-region (match-beginning 2) (match-end 2)))
4844 (t (throw 'objects-forbidden element)))
4845 ;; Also change type to retrieve correct restrictions.
4846 (setq type 'keyword))
4847 ;; At an item, objects can only be located within tag, if any.
4848 ((eq type 'item)
4849 (let ((tag (org-element-property :tag element)))
4850 (if (not tag) (throw 'objects-forbidden element)
4851 (beginning-of-line)
4852 (search-forward tag (line-end-position))
4853 (goto-char (match-beginning 0))
4854 (if (and (>= origin (point)) (< origin (match-end 0)))
4855 (narrow-to-region (point) (match-end 0))
4856 (throw 'objects-forbidden element)))))
4857 ;; At an headline or inlinetask, objects are located within
4858 ;; their title.
4859 ((memq type '(headline inlinetask))
4860 (goto-char (org-element-property :begin element))
4861 (skip-chars-forward "* ")
4862 (if (and (>= origin (point)) (< origin (line-end-position)))
4863 (narrow-to-region (point) (line-end-position))
4864 (throw 'objects-forbidden element)))
4865 ;; At a paragraph, a table-row or a verse block, objects are
4866 ;; located within their contents.
4867 ((memq type '(paragraph table-row verse-block))
4868 (let ((cbeg (org-element-property :contents-begin element))
4869 (cend (org-element-property :contents-end element)))
4870 ;; CBEG is nil for table rules.
4871 (if (and cbeg cend (>= origin cbeg) (< origin cend))
4872 (narrow-to-region cbeg cend)
4873 (throw 'objects-forbidden element))))
4874 ;; At a parsed keyword, objects are located within value.
4875 ((eq type 'keyword)
4876 (if (not (member (org-element-property :key element)
4877 org-element-document-properties))
4878 (throw 'objects-forbidden element)
4879 (beginning-of-line)
4880 (search-forward ":")
4881 (if (and (>= origin (point)) (< origin (line-end-position)))
4882 (narrow-to-region (point) (line-end-position))
4883 (throw 'objects-forbidden element))))
4884 (t (throw 'objects-forbidden element)))
4885 (goto-char (point-min))
4886 (let ((restriction (org-element-restriction type))
4887 (parent element)
4888 (candidates 'initial))
4889 (catch 'exit
4890 (while (setq candidates
4891 (org-element--get-next-object-candidates
4892 restriction candidates))
4893 (let ((closest-cand (rassq (apply 'min (mapcar 'cdr candidates))
4894 candidates)))
4895 ;; If ORIGIN is before next object in element, there's
4896 ;; no point in looking further.
4897 (if (> (cdr closest-cand) origin) (throw 'exit parent)
4898 (let* ((object
4899 (progn (goto-char (cdr closest-cand))
4900 (funcall (intern (format "org-element-%s-parser"
4901 (car closest-cand))))))
4902 (cbeg (org-element-property :contents-begin object))
4903 (cend (org-element-property :contents-end object))
4904 (obj-end (org-element-property :end object)))
4905 (cond
4906 ;; ORIGIN is after OBJECT, so skip it.
4907 ((<= obj-end origin) (goto-char obj-end))
4908 ;; ORIGIN is within a non-recursive object or at
4909 ;; an object boundaries: Return that object.
4910 ((or (not cbeg) (< origin cbeg) (>= origin cend))
4911 (throw 'exit
4912 (org-element-put-property object :parent parent)))
4913 ;; Otherwise, move within current object and
4914 ;; restrict search to the end of its contents.
4915 (t (goto-char cbeg)
4916 (narrow-to-region (point) cend)
4917 (org-element-put-property object :parent parent)
4918 (setq parent object
4919 restriction (org-element-restriction object)
4920 candidates 'initial)))))))
4921 parent))))))
4923 (defun org-element-nested-p (elem-A elem-B)
4924 "Non-nil when elements ELEM-A and ELEM-B are nested."
4925 (let ((beg-A (org-element-property :begin elem-A))
4926 (beg-B (org-element-property :begin elem-B))
4927 (end-A (org-element-property :end elem-A))
4928 (end-B (org-element-property :end elem-B)))
4929 (or (and (>= beg-A beg-B) (<= end-A end-B))
4930 (and (>= beg-B beg-A) (<= end-B end-A)))))
4932 (defun org-element-swap-A-B (elem-A elem-B)
4933 "Swap elements ELEM-A and ELEM-B.
4934 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
4935 end of ELEM-A."
4936 (goto-char (org-element-property :begin elem-A))
4937 ;; There are two special cases when an element doesn't start at bol:
4938 ;; the first paragraph in an item or in a footnote definition.
4939 (let ((specialp (not (bolp))))
4940 ;; Only a paragraph without any affiliated keyword can be moved at
4941 ;; ELEM-A position in such a situation. Note that the case of
4942 ;; a footnote definition is impossible: it cannot contain two
4943 ;; paragraphs in a row because it cannot contain a blank line.
4944 (if (and specialp
4945 (or (not (eq (org-element-type elem-B) 'paragraph))
4946 (/= (org-element-property :begin elem-B)
4947 (org-element-property :contents-begin elem-B))))
4948 (error "Cannot swap elements"))
4949 ;; In a special situation, ELEM-A will have no indentation. We'll
4950 ;; give it ELEM-B's (which will in, in turn, have no indentation).
4951 (let* ((ind-B (when specialp
4952 (goto-char (org-element-property :begin elem-B))
4953 (org-get-indentation)))
4954 (beg-A (org-element-property :begin elem-A))
4955 (end-A (save-excursion
4956 (goto-char (org-element-property :end elem-A))
4957 (skip-chars-backward " \r\t\n")
4958 (point-at-eol)))
4959 (beg-B (org-element-property :begin elem-B))
4960 (end-B (save-excursion
4961 (goto-char (org-element-property :end elem-B))
4962 (skip-chars-backward " \r\t\n")
4963 (point-at-eol)))
4964 ;; Store overlays responsible for visibility status. We
4965 ;; also need to store their boundaries as they will be
4966 ;; removed from buffer.
4967 (overlays
4968 (cons
4969 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4970 (overlays-in beg-A end-A))
4971 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4972 (overlays-in beg-B end-B))))
4973 ;; Get contents.
4974 (body-A (buffer-substring beg-A end-A))
4975 (body-B (delete-and-extract-region beg-B end-B)))
4976 (goto-char beg-B)
4977 (when specialp
4978 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
4979 (org-indent-to-column ind-B))
4980 (insert body-A)
4981 ;; Restore ex ELEM-A overlays.
4982 (let ((offset (- beg-B beg-A)))
4983 (mapc (lambda (ov)
4984 (move-overlay
4985 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
4986 (car overlays))
4987 (goto-char beg-A)
4988 (delete-region beg-A end-A)
4989 (insert body-B)
4990 ;; Restore ex ELEM-B overlays.
4991 (mapc (lambda (ov)
4992 (move-overlay
4993 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
4994 (cdr overlays)))
4995 (goto-char (org-element-property :end elem-B)))))
4997 (provide 'org-element)
4999 ;; Local variables:
5000 ;; generated-autoload-file: "org-loaddefs.el"
5001 ;; End:
5003 ;;; org-element.el ends here