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