Implement a basic API around macros
[org-mode.git] / lisp / org-element.el
blobdf6cc72e3ed7f28ffcc0d5884e8db60ddace5f0a
1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; This file is not part of GNU Emacs.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. 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 (namely `babel-call', `clock', `headline', `item',
34 ;; `keyword', `planning', `property-drawer' and `section' types), it
35 ;; can also accept a fixed set of keywords as attributes. Those are
36 ;; called "affiliated keywords" to distinguish them from other
37 ;; keywords, which are full-fledged elements. Almost all affiliated
38 ;; keywords are referenced in `org-element-affiliated-keywords'; the
39 ;; others are export attributes and start with "ATTR_" prefix.
41 ;; Element containing other elements (and only elements) are called
42 ;; greater elements. Concerned types are: `center-block', `drawer',
43 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
44 ;; `item', `plain-list', `quote-block', `section' and `special-block'.
46 ;; Other element types are: `babel-call', `clock', `comment',
47 ;; `comment-block', `example-block', `export-block', `fixed-width',
48 ;; `horizontal-rule', `keyword', `latex-environment', `paragraph',
49 ;; `planning', `property-drawer', `quote-section', `src-block',
50 ;; `table', `table-row' and `verse-block'. Among them, `paragraph'
51 ;; and `verse-block' types can contain Org objects and plain text.
53 ;; Objects are related to document's contents. Some of them are
54 ;; recursive. Associated types are of the following: `bold', `code',
55 ;; `entity', `export-snippet', `footnote-reference',
56 ;; `inline-babel-call', `inline-src-block', `italic',
57 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
58 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
59 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
61 ;; Some elements also have special properties whose value can hold
62 ;; objects themselves (i.e. an item tag or an headline name). Such
63 ;; values are called "secondary strings". Any object belongs to
64 ;; either an element or a secondary string.
66 ;; Notwithstanding affiliated keywords, each greater element, element
67 ;; and object has a fixed set of properties attached to it. Among
68 ;; them, four are shared by all types: `:begin' and `:end', which
69 ;; refer to the beginning and ending buffer positions of the
70 ;; considered element or object, `:post-blank', which holds the number
71 ;; of blank lines, or white spaces, at its end and `:parent' which
72 ;; refers to the element or object containing it. Greater elements
73 ;; and elements containing objects will also have `:contents-begin'
74 ;; and `:contents-end' properties to delimit contents.
76 ;; Lisp-wise, an element or an object can be represented as a list.
77 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
78 ;; TYPE is a symbol describing the Org element or object.
79 ;; PROPERTIES is the property list attached to it. See docstring of
80 ;; appropriate parsing function to get an exhaustive
81 ;; list.
82 ;; CONTENTS is a list of elements, objects or raw strings contained
83 ;; in the current element or object, when applicable.
85 ;; An Org buffer is a nested list of such elements and objects, whose
86 ;; type is `org-data' and properties is nil.
88 ;; The first part of this file defines Org syntax, while the second
89 ;; one provide accessors and setters functions.
91 ;; The next part implements a parser and an interpreter for each
92 ;; element and object type in Org syntax.
94 ;; The following part creates a fully recursive buffer parser. It
95 ;; also provides a tool to map a function to elements or objects
96 ;; matching some criteria in the parse tree. Functions of interest
97 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
98 ;; extent, `org-element-parse-secondary-string'.
100 ;; The penultimate part is the cradle of an interpreter for the
101 ;; obtained parse tree: `org-element-interpret-data'.
103 ;; The library ends by furnishing `org-element-at-point' function, and
104 ;; a way to give information about document structure around point
105 ;; with `org-element-context'.
108 ;;; Code:
110 (eval-when-compile
111 (require 'cl))
113 (require 'org)
116 ;;; Definitions And Rules
118 ;; Define elements, greater elements and specify recursive objects,
119 ;; along with the affiliated keywords recognized. Also set up
120 ;; restrictions on recursive objects combinations.
122 ;; These variables really act as a control center for the parsing
123 ;; process.
125 (defconst org-element-paragraph-separate
126 (concat "^\\(?:"
127 ;; Headlines, inlinetasks.
128 org-outline-regexp "\\|"
129 ;; Footnote definitions.
130 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
131 "[ \t]*\\(?:"
132 ;; Empty lines.
133 "$" "\\|"
134 ;; Tables (any type).
135 "\\(?:|\\|\\+-[-+]\\)" "\\|"
136 ;; Blocks (any type), Babel calls, drawers (any type),
137 ;; fixed-width areas and keywords. Note: this is only an
138 ;; indication and need some thorough check.
139 "[#:]" "\\|"
140 ;; Horizontal rules.
141 "-\\{5,\\}[ \t]*$" "\\|"
142 ;; LaTeX environments.
143 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
144 ;; Planning and Clock lines.
145 (regexp-opt (list org-scheduled-string
146 org-deadline-string
147 org-closed-string
148 org-clock-string))
149 "\\|"
150 ;; Lists.
151 (let ((term (case org-plain-list-ordered-item-terminator
152 (?\) ")") (?. "\\.") (otherwise "[.)]")))
153 (alpha (and org-alphabetical-lists "\\|[A-Za-z]")))
154 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
155 "\\(?:[ \t]\\|$\\)"))
156 "\\)\\)")
157 "Regexp to separate paragraphs in an Org buffer.
158 In the case of lines starting with \"#\" and \":\", this regexp
159 is not sufficient to know if point is at a paragraph ending. See
160 `org-element-paragraph-parser' for more information.")
162 (defconst org-element-all-elements
163 '(center-block clock comment comment-block drawer dynamic-block example-block
164 export-block fixed-width footnote-definition headline
165 horizontal-rule inlinetask item keyword latex-environment
166 babel-call paragraph plain-list planning property-drawer
167 quote-block quote-section section special-block src-block table
168 table-row verse-block)
169 "Complete list of element types.")
171 (defconst org-element-greater-elements
172 '(center-block drawer dynamic-block footnote-definition headline inlinetask
173 item plain-list quote-block section special-block table)
174 "List of recursive element types aka Greater Elements.")
176 (defconst org-element-all-successors
177 '(export-snippet footnote-reference inline-babel-call inline-src-block
178 latex-or-entity line-break link macro radio-target
179 statistics-cookie sub/superscript table-cell target
180 text-markup timestamp)
181 "Complete list of successors.")
183 (defconst org-element-object-successor-alist
184 '((subscript . sub/superscript) (superscript . sub/superscript)
185 (bold . text-markup) (code . text-markup) (italic . text-markup)
186 (strike-through . text-markup) (underline . text-markup)
187 (verbatim . text-markup) (entity . latex-or-entity)
188 (latex-fragment . latex-or-entity))
189 "Alist of translations between object type and successor name.
191 Sharing the same successor comes handy when, for example, the
192 regexp matching one object can also match the other object.")
194 (defconst org-element-all-objects
195 '(bold code entity export-snippet footnote-reference inline-babel-call
196 inline-src-block italic line-break latex-fragment link macro
197 radio-target statistics-cookie strike-through subscript superscript
198 table-cell target timestamp underline verbatim)
199 "Complete list of object types.")
201 (defconst org-element-recursive-objects
202 '(bold italic link macro subscript radio-target strike-through superscript
203 table-cell underline)
204 "List of recursive object types.")
206 (defconst org-element-block-name-alist
207 '(("CENTER" . org-element-center-block-parser)
208 ("COMMENT" . org-element-comment-block-parser)
209 ("EXAMPLE" . org-element-example-block-parser)
210 ("QUOTE" . org-element-quote-block-parser)
211 ("SRC" . org-element-src-block-parser)
212 ("VERSE" . org-element-verse-block-parser))
213 "Alist between block names and the associated parsing function.
214 Names must be uppercase. Any block whose name has no association
215 is parsed with `org-element-special-block-parser'.")
217 (defconst org-element-link-type-is-file
218 '("file" "file+emacs" "file+sys" "docview")
219 "List of link types equivalent to \"file\".
220 Only these types can accept search options and an explicit
221 application to open them.")
223 (defconst org-element-affiliated-keywords
224 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
225 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
226 "List of affiliated keywords as strings.
227 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
228 are affiliated keywords and need not to be in this list.")
230 (defconst org-element--affiliated-re
231 (format "[ \t]*#\\+%s:"
232 ;; Regular affiliated keywords.
233 (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
234 (regexp-opt org-element-affiliated-keywords)))
235 "Regexp matching any affiliated keyword.
237 Keyword name is put in match group 1. Moreover, if keyword
238 belongs to `org-element-dual-keywords', put the dual value in
239 match group 2.
241 Don't modify it, set `org-element-affiliated-keywords' instead.")
243 (defconst org-element-keyword-translation-alist
244 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
245 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
246 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
247 "Alist of usual translations for keywords.
248 The key is the old name and the value the new one. The property
249 holding their value will be named after the translated name.")
251 (defconst org-element-multiple-keywords '("HEADER")
252 "List of affiliated keywords that can occur more that once in an element.
254 Their value will be consed into a list of strings, which will be
255 returned as the value of the property.
257 This list is checked after translations have been applied. See
258 `org-element-keyword-translation-alist'.
260 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
261 allow multiple occurrences and need not to be in this list.")
263 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "DATE" "TITLE")
264 "List of keywords whose value can be parsed.
266 Their value will be stored as a secondary string: a list of
267 strings and objects.
269 This list is checked after translations have been applied. See
270 `org-element-keyword-translation-alist'.")
272 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
273 "List of keywords which can have a secondary value.
275 In Org syntax, they can be written with optional square brackets
276 before the colons. For example, results keyword can be
277 associated to a hash value with the following:
279 #+RESULTS[hash-string]: some-source
281 This list is checked after translations have been applied. See
282 `org-element-keyword-translation-alist'.")
284 (defconst org-element-object-restrictions
285 '((bold export-snippet inline-babel-call inline-src-block latex-or-entity link
286 radio-target sub/superscript target text-markup timestamp)
287 (footnote-reference export-snippet footnote-reference inline-babel-call
288 inline-src-block latex-or-entity line-break link macro
289 radio-target sub/superscript target text-markup
290 timestamp)
291 (headline inline-babel-call inline-src-block latex-or-entity link macro
292 radio-target statistics-cookie sub/superscript target text-markup
293 timestamp)
294 (inlinetask inline-babel-call inline-src-block latex-or-entity link macro
295 radio-target sub/superscript target text-markup timestamp)
296 (italic export-snippet inline-babel-call inline-src-block latex-or-entity
297 link radio-target sub/superscript target text-markup timestamp)
298 (item export-snippet footnote-reference inline-babel-call latex-or-entity
299 link macro radio-target sub/superscript target text-markup)
300 (keyword latex-or-entity macro sub/superscript text-markup)
301 (link export-snippet inline-babel-call inline-src-block latex-or-entity link
302 sub/superscript text-markup)
303 (macro macro)
304 (paragraph export-snippet footnote-reference inline-babel-call
305 inline-src-block latex-or-entity line-break link macro
306 radio-target statistics-cookie sub/superscript target text-markup
307 timestamp)
308 (radio-target export-snippet latex-or-entity sub/superscript)
309 (strike-through export-snippet inline-babel-call inline-src-block
310 latex-or-entity link radio-target sub/superscript target
311 text-markup timestamp)
312 (subscript export-snippet inline-babel-call inline-src-block latex-or-entity
313 sub/superscript target text-markup)
314 (superscript export-snippet inline-babel-call inline-src-block
315 latex-or-entity sub/superscript target text-markup)
316 (table-cell export-snippet latex-or-entity link macro radio-target
317 sub/superscript target text-markup timestamp)
318 (table-row table-cell)
319 (underline export-snippet inline-babel-call inline-src-block latex-or-entity
320 link radio-target sub/superscript target text-markup timestamp)
321 (verse-block footnote-reference inline-babel-call inline-src-block
322 latex-or-entity line-break link macro radio-target
323 sub/superscript target text-markup timestamp))
324 "Alist of objects restrictions.
326 CAR is an element or object type containing objects and CDR is
327 a list of successors that will be called within an element or
328 object of such type.
330 For example, in a `radio-target' object, one can only find
331 entities, export snippets, latex-fragments, subscript and
332 superscript.
334 This alist also applies to secondary string. For example, an
335 `headline' type element doesn't directly contain objects, but
336 still has an entry since one of its properties (`:title') does.")
338 (defconst org-element-secondary-value-alist
339 '((headline . :title)
340 (inlinetask . :title)
341 (item . :tag)
342 (footnote-reference . :inline-definition))
343 "Alist between element types and location of secondary value.")
347 ;;; Accessors and Setters
349 ;; Provide four accessors: `org-element-type', `org-element-property'
350 ;; `org-element-contents' and `org-element-restriction'.
352 ;; Setter functions allow to modify elements by side effect. There is
353 ;; `org-element-put-property', `org-element-set-contents',
354 ;; `org-element-set-element' and `org-element-adopt-element'. Note
355 ;; that `org-element-set-element' and `org-element-adopt-elements' are
356 ;; higher level functions since also update `:parent' property.
358 (defsubst org-element-type (element)
359 "Return type of ELEMENT.
361 The function returns the type of the element or object provided.
362 It can also return the following special value:
363 `plain-text' for a string
364 `org-data' for a complete document
365 nil in any other case."
366 (cond
367 ((not (consp element)) (and (stringp element) 'plain-text))
368 ((symbolp (car element)) (car element))))
370 (defsubst org-element-property (property element)
371 "Extract the value from the PROPERTY of an ELEMENT."
372 (plist-get (nth 1 element) property))
374 (defsubst org-element-contents (element)
375 "Extract contents from an ELEMENT."
376 (and (consp element) (nthcdr 2 element)))
378 (defsubst org-element-restriction (element)
379 "Return restriction associated to ELEMENT.
380 ELEMENT can be an element, an object or a symbol representing an
381 element or object type."
382 (cdr (assq (if (symbolp element) element (org-element-type element))
383 org-element-object-restrictions)))
385 (defsubst org-element-put-property (element property value)
386 "In ELEMENT set PROPERTY to VALUE.
387 Return modified element."
388 (when (consp element)
389 (setcar (cdr element) (plist-put (nth 1 element) property value)))
390 element)
392 (defsubst org-element-set-contents (element &rest contents)
393 "Set ELEMENT contents to CONTENTS.
394 Return modified element."
395 (cond ((not element) (list contents))
396 ((cdr element) (setcdr (cdr element) contents))
397 (t (nconc element contents))))
399 (defsubst org-element-set-element (old new)
400 "Replace element or object OLD with element or object NEW.
401 The function takes care of setting `:parent' property for NEW."
402 ;; Since OLD is going to be changed into NEW by side-effect, first
403 ;; make sure that every element or object within NEW has OLD as
404 ;; parent.
405 (mapc (lambda (blob) (org-element-put-property blob :parent old))
406 (org-element-contents new))
407 ;; Transfer contents.
408 (apply 'org-element-set-contents old (org-element-contents new))
409 ;; Ensure NEW has same parent as OLD, then overwrite OLD properties
410 ;; with NEW's.
411 (org-element-put-property new :parent (org-element-property :parent old))
412 (setcar (cdr old) (nth 1 new))
413 ;; Transfer type.
414 (setcar old (car new)))
416 (defsubst org-element-adopt-elements (parent &rest children)
417 "Append elements to the contents of another element.
419 PARENT is an element or object. CHILDREN can be elements,
420 objects, or a strings.
422 The function takes care of setting `:parent' property for CHILD.
423 Return parent element."
424 (if (not parent) children
425 ;; Link every child to PARENT.
426 (mapc (lambda (child)
427 (unless (stringp child)
428 (org-element-put-property child :parent parent)))
429 children)
430 ;; Add CHILDREN at the end of PARENT contents.
431 (apply 'org-element-set-contents
432 parent
433 (nconc (org-element-contents parent) children))
434 ;; Return modified PARENT element.
435 parent))
439 ;;; Greater elements
441 ;; For each greater element type, we define a parser and an
442 ;; interpreter.
444 ;; A parser returns the element or object as the list described above.
445 ;; Most of them accepts no argument. Though, exceptions exist. Hence
446 ;; every element containing a secondary string (see
447 ;; `org-element-secondary-value-alist') will accept an optional
448 ;; argument to toggle parsing of that secondary string. Moreover,
449 ;; `item' parser requires current list's structure as its first
450 ;; element.
452 ;; An interpreter accepts two arguments: the list representation of
453 ;; the element or object, and its contents. The latter may be nil,
454 ;; depending on the element or object considered. It returns the
455 ;; appropriate Org syntax, as a string.
457 ;; Parsing functions must follow the naming convention:
458 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
459 ;; defined in `org-element-greater-elements'.
461 ;; Similarly, interpreting functions must follow the naming
462 ;; convention: org-element-TYPE-interpreter.
464 ;; With the exception of `headline' and `item' types, greater elements
465 ;; cannot contain other greater elements of their own type.
467 ;; Beside implementing a parser and an interpreter, adding a new
468 ;; greater element requires to tweak `org-element--current-element'.
469 ;; Moreover, the newly defined type must be added to both
470 ;; `org-element-all-elements' and `org-element-greater-elements'.
473 ;;;; Center Block
475 (defun org-element-center-block-parser (limit)
476 "Parse a center block.
478 LIMIT bounds the search.
480 Return a list whose CAR is `center-block' and CDR is a plist
481 containing `:begin', `:end', `:hiddenp', `:contents-begin',
482 `:contents-end' and `:post-blank' keywords.
484 Assume point is at the beginning of the block."
485 (let ((case-fold-search t))
486 (if (not (save-excursion
487 (re-search-forward "^[ \t]*#\\+END_CENTER" limit t)))
488 ;; Incomplete block: parse it as a paragraph.
489 (org-element-paragraph-parser limit)
490 (let ((block-end-line (match-beginning 0)))
491 (let* ((keywords (org-element--collect-affiliated-keywords))
492 (begin (car keywords))
493 ;; Empty blocks have no contents.
494 (contents-begin (progn (forward-line)
495 (and (< (point) block-end-line)
496 (point))))
497 (contents-end (and contents-begin block-end-line))
498 (hidden (org-invisible-p2))
499 (pos-before-blank (progn (goto-char block-end-line)
500 (forward-line)
501 (point)))
502 (end (save-excursion (skip-chars-forward " \r\t\n" limit)
503 (if (eobp) (point) (point-at-bol)))))
504 (list 'center-block
505 (nconc
506 (list :begin begin
507 :end end
508 :hiddenp hidden
509 :contents-begin contents-begin
510 :contents-end contents-end
511 :post-blank (count-lines pos-before-blank end))
512 (cadr keywords))))))))
514 (defun org-element-center-block-interpreter (center-block contents)
515 "Interpret CENTER-BLOCK element as Org syntax.
516 CONTENTS is the contents of the element."
517 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
520 ;;;; Drawer
522 (defun org-element-drawer-parser (limit)
523 "Parse a drawer.
525 LIMIT bounds the search.
527 Return a list whose CAR is `drawer' and CDR is a plist containing
528 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
529 `:contents-end' and `:post-blank' keywords.
531 Assume point is at beginning of drawer."
532 (let ((case-fold-search t))
533 (if (not (save-excursion (re-search-forward "^[ \t]*:END:" limit t)))
534 ;; Incomplete drawer: parse it as a paragraph.
535 (org-element-paragraph-parser limit)
536 (let ((drawer-end-line (match-beginning 0)))
537 (save-excursion
538 (let* ((case-fold-search t)
539 (name (progn (looking-at org-drawer-regexp)
540 (org-match-string-no-properties 1)))
541 (keywords (org-element--collect-affiliated-keywords))
542 (begin (car keywords))
543 ;; Empty drawers have no contents.
544 (contents-begin (progn (forward-line)
545 (and (< (point) drawer-end-line)
546 (point))))
547 (contents-end (and contents-begin drawer-end-line))
548 (hidden (org-invisible-p2))
549 (pos-before-blank (progn (goto-char drawer-end-line)
550 (forward-line)
551 (point)))
552 (end (progn (skip-chars-forward " \r\t\n" limit)
553 (if (eobp) (point) (point-at-bol)))))
554 (list 'drawer
555 (nconc
556 (list :begin begin
557 :end end
558 :drawer-name name
559 :hiddenp hidden
560 :contents-begin contents-begin
561 :contents-end contents-end
562 :post-blank (count-lines pos-before-blank end))
563 (cadr keywords)))))))))
565 (defun org-element-drawer-interpreter (drawer contents)
566 "Interpret DRAWER element as Org syntax.
567 CONTENTS is the contents of the element."
568 (format ":%s:\n%s:END:"
569 (org-element-property :drawer-name drawer)
570 contents))
573 ;;;; Dynamic Block
575 (defun org-element-dynamic-block-parser (limit)
576 "Parse a dynamic block.
578 LIMIT bounds the search.
580 Return a list whose CAR is `dynamic-block' and CDR is a plist
581 containing `:block-name', `:begin', `:end', `:hiddenp',
582 `:contents-begin', `:contents-end', `:arguments' and
583 `:post-blank' keywords.
585 Assume point is at beginning of dynamic block."
586 (let ((case-fold-search t))
587 (if (not (save-excursion (re-search-forward org-dblock-end-re limit t)))
588 ;; Incomplete block: parse it as a paragraph.
589 (org-element-paragraph-parser limit)
590 (let ((block-end-line (match-beginning 0)))
591 (save-excursion
592 (let* ((name (progn (looking-at org-dblock-start-re)
593 (org-match-string-no-properties 1)))
594 (arguments (org-match-string-no-properties 3))
595 (keywords (org-element--collect-affiliated-keywords))
596 (begin (car keywords))
597 ;; Empty blocks have no contents.
598 (contents-begin (progn (forward-line)
599 (and (< (point) block-end-line)
600 (point))))
601 (contents-end (and contents-begin block-end-line))
602 (hidden (org-invisible-p2))
603 (pos-before-blank (progn (goto-char block-end-line)
604 (forward-line)
605 (point)))
606 (end (progn (skip-chars-forward " \r\t\n" limit)
607 (if (eobp) (point) (point-at-bol)))))
608 (list 'dynamic-block
609 (nconc
610 (list :begin begin
611 :end end
612 :block-name name
613 :arguments arguments
614 :hiddenp hidden
615 :contents-begin contents-begin
616 :contents-end contents-end
617 :post-blank (count-lines pos-before-blank end))
618 (cadr keywords)))))))))
620 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
621 "Interpret DYNAMIC-BLOCK element as Org syntax.
622 CONTENTS is the contents of the element."
623 (format "#+BEGIN: %s%s\n%s#+END:"
624 (org-element-property :block-name dynamic-block)
625 (let ((args (org-element-property :arguments dynamic-block)))
626 (and args (concat " " args)))
627 contents))
630 ;;;; Footnote Definition
632 (defun org-element-footnote-definition-parser (limit)
633 "Parse a footnote definition.
635 LIMIT bounds the search.
637 Return a list whose CAR is `footnote-definition' and CDR is
638 a plist containing `:label', `:begin' `:end', `:contents-begin',
639 `:contents-end' and `:post-blank' keywords.
641 Assume point is at the beginning of the footnote definition."
642 (save-excursion
643 (let* ((label (progn (looking-at org-footnote-definition-re)
644 (org-match-string-no-properties 1)))
645 (keywords (org-element--collect-affiliated-keywords))
646 (begin (car keywords))
647 (ending (save-excursion
648 (if (progn
649 (end-of-line)
650 (re-search-forward
651 (concat org-outline-regexp-bol "\\|"
652 org-footnote-definition-re "\\|"
653 "^[ \t]*$") limit 'move))
654 (match-beginning 0)
655 (point))))
656 (contents-begin (progn (search-forward "]")
657 (skip-chars-forward " \r\t\n" ending)
658 (and (/= (point) ending) (point))))
659 (contents-end (and contents-begin ending))
660 (end (progn (goto-char ending)
661 (skip-chars-forward " \r\t\n" limit)
662 (if (eobp) (point) (point-at-bol)))))
663 (list 'footnote-definition
664 (nconc
665 (list :label label
666 :begin begin
667 :end end
668 :contents-begin contents-begin
669 :contents-end contents-end
670 :post-blank (count-lines ending end))
671 (cadr keywords))))))
673 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
674 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
675 CONTENTS is the contents of the footnote-definition."
676 (concat (format "[%s]" (org-element-property :label footnote-definition))
678 contents))
681 ;;;; Headline
683 (defun org-element-headline-parser (limit &optional raw-secondary-p)
684 "Parse an headline.
686 Return a list whose CAR is `headline' and CDR is a plist
687 containing `:raw-value', `:title', `:begin', `:end',
688 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
689 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
690 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
691 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
692 keywords.
694 The plist also contains any property set in the property drawer,
695 with its name in lowercase, the underscores replaced with hyphens
696 and colons at the beginning (i.e. `:custom-id').
698 When RAW-SECONDARY-P is non-nil, headline's title will not be
699 parsed as a secondary string, but as a plain string instead.
701 Assume point is at beginning of the headline."
702 (save-excursion
703 (let* ((components (org-heading-components))
704 (level (nth 1 components))
705 (todo (nth 2 components))
706 (todo-type
707 (and todo (if (member todo org-done-keywords) 'done 'todo)))
708 (tags (let ((raw-tags (nth 5 components)))
709 (and raw-tags (org-split-string raw-tags ":"))))
710 (raw-value (nth 4 components))
711 (quotedp
712 (let ((case-fold-search nil))
713 (string-match (format "^%s +" org-quote-string) raw-value)))
714 (commentedp
715 (let ((case-fold-search nil))
716 (string-match (format "^%s +" org-comment-string) raw-value)))
717 (archivedp (member org-archive-tag tags))
718 (footnote-section-p (and org-footnote-section
719 (string= org-footnote-section raw-value)))
720 ;; Normalize property names: ":SOME_PROP:" becomes
721 ;; ":some-prop".
722 (standard-props (let (plist)
723 (mapc
724 (lambda (p)
725 (let ((p-name (downcase (car p))))
726 (while (string-match "_" p-name)
727 (setq p-name
728 (replace-match "-" nil nil p-name)))
729 (setq p-name (intern (concat ":" p-name)))
730 (setq plist
731 (plist-put plist p-name (cdr p)))))
732 (org-entry-properties nil 'standard))
733 plist))
734 (time-props (org-entry-properties nil 'special "CLOCK"))
735 (scheduled (cdr (assoc "SCHEDULED" time-props)))
736 (deadline (cdr (assoc "DEADLINE" time-props)))
737 (clock (cdr (assoc "CLOCK" time-props)))
738 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
739 (begin (point))
740 (end (save-excursion (goto-char (org-end-of-subtree t t))))
741 (pos-after-head (progn (forward-line) (point)))
742 (contents-begin (save-excursion
743 (skip-chars-forward " \r\t\n" end)
744 (and (/= (point) end) (line-beginning-position))))
745 (hidden (org-invisible-p2))
746 (contents-end (and contents-begin
747 (progn (goto-char end)
748 (skip-chars-backward " \r\t\n")
749 (forward-line)
750 (point)))))
751 ;; Clean RAW-VALUE from any quote or comment string.
752 (when (or quotedp commentedp)
753 (setq raw-value
754 (replace-regexp-in-string
755 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
757 raw-value)))
758 ;; Clean TAGS from archive tag, if any.
759 (when archivedp (setq tags (delete org-archive-tag tags)))
760 (let ((headline
761 (list 'headline
762 (nconc
763 (list :raw-value raw-value
764 :begin begin
765 :end end
766 :pre-blank
767 (if (not contents-begin) 0
768 (count-lines pos-after-head contents-begin))
769 :hiddenp hidden
770 :contents-begin contents-begin
771 :contents-end contents-end
772 :level level
773 :priority (nth 3 components)
774 :tags tags
775 :todo-keyword todo
776 :todo-type todo-type
777 :scheduled scheduled
778 :deadline deadline
779 :timestamp timestamp
780 :clock clock
781 :post-blank (count-lines
782 (if (not contents-end) pos-after-head
783 (goto-char contents-end)
784 (forward-line)
785 (point))
786 end)
787 :footnote-section-p footnote-section-p
788 :archivedp archivedp
789 :commentedp commentedp
790 :quotedp quotedp)
791 standard-props))))
792 (org-element-put-property
793 headline :title
794 (if raw-secondary-p raw-value
795 (org-element-parse-secondary-string
796 raw-value (org-element-restriction 'headline) headline)))))))
798 (defun org-element-headline-interpreter (headline contents)
799 "Interpret HEADLINE element as Org syntax.
800 CONTENTS is the contents of the element."
801 (let* ((level (org-element-property :level headline))
802 (todo (org-element-property :todo-keyword headline))
803 (priority (org-element-property :priority headline))
804 (title (org-element-interpret-data
805 (org-element-property :title headline)))
806 (tags (let ((tag-list (if (org-element-property :archivedp headline)
807 (cons org-archive-tag
808 (org-element-property :tags headline))
809 (org-element-property :tags headline))))
810 (and tag-list
811 (format ":%s:" (mapconcat 'identity tag-list ":")))))
812 (commentedp (org-element-property :commentedp headline))
813 (quotedp (org-element-property :quotedp headline))
814 (pre-blank (or (org-element-property :pre-blank headline) 0))
815 (heading (concat (make-string level ?*)
816 (and todo (concat " " todo))
817 (and quotedp (concat " " org-quote-string))
818 (and commentedp (concat " " org-comment-string))
819 (and priority
820 (format " [#%s]" (char-to-string priority)))
821 (cond ((and org-footnote-section
822 (org-element-property
823 :footnote-section-p headline))
824 (concat " " org-footnote-section))
825 (title (concat " " title))))))
826 (concat heading
827 ;; Align tags.
828 (when tags
829 (cond
830 ((zerop org-tags-column) (format " %s" tags))
831 ((< org-tags-column 0)
832 (concat
833 (make-string
834 (max (- (+ org-tags-column (length heading) (length tags))) 1)
836 tags))
838 (concat
839 (make-string (max (- org-tags-column (length heading)) 1) ? )
840 tags))))
841 (make-string (1+ pre-blank) 10)
842 contents)))
845 ;;;; Inlinetask
847 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
848 "Parse an inline task.
850 Return a list whose CAR is `inlinetask' and CDR is a plist
851 containing `:title', `:begin', `:end', `:hiddenp',
852 `:contents-begin' and `:contents-end', `:level', `:priority',
853 `:tags', `:todo-keyword', `:todo-type', `:scheduled',
854 `:deadline', `:timestamp', `:clock' and `:post-blank' keywords.
856 The plist also contains any property set in the property drawer,
857 with its name in lowercase, the underscores replaced with hyphens
858 and colons at the beginning (i.e. `:custom-id').
860 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
861 title will not be parsed as a secondary string, but as a plain
862 string instead.
864 Assume point is at beginning of the inline task."
865 (save-excursion
866 (let* ((keywords (org-element--collect-affiliated-keywords))
867 (begin (car keywords))
868 (components (org-heading-components))
869 (todo (nth 2 components))
870 (todo-type (and todo
871 (if (member todo org-done-keywords) 'done 'todo)))
872 (tags (let ((raw-tags (nth 5 components)))
873 (and raw-tags (org-split-string raw-tags ":"))))
874 ;; Normalize property names: ":SOME_PROP:" becomes
875 ;; ":some-prop".
876 (standard-props (let (plist)
877 (mapc
878 (lambda (p)
879 (let ((p-name (downcase (car p))))
880 (while (string-match "_" p-name)
881 (setq p-name
882 (replace-match "-" nil nil p-name)))
883 (setq p-name (intern (concat ":" p-name)))
884 (setq plist
885 (plist-put plist p-name (cdr p)))))
886 (org-entry-properties nil 'standard))
887 plist))
888 (time-props (org-entry-properties nil 'special "CLOCK"))
889 (scheduled (cdr (assoc "SCHEDULED" time-props)))
890 (deadline (cdr (assoc "DEADLINE" time-props)))
891 (clock (cdr (assoc "CLOCK" time-props)))
892 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
893 (task-end (save-excursion
894 (end-of-line)
895 (and (re-search-forward "^\\*+ END" limit t)
896 (match-beginning 0))))
897 (contents-begin (progn (forward-line)
898 (and task-end (< (point) task-end) (point))))
899 (hidden (and contents-begin (org-invisible-p2)))
900 (contents-end (and contents-begin task-end))
901 (before-blank (if (not task-end) (point)
902 (goto-char task-end)
903 (forward-line)
904 (point)))
905 (end (progn (skip-chars-forward " \r\t\n" limit)
906 (if (eobp) (point) (point-at-bol))))
907 (inlinetask
908 (list 'inlinetask
909 (nconc
910 (list :begin begin
911 :end end
912 :hiddenp hidden
913 :contents-begin contents-begin
914 :contents-end contents-end
915 :level (nth 1 components)
916 :priority (nth 3 components)
917 :tags tags
918 :todo-keyword todo
919 :todo-type todo-type
920 :scheduled scheduled
921 :deadline deadline
922 :timestamp timestamp
923 :clock clock
924 :post-blank (count-lines before-blank end))
925 standard-props
926 (cadr keywords)))))
927 (org-element-put-property
928 inlinetask :title
929 (if raw-secondary-p (nth 4 components)
930 (org-element-parse-secondary-string
931 (nth 4 components)
932 (org-element-restriction 'inlinetask)
933 inlinetask))))))
935 (defun org-element-inlinetask-interpreter (inlinetask contents)
936 "Interpret INLINETASK element as Org syntax.
937 CONTENTS is the contents of inlinetask."
938 (let* ((level (org-element-property :level inlinetask))
939 (todo (org-element-property :todo-keyword inlinetask))
940 (priority (org-element-property :priority inlinetask))
941 (title (org-element-interpret-data
942 (org-element-property :title inlinetask)))
943 (tags (let ((tag-list (org-element-property :tags inlinetask)))
944 (and tag-list
945 (format ":%s:" (mapconcat 'identity tag-list ":")))))
946 (task (concat (make-string level ?*)
947 (and todo (concat " " todo))
948 (and priority
949 (format " [#%s]" (char-to-string priority)))
950 (and title (concat " " title)))))
951 (concat task
952 ;; Align tags.
953 (when tags
954 (cond
955 ((zerop org-tags-column) (format " %s" tags))
956 ((< org-tags-column 0)
957 (concat
958 (make-string
959 (max (- (+ org-tags-column (length task) (length tags))) 1)
961 tags))
963 (concat
964 (make-string (max (- org-tags-column (length task)) 1) ? )
965 tags))))
966 ;; Prefer degenerate inlinetasks when there are no
967 ;; contents.
968 (when contents
969 (concat "\n"
970 contents
971 (make-string level ?*) " END")))))
974 ;;;; Item
976 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
977 "Parse an item.
979 STRUCT is the structure of the plain list.
981 Return a list whose CAR is `item' and CDR is a plist containing
982 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
983 `:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
984 `:post-blank' keywords.
986 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
987 any, will not be parsed as a secondary string, but as a plain
988 string instead.
990 Assume point is at the beginning of the item."
991 (save-excursion
992 (beginning-of-line)
993 (looking-at org-list-full-item-re)
994 (let* ((begin (point))
995 (bullet (org-match-string-no-properties 1))
996 (checkbox (let ((box (org-match-string-no-properties 3)))
997 (cond ((equal "[ ]" box) 'off)
998 ((equal "[X]" box) 'on)
999 ((equal "[-]" box) 'trans))))
1000 (counter (let ((c (org-match-string-no-properties 2)))
1001 (save-match-data
1002 (cond
1003 ((not c) nil)
1004 ((string-match "[A-Za-z]" c)
1005 (- (string-to-char (upcase (match-string 0 c)))
1006 64))
1007 ((string-match "[0-9]+" c)
1008 (string-to-number (match-string 0 c)))))))
1009 (end (save-excursion (goto-char (org-list-get-item-end begin struct))
1010 (unless (bolp) (forward-line))
1011 (point)))
1012 (contents-begin
1013 (progn (goto-char
1014 ;; Ignore tags in un-ordered lists: they are just
1015 ;; a part of item's body.
1016 (if (and (match-beginning 4)
1017 (save-match-data (string-match "[.)]" bullet)))
1018 (match-beginning 4)
1019 (match-end 0)))
1020 (skip-chars-forward " \r\t\n" limit)
1021 ;; If first line isn't empty, contents really start
1022 ;; at the text after item's meta-data.
1023 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1024 (hidden (progn (forward-line)
1025 (and (not (= (point) end)) (org-invisible-p2))))
1026 (contents-end (progn (goto-char end)
1027 (skip-chars-backward " \r\t\n")
1028 (forward-line)
1029 (point)))
1030 (item
1031 (list 'item
1032 (list :bullet bullet
1033 :begin begin
1034 :end end
1035 ;; CONTENTS-BEGIN and CONTENTS-END may be
1036 ;; mixed up in the case of an empty item
1037 ;; separated from the next by a blank line.
1038 ;; Thus ensure the former is always the
1039 ;; smallest.
1040 :contents-begin (min contents-begin contents-end)
1041 :contents-end (max contents-begin contents-end)
1042 :checkbox checkbox
1043 :counter counter
1044 :hiddenp hidden
1045 :structure struct
1046 :post-blank (count-lines contents-end end)))))
1047 (org-element-put-property
1048 item :tag
1049 (let ((raw-tag (org-list-get-tag begin struct)))
1050 (and raw-tag
1051 (if raw-secondary-p raw-tag
1052 (org-element-parse-secondary-string
1053 raw-tag (org-element-restriction 'item) item))))))))
1055 (defun org-element-item-interpreter (item contents)
1056 "Interpret ITEM element as Org syntax.
1057 CONTENTS is the contents of the element."
1058 (let* ((bullet (org-list-bullet-string (org-element-property :bullet item)))
1059 (checkbox (org-element-property :checkbox item))
1060 (counter (org-element-property :counter item))
1061 (tag (let ((tag (org-element-property :tag item)))
1062 (and tag (org-element-interpret-data tag))))
1063 ;; Compute indentation.
1064 (ind (make-string (length bullet) 32))
1065 (item-starts-with-par-p
1066 (eq (org-element-type (car (org-element-contents item)))
1067 'paragraph)))
1068 ;; Indent contents.
1069 (concat
1070 bullet
1071 (and counter (format "[@%d] " counter))
1072 (case checkbox
1073 (on "[X] ")
1074 (off "[ ] ")
1075 (trans "[-] "))
1076 (and tag (format "%s :: " tag))
1077 (let ((contents (replace-regexp-in-string
1078 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1079 (if item-starts-with-par-p (org-trim contents)
1080 (concat "\n" contents))))))
1083 ;;;; Plain List
1085 (defun org-element-plain-list-parser (limit &optional structure)
1086 "Parse a plain list.
1088 Optional argument STRUCTURE, when non-nil, is the structure of
1089 the plain list being parsed.
1091 Return a list whose CAR is `plain-list' and CDR is a plist
1092 containing `:type', `:begin', `:end', `:contents-begin' and
1093 `:contents-end', `:structure' and `:post-blank' keywords.
1095 Assume point is at the beginning of the list."
1096 (save-excursion
1097 (let* ((struct (or structure (org-list-struct)))
1098 (prevs (org-list-prevs-alist struct))
1099 (parents (org-list-parents-alist struct))
1100 (type (org-list-get-list-type (point) struct prevs))
1101 (contents-begin (point))
1102 (keywords (org-element--collect-affiliated-keywords))
1103 (begin (car keywords))
1104 (contents-end
1105 (progn (goto-char (org-list-get-list-end (point) struct prevs))
1106 (unless (bolp) (forward-line))
1107 (point)))
1108 (end (progn (skip-chars-forward " \r\t\n" limit)
1109 (if (eobp) (point) (point-at-bol)))))
1110 ;; Return value.
1111 (list 'plain-list
1112 (nconc
1113 (list :type type
1114 :begin begin
1115 :end end
1116 :contents-begin contents-begin
1117 :contents-end contents-end
1118 :structure struct
1119 :post-blank (count-lines contents-end end))
1120 (cadr keywords))))))
1122 (defun org-element-plain-list-interpreter (plain-list contents)
1123 "Interpret PLAIN-LIST element as Org syntax.
1124 CONTENTS is the contents of the element."
1125 (with-temp-buffer
1126 (insert contents)
1127 (goto-char (point-min))
1128 (org-list-repair)
1129 (buffer-string)))
1132 ;;;; Quote Block
1134 (defun org-element-quote-block-parser (limit)
1135 "Parse a quote block.
1137 LIMIT bounds the search.
1139 Return a list whose CAR is `quote-block' and CDR is a plist
1140 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1141 `:contents-end' and `:post-blank' keywords.
1143 Assume point is at the beginning of the block."
1144 (let ((case-fold-search t))
1145 (if (not (save-excursion
1146 (re-search-forward "^[ \t]*#\\+END_QUOTE" limit t)))
1147 ;; Incomplete block: parse it as a paragraph.
1148 (org-element-paragraph-parser limit)
1149 (let ((block-end-line (match-beginning 0)))
1150 (save-excursion
1151 (let* ((keywords (org-element--collect-affiliated-keywords))
1152 (begin (car keywords))
1153 ;; Empty blocks have no contents.
1154 (contents-begin (progn (forward-line)
1155 (and (< (point) block-end-line)
1156 (point))))
1157 (contents-end (and contents-begin block-end-line))
1158 (hidden (org-invisible-p2))
1159 (pos-before-blank (progn (goto-char block-end-line)
1160 (forward-line)
1161 (point)))
1162 (end (progn (skip-chars-forward " \r\t\n" limit)
1163 (if (eobp) (point) (point-at-bol)))))
1164 (list 'quote-block
1165 (nconc
1166 (list :begin begin
1167 :end end
1168 :hiddenp hidden
1169 :contents-begin contents-begin
1170 :contents-end contents-end
1171 :post-blank (count-lines pos-before-blank end))
1172 (cadr keywords)))))))))
1174 (defun org-element-quote-block-interpreter (quote-block contents)
1175 "Interpret QUOTE-BLOCK element as Org syntax.
1176 CONTENTS is the contents of the element."
1177 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1180 ;;;; Section
1182 (defun org-element-section-parser (limit)
1183 "Parse a section.
1185 LIMIT bounds the search.
1187 Return a list whose CAR is `section' and CDR is a plist
1188 containing `:begin', `:end', `:contents-begin', `contents-end'
1189 and `:post-blank' keywords."
1190 (save-excursion
1191 ;; Beginning of section is the beginning of the first non-blank
1192 ;; line after previous headline.
1193 (org-with-limited-levels
1194 (let ((begin (point))
1195 (end (progn (goto-char limit) (point)))
1196 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1197 (forward-line)
1198 (point))))
1199 (list 'section
1200 (list :begin begin
1201 :end end
1202 :contents-begin begin
1203 :contents-end pos-before-blank
1204 :post-blank (count-lines pos-before-blank end)))))))
1206 (defun org-element-section-interpreter (section contents)
1207 "Interpret SECTION element as Org syntax.
1208 CONTENTS is the contents of the element."
1209 contents)
1212 ;;;; Special Block
1214 (defun org-element-special-block-parser (limit)
1215 "Parse a special block.
1217 LIMIT bounds the search.
1219 Return a list whose CAR is `special-block' and CDR is a plist
1220 containing `:type', `:begin', `:end', `:hiddenp',
1221 `:contents-begin', `:contents-end' and `:post-blank' keywords.
1223 Assume point is at the beginning of the block."
1224 (let* ((case-fold-search t)
1225 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(S-+\\)")
1226 (upcase (match-string-no-properties 1)))))
1227 (if (not (save-excursion
1228 (re-search-forward (concat "^[ \t]*#\\+END_" type) limit t)))
1229 ;; Incomplete block: parse it as a paragraph.
1230 (org-element-paragraph-parser limit)
1231 (let ((block-end-line (match-beginning 0)))
1232 (save-excursion
1233 (let* ((keywords (org-element--collect-affiliated-keywords))
1234 (begin (car keywords))
1235 ;; Empty blocks have no contents.
1236 (contents-begin (progn (forward-line)
1237 (and (< (point) block-end-line)
1238 (point))))
1239 (contents-end (and contents-begin block-end-line))
1240 (hidden (org-invisible-p2))
1241 (pos-before-blank (progn (goto-char block-end-line)
1242 (forward-line)
1243 (point)))
1244 (end (progn (org-skip-whitespace)
1245 (if (eobp) (point) (point-at-bol)))))
1246 (list 'special-block
1247 (nconc
1248 (list :type type
1249 :begin begin
1250 :end end
1251 :hiddenp hidden
1252 :contents-begin contents-begin
1253 :contents-end contents-end
1254 :post-blank (count-lines pos-before-blank end))
1255 (cadr keywords)))))))))
1257 (defun org-element-special-block-interpreter (special-block contents)
1258 "Interpret SPECIAL-BLOCK element as Org syntax.
1259 CONTENTS is the contents of the element."
1260 (let ((block-type (org-element-property :type special-block)))
1261 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1265 ;;; Elements
1267 ;; For each element, a parser and an interpreter are also defined.
1268 ;; Both follow the same naming convention used for greater elements.
1270 ;; Also, as for greater elements, adding a new element type is done
1271 ;; through the following steps: implement a parser and an interpreter,
1272 ;; tweak `org-element--current-element' so that it recognizes the new
1273 ;; type and add that new type to `org-element-all-elements'.
1275 ;; As a special case, when the newly defined type is a block type,
1276 ;; `org-element-block-name-alist' has to be modified accordingly.
1279 ;;;; Babel Call
1281 (defun org-element-babel-call-parser (limit)
1282 "Parse a babel call.
1284 LIMIT bounds the search.
1286 Return a list whose CAR is `babel-call' and CDR is a plist
1287 containing `:begin', `:end', `:info' and `:post-blank' as
1288 keywords."
1289 (save-excursion
1290 (let ((case-fold-search t)
1291 (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
1292 (org-babel-lob-get-info)))
1293 (begin (point-at-bol))
1294 (pos-before-blank (progn (forward-line) (point)))
1295 (end (progn (skip-chars-forward " \r\t\n" limit)
1296 (if (eobp) (point) (point-at-bol)))))
1297 (list 'babel-call
1298 (list :begin begin
1299 :end end
1300 :info info
1301 :post-blank (count-lines pos-before-blank end))))))
1303 (defun org-element-babel-call-interpreter (babel-call contents)
1304 "Interpret BABEL-CALL element as Org syntax.
1305 CONTENTS is nil."
1306 (let* ((babel-info (org-element-property :info babel-call))
1307 (main (car babel-info))
1308 (post-options (nth 1 babel-info)))
1309 (concat "#+CALL: "
1310 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
1311 ;; Remove redundant square brackets.
1312 (replace-match (match-string 1 main) nil nil main))
1313 (and post-options (format "[%s]" post-options)))))
1316 ;;;; Clock
1318 (defun org-element-clock-parser (limit)
1319 "Parse a clock.
1321 LIMIT bounds the search.
1323 Return a list whose CAR is `clock' and CDR is a plist containing
1324 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1325 as keywords."
1326 (save-excursion
1327 (let* ((case-fold-search nil)
1328 (begin (point))
1329 (value (progn (search-forward org-clock-string (line-end-position) t)
1330 (org-skip-whitespace)
1331 (looking-at "\\[.*\\]")
1332 (org-match-string-no-properties 0)))
1333 (time (and (progn (goto-char (match-end 0))
1334 (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
1335 (org-match-string-no-properties 1)))
1336 (status (if time 'closed 'running))
1337 (post-blank (let ((before-blank (progn (forward-line) (point))))
1338 (skip-chars-forward " \r\t\n" limit)
1339 (unless (eobp) (beginning-of-line))
1340 (count-lines before-blank (point))))
1341 (end (point)))
1342 (list 'clock
1343 (list :status status
1344 :value value
1345 :time time
1346 :begin begin
1347 :end end
1348 :post-blank post-blank)))))
1350 (defun org-element-clock-interpreter (clock contents)
1351 "Interpret CLOCK element as Org syntax.
1352 CONTENTS is nil."
1353 (concat org-clock-string " "
1354 (org-element-property :value clock)
1355 (let ((time (org-element-property :time clock)))
1356 (and time
1357 (concat " => "
1358 (apply 'format
1359 "%2s:%02s"
1360 (org-split-string time ":")))))))
1363 ;;;; Comment
1365 (defun org-element-comment-parser (limit)
1366 "Parse a comment.
1368 LIMIT bounds the search.
1370 Return a list whose CAR is `comment' and CDR is a plist
1371 containing `:begin', `:end', `:value' and `:post-blank'
1372 keywords.
1374 Assume point is at comment beginning."
1375 (save-excursion
1376 (let* ((keywords (org-element--collect-affiliated-keywords))
1377 (begin (car keywords))
1378 (value (prog2 (looking-at "[ \t]*# ?")
1379 (buffer-substring-no-properties
1380 (match-end 0) (line-end-position))
1381 (forward-line)))
1382 (com-end
1383 ;; Get comments ending.
1384 (progn
1385 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1386 ;; Accumulate lines without leading hash and first
1387 ;; whitespace.
1388 (setq value
1389 (concat value
1390 "\n"
1391 (buffer-substring-no-properties
1392 (match-end 0) (line-end-position))))
1393 (forward-line))
1394 (point)))
1395 (end (progn (goto-char com-end)
1396 (skip-chars-forward " \r\t\n" limit)
1397 (if (eobp) (point) (point-at-bol)))))
1398 (list 'comment
1399 (nconc
1400 (list :begin begin
1401 :end end
1402 :value value
1403 :post-blank (count-lines com-end end))
1404 (cadr keywords))))))
1406 (defun org-element-comment-interpreter (comment contents)
1407 "Interpret COMMENT element as Org syntax.
1408 CONTENTS is nil."
1409 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1412 ;;;; Comment Block
1414 (defun org-element-comment-block-parser (limit)
1415 "Parse an export block.
1417 LIMIT bounds the search.
1419 Return a list whose CAR is `comment-block' and CDR is a plist
1420 containing `:begin', `:end', `:hiddenp', `:value' and
1421 `:post-blank' keywords.
1423 Assume point is at comment block beginning."
1424 (let ((case-fold-search t))
1425 (if (not (save-excursion
1426 (re-search-forward "^[ \t]*#\\+END_COMMENT" limit t)))
1427 ;; Incomplete block: parse it as a paragraph.
1428 (org-element-paragraph-parser limit)
1429 (let ((contents-end (match-beginning 0)))
1430 (save-excursion
1431 (let* ((keywords (org-element--collect-affiliated-keywords))
1432 (begin (car keywords))
1433 (contents-begin (progn (forward-line) (point)))
1434 (hidden (org-invisible-p2))
1435 (pos-before-blank (progn (goto-char contents-end)
1436 (forward-line)
1437 (point)))
1438 (end (progn (skip-chars-forward " \r\t\n" limit)
1439 (if (eobp) (point) (point-at-bol))))
1440 (value (buffer-substring-no-properties
1441 contents-begin contents-end)))
1442 (list 'comment-block
1443 (nconc
1444 (list :begin begin
1445 :end end
1446 :value value
1447 :hiddenp hidden
1448 :post-blank (count-lines pos-before-blank end))
1449 (cadr keywords)))))))))
1451 (defun org-element-comment-block-interpreter (comment-block contents)
1452 "Interpret COMMENT-BLOCK element as Org syntax.
1453 CONTENTS is nil."
1454 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1455 (org-remove-indentation (org-element-property :value comment-block))))
1458 ;;;; Example Block
1460 (defun org-element-example-block-parser (limit)
1461 "Parse an example block.
1463 LIMIT bounds the search.
1465 Return a list whose CAR is `example-block' and CDR is a plist
1466 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1467 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1468 `:switches', `:value' and `:post-blank' keywords."
1469 (let ((case-fold-search t))
1470 (if (not (save-excursion
1471 (re-search-forward "^[ \t]*#\\+END_EXAMPLE" limit t)))
1472 ;; Incomplete block: parse it as a paragraph.
1473 (org-element-paragraph-parser limit)
1474 (let ((contents-end (match-beginning 0)))
1475 (save-excursion
1476 (let* ((switches
1477 (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1478 (org-match-string-no-properties 1)))
1479 ;; Switches analysis
1480 (number-lines (cond ((not switches) nil)
1481 ((string-match "-n\\>" switches) 'new)
1482 ((string-match "+n\\>" switches) 'continued)))
1483 (preserve-indent (and switches (string-match "-i\\>" switches)))
1484 ;; Should labels be retained in (or stripped from) example
1485 ;; blocks?
1486 (retain-labels
1487 (or (not switches)
1488 (not (string-match "-r\\>" switches))
1489 (and number-lines (string-match "-k\\>" switches))))
1490 ;; What should code-references use - labels or
1491 ;; line-numbers?
1492 (use-labels
1493 (or (not switches)
1494 (and retain-labels (not (string-match "-k\\>" switches)))))
1495 (label-fmt (and switches
1496 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1497 (match-string 1 switches)))
1498 ;; Standard block parsing.
1499 (keywords (org-element--collect-affiliated-keywords))
1500 (begin (car keywords))
1501 (contents-begin (progn (forward-line) (point)))
1502 (hidden (org-invisible-p2))
1503 (value (buffer-substring-no-properties contents-begin contents-end))
1504 (pos-before-blank (progn (goto-char contents-end)
1505 (forward-line)
1506 (point)))
1507 (end (progn (skip-chars-forward " \r\t\n" limit)
1508 (if (eobp) (point) (point-at-bol)))))
1509 (list 'example-block
1510 (nconc
1511 (list :begin begin
1512 :end end
1513 :value value
1514 :switches switches
1515 :number-lines number-lines
1516 :preserve-indent preserve-indent
1517 :retain-labels retain-labels
1518 :use-labels use-labels
1519 :label-fmt label-fmt
1520 :hiddenp hidden
1521 :post-blank (count-lines pos-before-blank end))
1522 (cadr keywords)))))))))
1524 (defun org-element-example-block-interpreter (example-block contents)
1525 "Interpret EXAMPLE-BLOCK element as Org syntax.
1526 CONTENTS is nil."
1527 (let ((switches (org-element-property :switches example-block)))
1528 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1529 (org-remove-indentation
1530 (org-element-property :value example-block))
1531 "#+END_EXAMPLE")))
1534 ;;;; Export Block
1536 (defun org-element-export-block-parser (limit)
1537 "Parse an export block.
1539 LIMIT bounds the search.
1541 Return a list whose CAR is `export-block' and CDR is a plist
1542 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1543 `:post-blank' keywords.
1545 Assume point is at export-block beginning."
1546 (let* ((case-fold-search t)
1547 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1548 (upcase (org-match-string-no-properties 1)))))
1549 (if (not (save-excursion
1550 (re-search-forward (concat "^[ \t]*#\\+END_" type) limit t)))
1551 ;; Incomplete block: parse it as a paragraph.
1552 (org-element-paragraph-parser limit)
1553 (let ((contents-end (match-beginning 0)))
1554 (save-excursion
1555 (let* ((keywords (org-element--collect-affiliated-keywords))
1556 (begin (car keywords))
1557 (contents-begin (progn (forward-line) (point)))
1558 (hidden (org-invisible-p2))
1559 (pos-before-blank (progn (goto-char contents-end)
1560 (forward-line)
1561 (point)))
1562 (end (progn (skip-chars-forward " \r\t\n" limit)
1563 (if (eobp) (point) (point-at-bol))))
1564 (value (buffer-substring-no-properties contents-begin
1565 contents-end)))
1566 (list 'export-block
1567 (nconc
1568 (list :begin begin
1569 :end end
1570 :type type
1571 :value value
1572 :hiddenp hidden
1573 :post-blank (count-lines pos-before-blank end))
1574 (cadr keywords)))))))))
1576 (defun org-element-export-block-interpreter (export-block contents)
1577 "Interpret EXPORT-BLOCK element as Org syntax.
1578 CONTENTS is nil."
1579 (let ((type (org-element-property :type export-block)))
1580 (concat (format "#+BEGIN_%s\n" type)
1581 (org-element-property :value export-block)
1582 (format "#+END_%s" type))))
1585 ;;;; Fixed-width
1587 (defun org-element-fixed-width-parser (limit)
1588 "Parse a fixed-width section.
1590 LIMIT bounds the search.
1592 Return a list whose CAR is `fixed-width' and CDR is a plist
1593 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1595 Assume point is at the beginning of the fixed-width area."
1596 (save-excursion
1597 (let* ((keywords (org-element--collect-affiliated-keywords))
1598 (begin (car keywords))
1599 value
1600 (end-area
1601 (progn
1602 (while (and (< (point) limit)
1603 (looking-at "[ \t]*:\\( \\|$\\)"))
1604 ;; Accumulate text without starting colons.
1605 (setq value
1606 (concat value
1607 (buffer-substring-no-properties
1608 (match-end 0) (point-at-eol))
1609 "\n"))
1610 (forward-line))
1611 (point)))
1612 (end (progn (skip-chars-forward " \r\t\n" limit)
1613 (if (eobp) (point) (point-at-bol)))))
1614 (list 'fixed-width
1615 (nconc
1616 (list :begin begin
1617 :end end
1618 :value value
1619 :post-blank (count-lines end-area end))
1620 (cadr keywords))))))
1622 (defun org-element-fixed-width-interpreter (fixed-width contents)
1623 "Interpret FIXED-WIDTH element as Org syntax.
1624 CONTENTS is nil."
1625 (replace-regexp-in-string
1626 "^" ": " (substring (org-element-property :value fixed-width) 0 -1)))
1629 ;;;; Horizontal Rule
1631 (defun org-element-horizontal-rule-parser (limit)
1632 "Parse an horizontal rule.
1634 LIMIT bounds the search.
1636 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1637 containing `:begin', `:end' and `:post-blank' keywords."
1638 (save-excursion
1639 (let* ((keywords (org-element--collect-affiliated-keywords))
1640 (begin (car keywords))
1641 (post-hr (progn (forward-line) (point)))
1642 (end (progn (skip-chars-forward " \r\t\n" limit)
1643 (if (eobp) (point) (point-at-bol)))))
1644 (list 'horizontal-rule
1645 (nconc
1646 (list :begin begin
1647 :end end
1648 :post-blank (count-lines post-hr end))
1649 (cadr keywords))))))
1651 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1652 "Interpret HORIZONTAL-RULE element as Org syntax.
1653 CONTENTS is nil."
1654 "-----")
1657 ;;;; Keyword
1659 (defun org-element-keyword-parser (limit)
1660 "Parse a keyword at point.
1662 LIMIT bounds the search.
1664 Return a list whose CAR is `keyword' and CDR is a plist
1665 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1666 keywords."
1667 (save-excursion
1668 (let* ((case-fold-search t)
1669 (begin (point))
1670 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+\\):")
1671 (upcase (org-match-string-no-properties 1))))
1672 (value (org-trim (buffer-substring-no-properties
1673 (match-end 0) (point-at-eol))))
1674 (pos-before-blank (progn (forward-line) (point)))
1675 (end (progn (skip-chars-forward " \r\t\n" limit)
1676 (if (eobp) (point) (point-at-bol)))))
1677 (list 'keyword
1678 (list :key key
1679 :value value
1680 :begin begin
1681 :end end
1682 :post-blank (count-lines pos-before-blank end))))))
1684 (defun org-element-keyword-interpreter (keyword contents)
1685 "Interpret KEYWORD element as Org syntax.
1686 CONTENTS is nil."
1687 (format "#+%s: %s"
1688 (org-element-property :key keyword)
1689 (org-element-property :value keyword)))
1692 ;;;; Latex Environment
1694 (defun org-element-latex-environment-parser (limit)
1695 "Parse a LaTeX environment.
1697 LIMIT bounds the search.
1699 Return a list whose CAR is `latex-environment' and CDR is a plist
1700 containing `:begin', `:end', `:value' and `:post-blank'
1701 keywords.
1703 Assume point is at the beginning of the latex environment."
1704 (save-excursion
1705 (let* ((case-fold-search t)
1706 (code-begin (point))
1707 (keywords (org-element--collect-affiliated-keywords))
1708 (begin (car keywords))
1709 (env (progn (looking-at "^[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
1710 (regexp-quote (match-string 1))))
1711 (code-end
1712 (progn (re-search-forward (format "^[ \t]*\\\\end{%s}" env) limit t)
1713 (forward-line)
1714 (point)))
1715 (value (buffer-substring-no-properties code-begin code-end))
1716 (end (progn (skip-chars-forward " \r\t\n" limit)
1717 (if (eobp) (point) (point-at-bol)))))
1718 (list 'latex-environment
1719 (nconc
1720 (list :begin begin
1721 :end end
1722 :value value
1723 :post-blank (count-lines code-end end))
1724 (cadr keywords))))))
1726 (defun org-element-latex-environment-interpreter (latex-environment contents)
1727 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1728 CONTENTS is nil."
1729 (org-element-property :value latex-environment))
1732 ;;;; Paragraph
1734 (defun org-element-paragraph-parser (limit)
1735 "Parse a paragraph.
1737 LIMIT bounds the search.
1739 Return a list whose CAR is `paragraph' and CDR is a plist
1740 containing `:begin', `:end', `:contents-begin' and
1741 `:contents-end' and `:post-blank' keywords.
1743 Assume point is at the beginning of the paragraph."
1744 (save-excursion
1745 (let* (;; INNER-PAR-P is non-nil when paragraph is at the
1746 ;; beginning of an item or a footnote reference. In that
1747 ;; case, we mustn't look for affiliated keywords since they
1748 ;; belong to the container.
1749 (inner-par-p (not (bolp)))
1750 (contents-begin (point))
1751 (keywords (unless inner-par-p
1752 (org-element--collect-affiliated-keywords)))
1753 (begin (if inner-par-p contents-begin (car keywords)))
1754 (before-blank
1755 (let ((case-fold-search t))
1756 (end-of-line)
1757 (re-search-forward org-element-paragraph-separate limit 'm)
1758 (while (and (/= (point) limit)
1759 (cond
1760 ;; Skip non-existent or incomplete drawer.
1761 ((save-excursion
1762 (beginning-of-line)
1763 (and (looking-at "[ \t]*:\\S-")
1764 (or (not (looking-at org-drawer-regexp))
1765 (not (save-excursion
1766 (re-search-forward
1767 "^[ \t]*:END:" limit t)))))))
1768 ;; Stop at comments.
1769 ((save-excursion
1770 (beginning-of-line)
1771 (not (looking-at "[ \t]*#\\S-"))) nil)
1772 ;; Skip incomplete dynamic blocks.
1773 ((save-excursion
1774 (beginning-of-line)
1775 (looking-at "[ \t]*#\\+BEGIN: "))
1776 (not (save-excursion
1777 (re-search-forward
1778 "^[ \t]*\\+END:" limit t))))
1779 ;; Skip incomplete blocks.
1780 ((save-excursion
1781 (beginning-of-line)
1782 (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)"))
1783 (not (save-excursion
1784 (re-search-forward
1785 (concat "^[ \t]*#\\+END_"
1786 (match-string 1))
1787 limit t))))
1788 ;; Skip incomplete latex environments.
1789 ((save-excursion
1790 (beginning-of-line)
1791 (looking-at "^[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}"))
1792 (not (save-excursion
1793 (re-search-forward
1794 (format "^[ \t]*\\\\end{%s}"
1795 (match-string 1))
1796 limit t))))
1797 ;; Skip ill-formed keywords.
1798 ((not (save-excursion
1799 (beginning-of-line)
1800 (looking-at "[ \t]*#\\+\\S-+:"))))))
1801 (re-search-forward org-element-paragraph-separate limit 'm))
1802 (if (eobp) (point) (goto-char (line-beginning-position)))))
1803 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
1804 (forward-line)
1805 (point)))
1806 (end (progn (skip-chars-forward " \r\t\n" limit)
1807 (if (eobp) (point) (point-at-bol)))))
1808 (list 'paragraph
1809 (nconc
1810 (list :begin begin
1811 :end end
1812 :contents-begin contents-begin
1813 :contents-end contents-end
1814 :post-blank (count-lines before-blank end))
1815 (cadr keywords))))))
1817 (defun org-element-paragraph-interpreter (paragraph contents)
1818 "Interpret PARAGRAPH element as Org syntax.
1819 CONTENTS is the contents of the element."
1820 contents)
1823 ;;;; Planning
1825 (defun org-element-planning-parser (limit)
1826 "Parse a planning.
1828 LIMIT bounds the search.
1830 Return a list whose CAR is `planning' and CDR is a plist
1831 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
1832 and `:post-blank' keywords."
1833 (save-excursion
1834 (let* ((case-fold-search nil)
1835 (begin (point))
1836 (post-blank (let ((before-blank (progn (forward-line) (point))))
1837 (skip-chars-forward " \r\t\n" limit)
1838 (unless (eobp) (beginning-of-line))
1839 (count-lines before-blank (point))))
1840 (end (point))
1841 closed deadline scheduled)
1842 (goto-char begin)
1843 (while (re-search-forward org-keyword-time-not-clock-regexp
1844 (line-end-position) t)
1845 (goto-char (match-end 1))
1846 (org-skip-whitespace)
1847 (let ((time (buffer-substring-no-properties
1848 (1+ (point)) (1- (match-end 0))))
1849 (keyword (match-string 1)))
1850 (cond ((equal keyword org-closed-string) (setq closed time))
1851 ((equal keyword org-deadline-string) (setq deadline time))
1852 (t (setq scheduled time)))))
1853 (list 'planning
1854 (list :closed closed
1855 :deadline deadline
1856 :scheduled scheduled
1857 :begin begin
1858 :end end
1859 :post-blank post-blank)))))
1861 (defun org-element-planning-interpreter (planning contents)
1862 "Interpret PLANNING element as Org syntax.
1863 CONTENTS is nil."
1864 (mapconcat
1865 'identity
1866 (delq nil
1867 (list (let ((closed (org-element-property :closed planning)))
1868 (when closed (concat org-closed-string " [" closed "]")))
1869 (let ((deadline (org-element-property :deadline planning)))
1870 (when deadline (concat org-deadline-string " <" deadline ">")))
1871 (let ((scheduled (org-element-property :scheduled planning)))
1872 (when scheduled
1873 (concat org-scheduled-string " <" scheduled ">")))))
1874 " "))
1877 ;;;; Property Drawer
1879 (defun org-element-property-drawer-parser (limit)
1880 "Parse a property drawer.
1882 LIMIT bounds the search.
1884 Return a list whose CAR is `property-drawer' and CDR is a plist
1885 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1886 `:contents-end', `:properties' and `:post-blank' keywords.
1888 Assume point is at the beginning of the property drawer."
1889 (save-excursion
1890 (let ((case-fold-search t)
1891 (begin (point))
1892 (prop-begin (progn (forward-line) (point)))
1893 (hidden (org-invisible-p2))
1894 (properties
1895 (let (val)
1896 (while (not (looking-at "^[ \t]*:END:"))
1897 (when (looking-at "[ \t]*:\\([A-Za-z][-_A-Za-z0-9]*\\):")
1898 (push (cons (org-match-string-no-properties 1)
1899 (org-trim
1900 (buffer-substring-no-properties
1901 (match-end 0) (point-at-eol))))
1902 val))
1903 (forward-line))
1904 val))
1905 (prop-end (progn (re-search-forward "^[ \t]*:END:" limit t)
1906 (point-at-bol)))
1907 (pos-before-blank (progn (forward-line) (point)))
1908 (end (progn (skip-chars-forward " \r\t\n" limit)
1909 (if (eobp) (point) (point-at-bol)))))
1910 (list 'property-drawer
1911 (list :begin begin
1912 :end end
1913 :hiddenp hidden
1914 :properties properties
1915 :post-blank (count-lines pos-before-blank end))))))
1917 (defun org-element-property-drawer-interpreter (property-drawer contents)
1918 "Interpret PROPERTY-DRAWER element as Org syntax.
1919 CONTENTS is nil."
1920 (let ((props (org-element-property :properties property-drawer)))
1921 (concat
1922 ":PROPERTIES:\n"
1923 (mapconcat (lambda (p)
1924 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1925 (nreverse props) "\n")
1926 "\n:END:")))
1929 ;;;; Quote Section
1931 (defun org-element-quote-section-parser (limit)
1932 "Parse a quote section.
1934 LIMIT bounds the search.
1936 Return a list whose CAR is `quote-section' and CDR is a plist
1937 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1939 Assume point is at beginning of the section."
1940 (save-excursion
1941 (let* ((begin (point))
1942 (end (progn (org-with-limited-levels (outline-next-heading))
1943 (point)))
1944 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1945 (forward-line)
1946 (point)))
1947 (value (buffer-substring-no-properties begin pos-before-blank)))
1948 (list 'quote-section
1949 (list :begin begin
1950 :end end
1951 :value value
1952 :post-blank (count-lines pos-before-blank end))))))
1954 (defun org-element-quote-section-interpreter (quote-section contents)
1955 "Interpret QUOTE-SECTION element as Org syntax.
1956 CONTENTS is nil."
1957 (org-element-property :value quote-section))
1960 ;;;; Src Block
1962 (defun org-element-src-block-parser (limit)
1963 "Parse a src block.
1965 LIMIT bounds the search.
1967 Return a list whose CAR is `src-block' and CDR is a plist
1968 containing `:language', `:switches', `:parameters', `:begin',
1969 `:end', `:hiddenp', `:number-lines', `:retain-labels',
1970 `:use-labels', `:label-fmt', `:preserve-indent', `:value' and
1971 `:post-blank' keywords.
1973 Assume point is at the beginning of the block."
1974 (let ((case-fold-search t))
1975 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC" limit t)))
1976 ;; Incomplete block: parse it as a paragraph.
1977 (org-element-paragraph-parser limit)
1978 (let ((contents-end (match-beginning 0)))
1979 (save-excursion
1980 (let* ((keywords (org-element--collect-affiliated-keywords))
1981 ;; Get beginning position.
1982 (begin (car keywords))
1983 ;; Get language as a string.
1984 (language
1985 (progn
1986 (looking-at
1987 (concat "^[ \t]*#\\+BEGIN_SRC"
1988 "\\(?: +\\(\\S-+\\)\\)?"
1989 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
1990 "\\(.*\\)[ \t]*$"))
1991 (org-match-string-no-properties 1)))
1992 ;; Get switches.
1993 (switches (org-match-string-no-properties 2))
1994 ;; Get parameters.
1995 (parameters (org-match-string-no-properties 3))
1996 ;; Switches analysis
1997 (number-lines (cond ((not switches) nil)
1998 ((string-match "-n\\>" switches) 'new)
1999 ((string-match "+n\\>" switches) 'continued)))
2000 (preserve-indent (and switches (string-match "-i\\>" switches)))
2001 (label-fmt (and switches
2002 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2003 (match-string 1 switches)))
2004 ;; Should labels be retained in (or stripped from)
2005 ;; src blocks?
2006 (retain-labels
2007 (or (not switches)
2008 (not (string-match "-r\\>" switches))
2009 (and number-lines (string-match "-k\\>" switches))))
2010 ;; What should code-references use - labels or
2011 ;; line-numbers?
2012 (use-labels
2013 (or (not switches)
2014 (and retain-labels (not (string-match "-k\\>" switches)))))
2015 ;; Get visibility status.
2016 (hidden (progn (forward-line) (org-invisible-p2)))
2017 ;; Retrieve code.
2018 (value (buffer-substring-no-properties (point) contents-end))
2019 (pos-before-blank (progn (goto-char contents-end)
2020 (forward-line)
2021 (point)))
2022 ;; Get position after ending blank lines.
2023 (end (progn (skip-chars-forward " \r\t\n" limit)
2024 (if (eobp) (point) (point-at-bol)))))
2025 (list 'src-block
2026 (nconc
2027 (list :language language
2028 :switches (and (org-string-nw-p switches)
2029 (org-trim switches))
2030 :parameters (and (org-string-nw-p parameters)
2031 (org-trim parameters))
2032 :begin begin
2033 :end end
2034 :number-lines number-lines
2035 :preserve-indent preserve-indent
2036 :retain-labels retain-labels
2037 :use-labels use-labels
2038 :label-fmt label-fmt
2039 :hiddenp hidden
2040 :value value
2041 :post-blank (count-lines pos-before-blank end))
2042 (cadr keywords)))))))))
2044 (defun org-element-src-block-interpreter (src-block contents)
2045 "Interpret SRC-BLOCK element as Org syntax.
2046 CONTENTS is nil."
2047 (let ((lang (org-element-property :language src-block))
2048 (switches (org-element-property :switches src-block))
2049 (params (org-element-property :parameters src-block))
2050 (value (let ((val (org-element-property :value src-block)))
2051 (cond
2053 (org-src-preserve-indentation val)
2054 ((zerop org-edit-src-content-indentation)
2055 (org-remove-indentation val))
2057 (let ((ind (make-string
2058 org-edit-src-content-indentation 32)))
2059 (replace-regexp-in-string
2060 "\\(^\\)[ \t]*\\S-" ind
2061 (org-remove-indentation val) nil nil 1)))))))
2062 (concat (format "#+BEGIN_SRC%s\n"
2063 (concat (and lang (concat " " lang))
2064 (and switches (concat " " switches))
2065 (and params (concat " " params))))
2066 value
2067 "#+END_SRC")))
2070 ;;;; Table
2072 (defun org-element-table-parser (limit)
2073 "Parse a table at point.
2075 LIMIT bounds the search.
2077 Return a list whose CAR is `table' and CDR is a plist containing
2078 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2079 `:contents-end', `:value' and `:post-blank' keywords.
2081 Assume point is at the beginning of the table."
2082 (save-excursion
2083 (let* ((case-fold-search t)
2084 (table-begin (point))
2085 (type (if (org-at-table.el-p) 'table.el 'org))
2086 (keywords (org-element--collect-affiliated-keywords))
2087 (begin (car keywords))
2088 (table-end (goto-char (marker-position (org-table-end t))))
2089 (tblfm (let (acc)
2090 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2091 (push (org-match-string-no-properties 1) acc)
2092 (forward-line))
2093 acc))
2094 (pos-before-blank (point))
2095 (end (progn (skip-chars-forward " \r\t\n" limit)
2096 (if (eobp) (point) (point-at-bol)))))
2097 (list 'table
2098 (nconc
2099 (list :begin begin
2100 :end end
2101 :type type
2102 :tblfm tblfm
2103 ;; Only `org' tables have contents. `table.el' tables
2104 ;; use a `:value' property to store raw table as
2105 ;; a string.
2106 :contents-begin (and (eq type 'org) table-begin)
2107 :contents-end (and (eq type 'org) table-end)
2108 :value (and (eq type 'table.el)
2109 (buffer-substring-no-properties
2110 table-begin table-end))
2111 :post-blank (count-lines pos-before-blank end))
2112 (cadr keywords))))))
2114 (defun org-element-table-interpreter (table contents)
2115 "Interpret TABLE element as Org syntax.
2116 CONTENTS is nil."
2117 (if (eq (org-element-property :type table) 'table.el)
2118 (org-remove-indentation (org-element-property :value table))
2119 (concat (with-temp-buffer (insert contents)
2120 (org-table-align)
2121 (buffer-string))
2122 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2123 (reverse (org-element-property :tblfm table))
2124 "\n"))))
2127 ;;;; Table Row
2129 (defun org-element-table-row-parser (limit)
2130 "Parse table row at point.
2132 LIMIT bounds the search.
2134 Return a list whose CAR is `table-row' and CDR is a plist
2135 containing `:begin', `:end', `:contents-begin', `:contents-end',
2136 `:type' and `:post-blank' keywords."
2137 (save-excursion
2138 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2139 (begin (point))
2140 ;; A table rule has no contents. In that case, ensure
2141 ;; CONTENTS-BEGIN matches CONTENTS-END.
2142 (contents-begin (and (eq type 'standard)
2143 (search-forward "|")
2144 (point)))
2145 (contents-end (and (eq type 'standard)
2146 (progn
2147 (end-of-line)
2148 (skip-chars-backward " \t")
2149 (point))))
2150 (end (progn (forward-line) (point))))
2151 (list 'table-row
2152 (list :type type
2153 :begin begin
2154 :end end
2155 :contents-begin contents-begin
2156 :contents-end contents-end
2157 :post-blank 0)))))
2159 (defun org-element-table-row-interpreter (table-row contents)
2160 "Interpret TABLE-ROW element as Org syntax.
2161 CONTENTS is the contents of the table row."
2162 (if (eq (org-element-property :type table-row) 'rule) "|-"
2163 (concat "| " contents)))
2166 ;;;; Verse Block
2168 (defun org-element-verse-block-parser (limit)
2169 "Parse a verse block.
2171 LIMIT bounds the search.
2173 Return a list whose CAR is `verse-block' and CDR is a plist
2174 containing `:begin', `:end', `:contents-begin', `:contents-end',
2175 `:hiddenp' and `:post-blank' keywords.
2177 Assume point is at beginning of the block."
2178 (let ((case-fold-search t))
2179 (if (not (save-excursion
2180 (re-search-forward "^[ \t]*#\\+END_VERSE" limit t)))
2181 ;; Incomplete block: parse it as a paragraph.
2182 (org-element-paragraph-parser limit)
2183 (let ((contents-end (match-beginning 0)))
2184 (save-excursion
2185 (let* ((keywords (org-element--collect-affiliated-keywords))
2186 (begin (car keywords))
2187 (hidden (progn (forward-line) (org-invisible-p2)))
2188 (contents-begin (point))
2189 (pos-before-blank (progn (goto-char contents-end)
2190 (forward-line)
2191 (point)))
2192 (end (progn (skip-chars-forward " \r\t\n" limit)
2193 (if (eobp) (point) (point-at-bol)))))
2194 (list 'verse-block
2195 (nconc
2196 (list :begin begin
2197 :end end
2198 :contents-begin contents-begin
2199 :contents-end contents-end
2200 :hiddenp hidden
2201 :post-blank (count-lines pos-before-blank end))
2202 (cadr keywords)))))))))
2204 (defun org-element-verse-block-interpreter (verse-block contents)
2205 "Interpret VERSE-BLOCK element as Org syntax.
2206 CONTENTS is verse block contents."
2207 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2211 ;;; Objects
2213 ;; Unlike to elements, interstices can be found between objects.
2214 ;; That's why, along with the parser, successor functions are provided
2215 ;; for each object. Some objects share the same successor (i.e. `code'
2216 ;; and `verbatim' objects).
2218 ;; A successor must accept a single argument bounding the search. It
2219 ;; will return either a cons cell whose CAR is the object's type, as
2220 ;; a symbol, and CDR the position of its next occurrence, or nil.
2222 ;; Successors follow the naming convention:
2223 ;; org-element-NAME-successor, where NAME is the name of the
2224 ;; successor, as defined in `org-element-all-successors'.
2226 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2227 ;; object types they can contain will be specified in
2228 ;; `org-element-object-restrictions'.
2230 ;; Adding a new type of object is simple. Implement a successor,
2231 ;; a parser, and an interpreter for it, all following the naming
2232 ;; convention. Register type in `org-element-all-objects' and
2233 ;; successor in `org-element-all-successors'. Maybe tweak
2234 ;; restrictions about it, and that's it.
2237 ;;;; Bold
2239 (defun org-element-bold-parser ()
2240 "Parse bold object at point.
2242 Return a list whose CAR is `bold' and CDR is a plist with
2243 `:begin', `:end', `:contents-begin' and `:contents-end' and
2244 `:post-blank' keywords.
2246 Assume point is at the first star marker."
2247 (save-excursion
2248 (unless (bolp) (backward-char 1))
2249 (looking-at org-emph-re)
2250 (let ((begin (match-beginning 2))
2251 (contents-begin (match-beginning 4))
2252 (contents-end (match-end 4))
2253 (post-blank (progn (goto-char (match-end 2))
2254 (skip-chars-forward " \t")))
2255 (end (point)))
2256 (list 'bold
2257 (list :begin begin
2258 :end end
2259 :contents-begin contents-begin
2260 :contents-end contents-end
2261 :post-blank post-blank)))))
2263 (defun org-element-bold-interpreter (bold contents)
2264 "Interpret BOLD object as Org syntax.
2265 CONTENTS is the contents of the object."
2266 (format "*%s*" contents))
2268 (defun org-element-text-markup-successor (limit)
2269 "Search for the next text-markup object.
2271 LIMIT bounds the search.
2273 Return value is a cons cell whose CAR is a symbol among `bold',
2274 `italic', `underline', `strike-through', `code' and `verbatim'
2275 and CDR is beginning position."
2276 (save-excursion
2277 (unless (bolp) (backward-char))
2278 (when (re-search-forward org-emph-re limit t)
2279 (let ((marker (match-string 3)))
2280 (cons (cond
2281 ((equal marker "*") 'bold)
2282 ((equal marker "/") 'italic)
2283 ((equal marker "_") 'underline)
2284 ((equal marker "+") 'strike-through)
2285 ((equal marker "~") 'code)
2286 ((equal marker "=") 'verbatim)
2287 (t (error "Unknown marker at %d" (match-beginning 3))))
2288 (match-beginning 2))))))
2291 ;;;; Code
2293 (defun org-element-code-parser ()
2294 "Parse code object at point.
2296 Return a list whose CAR is `code' and CDR is a plist with
2297 `:value', `:begin', `:end' and `:post-blank' keywords.
2299 Assume point is at the first tilde marker."
2300 (save-excursion
2301 (unless (bolp) (backward-char 1))
2302 (looking-at org-emph-re)
2303 (let ((begin (match-beginning 2))
2304 (value (org-match-string-no-properties 4))
2305 (post-blank (progn (goto-char (match-end 2))
2306 (skip-chars-forward " \t")))
2307 (end (point)))
2308 (list 'code
2309 (list :value value
2310 :begin begin
2311 :end end
2312 :post-blank post-blank)))))
2314 (defun org-element-code-interpreter (code contents)
2315 "Interpret CODE object as Org syntax.
2316 CONTENTS is nil."
2317 (format "~%s~" (org-element-property :value code)))
2320 ;;;; Entity
2322 (defun org-element-entity-parser ()
2323 "Parse entity at point.
2325 Return a list whose CAR is `entity' and CDR a plist with
2326 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2327 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2328 keywords.
2330 Assume point is at the beginning of the entity."
2331 (save-excursion
2332 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2333 (let* ((value (org-entity-get (match-string 1)))
2334 (begin (match-beginning 0))
2335 (bracketsp (string= (match-string 2) "{}"))
2336 (post-blank (progn (goto-char (match-end 1))
2337 (when bracketsp (forward-char 2))
2338 (skip-chars-forward " \t")))
2339 (end (point)))
2340 (list 'entity
2341 (list :name (car value)
2342 :latex (nth 1 value)
2343 :latex-math-p (nth 2 value)
2344 :html (nth 3 value)
2345 :ascii (nth 4 value)
2346 :latin1 (nth 5 value)
2347 :utf-8 (nth 6 value)
2348 :begin begin
2349 :end end
2350 :use-brackets-p bracketsp
2351 :post-blank post-blank)))))
2353 (defun org-element-entity-interpreter (entity contents)
2354 "Interpret ENTITY object as Org syntax.
2355 CONTENTS is nil."
2356 (concat "\\"
2357 (org-element-property :name entity)
2358 (when (org-element-property :use-brackets-p entity) "{}")))
2360 (defun org-element-latex-or-entity-successor (limit)
2361 "Search for the next latex-fragment or entity object.
2363 LIMIT bounds the search.
2365 Return value is a cons cell whose CAR is `entity' or
2366 `latex-fragment' and CDR is beginning position."
2367 (save-excursion
2368 (let ((matchers
2369 (remove "begin" (plist-get org-format-latex-options :matchers)))
2370 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2371 (entity-re
2372 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2373 (when (re-search-forward
2374 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
2375 matchers "\\|")
2376 "\\|" entity-re)
2377 limit t)
2378 (goto-char (match-beginning 0))
2379 (if (looking-at entity-re)
2380 ;; Determine if it's a real entity or a LaTeX command.
2381 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2382 (match-beginning 0))
2383 ;; No entity nor command: point is at a LaTeX fragment.
2384 ;; Determine its type to get the correct beginning position.
2385 (cons 'latex-fragment
2386 (catch 'return
2387 (mapc (lambda (e)
2388 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
2389 (throw 'return
2390 (match-beginning
2391 (nth 2 (assoc e org-latex-regexps))))))
2392 matchers)
2393 (point))))))))
2396 ;;;; Export Snippet
2398 (defun org-element-export-snippet-parser ()
2399 "Parse export snippet at point.
2401 Return a list whose CAR is `export-snippet' and CDR a plist with
2402 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2403 keywords.
2405 Assume point is at the beginning of the snippet."
2406 (save-excursion
2407 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2408 (let* ((begin (match-beginning 0))
2409 (back-end (org-match-string-no-properties 1))
2410 (value (buffer-substring-no-properties
2411 (point)
2412 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2413 (post-blank (skip-chars-forward " \t"))
2414 (end (point)))
2415 (list 'export-snippet
2416 (list :back-end back-end
2417 :value value
2418 :begin begin
2419 :end end
2420 :post-blank post-blank)))))
2422 (defun org-element-export-snippet-interpreter (export-snippet contents)
2423 "Interpret EXPORT-SNIPPET object as Org syntax.
2424 CONTENTS is nil."
2425 (format "@@%s:%s@@"
2426 (org-element-property :back-end export-snippet)
2427 (org-element-property :value export-snippet)))
2429 (defun org-element-export-snippet-successor (limit)
2430 "Search for the next export-snippet object.
2432 LIMIT bounds the search.
2434 Return value is a cons cell whose CAR is `export-snippet' and CDR
2435 its beginning position."
2436 (save-excursion
2437 (let (beg)
2438 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" limit t)
2439 (setq beg (match-beginning 0))
2440 (search-forward "@@" limit t))
2441 (cons 'export-snippet beg)))))
2444 ;;;; Footnote Reference
2446 (defun org-element-footnote-reference-parser ()
2447 "Parse footnote reference at point.
2449 Return a list whose CAR is `footnote-reference' and CDR a plist
2450 with `:label', `:type', `:inline-definition', `:begin', `:end'
2451 and `:post-blank' as keywords."
2452 (save-excursion
2453 (looking-at org-footnote-re)
2454 (let* ((begin (point))
2455 (label (or (org-match-string-no-properties 2)
2456 (org-match-string-no-properties 3)
2457 (and (match-string 1)
2458 (concat "fn:" (org-match-string-no-properties 1)))))
2459 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2460 (inner-begin (match-end 0))
2461 (inner-end
2462 (let ((count 1))
2463 (forward-char)
2464 (while (and (> count 0) (re-search-forward "[][]" nil t))
2465 (if (equal (match-string 0) "[") (incf count) (decf count)))
2466 (1- (point))))
2467 (post-blank (progn (goto-char (1+ inner-end))
2468 (skip-chars-forward " \t")))
2469 (end (point))
2470 (footnote-reference
2471 (list 'footnote-reference
2472 (list :label label
2473 :type type
2474 :begin begin
2475 :end end
2476 :post-blank post-blank))))
2477 (org-element-put-property
2478 footnote-reference :inline-definition
2479 (and (eq type 'inline)
2480 (org-element-parse-secondary-string
2481 (buffer-substring inner-begin inner-end)
2482 (org-element-restriction 'footnote-reference)
2483 footnote-reference))))))
2485 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2486 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2487 CONTENTS is nil."
2488 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2489 (def
2490 (let ((inline-def
2491 (org-element-property :inline-definition footnote-reference)))
2492 (if (not inline-def) ""
2493 (concat ":" (org-element-interpret-data inline-def))))))
2494 (format "[%s]" (concat label def))))
2496 (defun org-element-footnote-reference-successor (limit)
2497 "Search for the next footnote-reference object.
2499 LIMIT bounds the search.
2501 Return value is a cons cell whose CAR is `footnote-reference' and
2502 CDR is beginning position."
2503 (save-excursion
2504 (catch 'exit
2505 (while (re-search-forward org-footnote-re limit t)
2506 (save-excursion
2507 (let ((beg (match-beginning 0))
2508 (count 1))
2509 (backward-char)
2510 (while (re-search-forward "[][]" limit t)
2511 (if (equal (match-string 0) "[") (incf count) (decf count))
2512 (when (zerop count)
2513 (throw 'exit (cons 'footnote-reference beg))))))))))
2516 ;;;; Inline Babel Call
2518 (defun org-element-inline-babel-call-parser ()
2519 "Parse inline babel call at point.
2521 Return a list whose CAR is `inline-babel-call' and CDR a plist
2522 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2524 Assume point is at the beginning of the babel call."
2525 (save-excursion
2526 (unless (bolp) (backward-char))
2527 (looking-at org-babel-inline-lob-one-liner-regexp)
2528 (let ((info (save-match-data (org-babel-lob-get-info)))
2529 (begin (match-end 1))
2530 (post-blank (progn (goto-char (match-end 0))
2531 (skip-chars-forward " \t")))
2532 (end (point)))
2533 (list 'inline-babel-call
2534 (list :begin begin
2535 :end end
2536 :info info
2537 :post-blank post-blank)))))
2539 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2540 "Interpret INLINE-BABEL-CALL object as Org syntax.
2541 CONTENTS is nil."
2542 (let* ((babel-info (org-element-property :info inline-babel-call))
2543 (main-source (car babel-info))
2544 (post-options (nth 1 babel-info)))
2545 (concat "call_"
2546 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2547 ;; Remove redundant square brackets.
2548 (replace-match
2549 (match-string 1 main-source) nil nil main-source)
2550 main-source)
2551 (and post-options (format "[%s]" post-options)))))
2553 (defun org-element-inline-babel-call-successor (limit)
2554 "Search for the next inline-babel-call object.
2556 LIMIT bounds the search.
2558 Return value is a cons cell whose CAR is `inline-babel-call' and
2559 CDR is beginning position."
2560 (save-excursion
2561 ;; Use a simplified version of
2562 ;; `org-babel-inline-lob-one-liner-regexp'.
2563 (when (re-search-forward
2564 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2565 limit t)
2566 (cons 'inline-babel-call (match-beginning 0)))))
2569 ;;;; Inline Src Block
2571 (defun org-element-inline-src-block-parser ()
2572 "Parse inline source block at point.
2574 LIMIT bounds the search.
2576 Return a list whose CAR is `inline-src-block' and CDR a plist
2577 with `:begin', `:end', `:language', `:value', `:parameters' and
2578 `:post-blank' as keywords.
2580 Assume point is at the beginning of the inline src block."
2581 (save-excursion
2582 (unless (bolp) (backward-char))
2583 (looking-at org-babel-inline-src-block-regexp)
2584 (let ((begin (match-beginning 1))
2585 (language (org-match-string-no-properties 2))
2586 (parameters (org-match-string-no-properties 4))
2587 (value (org-match-string-no-properties 5))
2588 (post-blank (progn (goto-char (match-end 0))
2589 (skip-chars-forward " \t")))
2590 (end (point)))
2591 (list 'inline-src-block
2592 (list :language language
2593 :value value
2594 :parameters parameters
2595 :begin begin
2596 :end end
2597 :post-blank post-blank)))))
2599 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2600 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2601 CONTENTS is nil."
2602 (let ((language (org-element-property :language inline-src-block))
2603 (arguments (org-element-property :parameters inline-src-block))
2604 (body (org-element-property :value inline-src-block)))
2605 (format "src_%s%s{%s}"
2606 language
2607 (if arguments (format "[%s]" arguments) "")
2608 body)))
2610 (defun org-element-inline-src-block-successor (limit)
2611 "Search for the next inline-babel-call element.
2613 LIMIT bounds the search.
2615 Return value is a cons cell whose CAR is `inline-babel-call' and
2616 CDR is beginning position."
2617 (save-excursion
2618 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
2619 (cons 'inline-src-block (match-beginning 1)))))
2621 ;;;; Italic
2623 (defun org-element-italic-parser ()
2624 "Parse italic object at point.
2626 Return a list whose CAR is `italic' and CDR is a plist with
2627 `:begin', `:end', `:contents-begin' and `:contents-end' and
2628 `:post-blank' keywords.
2630 Assume point is at the first slash marker."
2631 (save-excursion
2632 (unless (bolp) (backward-char 1))
2633 (looking-at org-emph-re)
2634 (let ((begin (match-beginning 2))
2635 (contents-begin (match-beginning 4))
2636 (contents-end (match-end 4))
2637 (post-blank (progn (goto-char (match-end 2))
2638 (skip-chars-forward " \t")))
2639 (end (point)))
2640 (list 'italic
2641 (list :begin begin
2642 :end end
2643 :contents-begin contents-begin
2644 :contents-end contents-end
2645 :post-blank post-blank)))))
2647 (defun org-element-italic-interpreter (italic contents)
2648 "Interpret ITALIC object as Org syntax.
2649 CONTENTS is the contents of the object."
2650 (format "/%s/" contents))
2653 ;;;; Latex Fragment
2655 (defun org-element-latex-fragment-parser ()
2656 "Parse latex fragment at point.
2658 Return a list whose CAR is `latex-fragment' and CDR a plist with
2659 `:value', `:begin', `:end', and `:post-blank' as keywords.
2661 Assume point is at the beginning of the latex fragment."
2662 (save-excursion
2663 (let* ((begin (point))
2664 (substring-match
2665 (catch 'exit
2666 (mapc (lambda (e)
2667 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2668 (when (or (looking-at latex-regexp)
2669 (and (not (bobp))
2670 (save-excursion
2671 (backward-char)
2672 (looking-at latex-regexp))))
2673 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2674 (plist-get org-format-latex-options :matchers))
2675 ;; None found: it's a macro.
2676 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2678 (value (match-string-no-properties substring-match))
2679 (post-blank (progn (goto-char (match-end substring-match))
2680 (skip-chars-forward " \t")))
2681 (end (point)))
2682 (list 'latex-fragment
2683 (list :value value
2684 :begin begin
2685 :end end
2686 :post-blank post-blank)))))
2688 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2689 "Interpret LATEX-FRAGMENT object as Org syntax.
2690 CONTENTS is nil."
2691 (org-element-property :value latex-fragment))
2693 ;;;; Line Break
2695 (defun org-element-line-break-parser ()
2696 "Parse line break at point.
2698 Return a list whose CAR is `line-break', and CDR a plist with
2699 `:begin', `:end' and `:post-blank' keywords.
2701 Assume point is at the beginning of the line break."
2702 (list 'line-break (list :begin (point) :end (point-at-eol) :post-blank 0)))
2704 (defun org-element-line-break-interpreter (line-break contents)
2705 "Interpret LINE-BREAK object as Org syntax.
2706 CONTENTS is nil."
2707 "\\\\")
2709 (defun org-element-line-break-successor (limit)
2710 "Search for the next line-break object.
2712 LIMIT bounds the search.
2714 Return value is a cons cell whose CAR is `line-break' and CDR is
2715 beginning position."
2716 (save-excursion
2717 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2718 (goto-char (match-beginning 1)))))
2719 ;; A line break can only happen on a non-empty line.
2720 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2721 (cons 'line-break beg)))))
2724 ;;;; Link
2726 (defun org-element-link-parser ()
2727 "Parse link at point.
2729 Return a list whose CAR is `link' and CDR a plist with `:type',
2730 `:path', `:raw-link', `:application', `:search-option', `:begin',
2731 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
2732 keywords.
2734 Assume point is at the beginning of the link."
2735 (save-excursion
2736 (let ((begin (point))
2737 end contents-begin contents-end link-end post-blank path type
2738 raw-link link search-option application)
2739 (cond
2740 ;; Type 1: Text targeted from a radio target.
2741 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2742 (setq type "radio"
2743 link-end (match-end 0)
2744 path (org-match-string-no-properties 0)))
2745 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2746 ((looking-at org-bracket-link-regexp)
2747 (setq contents-begin (match-beginning 3)
2748 contents-end (match-end 3)
2749 link-end (match-end 0)
2750 ;; RAW-LINK is the original link.
2751 raw-link (org-match-string-no-properties 1)
2752 link (org-translate-link
2753 (org-link-expand-abbrev
2754 (org-link-unescape raw-link))))
2755 ;; Determine TYPE of link and set PATH accordingly.
2756 (cond
2757 ;; File type.
2758 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2759 (setq type "file" path link))
2760 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2761 ((string-match org-link-re-with-space3 link)
2762 (setq type (match-string 1 link) path (match-string 2 link)))
2763 ;; Id type: PATH is the id.
2764 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2765 (setq type "id" path (match-string 1 link)))
2766 ;; Code-ref type: PATH is the name of the reference.
2767 ((string-match "^(\\(.*\\))$" link)
2768 (setq type "coderef" path (match-string 1 link)))
2769 ;; Custom-id type: PATH is the name of the custom id.
2770 ((= (aref link 0) ?#)
2771 (setq type "custom-id" path (substring link 1)))
2772 ;; Fuzzy type: Internal link either matches a target, an
2773 ;; headline name or nothing. PATH is the target or
2774 ;; headline's name.
2775 (t (setq type "fuzzy" path link))))
2776 ;; Type 3: Plain link, i.e. http://orgmode.org
2777 ((looking-at org-plain-link-re)
2778 (setq raw-link (org-match-string-no-properties 0)
2779 type (org-match-string-no-properties 1)
2780 path (org-match-string-no-properties 2)
2781 link-end (match-end 0)))
2782 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2783 ((looking-at org-angle-link-re)
2784 (setq raw-link (buffer-substring-no-properties
2785 (match-beginning 1) (match-end 2))
2786 type (org-match-string-no-properties 1)
2787 path (org-match-string-no-properties 2)
2788 link-end (match-end 0))))
2789 ;; In any case, deduce end point after trailing white space from
2790 ;; LINK-END variable.
2791 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2792 end (point))
2793 ;; Extract search option and opening application out of
2794 ;; "file"-type links.
2795 (when (member type org-element-link-type-is-file)
2796 ;; Application.
2797 (cond ((string-match "^file\\+\\(.*\\)$" type)
2798 (setq application (match-string 1 type)))
2799 ((not (string-match "^file" type))
2800 (setq application type)))
2801 ;; Extract search option from PATH.
2802 (when (string-match "::\\(.*\\)$" path)
2803 (setq search-option (match-string 1 path)
2804 path (replace-match "" nil nil path)))
2805 ;; Make sure TYPE always report "file".
2806 (setq type "file"))
2807 (list 'link
2808 (list :type type
2809 :path path
2810 :raw-link (or raw-link path)
2811 :application application
2812 :search-option search-option
2813 :begin begin
2814 :end end
2815 :contents-begin contents-begin
2816 :contents-end contents-end
2817 :post-blank post-blank)))))
2819 (defun org-element-link-interpreter (link contents)
2820 "Interpret LINK object as Org syntax.
2821 CONTENTS is the contents of the object, or nil."
2822 (let ((type (org-element-property :type link))
2823 (raw-link (org-element-property :raw-link link)))
2824 (if (string= type "radio") raw-link
2825 (format "[[%s]%s]"
2826 raw-link
2827 (if contents (format "[%s]" contents) "")))))
2829 (defun org-element-link-successor (limit)
2830 "Search for the next link object.
2832 LIMIT bounds the search.
2834 Return value is a cons cell whose CAR is `link' and CDR is
2835 beginning position."
2836 (save-excursion
2837 (let ((link-regexp
2838 (if (not org-target-link-regexp) org-any-link-re
2839 (concat org-any-link-re "\\|" org-target-link-regexp))))
2840 (when (re-search-forward link-regexp limit t)
2841 (cons 'link (match-beginning 0))))))
2844 ;;;; Macro
2846 (defun org-element-macro-parser ()
2847 "Parse macro at point.
2849 Return a list whose CAR is `macro' and CDR a plist with `:key',
2850 `:args', `:begin', `:end', `:value' and `:post-blank' as
2851 keywords.
2853 Assume point is at the macro."
2854 (save-excursion
2855 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2856 (let ((begin (point))
2857 (key (downcase (org-match-string-no-properties 1)))
2858 (value (org-match-string-no-properties 0))
2859 (post-blank (progn (goto-char (match-end 0))
2860 (skip-chars-forward " \t")))
2861 (end (point))
2862 (args (let ((args (org-match-string-no-properties 3)) args2)
2863 (when args
2864 (setq args (org-split-string args ","))
2865 (while args
2866 (while (string-match "\\\\\\'" (car args))
2867 ;; Repair bad splits.
2868 (setcar (cdr args) (concat (substring (car args) 0 -1)
2869 "," (nth 1 args)))
2870 (pop args))
2871 (push (pop args) args2))
2872 (mapcar 'org-trim (nreverse args2))))))
2873 (list 'macro
2874 (list :key key
2875 :value value
2876 :args args
2877 :begin begin
2878 :end end
2879 :post-blank post-blank)))))
2881 (defun org-element-macro-interpreter (macro contents)
2882 "Interpret MACRO object as Org syntax.
2883 CONTENTS is nil."
2884 (org-element-property :value macro))
2886 (defun org-element-macro-successor (limit)
2887 "Search for the next macro object.
2889 LIMIT bounds the search.
2891 Return value is cons cell whose CAR is `macro' and CDR is
2892 beginning position."
2893 (save-excursion
2894 (when (re-search-forward
2895 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2896 limit t)
2897 (cons 'macro (match-beginning 0)))))
2900 ;;;; Radio-target
2902 (defun org-element-radio-target-parser ()
2903 "Parse radio target at point.
2905 Return a list whose CAR is `radio-target' and CDR a plist with
2906 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2907 and `:post-blank' as keywords.
2909 Assume point is at the radio target."
2910 (save-excursion
2911 (looking-at org-radio-target-regexp)
2912 (let ((begin (point))
2913 (contents-begin (match-beginning 1))
2914 (contents-end (match-end 1))
2915 (value (org-match-string-no-properties 1))
2916 (post-blank (progn (goto-char (match-end 0))
2917 (skip-chars-forward " \t")))
2918 (end (point)))
2919 (list 'radio-target
2920 (list :begin begin
2921 :end end
2922 :contents-begin contents-begin
2923 :contents-end contents-end
2924 :post-blank post-blank
2925 :value value)))))
2927 (defun org-element-radio-target-interpreter (target contents)
2928 "Interpret TARGET object as Org syntax.
2929 CONTENTS is the contents of the object."
2930 (concat "<<<" contents ">>>"))
2932 (defun org-element-radio-target-successor (limit)
2933 "Search for the next radio-target object.
2935 LIMIT bounds the search.
2937 Return value is a cons cell whose CAR is `radio-target' and CDR
2938 is beginning position."
2939 (save-excursion
2940 (when (re-search-forward org-radio-target-regexp limit t)
2941 (cons 'radio-target (match-beginning 0)))))
2944 ;;;; Statistics Cookie
2946 (defun org-element-statistics-cookie-parser ()
2947 "Parse statistics cookie at point.
2949 Return a list whose CAR is `statistics-cookie', and CDR a plist
2950 with `:begin', `:end', `:value' and `:post-blank' keywords.
2952 Assume point is at the beginning of the statistics-cookie."
2953 (save-excursion
2954 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2955 (let* ((begin (point))
2956 (value (buffer-substring-no-properties
2957 (match-beginning 0) (match-end 0)))
2958 (post-blank (progn (goto-char (match-end 0))
2959 (skip-chars-forward " \t")))
2960 (end (point)))
2961 (list 'statistics-cookie
2962 (list :begin begin
2963 :end end
2964 :value value
2965 :post-blank post-blank)))))
2967 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2968 "Interpret STATISTICS-COOKIE object as Org syntax.
2969 CONTENTS is nil."
2970 (org-element-property :value statistics-cookie))
2972 (defun org-element-statistics-cookie-successor (limit)
2973 "Search for the next statistics cookie object.
2975 LIMIT bounds the search.
2977 Return value is a cons cell whose CAR is `statistics-cookie' and
2978 CDR is beginning position."
2979 (save-excursion
2980 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2981 (cons 'statistics-cookie (match-beginning 0)))))
2984 ;;;; Strike-Through
2986 (defun org-element-strike-through-parser ()
2987 "Parse strike-through object at point.
2989 Return a list whose CAR is `strike-through' and CDR is a plist
2990 with `:begin', `:end', `:contents-begin' and `:contents-end' and
2991 `:post-blank' keywords.
2993 Assume point is at the first plus sign marker."
2994 (save-excursion
2995 (unless (bolp) (backward-char 1))
2996 (looking-at org-emph-re)
2997 (let ((begin (match-beginning 2))
2998 (contents-begin (match-beginning 4))
2999 (contents-end (match-end 4))
3000 (post-blank (progn (goto-char (match-end 2))
3001 (skip-chars-forward " \t")))
3002 (end (point)))
3003 (list 'strike-through
3004 (list :begin begin
3005 :end end
3006 :contents-begin contents-begin
3007 :contents-end contents-end
3008 :post-blank post-blank)))))
3010 (defun org-element-strike-through-interpreter (strike-through contents)
3011 "Interpret STRIKE-THROUGH object as Org syntax.
3012 CONTENTS is the contents of the object."
3013 (format "+%s+" contents))
3016 ;;;; Subscript
3018 (defun org-element-subscript-parser ()
3019 "Parse subscript at point.
3021 Return a list whose CAR is `subscript' and CDR a plist with
3022 `:begin', `:end', `:contents-begin', `:contents-end',
3023 `:use-brackets-p' and `:post-blank' as keywords.
3025 Assume point is at the underscore."
3026 (save-excursion
3027 (unless (bolp) (backward-char))
3028 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3030 (not (looking-at org-match-substring-regexp))))
3031 (begin (match-beginning 2))
3032 (contents-begin (or (match-beginning 5)
3033 (match-beginning 3)))
3034 (contents-end (or (match-end 5) (match-end 3)))
3035 (post-blank (progn (goto-char (match-end 0))
3036 (skip-chars-forward " \t")))
3037 (end (point)))
3038 (list 'subscript
3039 (list :begin begin
3040 :end end
3041 :use-brackets-p bracketsp
3042 :contents-begin contents-begin
3043 :contents-end contents-end
3044 :post-blank post-blank)))))
3046 (defun org-element-subscript-interpreter (subscript contents)
3047 "Interpret SUBSCRIPT object as Org syntax.
3048 CONTENTS is the contents of the object."
3049 (format
3050 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3051 contents))
3053 (defun org-element-sub/superscript-successor (limit)
3054 "Search for the next sub/superscript object.
3056 LIMIT bounds the search.
3058 Return value is a cons cell whose CAR is either `subscript' or
3059 `superscript' and CDR is beginning position."
3060 (save-excursion
3061 (when (re-search-forward org-match-substring-regexp limit t)
3062 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3063 (match-beginning 2)))))
3066 ;;;; Superscript
3068 (defun org-element-superscript-parser ()
3069 "Parse superscript at point.
3071 Return a list whose CAR is `superscript' and CDR a plist with
3072 `:begin', `:end', `:contents-begin', `:contents-end',
3073 `:use-brackets-p' and `:post-blank' as keywords.
3075 Assume point is at the caret."
3076 (save-excursion
3077 (unless (bolp) (backward-char))
3078 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3079 (not (looking-at org-match-substring-regexp))))
3080 (begin (match-beginning 2))
3081 (contents-begin (or (match-beginning 5)
3082 (match-beginning 3)))
3083 (contents-end (or (match-end 5) (match-end 3)))
3084 (post-blank (progn (goto-char (match-end 0))
3085 (skip-chars-forward " \t")))
3086 (end (point)))
3087 (list 'superscript
3088 (list :begin begin
3089 :end end
3090 :use-brackets-p bracketsp
3091 :contents-begin contents-begin
3092 :contents-end contents-end
3093 :post-blank post-blank)))))
3095 (defun org-element-superscript-interpreter (superscript contents)
3096 "Interpret SUPERSCRIPT object as Org syntax.
3097 CONTENTS is the contents of the object."
3098 (format
3099 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3100 contents))
3103 ;;;; Table Cell
3105 (defun org-element-table-cell-parser ()
3106 "Parse table cell at point.
3108 Return a list whose CAR is `table-cell' and CDR is a plist
3109 containing `:begin', `:end', `:contents-begin', `:contents-end'
3110 and `:post-blank' keywords."
3111 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3112 (let* ((begin (match-beginning 0))
3113 (end (match-end 0))
3114 (contents-begin (match-beginning 1))
3115 (contents-end (match-end 1)))
3116 (list 'table-cell
3117 (list :begin begin
3118 :end end
3119 :contents-begin contents-begin
3120 :contents-end contents-end
3121 :post-blank 0))))
3123 (defun org-element-table-cell-interpreter (table-cell contents)
3124 "Interpret TABLE-CELL element as Org syntax.
3125 CONTENTS is the contents of the cell, or nil."
3126 (concat " " contents " |"))
3128 (defun org-element-table-cell-successor (limit)
3129 "Search for the next table-cell object.
3131 LIMIT bounds the search.
3133 Return value is a cons cell whose CAR is `table-cell' and CDR is
3134 beginning position."
3135 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
3138 ;;;; Target
3140 (defun org-element-target-parser ()
3141 "Parse target at point.
3143 Return a list whose CAR is `target' and CDR a plist with
3144 `:begin', `:end', `:value' and `:post-blank' as keywords.
3146 Assume point is at the target."
3147 (save-excursion
3148 (looking-at org-target-regexp)
3149 (let ((begin (point))
3150 (value (org-match-string-no-properties 1))
3151 (post-blank (progn (goto-char (match-end 0))
3152 (skip-chars-forward " \t")))
3153 (end (point)))
3154 (list 'target
3155 (list :begin begin
3156 :end end
3157 :value value
3158 :post-blank post-blank)))))
3160 (defun org-element-target-interpreter (target contents)
3161 "Interpret TARGET object as Org syntax.
3162 CONTENTS is nil."
3163 (format "<<%s>>" (org-element-property :value target)))
3165 (defun org-element-target-successor (limit)
3166 "Search for the next target object.
3168 LIMIT bounds the search.
3170 Return value is a cons cell whose CAR is `target' and CDR is
3171 beginning position."
3172 (save-excursion
3173 (when (re-search-forward org-target-regexp limit t)
3174 (cons 'target (match-beginning 0)))))
3177 ;;;; Timestamp
3179 (defun org-element-timestamp-parser ()
3180 "Parse time stamp at point.
3182 Return a list whose CAR is `timestamp', and CDR a plist with
3183 `:type', `:begin', `:end', `:value' and `:post-blank' keywords.
3185 Assume point is at the beginning of the timestamp."
3186 (save-excursion
3187 (let* ((begin (point))
3188 (activep (eq (char-after) ?<))
3189 (main-value
3190 (progn
3191 (looking-at "[<[]\\(\\(%%\\)?.*?\\)[]>]\\(?:--[<[]\\(.*?\\)[]>]\\)?")
3192 (match-string-no-properties 1)))
3193 (range-end (match-string-no-properties 3))
3194 (type (cond ((match-string 2) 'diary)
3195 ((and activep range-end) 'active-range)
3196 (activep 'active)
3197 (range-end 'inactive-range)
3198 (t 'inactive)))
3199 (post-blank (progn (goto-char (match-end 0))
3200 (skip-chars-forward " \t")))
3201 (end (point)))
3202 (list 'timestamp
3203 (list :type type
3204 :value main-value
3205 :range-end range-end
3206 :begin begin
3207 :end end
3208 :post-blank post-blank)))))
3210 (defun org-element-timestamp-interpreter (timestamp contents)
3211 "Interpret TIMESTAMP object as Org syntax.
3212 CONTENTS is nil."
3213 (let ((type (org-element-property :type timestamp) ))
3214 (concat
3215 (format (if (memq type '(inactive inactive-range)) "[%s]" "<%s>")
3216 (org-element-property :value timestamp))
3217 (let ((range-end (org-element-property :range-end timestamp)))
3218 (when range-end
3219 (concat "--"
3220 (format (if (eq type 'inactive-range) "[%s]" "<%s>")
3221 range-end)))))))
3223 (defun org-element-timestamp-successor (limit)
3224 "Search for the next timestamp object.
3226 LIMIT bounds the search.
3228 Return value is a cons cell whose CAR is `timestamp' and CDR is
3229 beginning position."
3230 (save-excursion
3231 (when (re-search-forward
3232 (concat org-ts-regexp-both
3233 "\\|"
3234 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3235 "\\|"
3236 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3237 limit t)
3238 (cons 'timestamp (match-beginning 0)))))
3241 ;;;; Underline
3243 (defun org-element-underline-parser ()
3244 "Parse underline object at point.
3246 Return a list whose CAR is `underline' and CDR is a plist with
3247 `:begin', `:end', `:contents-begin' and `:contents-end' and
3248 `:post-blank' keywords.
3250 Assume point is at the first underscore marker."
3251 (save-excursion
3252 (unless (bolp) (backward-char 1))
3253 (looking-at org-emph-re)
3254 (let ((begin (match-beginning 2))
3255 (contents-begin (match-beginning 4))
3256 (contents-end (match-end 4))
3257 (post-blank (progn (goto-char (match-end 2))
3258 (skip-chars-forward " \t")))
3259 (end (point)))
3260 (list 'underline
3261 (list :begin begin
3262 :end end
3263 :contents-begin contents-begin
3264 :contents-end contents-end
3265 :post-blank post-blank)))))
3267 (defun org-element-underline-interpreter (underline contents)
3268 "Interpret UNDERLINE object as Org syntax.
3269 CONTENTS is the contents of the object."
3270 (format "_%s_" contents))
3273 ;;;; Verbatim
3275 (defun org-element-verbatim-parser ()
3276 "Parse verbatim object at point.
3278 Return a list whose CAR is `verbatim' and CDR is a plist with
3279 `:value', `:begin', `:end' and `:post-blank' keywords.
3281 Assume point is at the first equal sign marker."
3282 (save-excursion
3283 (unless (bolp) (backward-char 1))
3284 (looking-at org-emph-re)
3285 (let ((begin (match-beginning 2))
3286 (value (org-match-string-no-properties 4))
3287 (post-blank (progn (goto-char (match-end 2))
3288 (skip-chars-forward " \t")))
3289 (end (point)))
3290 (list 'verbatim
3291 (list :value value
3292 :begin begin
3293 :end end
3294 :post-blank post-blank)))))
3296 (defun org-element-verbatim-interpreter (verbatim contents)
3297 "Interpret VERBATIM object as Org syntax.
3298 CONTENTS is nil."
3299 (format "=%s=" (org-element-property :value verbatim)))
3303 ;;; Parsing Element Starting At Point
3305 ;; `org-element--current-element' is the core function of this section.
3306 ;; It returns the Lisp representation of the element starting at
3307 ;; point.
3309 ;; `org-element--current-element' makes use of special modes. They
3310 ;; are activated for fixed element chaining (i.e. `plain-list' >
3311 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3312 ;; `section'). Special modes are: `first-section', `section',
3313 ;; `quote-section', `item' and `table-row'.
3315 (defun org-element--current-element
3316 (limit &optional granularity special structure)
3317 "Parse the element starting at point.
3319 LIMIT bounds the search.
3321 Return value is a list like (TYPE PROPS) where TYPE is the type
3322 of the element and PROPS a plist of properties associated to the
3323 element.
3325 Possible types are defined in `org-element-all-elements'.
3327 Optional argument GRANULARITY determines the depth of the
3328 recursion. Allowed values are `headline', `greater-element',
3329 `element', `object' or nil. When it is broader than `object' (or
3330 nil), secondary values will not be parsed, since they only
3331 contain objects.
3333 Optional argument SPECIAL, when non-nil, can be either
3334 `first-section', `section', `quote-section', `table-row' and
3335 `item'.
3337 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3338 be computed.
3340 This function assumes point is always at the beginning of the
3341 element it has to parse."
3342 (save-excursion
3343 ;; If point is at an affiliated keyword, try moving to the
3344 ;; beginning of the associated element. If none is found, the
3345 ;; keyword is orphaned and will be treated as plain text.
3346 (when (looking-at org-element--affiliated-re)
3347 (let ((opoint (point)))
3348 (while (looking-at org-element--affiliated-re) (forward-line))
3349 (when (looking-at "[ \t]*$") (goto-char opoint))))
3350 (let ((case-fold-search t)
3351 ;; Determine if parsing depth allows for secondary strings
3352 ;; parsing. It only applies to elements referenced in
3353 ;; `org-element-secondary-value-alist'.
3354 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3355 (cond
3356 ;; Item.
3357 ((eq special 'item)
3358 (org-element-item-parser limit structure raw-secondary-p))
3359 ;; Quote Section.
3360 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3361 ;; Table Row.
3362 ((eq special 'table-row) (org-element-table-row-parser limit))
3363 ;; Headline.
3364 ((org-with-limited-levels (org-at-heading-p))
3365 (org-element-headline-parser limit raw-secondary-p))
3366 ;; Section (must be checked after headline).
3367 ((eq special 'section) (org-element-section-parser limit))
3368 ((eq special 'first-section)
3369 (org-element-section-parser
3370 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3371 limit)))
3372 ;; Planning and Clock.
3373 ((and (looking-at org-planning-or-clock-line-re))
3374 (if (equal (match-string 1) org-clock-string)
3375 (org-element-clock-parser limit)
3376 (org-element-planning-parser limit)))
3377 ;; Inlinetask.
3378 ((org-at-heading-p)
3379 (org-element-inlinetask-parser limit raw-secondary-p))
3380 ;; LaTeX Environment.
3381 ((looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}")
3382 (if (save-excursion
3383 (re-search-forward
3384 (format "[ \t]*\\\\end{%s}[ \t]*"
3385 (regexp-quote (match-string 1)))
3386 nil t))
3387 (org-element-latex-environment-parser limit)
3388 (org-element-paragraph-parser limit)))
3389 ;; Drawer and Property Drawer.
3390 ((looking-at org-drawer-regexp)
3391 (let ((name (match-string 1)))
3392 (cond
3393 ((not (save-excursion
3394 (re-search-forward "^[ \t]*:END:[ \t]*$" nil t)))
3395 (org-element-paragraph-parser limit))
3396 ((equal "PROPERTIES" name)
3397 (org-element-property-drawer-parser limit))
3398 (t (org-element-drawer-parser limit)))))
3399 ;; Fixed Width
3400 ((looking-at "[ \t]*:\\( \\|$\\)")
3401 (org-element-fixed-width-parser limit))
3402 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3403 ;; Keywords.
3404 ((looking-at "[ \t]*#")
3405 (goto-char (match-end 0))
3406 (cond ((looking-at "\\(?: \\|$\\)")
3407 (beginning-of-line)
3408 (org-element-comment-parser limit))
3409 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3410 (beginning-of-line)
3411 (let ((parser (assoc (upcase (match-string 1))
3412 org-element-block-name-alist)))
3413 (if parser (funcall (cdr parser) limit)
3414 (org-element-special-block-parser limit))))
3415 ((looking-at "\\+CALL:")
3416 (beginning-of-line)
3417 (org-element-babel-call-parser limit))
3418 ((looking-at "\\+BEGIN:? ")
3419 (beginning-of-line)
3420 (org-element-dynamic-block-parser limit))
3421 ((looking-at "\\+\\S-+:")
3422 (beginning-of-line)
3423 (org-element-keyword-parser limit))
3425 (beginning-of-line)
3426 (org-element-paragraph-parser limit))))
3427 ;; Footnote Definition.
3428 ((looking-at org-footnote-definition-re)
3429 (org-element-footnote-definition-parser limit))
3430 ;; Horizontal Rule.
3431 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3432 (org-element-horizontal-rule-parser limit))
3433 ;; Table.
3434 ((org-at-table-p t) (org-element-table-parser limit))
3435 ;; List.
3436 ((looking-at (org-item-re))
3437 (org-element-plain-list-parser limit (or structure (org-list-struct))))
3438 ;; Default element: Paragraph.
3439 (t (org-element-paragraph-parser limit))))))
3442 ;; Most elements can have affiliated keywords. When looking for an
3443 ;; element beginning, we want to move before them, as they belong to
3444 ;; that element, and, in the meantime, collect information they give
3445 ;; into appropriate properties. Hence the following function.
3447 ;; Usage of optional arguments may not be obvious at first glance:
3449 ;; - TRANS-LIST is used to polish keywords names that have evolved
3450 ;; during Org history. In example, even though =result= and
3451 ;; =results= coexist, we want to have them under the same =result=
3452 ;; property. It's also true for "srcname" and "name", where the
3453 ;; latter seems to be preferred nowadays (thus the "name" property).
3455 ;; - CONSED allows to regroup multi-lines keywords under the same
3456 ;; property, while preserving their own identity. This is mostly
3457 ;; used for "attr_latex" and al.
3459 ;; - PARSED prepares a keyword value for export. This is useful for
3460 ;; "caption". Objects restrictions for such keywords are defined in
3461 ;; `org-element-object-restrictions'.
3463 ;; - DUALS is used to take care of keywords accepting a main and an
3464 ;; optional secondary values. For example "results" has its
3465 ;; source's name as the main value, and may have an hash string in
3466 ;; optional square brackets as the secondary one.
3468 ;; A keyword may belong to more than one category.
3470 (defun org-element--collect-affiliated-keywords
3471 (&optional key-re trans-list consed parsed duals)
3472 "Collect affiliated keywords before point.
3474 Optional argument KEY-RE is a regexp matching keywords, which
3475 puts matched keyword in group 1. It defaults to
3476 `org-element--affiliated-re'.
3478 TRANS-LIST is an alist where key is the keyword and value the
3479 property name it should be translated to, without the colons. It
3480 defaults to `org-element-keyword-translation-alist'.
3482 CONSED is a list of strings. Any keyword belonging to that list
3483 will have its value consed. The check is done after keyword
3484 translation. It defaults to `org-element-multiple-keywords'.
3486 PARSED is a list of strings. Any keyword member of this list
3487 will have its value parsed. The check is done after keyword
3488 translation. If a keyword is a member of both CONSED and PARSED,
3489 it's value will be a list of parsed strings. It defaults to
3490 `org-element-parsed-keywords'.
3492 DUALS is a list of strings. Any keyword member of this list can
3493 have two parts: one mandatory and one optional. Its value is
3494 a cons cell whose CAR is the former, and the CDR the latter. If
3495 a keyword is a member of both PARSED and DUALS, both values will
3496 be parsed. It defaults to `org-element-dual-keywords'.
3498 Return a list whose CAR is the position at the first of them and
3499 CDR a plist of keywords and values."
3500 (save-excursion
3501 (let ((case-fold-search t)
3502 (key-re (or key-re org-element--affiliated-re))
3503 (trans-list (or trans-list org-element-keyword-translation-alist))
3504 (consed (or consed org-element-multiple-keywords))
3505 (parsed (or parsed org-element-parsed-keywords))
3506 (duals (or duals org-element-dual-keywords))
3507 ;; RESTRICT is the list of objects allowed in parsed
3508 ;; keywords value.
3509 (restrict (org-element-restriction 'keyword))
3510 output)
3511 (unless (bobp)
3512 (while (and (not (bobp)) (progn (forward-line -1) (looking-at key-re)))
3513 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3514 ;; Apply translation to RAW-KWD. From there, KWD is
3515 ;; the official keyword.
3516 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3517 ;; Find main value for any keyword.
3518 (value
3519 (save-match-data
3520 (org-trim
3521 (buffer-substring-no-properties
3522 (match-end 0) (point-at-eol)))))
3523 ;; If KWD is a dual keyword, find its secondary
3524 ;; value. Maybe parse it.
3525 (dual-value
3526 (and (member kwd duals)
3527 (let ((sec (org-match-string-no-properties 3)))
3528 (if (or (not sec) (not (member kwd parsed))) sec
3529 (org-element-parse-secondary-string sec restrict)))))
3530 ;; Attribute a property name to KWD.
3531 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3532 ;; Now set final shape for VALUE.
3533 (when (member kwd parsed)
3534 (setq value (org-element-parse-secondary-string value restrict)))
3535 (when (member kwd duals)
3536 ;; VALUE is mandatory. Set it to nil if there is none.
3537 (setq value (and value (cons value dual-value))))
3538 ;; Attributes are always consed.
3539 (when (or (member kwd consed) (string-match "^ATTR_" kwd))
3540 (setq value (cons value (plist-get output kwd-sym))))
3541 ;; Eventually store the new value in OUTPUT.
3542 (setq output (plist-put output kwd-sym value))))
3543 (unless (looking-at key-re) (forward-line 1)))
3544 (list (point) output))))
3548 ;;; The Org Parser
3550 ;; The two major functions here are `org-element-parse-buffer', which
3551 ;; parses Org syntax inside the current buffer, taking into account
3552 ;; region, narrowing, or even visibility if specified, and
3553 ;; `org-element-parse-secondary-string', which parses objects within
3554 ;; a given string.
3556 ;; The (almost) almighty `org-element-map' allows to apply a function
3557 ;; on elements or objects matching some type, and accumulate the
3558 ;; resulting values. In an export situation, it also skips unneeded
3559 ;; parts of the parse tree.
3561 (defun org-element-parse-buffer (&optional granularity visible-only)
3562 "Recursively parse the buffer and return structure.
3563 If narrowing is in effect, only parse the visible part of the
3564 buffer.
3566 Optional argument GRANULARITY determines the depth of the
3567 recursion. It can be set to the following symbols:
3569 `headline' Only parse headlines.
3570 `greater-element' Don't recurse into greater elements excepted
3571 headlines and sections. Thus, elements
3572 parsed are the top-level ones.
3573 `element' Parse everything but objects and plain text.
3574 `object' Parse the complete buffer (default).
3576 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3577 elements.
3579 Assume buffer is in Org mode."
3580 (save-excursion
3581 (goto-char (point-min))
3582 (org-skip-whitespace)
3583 (org-element--parse-elements
3584 (point-at-bol) (point-max)
3585 ;; Start in `first-section' mode so text before the first
3586 ;; headline belongs to a section.
3587 'first-section nil granularity visible-only (list 'org-data nil))))
3589 (defun org-element-parse-secondary-string (string restriction &optional parent)
3590 "Recursively parse objects in STRING and return structure.
3592 RESTRICTION is a symbol limiting the object types that will be
3593 looked after.
3595 Optional argument PARENT, when non-nil, is the element or object
3596 containing the secondary string. It is used to set correctly
3597 `:parent' property within the string."
3598 (with-temp-buffer
3599 (insert string)
3600 (let ((secondary (org-element--parse-objects
3601 (point-min) (point-max) nil restriction)))
3602 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
3603 secondary))))
3605 (defun org-element-map (data types fun &optional info first-match no-recursion)
3606 "Map a function on selected elements or objects.
3608 DATA is the parsed tree, as returned by, i.e,
3609 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3610 of elements or objects types. FUN is the function called on the
3611 matching element or object. It must accept one arguments: the
3612 element or object itself.
3614 When optional argument INFO is non-nil, it should be a plist
3615 holding export options. In that case, parts of the parse tree
3616 not exportable according to that property list will be skipped.
3618 When optional argument FIRST-MATCH is non-nil, stop at the first
3619 match for which FUN doesn't return nil, and return that value.
3621 Optional argument NO-RECURSION is a symbol or a list of symbols
3622 representing elements or objects types. `org-element-map' won't
3623 enter any recursive element or object whose type belongs to that
3624 list. Though, FUN can still be applied on them.
3626 Nil values returned from FUN do not appear in the results."
3627 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3628 (unless (listp types) (setq types (list types)))
3629 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3630 ;; Recursion depth is determined by --CATEGORY.
3631 (let* ((--category
3632 (catch 'found
3633 (let ((category 'greater-elements))
3634 (mapc (lambda (type)
3635 (cond ((or (memq type org-element-all-objects)
3636 (eq type 'plain-text))
3637 ;; If one object is found, the function
3638 ;; has to recurse into every object.
3639 (throw 'found 'objects))
3640 ((not (memq type org-element-greater-elements))
3641 ;; If one regular element is found, the
3642 ;; function has to recurse, at least,
3643 ;; into every element it encounters.
3644 (and (not (eq category 'elements))
3645 (setq category 'elements)))))
3646 types)
3647 category)))
3648 --acc
3649 --walk-tree
3650 (--walk-tree
3651 (function
3652 (lambda (--data)
3653 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3654 ;; holding contextual information.
3655 (let ((--type (org-element-type --data)))
3656 (cond
3657 ((not --data))
3658 ;; Ignored element in an export context.
3659 ((and info (memq --data (plist-get info :ignore-list))))
3660 ;; Secondary string: only objects can be found there.
3661 ((not --type)
3662 (when (eq --category 'objects) (mapc --walk-tree --data)))
3663 ;; Unconditionally enter parse trees.
3664 ((eq --type 'org-data)
3665 (mapc --walk-tree (org-element-contents --data)))
3667 ;; Check if TYPE is matching among TYPES. If so,
3668 ;; apply FUN to --DATA and accumulate return value
3669 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3670 (when (memq --type types)
3671 (let ((result (funcall fun --data)))
3672 (cond ((not result))
3673 (first-match (throw '--map-first-match result))
3674 (t (push result --acc)))))
3675 ;; If --DATA has a secondary string that can contain
3676 ;; objects with their type among TYPES, look into it.
3677 (when (eq --category 'objects)
3678 (let ((sec-prop
3679 (assq --type org-element-secondary-value-alist)))
3680 (when sec-prop
3681 (funcall --walk-tree
3682 (org-element-property (cdr sec-prop) --data)))))
3683 ;; Determine if a recursion into --DATA is possible.
3684 (cond
3685 ;; --TYPE is explicitly removed from recursion.
3686 ((memq --type no-recursion))
3687 ;; --DATA has no contents.
3688 ((not (org-element-contents --data)))
3689 ;; Looking for greater elements but --DATA is simply
3690 ;; an element or an object.
3691 ((and (eq --category 'greater-elements)
3692 (not (memq --type org-element-greater-elements))))
3693 ;; Looking for elements but --DATA is an object.
3694 ((and (eq --category 'elements)
3695 (memq --type org-element-all-objects)))
3696 ;; In any other case, map contents.
3697 (t (mapc --walk-tree (org-element-contents --data)))))))))))
3698 (catch '--map-first-match
3699 (funcall --walk-tree data)
3700 ;; Return value in a proper order.
3701 (nreverse --acc))))
3703 ;; The following functions are internal parts of the parser.
3705 ;; The first one, `org-element--parse-elements' acts at the element's
3706 ;; level.
3708 ;; The second one, `org-element--parse-objects' applies on all objects
3709 ;; of a paragraph or a secondary string. It uses
3710 ;; `org-element--get-next-object-candidates' to optimize the search of
3711 ;; the next object in the buffer.
3713 ;; More precisely, that function looks for every allowed object type
3714 ;; first. Then, it discards failed searches, keeps further matches,
3715 ;; and searches again types matched behind point, for subsequent
3716 ;; calls. Thus, searching for a given type fails only once, and every
3717 ;; object is searched only once at top level (but sometimes more for
3718 ;; nested types).
3720 (defun org-element--parse-elements
3721 (beg end special structure granularity visible-only acc)
3722 "Parse elements between BEG and END positions.
3724 SPECIAL prioritize some elements over the others. It can be set
3725 to `first-section', `quote-section', `section' `item' or
3726 `table-row'.
3728 When value is `item', STRUCTURE will be used as the current list
3729 structure.
3731 GRANULARITY determines the depth of the recursion. See
3732 `org-element-parse-buffer' for more information.
3734 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3735 elements.
3737 Elements are accumulated into ACC."
3738 (save-excursion
3739 (goto-char beg)
3740 ;; When parsing only headlines, skip any text before first one.
3741 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3742 (org-with-limited-levels (outline-next-heading)))
3743 ;; Main loop start.
3744 (while (< (point) end)
3745 ;; Find current element's type and parse it accordingly to
3746 ;; its category.
3747 (let* ((element (org-element--current-element
3748 end granularity special structure))
3749 (type (org-element-type element))
3750 (cbeg (org-element-property :contents-begin element)))
3751 (goto-char (org-element-property :end element))
3752 ;; Fill ELEMENT contents by side-effect.
3753 (cond
3754 ;; If VISIBLE-ONLY is true and element is hidden or if it has
3755 ;; no contents, don't modify it.
3756 ((or (and visible-only (org-element-property :hiddenp element))
3757 (not cbeg)))
3758 ;; Greater element: parse it between `contents-begin' and
3759 ;; `contents-end'. Make sure GRANULARITY allows the
3760 ;; recursion, or ELEMENT is an headline, in which case going
3761 ;; inside is mandatory, in order to get sub-level headings.
3762 ((and (memq type org-element-greater-elements)
3763 (or (memq granularity '(element object nil))
3764 (and (eq granularity 'greater-element)
3765 (eq type 'section))
3766 (eq type 'headline)))
3767 (org-element--parse-elements
3768 cbeg (org-element-property :contents-end element)
3769 ;; Possibly switch to a special mode.
3770 (case type
3771 (headline
3772 (if (org-element-property :quotedp element) 'quote-section
3773 'section))
3774 (plain-list 'item)
3775 (table 'table-row))
3776 (org-element-property :structure element)
3777 granularity visible-only element))
3778 ;; ELEMENT has contents. Parse objects inside, if
3779 ;; GRANULARITY allows it.
3780 ((memq granularity '(object nil))
3781 (org-element--parse-objects
3782 cbeg (org-element-property :contents-end element) element
3783 (org-element-restriction type))))
3784 (org-element-adopt-elements acc element)))
3785 ;; Return result.
3786 acc))
3788 (defun org-element--parse-objects (beg end acc restriction)
3789 "Parse objects between BEG and END and return recursive structure.
3791 Objects are accumulated in ACC.
3793 RESTRICTION is a list of object types which are allowed in the
3794 current object."
3795 (let (candidates)
3796 (save-excursion
3797 (goto-char beg)
3798 (while (and (< (point) end)
3799 (setq candidates (org-element--get-next-object-candidates
3800 end restriction candidates)))
3801 (let ((next-object
3802 (let ((pos (apply 'min (mapcar 'cdr candidates))))
3803 (save-excursion
3804 (goto-char pos)
3805 (funcall (intern (format "org-element-%s-parser"
3806 (car (rassq pos candidates)))))))))
3807 ;; 1. Text before any object. Untabify it.
3808 (let ((obj-beg (org-element-property :begin next-object)))
3809 (unless (= (point) obj-beg)
3810 (setq acc
3811 (org-element-adopt-elements
3813 (replace-regexp-in-string
3814 "\t" (make-string tab-width ? )
3815 (buffer-substring-no-properties (point) obj-beg))))))
3816 ;; 2. Object...
3817 (let ((obj-end (org-element-property :end next-object))
3818 (cont-beg (org-element-property :contents-begin next-object)))
3819 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
3820 ;; a recursive type.
3821 (when (and cont-beg
3822 (memq (car next-object) org-element-recursive-objects))
3823 (save-restriction
3824 (narrow-to-region
3825 cont-beg
3826 (org-element-property :contents-end next-object))
3827 (org-element--parse-objects
3828 (point-min) (point-max) next-object
3829 (org-element-restriction next-object))))
3830 (setq acc (org-element-adopt-elements acc next-object))
3831 (goto-char obj-end))))
3832 ;; 3. Text after last object. Untabify it.
3833 (unless (= (point) end)
3834 (setq acc
3835 (org-element-adopt-elements
3837 (replace-regexp-in-string
3838 "\t" (make-string tab-width ? )
3839 (buffer-substring-no-properties (point) end)))))
3840 ;; Result.
3841 acc)))
3843 (defun org-element--get-next-object-candidates (limit restriction objects)
3844 "Return an alist of candidates for the next object.
3846 LIMIT bounds the search, and RESTRICTION narrows candidates to
3847 some object types.
3849 Return value is an alist whose CAR is position and CDR the object
3850 type, as a symbol.
3852 OBJECTS is the previous candidates alist."
3853 (let (next-candidates types-to-search)
3854 ;; If no previous result, search every object type in RESTRICTION.
3855 ;; Otherwise, keep potential candidates (old objects located after
3856 ;; point) and ask to search again those which had matched before.
3857 (if (not objects) (setq types-to-search restriction)
3858 (mapc (lambda (obj)
3859 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3860 (push obj next-candidates)))
3861 objects))
3862 ;; Call the appropriate successor function for each type to search
3863 ;; and accumulate matches.
3864 (mapc
3865 (lambda (type)
3866 (let* ((successor-fun
3867 (intern
3868 (format "org-element-%s-successor"
3869 (or (cdr (assq type org-element-object-successor-alist))
3870 type))))
3871 (obj (funcall successor-fun limit)))
3872 (and obj (push obj next-candidates))))
3873 types-to-search)
3874 ;; Return alist.
3875 next-candidates))
3879 ;;; Towards A Bijective Process
3881 ;; The parse tree obtained with `org-element-parse-buffer' is really
3882 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3883 ;; interpreted and expanded into a string with canonical Org syntax.
3884 ;; Hence `org-element-interpret-data'.
3886 ;; The function relies internally on
3887 ;; `org-element--interpret-affiliated-keywords'.
3889 ;;;###autoload
3890 (defun org-element-interpret-data (data &optional parent)
3891 "Interpret DATA as Org syntax.
3893 DATA is a parse tree, an element, an object or a secondary string
3894 to interpret.
3896 Optional argument PARENT is used for recursive calls. It contains
3897 the element or object containing data, or nil.
3899 Return Org syntax as a string."
3900 (let* ((type (org-element-type data))
3901 (results
3902 (cond
3903 ;; Secondary string.
3904 ((not type)
3905 (mapconcat
3906 (lambda (obj) (org-element-interpret-data obj parent))
3907 data ""))
3908 ;; Full Org document.
3909 ((eq type 'org-data)
3910 (mapconcat
3911 (lambda (obj) (org-element-interpret-data obj parent))
3912 (org-element-contents data) ""))
3913 ;; Plain text.
3914 ((stringp data) data)
3915 ;; Element/Object without contents.
3916 ((not (org-element-contents data))
3917 (funcall (intern (format "org-element-%s-interpreter" type))
3918 data nil))
3919 ;; Element/Object with contents.
3921 (let* ((greaterp (memq type org-element-greater-elements))
3922 (objectp (and (not greaterp)
3923 (memq type org-element-recursive-objects)))
3924 (contents
3925 (mapconcat
3926 (lambda (obj) (org-element-interpret-data obj data))
3927 (org-element-contents
3928 (if (or greaterp objectp) data
3929 ;; Elements directly containing objects must
3930 ;; have their indentation normalized first.
3931 (org-element-normalize-contents
3932 data
3933 ;; When normalizing first paragraph of an
3934 ;; item or a footnote-definition, ignore
3935 ;; first line's indentation.
3936 (and (eq type 'paragraph)
3937 (equal data (car (org-element-contents parent)))
3938 (memq (org-element-type parent)
3939 '(footnote-definiton item))))))
3940 "")))
3941 (funcall (intern (format "org-element-%s-interpreter" type))
3942 data
3943 (if greaterp (org-element-normalize-contents contents)
3944 contents)))))))
3945 (if (memq type '(org-data plain-text nil)) results
3946 ;; Build white spaces. If no `:post-blank' property is
3947 ;; specified, assume its value is 0.
3948 (let ((post-blank (or (org-element-property :post-blank data) 0)))
3949 (if (memq type org-element-all-objects)
3950 (concat results (make-string post-blank 32))
3951 (concat
3952 (org-element--interpret-affiliated-keywords data)
3953 (org-element-normalize-string results)
3954 (make-string post-blank 10)))))))
3956 (defun org-element--interpret-affiliated-keywords (element)
3957 "Return ELEMENT's affiliated keywords as Org syntax.
3958 If there is no affiliated keyword, return the empty string."
3959 (let ((keyword-to-org
3960 (function
3961 (lambda (key value)
3962 (let (dual)
3963 (when (member key org-element-dual-keywords)
3964 (setq dual (cdr value) value (car value)))
3965 (concat "#+" key
3966 (and dual
3967 (format "[%s]" (org-element-interpret-data dual)))
3968 ": "
3969 (if (member key org-element-parsed-keywords)
3970 (org-element-interpret-data value)
3971 value)
3972 "\n"))))))
3973 (mapconcat
3974 (lambda (prop)
3975 (let ((value (org-element-property prop element))
3976 (keyword (upcase (substring (symbol-name prop) 1))))
3977 (when value
3978 (if (or (member keyword org-element-multiple-keywords)
3979 ;; All attribute keywords can have multiple lines.
3980 (string-match "^ATTR_" keyword))
3981 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
3982 value
3984 (funcall keyword-to-org keyword value)))))
3985 ;; List all ELEMENT's properties matching an attribute line or an
3986 ;; affiliated keyword, but ignore translated keywords since they
3987 ;; cannot belong to the property list.
3988 (loop for prop in (nth 1 element) by 'cddr
3989 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
3990 (or (string-match "^ATTR_" keyword)
3991 (and
3992 (member keyword org-element-affiliated-keywords)
3993 (not (assoc keyword
3994 org-element-keyword-translation-alist)))))
3995 collect prop)
3996 "")))
3998 ;; Because interpretation of the parse tree must return the same
3999 ;; number of blank lines between elements and the same number of white
4000 ;; space after objects, some special care must be given to white
4001 ;; spaces.
4003 ;; The first function, `org-element-normalize-string', ensures any
4004 ;; string different from the empty string will end with a single
4005 ;; newline character.
4007 ;; The second function, `org-element-normalize-contents', removes
4008 ;; global indentation from the contents of the current element.
4010 (defun org-element-normalize-string (s)
4011 "Ensure string S ends with a single newline character.
4013 If S isn't a string return it unchanged. If S is the empty
4014 string, return it. Otherwise, return a new string with a single
4015 newline character at its end."
4016 (cond
4017 ((not (stringp s)) s)
4018 ((string= "" s) "")
4019 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4020 (replace-match "\n" nil nil s)))))
4022 (defun org-element-normalize-contents (element &optional ignore-first)
4023 "Normalize plain text in ELEMENT's contents.
4025 ELEMENT must only contain plain text and objects.
4027 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4028 indentation to compute maximal common indentation.
4030 Return the normalized element that is element with global
4031 indentation removed from its contents. The function assumes that
4032 indentation is not done with TAB characters."
4033 (let* (ind-list ; for byte-compiler
4034 collect-inds ; for byte-compiler
4035 (collect-inds
4036 (function
4037 ;; Return list of indentations within BLOB. This is done by
4038 ;; walking recursively BLOB and updating IND-LIST along the
4039 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4040 ;; been seen yet. It is required as this string is the only
4041 ;; one whose indentation doesn't happen after a newline
4042 ;; character.
4043 (lambda (blob first-flag)
4044 (mapc
4045 (lambda (object)
4046 (when (and first-flag (stringp object))
4047 (setq first-flag nil)
4048 (string-match "\\`\\( *\\)" object)
4049 (let ((len (length (match-string 1 object))))
4050 ;; An indentation of zero means no string will be
4051 ;; modified. Quit the process.
4052 (if (zerop len) (throw 'zero (setq ind-list nil))
4053 (push len ind-list))))
4054 (cond
4055 ((stringp object)
4056 (let ((start 0))
4057 ;; Avoid matching blank or empty lines.
4058 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4059 (not (equal (match-string 2 object) " ")))
4060 (setq start (match-end 0))
4061 (push (length (match-string 1 object)) ind-list))))
4062 ((memq (org-element-type object) org-element-recursive-objects)
4063 (funcall collect-inds object first-flag))))
4064 (org-element-contents blob))))))
4065 ;; Collect indentation list in ELEMENT. Possibly remove first
4066 ;; value if IGNORE-FIRST is non-nil.
4067 (catch 'zero (funcall collect-inds element (not ignore-first)))
4068 (if (not ind-list) element
4069 ;; Build ELEMENT back, replacing each string with the same
4070 ;; string minus common indentation.
4071 (let* (build ; For byte compiler.
4072 (build
4073 (function
4074 (lambda (blob mci first-flag)
4075 ;; Return BLOB with all its strings indentation
4076 ;; shortened from MCI white spaces. FIRST-FLAG is
4077 ;; non-nil when the first string hasn't been seen
4078 ;; yet.
4079 (setcdr (cdr blob)
4080 (mapcar
4081 (lambda (object)
4082 (when (and first-flag (stringp object))
4083 (setq first-flag nil)
4084 (setq object
4085 (replace-regexp-in-string
4086 (format "\\` \\{%d\\}" mci) "" object)))
4087 (cond
4088 ((stringp object)
4089 (replace-regexp-in-string
4090 (format "\n \\{%d\\}" mci) "\n" object))
4091 ((memq (org-element-type object)
4092 org-element-recursive-objects)
4093 (funcall build object mci first-flag))
4094 (t object)))
4095 (org-element-contents blob)))
4096 blob))))
4097 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4101 ;;; The Toolbox
4103 ;; The first move is to implement a way to obtain the smallest element
4104 ;; containing point. This is the job of `org-element-at-point'. It
4105 ;; basically jumps back to the beginning of section containing point
4106 ;; and moves, element after element, with
4107 ;; `org-element--current-element' until the container is found. Note:
4108 ;; When using `org-element-at-point', secondary values are never
4109 ;; parsed since the function focuses on elements, not on objects.
4111 ;; At a deeper level, `org-element-context' lists all elements and
4112 ;; objects containing point.
4114 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4115 ;; internally by navigation and manipulation tools.
4117 ;;;###autoload
4118 (defun org-element-at-point (&optional keep-trail)
4119 "Determine closest element around point.
4121 Return value is a list like (TYPE PROPS) where TYPE is the type
4122 of the element and PROPS a plist of properties associated to the
4123 element.
4125 Possible types are defined in `org-element-all-elements'.
4126 Properties depend on element or object type, but always
4127 include :begin, :end, :parent and :post-blank properties.
4129 As a special case, if point is at the very beginning of a list or
4130 sub-list, returned element will be that list instead of the first
4131 item. In the same way, if point is at the beginning of the first
4132 row of a table, returned element will be the table instead of the
4133 first row.
4135 If optional argument KEEP-TRAIL is non-nil, the function returns
4136 a list of of elements leading to element at point. The list's
4137 CAR is always the element at point. Following positions contain
4138 element's siblings, then parents, siblings of parents, until the
4139 first element of current section."
4140 (org-with-wide-buffer
4141 ;; If at an headline, parse it. It is the sole element that
4142 ;; doesn't require to know about context. Be sure to disallow
4143 ;; secondary string parsing, though.
4144 (if (org-with-limited-levels (org-at-heading-p))
4145 (progn
4146 (beginning-of-line)
4147 (if (not keep-trail) (org-element-headline-parser (point-max) t)
4148 (list (org-element-headline-parser (point-max) t))))
4149 ;; Otherwise move at the beginning of the section containing
4150 ;; point.
4151 (let ((origin (point))
4152 (end (save-excursion
4153 (org-with-limited-levels (outline-next-heading)) (point)))
4154 element type special-flag trail struct prevs parent)
4155 (org-with-limited-levels
4156 (if (org-with-limited-levels (org-before-first-heading-p))
4157 (goto-char (point-min))
4158 (org-back-to-heading)
4159 (forward-line)))
4160 (org-skip-whitespace)
4161 (beginning-of-line)
4162 ;; Parse successively each element, skipping those ending
4163 ;; before original position.
4164 (catch 'exit
4165 (while t
4166 (setq element
4167 (org-element--current-element end 'element special-flag struct)
4168 type (car element))
4169 (org-element-put-property element :parent parent)
4170 (when keep-trail (push element trail))
4171 (cond
4172 ;; 1. Skip any element ending before point. Also skip
4173 ;; element ending at point when we're sure that another
4174 ;; element has started.
4175 ((let ((elem-end (org-element-property :end element)))
4176 (when (or (< elem-end origin)
4177 (and (= elem-end origin) (/= elem-end end)))
4178 (goto-char elem-end))))
4179 ;; 2. An element containing point is always the element at
4180 ;; point.
4181 ((not (memq type org-element-greater-elements))
4182 (throw 'exit (if keep-trail trail element)))
4183 ;; 3. At any other greater element type, if point is
4184 ;; within contents, move into it.
4186 (let ((cbeg (org-element-property :contents-begin element))
4187 (cend (org-element-property :contents-end element)))
4188 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
4189 ;; Create an anchor for tables and plain lists:
4190 ;; when point is at the very beginning of these
4191 ;; elements, ignoring affiliated keywords,
4192 ;; target them instead of their contents.
4193 (and (= cbeg origin) (memq type '(plain-list table)))
4194 ;; When point is at contents end, do not move
4195 ;; into elements with an explicit ending, but
4196 ;; return that element instead.
4197 (and (= cend origin)
4198 (memq type
4199 '(center-block
4200 drawer dynamic-block inlinetask item
4201 plain-list quote-block special-block))))
4202 (throw 'exit (if keep-trail trail element))
4203 (setq parent element)
4204 (case type
4205 (plain-list
4206 (setq special-flag 'item
4207 struct (org-element-property :structure element)))
4208 (table (setq special-flag 'table-row))
4209 (otherwise (setq special-flag nil)))
4210 (setq end cend)
4211 (goto-char cbeg)))))))))))
4213 ;;;###autoload
4214 (defun org-element-context ()
4215 "Return closest element or object around point.
4217 Return value is a list like (TYPE PROPS) where TYPE is the type
4218 of the element or object and PROPS a plist of properties
4219 associated to it.
4221 Possible types are defined in `org-element-all-elements' and
4222 `org-element-all-objects'. Properties depend on element or
4223 object type, but always include :begin, :end, :parent
4224 and :post-blank properties."
4225 (org-with-wide-buffer
4226 (let* ((origin (point))
4227 (element (org-element-at-point))
4228 (type (car element))
4229 end)
4230 ;; Check if point is inside an element containing objects or at
4231 ;; a secondary string. In that case, move to beginning of the
4232 ;; element or secondary string and set END to the other side.
4233 (if (not (or (and (eq type 'item)
4234 (let ((tag (org-element-property :tag element)))
4235 (and tag
4236 (progn
4237 (beginning-of-line)
4238 (search-forward tag (point-at-eol))
4239 (goto-char (match-beginning 0))
4240 (and (>= origin (point))
4241 (<= origin
4242 ;; `1+' is required so some
4243 ;; successors can match
4244 ;; properly their object.
4245 (setq end (1+ (match-end 0)))))))))
4246 (and (memq type '(headline inlinetask))
4247 (progn (beginning-of-line)
4248 (skip-chars-forward "* ")
4249 (setq end (point-at-eol))))
4250 (and (memq type '(paragraph table-cell verse-block))
4251 (let ((cbeg (org-element-property
4252 :contents-begin element))
4253 (cend (org-element-property
4254 :contents-end element)))
4255 (and (>= origin cbeg)
4256 (<= origin cend)
4257 (progn (goto-char cbeg) (setq end cend)))))))
4258 element
4259 (let ((restriction (org-element-restriction element))
4260 (parent element)
4261 candidates)
4262 (catch 'exit
4263 (while (setq candidates (org-element--get-next-object-candidates
4264 end restriction candidates))
4265 (let ((closest-cand (rassq (apply 'min (mapcar 'cdr candidates))
4266 candidates)))
4267 ;; If ORIGIN is before next object in element, there's
4268 ;; no point in looking further.
4269 (if (> (cdr closest-cand) origin) (throw 'exit element)
4270 (let* ((object
4271 (progn (goto-char (cdr closest-cand))
4272 (funcall (intern (format "org-element-%s-parser"
4273 (car closest-cand))))))
4274 (cbeg (org-element-property :contents-begin object))
4275 (cend (org-element-property :contents-end object)))
4276 (cond
4277 ;; ORIGIN is after OBJECT, so skip it.
4278 ((< (org-element-property :end object) origin)
4279 (goto-char (org-element-property :end object)))
4280 ;; ORIGIN is within a non-recursive object or at an
4281 ;; object boundaries: Return that object.
4282 ((or (not cbeg) (> cbeg origin) (< cend origin))
4283 (throw 'exit
4284 (org-element-put-property object :parent parent)))
4285 ;; Otherwise, move within current object and restrict
4286 ;; search to the end of its contents.
4287 (t (goto-char cbeg)
4288 (org-element-put-property object :parent parent)
4289 (setq parent object end cend)))))))
4290 parent))))))
4292 (defsubst org-element-nested-p (elem-A elem-B)
4293 "Non-nil when elements ELEM-A and ELEM-B are nested."
4294 (let ((beg-A (org-element-property :begin elem-A))
4295 (beg-B (org-element-property :begin elem-B))
4296 (end-A (org-element-property :end elem-A))
4297 (end-B (org-element-property :end elem-B)))
4298 (or (and (>= beg-A beg-B) (<= end-A end-B))
4299 (and (>= beg-B beg-A) (<= end-B end-A)))))
4301 (defun org-element-swap-A-B (elem-A elem-B)
4302 "Swap elements ELEM-A and ELEM-B.
4303 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
4304 end of ELEM-A."
4305 (goto-char (org-element-property :begin elem-A))
4306 ;; There are two special cases when an element doesn't start at bol:
4307 ;; the first paragraph in an item or in a footnote definition.
4308 (let ((specialp (not (bolp))))
4309 ;; Only a paragraph without any affiliated keyword can be moved at
4310 ;; ELEM-A position in such a situation. Note that the case of
4311 ;; a footnote definition is impossible: it cannot contain two
4312 ;; paragraphs in a row because it cannot contain a blank line.
4313 (if (and specialp
4314 (or (not (eq (org-element-type elem-B) 'paragraph))
4315 (/= (org-element-property :begin elem-B)
4316 (org-element-property :contents-begin elem-B))))
4317 (error "Cannot swap elements"))
4318 ;; In a special situation, ELEM-A will have no indentation. We'll
4319 ;; give it ELEM-B's (which will in, in turn, have no indentation).
4320 (let* ((ind-B (when specialp
4321 (goto-char (org-element-property :begin elem-B))
4322 (org-get-indentation)))
4323 (beg-A (org-element-property :begin elem-A))
4324 (end-A (save-excursion
4325 (goto-char (org-element-property :end elem-A))
4326 (skip-chars-backward " \r\t\n")
4327 (point-at-eol)))
4328 (beg-B (org-element-property :begin elem-B))
4329 (end-B (save-excursion
4330 (goto-char (org-element-property :end elem-B))
4331 (skip-chars-backward " \r\t\n")
4332 (point-at-eol)))
4333 ;; Store overlays responsible for visibility status. We
4334 ;; also need to store their boundaries as they will be
4335 ;; removed from buffer.
4336 (overlays
4337 (cons
4338 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4339 (overlays-in beg-A end-A))
4340 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4341 (overlays-in beg-B end-B))))
4342 ;; Get contents.
4343 (body-A (buffer-substring beg-A end-A))
4344 (body-B (delete-and-extract-region beg-B end-B)))
4345 (goto-char beg-B)
4346 (when specialp
4347 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
4348 (org-indent-to-column ind-B))
4349 (insert body-A)
4350 ;; Restore ex ELEM-A overlays.
4351 (let ((offset (- beg-B beg-A)))
4352 (mapc (lambda (ov)
4353 (move-overlay
4354 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
4355 (car overlays))
4356 (goto-char beg-A)
4357 (delete-region beg-A end-A)
4358 (insert body-B)
4359 ;; Restore ex ELEM-B overlays.
4360 (mapc (lambda (ov)
4361 (move-overlay
4362 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
4363 (cdr overlays)))
4364 (goto-char (org-element-property :end elem-B)))))
4367 (provide 'org-element)
4368 ;;; org-element.el ends here