org-element: Fix previous patch
[org-mode.git] / lisp / org-element.el
blobb7cdc4428cb14a5e225ade43bc9f20fab8d0de7d
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\\|end\\)" "\\|"
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 (t "[.)]") (?\) ")") (?. "\\.") (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-affiliated-keywords
218 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
219 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
220 "List of affiliated keywords as strings.
221 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
222 are affiliated keywords and need not to be in this list.")
224 (defconst org-element--affiliated-re
225 (format "[ \t]*#\\+%s:"
226 ;; Regular affiliated keywords.
227 (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
228 (regexp-opt org-element-affiliated-keywords)))
229 "Regexp matching any affiliated keyword.
231 Keyword name is put in match group 1. Moreover, if keyword
232 belongs to `org-element-dual-keywords', put the dual value in
233 match group 2.
235 Don't modify it, set `org-element-affiliated-keywords' instead.")
237 (defconst org-element-keyword-translation-alist
238 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
239 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
240 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
241 "Alist of usual translations for keywords.
242 The key is the old name and the value the new one. The property
243 holding their value will be named after the translated name.")
245 (defconst org-element-multiple-keywords '("HEADER")
246 "List of affiliated keywords that can occur more that once in an element.
248 Their value will be consed into a list of strings, which will be
249 returned as the value of the property.
251 This list is checked after translations have been applied. See
252 `org-element-keyword-translation-alist'.
254 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
255 allow multiple occurrences and need not to be in this list.")
257 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "DATE" "TITLE")
258 "List of keywords whose value can be parsed.
260 Their value will be stored as a secondary string: a list of
261 strings and objects.
263 This list is checked after translations have been applied. See
264 `org-element-keyword-translation-alist'.")
266 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
267 "List of keywords which can have a secondary value.
269 In Org syntax, they can be written with optional square brackets
270 before the colons. For example, results keyword can be
271 associated to a hash value with the following:
273 #+RESULTS[hash-string]: some-source
275 This list is checked after translations have been applied. See
276 `org-element-keyword-translation-alist'.")
278 (defconst org-element-object-restrictions
279 '((bold export-snippet inline-babel-call inline-src-block latex-or-entity link
280 radio-target sub/superscript target text-markup timestamp)
281 (footnote-reference export-snippet footnote-reference inline-babel-call
282 inline-src-block latex-or-entity line-break link macro
283 radio-target sub/superscript target text-markup
284 timestamp)
285 (headline inline-babel-call inline-src-block latex-or-entity link macro
286 radio-target statistics-cookie sub/superscript target text-markup
287 timestamp)
288 (inlinetask inline-babel-call inline-src-block latex-or-entity link macro
289 radio-target sub/superscript target text-markup timestamp)
290 (italic export-snippet inline-babel-call inline-src-block latex-or-entity
291 link radio-target sub/superscript target text-markup timestamp)
292 (item export-snippet footnote-reference inline-babel-call latex-or-entity
293 link macro radio-target sub/superscript target text-markup)
294 (keyword latex-or-entity macro sub/superscript text-markup)
295 (link export-snippet inline-babel-call inline-src-block latex-or-entity link
296 sub/superscript text-markup)
297 (macro macro)
298 (paragraph export-snippet footnote-reference inline-babel-call
299 inline-src-block latex-or-entity line-break link macro
300 radio-target statistics-cookie sub/superscript target text-markup
301 timestamp)
302 (radio-target export-snippet latex-or-entity sub/superscript)
303 (strike-through export-snippet inline-babel-call inline-src-block
304 latex-or-entity link radio-target sub/superscript target
305 text-markup timestamp)
306 (subscript export-snippet inline-babel-call inline-src-block latex-or-entity
307 sub/superscript target text-markup)
308 (superscript export-snippet inline-babel-call inline-src-block
309 latex-or-entity sub/superscript target text-markup)
310 (table-cell export-snippet latex-or-entity link macro radio-target
311 sub/superscript target text-markup timestamp)
312 (table-row table-cell)
313 (underline export-snippet inline-babel-call inline-src-block latex-or-entity
314 link radio-target sub/superscript target text-markup timestamp)
315 (verse-block footnote-reference inline-babel-call inline-src-block
316 latex-or-entity line-break link macro radio-target
317 sub/superscript target text-markup timestamp))
318 "Alist of objects restrictions.
320 CAR is an element or object type containing objects and CDR is
321 a list of successors that will be called within an element or
322 object of such type.
324 For example, in a `radio-target' object, one can only find
325 entities, export snippets, latex-fragments, subscript and
326 superscript.
328 This alist also applies to secondary string. For example, an
329 `headline' type element doesn't directly contain objects, but
330 still has an entry since one of its properties (`:title') does.")
332 (defconst org-element-secondary-value-alist
333 '((headline . :title)
334 (inlinetask . :title)
335 (item . :tag)
336 (footnote-reference . :inline-definition))
337 "Alist between element types and location of secondary value.")
341 ;;; Accessors and Setters
343 ;; Provide four accessors: `org-element-type', `org-element-property'
344 ;; `org-element-contents' and `org-element-restriction'.
346 ;; Setter functions allow to modify elements by side effect. There is
347 ;; `org-element-put-property', `org-element-set-contents',
348 ;; `org-element-set-element' and `org-element-adopt-element'. Note
349 ;; that `org-element-set-element' and `org-element-adopt-element' are
350 ;; higher level functions since also update `:parent' property.
352 (defsubst org-element-type (element)
353 "Return type of ELEMENT.
355 The function returns the type of the element or object provided.
356 It can also return the following special value:
357 `plain-text' for a string
358 `org-data' for a complete document
359 nil in any other case."
360 (cond
361 ((not (consp element)) (and (stringp element) 'plain-text))
362 ((symbolp (car element)) (car element))))
364 (defsubst org-element-property (property element)
365 "Extract the value from the PROPERTY of an ELEMENT."
366 (plist-get (nth 1 element) property))
368 (defsubst org-element-contents (element)
369 "Extract contents from an ELEMENT."
370 (and (consp element) (nthcdr 2 element)))
372 (defsubst org-element-restriction (element)
373 "Return restriction associated to ELEMENT.
374 ELEMENT can be an element, an object or a symbol representing an
375 element or object type."
376 (cdr (assq (if (symbolp element) element (org-element-type element))
377 org-element-object-restrictions)))
379 (defsubst org-element-put-property (element property value)
380 "In ELEMENT set PROPERTY to VALUE.
381 Return modified element."
382 (when (consp element)
383 (setcar (cdr element) (plist-put (nth 1 element) property value)))
384 element)
386 (defsubst org-element-set-contents (element &rest contents)
387 "Set ELEMENT contents to CONTENTS.
388 Return modified element."
389 (cond ((not element) (list contents))
390 ((cdr element) (setcdr (cdr element) contents))
391 (t (nconc element contents))))
393 (defsubst org-element-set-element (old new)
394 "Replace element or object OLD with element or object NEW.
395 The function takes care of setting `:parent' property for NEW."
396 ;; OLD can belong to the contents of PARENT or to its secondary
397 ;; string.
398 (let* ((parent (org-element-property :parent old))
399 (sec-loc (cdr (assq (org-element-type parent)
400 org-element-secondary-value-alist)))
401 (sec-value (and sec-loc (org-element-property sec-loc parent)))
402 (place (or (memq old sec-value) (memq old parent))))
403 ;; Make sure NEW has correct `:parent' property.
404 (org-element-put-property new :parent parent)
405 ;; Replace OLD with NEW in PARENT.
406 (setcar place new)))
408 (defsubst org-element-adopt-element (parent child &optional append)
409 "Add an element to the contents of another element.
411 PARENT is an element or object. CHILD is an element, an object,
412 or a string.
414 CHILD is added at the beginning of PARENT contents, unless the
415 optional argument APPEND is non-nil, in which case CHILD is added
416 at the end.
418 The function takes care of setting `:parent' property for CHILD.
419 Return parent element."
420 (if (not parent) (list child)
421 (let ((contents (org-element-contents parent)))
422 (apply 'org-element-set-contents
423 parent
424 (if append (append contents (list child)) (cons child contents))))
425 ;; Link the CHILD element with PARENT.
426 (when (consp child) (org-element-put-property child :parent parent))
427 ;; Return the parent element.
428 parent))
432 ;;; Greater elements
434 ;; For each greater element type, we define a parser and an
435 ;; interpreter.
437 ;; A parser returns the element or object as the list described above.
438 ;; Most of them accepts no argument. Though, exceptions exist. Hence
439 ;; every element containing a secondary string (see
440 ;; `org-element-secondary-value-alist') will accept an optional
441 ;; argument to toggle parsing of that secondary string. Moreover,
442 ;; `item' parser requires current list's structure as its first
443 ;; element.
445 ;; An interpreter accepts two arguments: the list representation of
446 ;; the element or object, and its contents. The latter may be nil,
447 ;; depending on the element or object considered. It returns the
448 ;; appropriate Org syntax, as a string.
450 ;; Parsing functions must follow the naming convention:
451 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
452 ;; defined in `org-element-greater-elements'.
454 ;; Similarly, interpreting functions must follow the naming
455 ;; convention: org-element-TYPE-interpreter.
457 ;; With the exception of `headline' and `item' types, greater elements
458 ;; cannot contain other greater elements of their own type.
460 ;; Beside implementing a parser and an interpreter, adding a new
461 ;; greater element requires to tweak `org-element--current-element'.
462 ;; Moreover, the newly defined type must be added to both
463 ;; `org-element-all-elements' and `org-element-greater-elements'.
466 ;;;; Center Block
468 (defun org-element-center-block-parser (limit)
469 "Parse a center block.
471 LIMIT bounds the search.
473 Return a list whose CAR is `center-block' and CDR is a plist
474 containing `:begin', `:end', `:hiddenp', `:contents-begin',
475 `:contents-end' and `:post-blank' keywords.
477 Assume point is at the beginning of the block."
478 (let ((case-fold-search t))
479 (if (not (save-excursion
480 (re-search-forward "^[ \t]*#\\+END_CENTER" limit t)))
481 ;; Incomplete block: parse it as a comment.
482 (org-element-paragraph-parser limit)
483 (let ((block-end-line (match-beginning 0)))
484 (let* ((keywords (org-element--collect-affiliated-keywords))
485 (begin (car keywords))
486 ;; Empty blocks have no contents.
487 (contents-begin (progn (forward-line)
488 (and (< (point) block-end-line)
489 (point))))
490 (contents-end (and contents-begin block-end-line))
491 (hidden (org-invisible-p2))
492 (pos-before-blank (progn (goto-char block-end-line)
493 (forward-line)
494 (point)))
495 (end (save-excursion (skip-chars-forward " \r\t\n" limit)
496 (if (eobp) (point) (point-at-bol)))))
497 (list 'center-block
498 (nconc
499 (list :begin begin
500 :end end
501 :hiddenp hidden
502 :contents-begin contents-begin
503 :contents-end contents-end
504 :post-blank (count-lines pos-before-blank end))
505 (cadr keywords))))))))
507 (defun org-element-center-block-interpreter (center-block contents)
508 "Interpret CENTER-BLOCK element as Org syntax.
509 CONTENTS is the contents of the element."
510 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
513 ;;;; Drawer
515 (defun org-element-drawer-parser (limit)
516 "Parse a drawer.
518 LIMIT bounds the search.
520 Return a list whose CAR is `drawer' and CDR is a plist containing
521 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
522 `:contents-end' and `:post-blank' keywords.
524 Assume point is at beginning of drawer."
525 (let ((case-fold-search t))
526 (if (not (save-excursion (re-search-forward "^[ \t]*:END:" limit t)))
527 ;; Incomplete drawer: parse it as a paragraph.
528 (org-element-paragraph-parser limit)
529 (let ((drawer-end-line (match-beginning 0)))
530 (save-excursion
531 (let* ((case-fold-search t)
532 (name (progn (looking-at org-drawer-regexp)
533 (org-match-string-no-properties 1)))
534 (keywords (org-element--collect-affiliated-keywords))
535 (begin (car keywords))
536 ;; Empty drawers have no contents.
537 (contents-begin (progn (forward-line)
538 (and (< (point) drawer-end-line)
539 (point))))
540 (contents-end (and contents-begin drawer-end-line))
541 (hidden (org-invisible-p2))
542 (pos-before-blank (progn (goto-char drawer-end-line)
543 (forward-line)
544 (point)))
545 (end (progn (skip-chars-forward " \r\t\n" limit)
546 (if (eobp) (point) (point-at-bol)))))
547 (list 'drawer
548 (nconc
549 (list :begin begin
550 :end end
551 :drawer-name name
552 :hiddenp hidden
553 :contents-begin contents-begin
554 :contents-end contents-end
555 :post-blank (count-lines pos-before-blank end))
556 (cadr keywords)))))))))
558 (defun org-element-drawer-interpreter (drawer contents)
559 "Interpret DRAWER element as Org syntax.
560 CONTENTS is the contents of the element."
561 (format ":%s:\n%s:END:"
562 (org-element-property :drawer-name drawer)
563 contents))
566 ;;;; Dynamic Block
568 (defun org-element-dynamic-block-parser (limit)
569 "Parse a dynamic block.
571 LIMIT bounds the search.
573 Return a list whose CAR is `dynamic-block' and CDR is a plist
574 containing `:block-name', `:begin', `:end', `:hiddenp',
575 `:contents-begin', `:contents-end', `:arguments' and
576 `:post-blank' keywords.
578 Assume point is at beginning of dynamic block."
579 (let ((case-fold-search t))
580 (if (not (save-excursion (re-search-forward org-dblock-end-re limit t)))
581 ;; Incomplete block: parse it as a comment.
582 (org-element-paragraph-parser limit)
583 (let ((block-end-line (match-beginning 0)))
584 (save-excursion
585 (let* ((name (progn (looking-at org-dblock-start-re)
586 (org-match-string-no-properties 1)))
587 (arguments (org-match-string-no-properties 3))
588 (keywords (org-element--collect-affiliated-keywords))
589 (begin (car keywords))
590 ;; Empty blocks have no contents.
591 (contents-begin (progn (forward-line)
592 (and (< (point) block-end-line)
593 (point))))
594 (contents-end (and contents-begin block-end-line))
595 (hidden (org-invisible-p2))
596 (pos-before-blank (progn (goto-char block-end-line)
597 (forward-line)
598 (point)))
599 (end (progn (skip-chars-forward " \r\t\n" limit)
600 (if (eobp) (point) (point-at-bol)))))
601 (list 'dynamic-block
602 (nconc
603 (list :begin begin
604 :end end
605 :block-name name
606 :arguments arguments
607 :hiddenp hidden
608 :contents-begin contents-begin
609 :contents-end contents-end
610 :post-blank (count-lines pos-before-blank end))
611 (cadr keywords)))))))))
613 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
614 "Interpret DYNAMIC-BLOCK element as Org syntax.
615 CONTENTS is the contents of the element."
616 (format "#+BEGIN: %s%s\n%s#+END:"
617 (org-element-property :block-name dynamic-block)
618 (let ((args (org-element-property :arguments dynamic-block)))
619 (and args (concat " " args)))
620 contents))
623 ;;;; Footnote Definition
625 (defun org-element-footnote-definition-parser (limit)
626 "Parse a footnote definition.
628 LIMIT bounds the search.
630 Return a list whose CAR is `footnote-definition' and CDR is
631 a plist containing `:label', `:begin' `:end', `:contents-begin',
632 `:contents-end' and `:post-blank' keywords.
634 Assume point is at the beginning of the footnote definition."
635 (save-excursion
636 (let* ((label (progn (looking-at org-footnote-definition-re)
637 (org-match-string-no-properties 1)))
638 (keywords (org-element--collect-affiliated-keywords))
639 (begin (car keywords))
640 (ending (save-excursion
641 (if (progn
642 (end-of-line)
643 (re-search-forward
644 (concat org-outline-regexp-bol "\\|"
645 org-footnote-definition-re "\\|"
646 "^[ \t]*$") limit 'move))
647 (match-beginning 0)
648 (point))))
649 (contents-begin (progn (search-forward "]")
650 (skip-chars-forward " \r\t\n" ending)
651 (and (/= (point) ending) (point))))
652 (contents-end (and contents-begin ending))
653 (end (progn (goto-char ending)
654 (skip-chars-forward " \r\t\n" limit)
655 (if (eobp) (point) (point-at-bol)))))
656 (list 'footnote-definition
657 (nconc
658 (list :label label
659 :begin begin
660 :end end
661 :contents-begin contents-begin
662 :contents-end contents-end
663 :post-blank (count-lines ending end))
664 (cadr keywords))))))
666 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
667 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
668 CONTENTS is the contents of the footnote-definition."
669 (concat (format "[%s]" (org-element-property :label footnote-definition))
671 contents))
674 ;;;; Headline
676 (defun org-element-headline-parser (limit &optional raw-secondary-p)
677 "Parse an headline.
679 Return a list whose CAR is `headline' and CDR is a plist
680 containing `:raw-value', `:title', `:begin', `:end',
681 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
682 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
683 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
684 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
685 keywords.
687 The plist also contains any property set in the property drawer,
688 with its name in lowercase, the underscores replaced with hyphens
689 and colons at the beginning (i.e. `:custom-id').
691 When RAW-SECONDARY-P is non-nil, headline's title will not be
692 parsed as a secondary string, but as a plain string instead.
694 Assume point is at beginning of the headline."
695 (save-excursion
696 (let* ((components (org-heading-components))
697 (level (nth 1 components))
698 (todo (nth 2 components))
699 (todo-type
700 (and todo (if (member todo org-done-keywords) 'done 'todo)))
701 (tags (let ((raw-tags (nth 5 components)))
702 (and raw-tags (org-split-string raw-tags ":"))))
703 (raw-value (nth 4 components))
704 (quotedp
705 (let ((case-fold-search nil))
706 (string-match (format "^%s +" org-quote-string) raw-value)))
707 (commentedp
708 (let ((case-fold-search nil))
709 (string-match (format "^%s +" org-comment-string) raw-value)))
710 (archivedp (member org-archive-tag tags))
711 (footnote-section-p (and org-footnote-section
712 (string= org-footnote-section raw-value)))
713 ;; Normalize property names: ":SOME_PROP:" becomes
714 ;; ":some-prop".
715 (standard-props (let (plist)
716 (mapc
717 (lambda (p)
718 (let ((p-name (downcase (car p))))
719 (while (string-match "_" p-name)
720 (setq p-name
721 (replace-match "-" nil nil p-name)))
722 (setq p-name (intern (concat ":" p-name)))
723 (setq plist
724 (plist-put plist p-name (cdr p)))))
725 (org-entry-properties nil 'standard))
726 plist))
727 (time-props (org-entry-properties nil 'special "CLOCK"))
728 (scheduled (cdr (assoc "SCHEDULED" time-props)))
729 (deadline (cdr (assoc "DEADLINE" time-props)))
730 (clock (cdr (assoc "CLOCK" time-props)))
731 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
732 (begin (point))
733 (end (save-excursion (goto-char (org-end-of-subtree t t))))
734 (pos-after-head (progn (forward-line) (point)))
735 (contents-begin (save-excursion
736 (skip-chars-forward " \r\t\n" end)
737 (and (/= (point) end) (line-beginning-position))))
738 (hidden (org-invisible-p2))
739 (contents-end (and contents-begin
740 (progn (goto-char end)
741 (skip-chars-backward " \r\t\n")
742 (forward-line)
743 (point)))))
744 ;; Clean RAW-VALUE from any quote or comment string.
745 (when (or quotedp commentedp)
746 (setq raw-value
747 (replace-regexp-in-string
748 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
750 raw-value)))
751 ;; Clean TAGS from archive tag, if any.
752 (when archivedp (setq tags (delete org-archive-tag tags)))
753 (let ((headline
754 (list 'headline
755 (nconc
756 (list :raw-value raw-value
757 :begin begin
758 :end end
759 :pre-blank
760 (if (not contents-begin) 0
761 (count-lines pos-after-head contents-begin))
762 :hiddenp hidden
763 :contents-begin contents-begin
764 :contents-end contents-end
765 :level level
766 :priority (nth 3 components)
767 :tags tags
768 :todo-keyword todo
769 :todo-type todo-type
770 :scheduled scheduled
771 :deadline deadline
772 :timestamp timestamp
773 :clock clock
774 :post-blank (count-lines
775 (if (not contents-end) pos-after-head
776 (goto-char contents-end)
777 (forward-line)
778 (point))
779 end)
780 :footnote-section-p footnote-section-p
781 :archivedp archivedp
782 :commentedp commentedp
783 :quotedp quotedp)
784 standard-props))))
785 (org-element-put-property
786 headline :title
787 (if raw-secondary-p raw-value
788 (org-element-parse-secondary-string
789 raw-value (org-element-restriction 'headline) headline)))))))
791 (defun org-element-headline-interpreter (headline contents)
792 "Interpret HEADLINE element as Org syntax.
793 CONTENTS is the contents of the element."
794 (let* ((level (org-element-property :level headline))
795 (todo (org-element-property :todo-keyword headline))
796 (priority (org-element-property :priority headline))
797 (title (org-element-interpret-data
798 (org-element-property :title headline)))
799 (tags (let ((tag-list (if (org-element-property :archivedp headline)
800 (cons org-archive-tag
801 (org-element-property :tags headline))
802 (org-element-property :tags headline))))
803 (and tag-list
804 (format ":%s:" (mapconcat 'identity tag-list ":")))))
805 (commentedp (org-element-property :commentedp headline))
806 (quotedp (org-element-property :quotedp headline))
807 (pre-blank (or (org-element-property :pre-blank headline) 0))
808 (heading (concat (make-string level ?*)
809 (and todo (concat " " todo))
810 (and quotedp (concat " " org-quote-string))
811 (and commentedp (concat " " org-comment-string))
812 (and priority
813 (format " [#%s]" (char-to-string priority)))
814 (cond ((and org-footnote-section
815 (org-element-property
816 :footnote-section-p headline))
817 (concat " " org-footnote-section))
818 (title (concat " " title))))))
819 (concat heading
820 ;; Align tags.
821 (when tags
822 (cond
823 ((zerop org-tags-column) (format " %s" tags))
824 ((< org-tags-column 0)
825 (concat
826 (make-string
827 (max (- (+ org-tags-column (length heading) (length tags))) 1)
829 tags))
831 (concat
832 (make-string (max (- org-tags-column (length heading)) 1) ? )
833 tags))))
834 (make-string (1+ pre-blank) 10)
835 contents)))
838 ;;;; Inlinetask
840 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
841 "Parse an inline task.
843 Return a list whose CAR is `inlinetask' and CDR is a plist
844 containing `:title', `:begin', `:end', `:hiddenp',
845 `:contents-begin' and `:contents-end', `:level', `:priority',
846 `:tags', `:todo-keyword', `:todo-type', `:scheduled',
847 `:deadline', `:timestamp', `:clock' and `:post-blank' keywords.
849 The plist also contains any property set in the property drawer,
850 with its name in lowercase, the underscores replaced with hyphens
851 and colons at the beginning (i.e. `:custom-id').
853 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
854 title will not be parsed as a secondary string, but as a plain
855 string instead.
857 Assume point is at beginning of the inline task."
858 (save-excursion
859 (let* ((keywords (org-element--collect-affiliated-keywords))
860 (begin (car keywords))
861 (components (org-heading-components))
862 (todo (nth 2 components))
863 (todo-type (and todo
864 (if (member todo org-done-keywords) 'done 'todo)))
865 (tags (let ((raw-tags (nth 5 components)))
866 (and raw-tags (org-split-string raw-tags ":"))))
867 ;; Normalize property names: ":SOME_PROP:" becomes
868 ;; ":some-prop".
869 (standard-props (let (plist)
870 (mapc
871 (lambda (p)
872 (let ((p-name (downcase (car p))))
873 (while (string-match "_" p-name)
874 (setq p-name
875 (replace-match "-" nil nil p-name)))
876 (setq p-name (intern (concat ":" p-name)))
877 (setq plist
878 (plist-put plist p-name (cdr p)))))
879 (org-entry-properties nil 'standard))
880 plist))
881 (time-props (org-entry-properties nil 'special "CLOCK"))
882 (scheduled (cdr (assoc "SCHEDULED" time-props)))
883 (deadline (cdr (assoc "DEADLINE" time-props)))
884 (clock (cdr (assoc "CLOCK" time-props)))
885 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
886 (task-end (save-excursion
887 (end-of-line)
888 (and (re-search-forward "^\\*+ END" limit t)
889 (match-beginning 0))))
890 (contents-begin (progn (forward-line)
891 (and task-end (< (point) task-end) (point))))
892 (hidden (and contents-begin (org-invisible-p2)))
893 (contents-end (and contents-begin task-end))
894 (before-blank (if (not task-end) (point)
895 (goto-char task-end)
896 (forward-line)
897 (point)))
898 (end (progn (skip-chars-forward " \r\t\n" limit)
899 (if (eobp) (point) (point-at-bol))))
900 (inlinetask
901 (list 'inlinetask
902 (nconc
903 (list :begin begin
904 :end end
905 :hiddenp hidden
906 :contents-begin contents-begin
907 :contents-end contents-end
908 :level (nth 1 components)
909 :priority (nth 3 components)
910 :tags tags
911 :todo-keyword todo
912 :todo-type todo-type
913 :scheduled scheduled
914 :deadline deadline
915 :timestamp timestamp
916 :clock clock
917 :post-blank (count-lines before-blank end))
918 standard-props
919 (cadr keywords)))))
920 (org-element-put-property
921 inlinetask :title
922 (if raw-secondary-p (nth 4 components)
923 (org-element-parse-secondary-string
924 (nth 4 components)
925 (org-element-restriction 'inlinetask)
926 inlinetask))))))
928 (defun org-element-inlinetask-interpreter (inlinetask contents)
929 "Interpret INLINETASK element as Org syntax.
930 CONTENTS is the contents of inlinetask."
931 (let* ((level (org-element-property :level inlinetask))
932 (todo (org-element-property :todo-keyword inlinetask))
933 (priority (org-element-property :priority inlinetask))
934 (title (org-element-interpret-data
935 (org-element-property :title inlinetask)))
936 (tags (let ((tag-list (org-element-property :tags inlinetask)))
937 (and tag-list
938 (format ":%s:" (mapconcat 'identity tag-list ":")))))
939 (task (concat (make-string level ?*)
940 (and todo (concat " " todo))
941 (and priority
942 (format " [#%s]" (char-to-string priority)))
943 (and title (concat " " title)))))
944 (concat task
945 ;; Align tags.
946 (when tags
947 (cond
948 ((zerop org-tags-column) (format " %s" tags))
949 ((< org-tags-column 0)
950 (concat
951 (make-string
952 (max (- (+ org-tags-column (length task) (length tags))) 1)
954 tags))
956 (concat
957 (make-string (max (- org-tags-column (length task)) 1) ? )
958 tags))))
959 ;; Prefer degenerate inlinetasks when there are no
960 ;; contents.
961 (when contents
962 (concat "\n"
963 contents
964 (make-string level ?*) " END")))))
967 ;;;; Item
969 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
970 "Parse an item.
972 STRUCT is the structure of the plain list.
974 Return a list whose CAR is `item' and CDR is a plist containing
975 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
976 `:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
977 `:post-blank' keywords.
979 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
980 any, will not be parsed as a secondary string, but as a plain
981 string instead.
983 Assume point is at the beginning of the item."
984 (save-excursion
985 (beginning-of-line)
986 (let* ((begin (point))
987 (bullet (org-list-get-bullet (point) struct))
988 (checkbox (let ((box (org-list-get-checkbox begin struct)))
989 (cond ((equal "[ ]" box) 'off)
990 ((equal "[X]" box) 'on)
991 ((equal "[-]" box) 'trans))))
992 (counter (let ((c (org-list-get-counter begin struct)))
993 (cond
994 ((not c) nil)
995 ((string-match "[A-Za-z]" c)
996 (- (string-to-char (upcase (match-string 0 c)))
997 64))
998 ((string-match "[0-9]+" c)
999 (string-to-number (match-string 0 c))))))
1000 (end (save-excursion (goto-char (org-list-get-item-end begin struct))
1001 (unless (bolp) (forward-line))
1002 (point)))
1003 (contents-begin (progn (looking-at org-list-full-item-re)
1004 (goto-char (match-end 0))
1005 (skip-chars-forward " \r\t\n" limit)
1006 ;; If first line isn't empty,
1007 ;; contents really start at the text
1008 ;; after item's meta-data.
1009 (if (= (point-at-bol) begin) (point)
1010 (point-at-bol))))
1011 (hidden (progn (forward-line)
1012 (and (not (= (point) end))
1013 (org-invisible-p2))))
1014 (contents-end (progn (goto-char end)
1015 (skip-chars-backward " \r\t\n")
1016 (forward-line)
1017 (point)))
1018 (item
1019 (list 'item
1020 (list :bullet bullet
1021 :begin begin
1022 :end end
1023 ;; CONTENTS-BEGIN and CONTENTS-END may be
1024 ;; mixed up in the case of an empty item
1025 ;; separated from the next by a blank line.
1026 ;; Thus ensure the former is always the
1027 ;; smallest.
1028 :contents-begin (min contents-begin contents-end)
1029 :contents-end (max contents-begin contents-end)
1030 :checkbox checkbox
1031 :counter counter
1032 :hiddenp hidden
1033 :structure struct
1034 :post-blank (count-lines contents-end end)))))
1035 (org-element-put-property
1036 item :tag
1037 (let ((raw-tag (org-list-get-tag begin struct)))
1038 (and raw-tag
1039 (if raw-secondary-p raw-tag
1040 (org-element-parse-secondary-string
1041 raw-tag (org-element-restriction 'item) item))))))))
1043 (defun org-element-item-interpreter (item contents)
1044 "Interpret ITEM element as Org syntax.
1045 CONTENTS is the contents of the element."
1046 (let* ((bullet (org-list-bullet-string (org-element-property :bullet item)))
1047 (checkbox (org-element-property :checkbox item))
1048 (counter (org-element-property :counter item))
1049 (tag (let ((tag (org-element-property :tag item)))
1050 (and tag (org-element-interpret-data tag))))
1051 ;; Compute indentation.
1052 (ind (make-string (length bullet) 32))
1053 (item-starts-with-par-p
1054 (eq (org-element-type (car (org-element-contents item)))
1055 'paragraph)))
1056 ;; Indent contents.
1057 (concat
1058 bullet
1059 (and counter (format "[@%d] " counter))
1060 (case checkbox
1061 (on "[X] ")
1062 (off "[ ] ")
1063 (trans "[-] "))
1064 (and tag (format "%s :: " tag))
1065 (let ((contents (replace-regexp-in-string
1066 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1067 (if item-starts-with-par-p (org-trim contents)
1068 (concat "\n" contents))))))
1071 ;;;; Plain List
1073 (defun org-element-plain-list-parser (limit &optional structure)
1074 "Parse a plain list.
1076 Optional argument STRUCTURE, when non-nil, is the structure of
1077 the plain list being parsed.
1079 Return a list whose CAR is `plain-list' and CDR is a plist
1080 containing `:type', `:begin', `:end', `:contents-begin' and
1081 `:contents-end', `:structure' and `:post-blank' keywords.
1083 Assume point is at the beginning of the list."
1084 (save-excursion
1085 (let* ((struct (or structure (org-list-struct)))
1086 (prevs (org-list-prevs-alist struct))
1087 (parents (org-list-parents-alist struct))
1088 (type (org-list-get-list-type (point) struct prevs))
1089 (contents-begin (point))
1090 (keywords (org-element--collect-affiliated-keywords))
1091 (begin (car keywords))
1092 (contents-end
1093 (progn (goto-char (org-list-get-list-end (point) struct prevs))
1094 (unless (bolp) (forward-line))
1095 (point)))
1096 (end (progn (skip-chars-forward " \r\t\n" limit)
1097 (if (eobp) (point) (point-at-bol)))))
1098 ;; Return value.
1099 (list 'plain-list
1100 (nconc
1101 (list :type type
1102 :begin begin
1103 :end end
1104 :contents-begin contents-begin
1105 :contents-end contents-end
1106 :structure struct
1107 :post-blank (count-lines contents-end end))
1108 (cadr keywords))))))
1110 (defun org-element-plain-list-interpreter (plain-list contents)
1111 "Interpret PLAIN-LIST element as Org syntax.
1112 CONTENTS is the contents of the element."
1113 (with-temp-buffer
1114 (insert contents)
1115 (goto-char (point-min))
1116 (org-list-repair)
1117 (buffer-string)))
1120 ;;;; Quote Block
1122 (defun org-element-quote-block-parser (limit)
1123 "Parse a quote block.
1125 LIMIT bounds the search.
1127 Return a list whose CAR is `quote-block' and CDR is a plist
1128 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1129 `:contents-end' and `:post-blank' keywords.
1131 Assume point is at the beginning of the block."
1132 (let ((case-fold-search t))
1133 (if (not (save-excursion
1134 (re-search-forward "^[ \t]*#\\+END_QUOTE" limit t)))
1135 ;; Incomplete block: parse it as a comment.
1136 (org-element-paragraph-parser limit)
1137 (let ((block-end-line (match-beginning 0)))
1138 (save-excursion
1139 (let* ((keywords (org-element--collect-affiliated-keywords))
1140 (begin (car keywords))
1141 ;; Empty blocks have no contents.
1142 (contents-begin (progn (forward-line)
1143 (and (< (point) block-end-line)
1144 (point))))
1145 (contents-end (and contents-begin block-end-line))
1146 (hidden (org-invisible-p2))
1147 (pos-before-blank (progn (goto-char block-end-line)
1148 (forward-line)
1149 (point)))
1150 (end (progn (skip-chars-forward " \r\t\n" limit)
1151 (if (eobp) (point) (point-at-bol)))))
1152 (list 'quote-block
1153 (nconc
1154 (list :begin begin
1155 :end end
1156 :hiddenp hidden
1157 :contents-begin contents-begin
1158 :contents-end contents-end
1159 :post-blank (count-lines pos-before-blank end))
1160 (cadr keywords)))))))))
1162 (defun org-element-quote-block-interpreter (quote-block contents)
1163 "Interpret QUOTE-BLOCK element as Org syntax.
1164 CONTENTS is the contents of the element."
1165 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1168 ;;;; Section
1170 (defun org-element-section-parser (limit)
1171 "Parse a section.
1173 LIMIT bounds the search.
1175 Return a list whose CAR is `section' and CDR is a plist
1176 containing `:begin', `:end', `:contents-begin', `contents-end'
1177 and `:post-blank' keywords."
1178 (save-excursion
1179 ;; Beginning of section is the beginning of the first non-blank
1180 ;; line after previous headline.
1181 (org-with-limited-levels
1182 (let ((begin (point))
1183 (end (progn (goto-char limit) (point)))
1184 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1185 (forward-line)
1186 (point))))
1187 (list 'section
1188 (list :begin begin
1189 :end end
1190 :contents-begin begin
1191 :contents-end pos-before-blank
1192 :post-blank (count-lines pos-before-blank end)))))))
1194 (defun org-element-section-interpreter (section contents)
1195 "Interpret SECTION element as Org syntax.
1196 CONTENTS is the contents of the element."
1197 contents)
1200 ;;;; Special Block
1202 (defun org-element-special-block-parser (limit)
1203 "Parse a special block.
1205 LIMIT bounds the search.
1207 Return a list whose CAR is `special-block' and CDR is a plist
1208 containing `:type', `:begin', `:end', `:hiddenp',
1209 `:contents-begin', `:contents-end' and `:post-blank' keywords.
1211 Assume point is at the beginning of the block."
1212 (let* ((case-fold-search t)
1213 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(S-+\\)")
1214 (upcase (match-string-no-properties 1)))))
1215 (if (not (save-excursion
1216 (re-search-forward (concat "^[ \t]*#\\+END_" type) limit t)))
1217 ;; Incomplete block: parse it as a comment.
1218 (org-element-paragraph-parser limit)
1219 (let ((block-end-line (match-beginning 0)))
1220 (save-excursion
1221 (let* ((keywords (org-element--collect-affiliated-keywords))
1222 (begin (car keywords))
1223 ;; Empty blocks have no contents.
1224 (contents-begin (progn (forward-line)
1225 (and (< (point) block-end-line)
1226 (point))))
1227 (contents-end (and contents-begin block-end-line))
1228 (hidden (org-invisible-p2))
1229 (pos-before-blank (progn (goto-char block-end-line)
1230 (forward-line)
1231 (point)))
1232 (end (progn (org-skip-whitespace)
1233 (if (eobp) (point) (point-at-bol)))))
1234 (list 'special-block
1235 (nconc
1236 (list :type type
1237 :begin begin
1238 :end end
1239 :hiddenp hidden
1240 :contents-begin contents-begin
1241 :contents-end contents-end
1242 :post-blank (count-lines pos-before-blank end))
1243 (cadr keywords)))))))))
1245 (defun org-element-special-block-interpreter (special-block contents)
1246 "Interpret SPECIAL-BLOCK element as Org syntax.
1247 CONTENTS is the contents of the element."
1248 (let ((block-type (org-element-property :type special-block)))
1249 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1253 ;;; Elements
1255 ;; For each element, a parser and an interpreter are also defined.
1256 ;; Both follow the same naming convention used for greater elements.
1258 ;; Also, as for greater elements, adding a new element type is done
1259 ;; through the following steps: implement a parser and an interpreter,
1260 ;; tweak `org-element--current-element' so that it recognizes the new
1261 ;; type and add that new type to `org-element-all-elements'.
1263 ;; As a special case, when the newly defined type is a block type,
1264 ;; `org-element-block-name-alist' has to be modified accordingly.
1267 ;;;; Babel Call
1269 (defun org-element-babel-call-parser (limit)
1270 "Parse a babel call.
1272 LIMIT bounds the search.
1274 Return a list whose CAR is `babel-call' and CDR is a plist
1275 containing `:begin', `:end', `:info' and `:post-blank' as
1276 keywords."
1277 (save-excursion
1278 (let ((case-fold-search t)
1279 (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
1280 (org-babel-lob-get-info)))
1281 (begin (point-at-bol))
1282 (pos-before-blank (progn (forward-line) (point)))
1283 (end (progn (skip-chars-forward " \r\t\n" limit)
1284 (if (eobp) (point) (point-at-bol)))))
1285 (list 'babel-call
1286 (list :begin begin
1287 :end end
1288 :info info
1289 :post-blank (count-lines pos-before-blank end))))))
1291 (defun org-element-babel-call-interpreter (babel-call contents)
1292 "Interpret BABEL-CALL element as Org syntax.
1293 CONTENTS is nil."
1294 (let* ((babel-info (org-element-property :info babel-call))
1295 (main (car babel-info))
1296 (post-options (nth 1 babel-info)))
1297 (concat "#+CALL: "
1298 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
1299 ;; Remove redundant square brackets.
1300 (replace-match (match-string 1 main) nil nil main))
1301 (and post-options (format "[%s]" post-options)))))
1304 ;;;; Clock
1306 (defun org-element-clock-parser (limit)
1307 "Parse a clock.
1309 LIMIT bounds the search.
1311 Return a list whose CAR is `clock' and CDR is a plist containing
1312 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1313 as keywords."
1314 (save-excursion
1315 (let* ((case-fold-search nil)
1316 (begin (point))
1317 (value (progn (search-forward org-clock-string (line-end-position) t)
1318 (org-skip-whitespace)
1319 (looking-at "\\[.*\\]")
1320 (org-match-string-no-properties 0)))
1321 (time (and (progn (goto-char (match-end 0))
1322 (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
1323 (org-match-string-no-properties 1)))
1324 (status (if time 'closed 'running))
1325 (post-blank (let ((before-blank (progn (forward-line) (point))))
1326 (skip-chars-forward " \r\t\n" limit)
1327 (unless (eobp) (beginning-of-line))
1328 (count-lines before-blank (point))))
1329 (end (point)))
1330 (list 'clock
1331 (list :status status
1332 :value value
1333 :time time
1334 :begin begin
1335 :end end
1336 :post-blank post-blank)))))
1338 (defun org-element-clock-interpreter (clock contents)
1339 "Interpret CLOCK element as Org syntax.
1340 CONTENTS is nil."
1341 (concat org-clock-string " "
1342 (org-element-property :value clock)
1343 (let ((time (org-element-property :time clock)))
1344 (and time
1345 (concat " => "
1346 (apply 'format
1347 "%2s:%02s"
1348 (org-split-string time ":")))))))
1351 ;;;; Comment
1353 (defun org-element-comment-parser (limit)
1354 "Parse a comment.
1356 LIMIT bounds the search.
1358 Return a list whose CAR is `comment' and CDR is a plist
1359 containing `:begin', `:end', `:value' and `:post-blank'
1360 keywords.
1362 Assume point is at comment beginning."
1363 (save-excursion
1364 (let* ((keywords (org-element--collect-affiliated-keywords))
1365 (begin (car keywords))
1366 (value (prog2 (looking-at "[ \t]*# ?")
1367 (buffer-substring-no-properties
1368 (match-end 0) (line-end-position))
1369 (forward-line)))
1370 (com-end
1371 ;; Get comments ending.
1372 (progn
1373 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1374 ;; Accumulate lines without leading hash and first
1375 ;; whitespace.
1376 (setq value
1377 (concat value
1378 "\n"
1379 (buffer-substring-no-properties
1380 (match-end 0) (line-end-position))))
1381 (forward-line))
1382 (point)))
1383 (end (progn (goto-char com-end)
1384 (skip-chars-forward " \r\t\n" limit)
1385 (if (eobp) (point) (point-at-bol)))))
1386 (list 'comment
1387 (nconc
1388 (list :begin begin
1389 :end end
1390 :value value
1391 :post-blank (count-lines com-end end))
1392 (cadr keywords))))))
1394 (defun org-element-comment-interpreter (comment contents)
1395 "Interpret COMMENT element as Org syntax.
1396 CONTENTS is nil."
1397 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1400 ;;;; Comment Block
1402 (defun org-element-comment-block-parser (limit)
1403 "Parse an export block.
1405 LIMIT bounds the search.
1407 Return a list whose CAR is `comment-block' and CDR is a plist
1408 containing `:begin', `:end', `:hiddenp', `:value' and
1409 `:post-blank' keywords.
1411 Assume point is at comment block beginning."
1412 (let ((case-fold-search t))
1413 (if (not (save-excursion
1414 (re-search-forward "^[ \t]*#\\+END_COMMENT" limit t)))
1415 ;; Incomplete block: parse it as a comment.
1416 (org-element-paragraph-parser limit)
1417 (let ((contents-end (match-beginning 0)))
1418 (save-excursion
1419 (let* ((keywords (org-element--collect-affiliated-keywords))
1420 (begin (car keywords))
1421 (contents-begin (progn (forward-line) (point)))
1422 (hidden (org-invisible-p2))
1423 (pos-before-blank (progn (goto-char contents-end)
1424 (forward-line)
1425 (point)))
1426 (end (progn (skip-chars-forward " \r\t\n" limit)
1427 (if (eobp) (point) (point-at-bol))))
1428 (value (buffer-substring-no-properties
1429 contents-begin contents-end)))
1430 (list 'comment-block
1431 (nconc
1432 (list :begin begin
1433 :end end
1434 :value value
1435 :hiddenp hidden
1436 :post-blank (count-lines pos-before-blank end))
1437 (cadr keywords)))))))))
1439 (defun org-element-comment-block-interpreter (comment-block contents)
1440 "Interpret COMMENT-BLOCK element as Org syntax.
1441 CONTENTS is nil."
1442 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1443 (org-remove-indentation (org-element-property :value comment-block))))
1446 ;;;; Example Block
1448 (defun org-element-example-block-parser (limit)
1449 "Parse an example block.
1451 LIMIT bounds the search.
1453 Return a list whose CAR is `example-block' and CDR is a plist
1454 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1455 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1456 `:switches', `:value' and `:post-blank' keywords."
1457 (let ((case-fold-search t))
1458 (if (not (save-excursion
1459 (re-search-forward "^[ \t]*#\\+END_EXAMPLE" limit t)))
1460 ;; Incomplete block: parse it as a comment.
1461 (org-element-paragraph-parser limit)
1462 (let ((contents-end (match-beginning 0)))
1463 (save-excursion
1464 (let* ((switches
1465 (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1466 (org-match-string-no-properties 1)))
1467 ;; Switches analysis
1468 (number-lines (cond ((not switches) nil)
1469 ((string-match "-n\\>" switches) 'new)
1470 ((string-match "+n\\>" switches) 'continued)))
1471 (preserve-indent (and switches (string-match "-i\\>" switches)))
1472 ;; Should labels be retained in (or stripped from) example
1473 ;; blocks?
1474 (retain-labels
1475 (or (not switches)
1476 (not (string-match "-r\\>" switches))
1477 (and number-lines (string-match "-k\\>" switches))))
1478 ;; What should code-references use - labels or
1479 ;; line-numbers?
1480 (use-labels
1481 (or (not switches)
1482 (and retain-labels (not (string-match "-k\\>" switches)))))
1483 (label-fmt (and switches
1484 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1485 (match-string 1 switches)))
1486 ;; Standard block parsing.
1487 (keywords (org-element--collect-affiliated-keywords))
1488 (begin (car keywords))
1489 (contents-begin (progn (forward-line) (point)))
1490 (hidden (org-invisible-p2))
1491 (value (buffer-substring-no-properties contents-begin contents-end))
1492 (pos-before-blank (progn (goto-char contents-end)
1493 (forward-line)
1494 (point)))
1495 (end (progn (skip-chars-forward " \r\t\n" limit)
1496 (if (eobp) (point) (point-at-bol)))))
1497 (list 'example-block
1498 (nconc
1499 (list :begin begin
1500 :end end
1501 :value value
1502 :switches switches
1503 :number-lines number-lines
1504 :preserve-indent preserve-indent
1505 :retain-labels retain-labels
1506 :use-labels use-labels
1507 :label-fmt label-fmt
1508 :hiddenp hidden
1509 :post-blank (count-lines pos-before-blank end))
1510 (cadr keywords)))))))))
1512 (defun org-element-example-block-interpreter (example-block contents)
1513 "Interpret EXAMPLE-BLOCK element as Org syntax.
1514 CONTENTS is nil."
1515 (let ((switches (org-element-property :switches example-block)))
1516 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1517 (org-remove-indentation
1518 (org-element-property :value example-block))
1519 "#+END_EXAMPLE")))
1522 ;;;; Export Block
1524 (defun org-element-export-block-parser (limit)
1525 "Parse an export block.
1527 LIMIT bounds the search.
1529 Return a list whose CAR is `export-block' and CDR is a plist
1530 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1531 `:post-blank' keywords.
1533 Assume point is at export-block beginning."
1534 (let* ((case-fold-search t)
1535 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1536 (upcase (org-match-string-no-properties 1)))))
1537 (if (not (save-excursion
1538 (re-search-forward (concat "^[ \t]*#\\+END_" type) limit t)))
1539 ;; Incomplete block: parse it as a comment.
1540 (org-element-paragraph-parser limit)
1541 (let ((contents-end (match-beginning 0)))
1542 (save-excursion
1543 (let* ((keywords (org-element--collect-affiliated-keywords))
1544 (begin (car keywords))
1545 (contents-begin (progn (forward-line) (point)))
1546 (hidden (org-invisible-p2))
1547 (pos-before-blank (progn (goto-char contents-end)
1548 (forward-line)
1549 (point)))
1550 (end (progn (skip-chars-forward " \r\t\n" limit)
1551 (if (eobp) (point) (point-at-bol))))
1552 (value (buffer-substring-no-properties contents-begin
1553 contents-end)))
1554 (list 'export-block
1555 (nconc
1556 (list :begin begin
1557 :end end
1558 :type type
1559 :value value
1560 :hiddenp hidden
1561 :post-blank (count-lines pos-before-blank end))
1562 (cadr keywords)))))))))
1564 (defun org-element-export-block-interpreter (export-block contents)
1565 "Interpret EXPORT-BLOCK element as Org syntax.
1566 CONTENTS is nil."
1567 (let ((type (org-element-property :type export-block)))
1568 (concat (format "#+BEGIN_%s\n" type)
1569 (org-element-property :value export-block)
1570 (format "#+END_%s" type))))
1573 ;;;; Fixed-width
1575 (defun org-element-fixed-width-parser (limit)
1576 "Parse a fixed-width section.
1578 LIMIT bounds the search.
1580 Return a list whose CAR is `fixed-width' and CDR is a plist
1581 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1583 Assume point is at the beginning of the fixed-width area."
1584 (save-excursion
1585 (let* ((keywords (org-element--collect-affiliated-keywords))
1586 (begin (car keywords))
1587 value
1588 (end-area
1589 (progn
1590 (while (and (< (point) limit)
1591 (looking-at "[ \t]*:\\( \\|$\\)"))
1592 ;; Accumulate text without starting colons.
1593 (setq value
1594 (concat value
1595 (buffer-substring-no-properties
1596 (match-end 0) (point-at-eol))
1597 "\n"))
1598 (forward-line))
1599 (point)))
1600 (end (progn (skip-chars-forward " \r\t\n" limit)
1601 (if (eobp) (point) (point-at-bol)))))
1602 (list 'fixed-width
1603 (nconc
1604 (list :begin begin
1605 :end end
1606 :value value
1607 :post-blank (count-lines end-area end))
1608 (cadr keywords))))))
1610 (defun org-element-fixed-width-interpreter (fixed-width contents)
1611 "Interpret FIXED-WIDTH element as Org syntax.
1612 CONTENTS is nil."
1613 (replace-regexp-in-string
1614 "^" ": " (substring (org-element-property :value fixed-width) 0 -1)))
1617 ;;;; Horizontal Rule
1619 (defun org-element-horizontal-rule-parser (limit)
1620 "Parse an horizontal rule.
1622 LIMIT bounds the search.
1624 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1625 containing `:begin', `:end' and `:post-blank' keywords."
1626 (save-excursion
1627 (let* ((keywords (org-element--collect-affiliated-keywords))
1628 (begin (car keywords))
1629 (post-hr (progn (forward-line) (point)))
1630 (end (progn (skip-chars-forward " \r\t\n" limit)
1631 (if (eobp) (point) (point-at-bol)))))
1632 (list 'horizontal-rule
1633 (nconc
1634 (list :begin begin
1635 :end end
1636 :post-blank (count-lines post-hr end))
1637 (cadr keywords))))))
1639 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1640 "Interpret HORIZONTAL-RULE element as Org syntax.
1641 CONTENTS is nil."
1642 "-----")
1645 ;;;; Keyword
1647 (defun org-element-keyword-parser (limit)
1648 "Parse a keyword at point.
1650 LIMIT bounds the search.
1652 Return a list whose CAR is `keyword' and CDR is a plist
1653 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1654 keywords."
1655 (save-excursion
1656 (let* ((case-fold-search t)
1657 (begin (point))
1658 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+\\):")
1659 (upcase (org-match-string-no-properties 1))))
1660 (value (org-trim (buffer-substring-no-properties
1661 (match-end 0) (point-at-eol))))
1662 (pos-before-blank (progn (forward-line) (point)))
1663 (end (progn (skip-chars-forward " \r\t\n" limit)
1664 (if (eobp) (point) (point-at-bol)))))
1665 (list 'keyword
1666 (list :key key
1667 :value value
1668 :begin begin
1669 :end end
1670 :post-blank (count-lines pos-before-blank end))))))
1672 (defun org-element-keyword-interpreter (keyword contents)
1673 "Interpret KEYWORD element as Org syntax.
1674 CONTENTS is nil."
1675 (format "#+%s: %s"
1676 (org-element-property :key keyword)
1677 (org-element-property :value keyword)))
1680 ;;;; Latex Environment
1682 (defun org-element-latex-environment-parser (limit)
1683 "Parse a LaTeX environment.
1685 LIMIT bounds the search.
1687 Return a list whose CAR is `latex-environment' and CDR is a plist
1688 containing `:begin', `:end', `:value' and `:post-blank'
1689 keywords.
1691 Assume point is at the beginning of the latex environment."
1692 (save-excursion
1693 (let* ((case-fold-search t)
1694 (code-begin (point))
1695 (keywords (org-element--collect-affiliated-keywords))
1696 (begin (car keywords))
1697 (env (progn (looking-at "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}")
1698 (regexp-quote (match-string 1))))
1699 (code-end
1700 (progn (re-search-forward (format "^[ \t]*\\\\end{%s}" env) limit t)
1701 (forward-line)
1702 (point)))
1703 (value (buffer-substring-no-properties code-begin code-end))
1704 (end (progn (skip-chars-forward " \r\t\n" limit)
1705 (if (eobp) (point) (point-at-bol)))))
1706 (list 'latex-environment
1707 (nconc
1708 (list :begin begin
1709 :end end
1710 :value value
1711 :post-blank (count-lines code-end end))
1712 (cadr keywords))))))
1714 (defun org-element-latex-environment-interpreter (latex-environment contents)
1715 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1716 CONTENTS is nil."
1717 (org-element-property :value latex-environment))
1720 ;;;; Paragraph
1722 (defun org-element-paragraph-parser (limit)
1723 "Parse a paragraph.
1725 LIMIT bounds the search.
1727 Return a list whose CAR is `paragraph' and CDR is a plist
1728 containing `:begin', `:end', `:contents-begin' and
1729 `:contents-end' and `:post-blank' keywords.
1731 Assume point is at the beginning of the paragraph."
1732 (save-excursion
1733 (let* ((contents-begin (point))
1734 (keywords (org-element--collect-affiliated-keywords))
1735 (begin (car keywords))
1736 (before-blank
1737 (let ((case-fold-search t))
1738 (end-of-line)
1739 (re-search-forward org-element-paragraph-separate limit 'm)
1740 (while (and (/= (point) limit)
1741 (cond
1742 ;; Skip non-existent or incomplete drawer.
1743 ((save-excursion
1744 (beginning-of-line)
1745 (and (looking-at "[ \t]*:\\S-")
1746 (or (not (looking-at org-drawer-regexp))
1747 (not (save-excursion
1748 (re-search-forward
1749 "^[ \t]*:END:" limit t)))))))
1750 ;; Stop at comments.
1751 ((save-excursion
1752 (beginning-of-line)
1753 (not (looking-at "[ \t]*#\\S-"))) nil)
1754 ;; Skip incomplete dynamic blocks.
1755 ((save-excursion
1756 (beginning-of-line)
1757 (looking-at "[ \t]*#\\+BEGIN: "))
1758 (not (save-excursion
1759 (re-search-forward
1760 "^[ \t]*\\+END:" limit t))))
1761 ;; Skip incomplete blocks.
1762 ((save-excursion
1763 (beginning-of-line)
1764 (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)"))
1765 (not (save-excursion
1766 (re-search-forward
1767 (concat "^[ \t]*#\\+END_"
1768 (match-string 1))
1769 limit t))))
1770 ;; Skip ill-formed keywords.
1771 ((not (save-excursion
1772 (beginning-of-line)
1773 (looking-at "[ \t]*#\\+\\S-+:"))))))
1774 (re-search-forward org-element-paragraph-separate limit 'm))
1775 (if (eobp) (point) (goto-char (line-beginning-position)))))
1776 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
1777 (forward-line)
1778 (point)))
1779 (end (progn (skip-chars-forward " \r\t\n" limit)
1780 (if (eobp) (point) (point-at-bol)))))
1781 (list 'paragraph
1782 ;; If paragraph has no affiliated keywords, it may not begin
1783 ;; at beginning of line if it starts an item.
1784 (nconc
1785 (list :begin (if (cadr keywords) begin contents-begin)
1786 :end end
1787 :contents-begin contents-begin
1788 :contents-end contents-end
1789 :post-blank (count-lines before-blank end))
1790 (cadr keywords))))))
1792 (defun org-element-paragraph-interpreter (paragraph contents)
1793 "Interpret PARAGRAPH element as Org syntax.
1794 CONTENTS is the contents of the element."
1795 contents)
1798 ;;;; Planning
1800 (defun org-element-planning-parser (limit)
1801 "Parse a planning.
1803 LIMIT bounds the search.
1805 Return a list whose CAR is `planning' and CDR is a plist
1806 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
1807 and `:post-blank' keywords."
1808 (save-excursion
1809 (let* ((case-fold-search nil)
1810 (begin (point))
1811 (post-blank (let ((before-blank (progn (forward-line) (point))))
1812 (skip-chars-forward " \r\t\n" limit)
1813 (unless (eobp) (beginning-of-line))
1814 (count-lines before-blank (point))))
1815 (end (point))
1816 closed deadline scheduled)
1817 (goto-char begin)
1818 (while (re-search-forward org-keyword-time-not-clock-regexp
1819 (line-end-position) t)
1820 (goto-char (match-end 1))
1821 (org-skip-whitespace)
1822 (let ((time (buffer-substring-no-properties
1823 (1+ (point)) (1- (match-end 0))))
1824 (keyword (match-string 1)))
1825 (cond ((equal keyword org-closed-string) (setq closed time))
1826 ((equal keyword org-deadline-string) (setq deadline time))
1827 (t (setq scheduled time)))))
1828 (list 'planning
1829 (list :closed closed
1830 :deadline deadline
1831 :scheduled scheduled
1832 :begin begin
1833 :end end
1834 :post-blank post-blank)))))
1836 (defun org-element-planning-interpreter (planning contents)
1837 "Interpret PLANNING element as Org syntax.
1838 CONTENTS is nil."
1839 (mapconcat
1840 'identity
1841 (delq nil
1842 (list (let ((closed (org-element-property :closed planning)))
1843 (when closed (concat org-closed-string " [" closed "]")))
1844 (let ((deadline (org-element-property :deadline planning)))
1845 (when deadline (concat org-deadline-string " <" deadline ">")))
1846 (let ((scheduled (org-element-property :scheduled planning)))
1847 (when scheduled
1848 (concat org-scheduled-string " <" scheduled ">")))))
1849 " "))
1852 ;;;; Property Drawer
1854 (defun org-element-property-drawer-parser (limit)
1855 "Parse a property drawer.
1857 LIMIT bounds the search.
1859 Return a list whose CAR is `property-drawer' and CDR is a plist
1860 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1861 `:contents-end', `:properties' and `:post-blank' keywords.
1863 Assume point is at the beginning of the property drawer."
1864 (save-excursion
1865 (let ((case-fold-search t)
1866 (begin (point))
1867 (prop-begin (progn (forward-line) (point)))
1868 (hidden (org-invisible-p2))
1869 (properties
1870 (let (val)
1871 (while (not (looking-at "^[ \t]*:END:"))
1872 (when (looking-at "[ \t]*:\\([A-Za-z][-_A-Za-z0-9]*\\):")
1873 (push (cons (org-match-string-no-properties 1)
1874 (org-trim
1875 (buffer-substring-no-properties
1876 (match-end 0) (point-at-eol))))
1877 val))
1878 (forward-line))
1879 val))
1880 (prop-end (progn (re-search-forward "^[ \t]*:END:" limit t)
1881 (point-at-bol)))
1882 (pos-before-blank (progn (forward-line) (point)))
1883 (end (progn (skip-chars-forward " \r\t\n" limit)
1884 (if (eobp) (point) (point-at-bol)))))
1885 (list 'property-drawer
1886 (list :begin begin
1887 :end end
1888 :hiddenp hidden
1889 :properties properties
1890 :post-blank (count-lines pos-before-blank end))))))
1892 (defun org-element-property-drawer-interpreter (property-drawer contents)
1893 "Interpret PROPERTY-DRAWER element as Org syntax.
1894 CONTENTS is nil."
1895 (let ((props (org-element-property :properties property-drawer)))
1896 (concat
1897 ":PROPERTIES:\n"
1898 (mapconcat (lambda (p)
1899 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1900 (nreverse props) "\n")
1901 "\n:END:")))
1904 ;;;; Quote Section
1906 (defun org-element-quote-section-parser (limit)
1907 "Parse a quote section.
1909 LIMIT bounds the search.
1911 Return a list whose CAR is `quote-section' and CDR is a plist
1912 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1914 Assume point is at beginning of the section."
1915 (save-excursion
1916 (let* ((begin (point))
1917 (end (progn (org-with-limited-levels (outline-next-heading))
1918 (point)))
1919 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1920 (forward-line)
1921 (point)))
1922 (value (buffer-substring-no-properties begin pos-before-blank)))
1923 (list 'quote-section
1924 (list :begin begin
1925 :end end
1926 :value value
1927 :post-blank (count-lines pos-before-blank end))))))
1929 (defun org-element-quote-section-interpreter (quote-section contents)
1930 "Interpret QUOTE-SECTION element as Org syntax.
1931 CONTENTS is nil."
1932 (org-element-property :value quote-section))
1935 ;;;; Src Block
1937 (defun org-element-src-block-parser (limit)
1938 "Parse a src block.
1940 LIMIT bounds the search.
1942 Return a list whose CAR is `src-block' and CDR is a plist
1943 containing `:language', `:switches', `:parameters', `:begin',
1944 `:end', `:hiddenp', `:number-lines', `:retain-labels',
1945 `:use-labels', `:label-fmt', `:preserve-indent', `:value' and
1946 `:post-blank' keywords.
1948 Assume point is at the beginning of the block."
1949 (let ((case-fold-search t))
1950 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC" limit t)))
1951 ;; Incomplete block: parse it as a comment.
1952 (org-element-paragraph-parser limit)
1953 (let ((contents-end (match-beginning 0)))
1954 (save-excursion
1955 (let* ((keywords (org-element--collect-affiliated-keywords))
1956 ;; Get beginning position.
1957 (begin (car keywords))
1958 ;; Get language as a string.
1959 (language
1960 (progn
1961 (looking-at
1962 (concat "^[ \t]*#\\+BEGIN_SRC"
1963 "\\(?: +\\(\\S-+\\)\\)?"
1964 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
1965 "\\(.*\\)[ \t]*$"))
1966 (org-match-string-no-properties 1)))
1967 ;; Get switches.
1968 (switches (org-match-string-no-properties 2))
1969 ;; Get parameters.
1970 (parameters (org-match-string-no-properties 3))
1971 ;; Switches analysis
1972 (number-lines (cond ((not switches) nil)
1973 ((string-match "-n\\>" switches) 'new)
1974 ((string-match "+n\\>" switches) 'continued)))
1975 (preserve-indent (and switches (string-match "-i\\>" switches)))
1976 (label-fmt (and switches
1977 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1978 (match-string 1 switches)))
1979 ;; Should labels be retained in (or stripped from)
1980 ;; src blocks?
1981 (retain-labels
1982 (or (not switches)
1983 (not (string-match "-r\\>" switches))
1984 (and number-lines (string-match "-k\\>" switches))))
1985 ;; What should code-references use - labels or
1986 ;; line-numbers?
1987 (use-labels
1988 (or (not switches)
1989 (and retain-labels (not (string-match "-k\\>" switches)))))
1990 ;; Get visibility status.
1991 (hidden (progn (forward-line) (org-invisible-p2)))
1992 ;; Retrieve code.
1993 (value (buffer-substring-no-properties (point) contents-end))
1994 (pos-before-blank (progn (goto-char contents-end)
1995 (forward-line)
1996 (point)))
1997 ;; Get position after ending blank lines.
1998 (end (progn (skip-chars-forward " \r\t\n" limit)
1999 (if (eobp) (point) (point-at-bol)))))
2000 (list 'src-block
2001 (nconc
2002 (list :language language
2003 :switches (and (org-string-nw-p switches)
2004 (org-trim switches))
2005 :parameters (and (org-string-nw-p parameters)
2006 (org-trim parameters))
2007 :begin begin
2008 :end end
2009 :number-lines number-lines
2010 :preserve-indent preserve-indent
2011 :retain-labels retain-labels
2012 :use-labels use-labels
2013 :label-fmt label-fmt
2014 :hiddenp hidden
2015 :value value
2016 :post-blank (count-lines pos-before-blank end))
2017 (cadr keywords)))))))))
2019 (defun org-element-src-block-interpreter (src-block contents)
2020 "Interpret SRC-BLOCK element as Org syntax.
2021 CONTENTS is nil."
2022 (let ((lang (org-element-property :language src-block))
2023 (switches (org-element-property :switches src-block))
2024 (params (org-element-property :parameters src-block))
2025 (value (let ((val (org-element-property :value src-block)))
2026 (cond
2028 (org-src-preserve-indentation val)
2029 ((zerop org-edit-src-content-indentation)
2030 (org-remove-indentation val))
2032 (let ((ind (make-string
2033 org-edit-src-content-indentation 32)))
2034 (replace-regexp-in-string
2035 "\\(^\\)[ \t]*\\S-" ind
2036 (org-remove-indentation val) nil nil 1)))))))
2037 (concat (format "#+BEGIN_SRC%s\n"
2038 (concat (and lang (concat " " lang))
2039 (and switches (concat " " switches))
2040 (and params (concat " " params))))
2041 value
2042 "#+END_SRC")))
2045 ;;;; Table
2047 (defun org-element-table-parser (limit)
2048 "Parse a table at point.
2050 LIMIT bounds the search.
2052 Return a list whose CAR is `table' and CDR is a plist containing
2053 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2054 `:contents-end', `:value' and `:post-blank' keywords.
2056 Assume point is at the beginning of the table."
2057 (save-excursion
2058 (let* ((case-fold-search t)
2059 (table-begin (point))
2060 (type (if (org-at-table.el-p) 'table.el 'org))
2061 (keywords (org-element--collect-affiliated-keywords))
2062 (begin (car keywords))
2063 (table-end (goto-char (marker-position (org-table-end t))))
2064 (tblfm (let (acc)
2065 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2066 (push (org-match-string-no-properties 1) acc)
2067 (forward-line))
2068 acc))
2069 (pos-before-blank (point))
2070 (end (progn (skip-chars-forward " \r\t\n" limit)
2071 (if (eobp) (point) (point-at-bol)))))
2072 (list 'table
2073 (nconc
2074 (list :begin begin
2075 :end end
2076 :type type
2077 :tblfm tblfm
2078 ;; Only `org' tables have contents. `table.el' tables
2079 ;; use a `:value' property to store raw table as
2080 ;; a string.
2081 :contents-begin (and (eq type 'org) table-begin)
2082 :contents-end (and (eq type 'org) table-end)
2083 :value (and (eq type 'table.el)
2084 (buffer-substring-no-properties
2085 table-begin table-end))
2086 :post-blank (count-lines pos-before-blank end))
2087 (cadr keywords))))))
2089 (defun org-element-table-interpreter (table contents)
2090 "Interpret TABLE element as Org syntax.
2091 CONTENTS is nil."
2092 (if (eq (org-element-property :type table) 'table.el)
2093 (org-remove-indentation (org-element-property :value table))
2094 (concat (with-temp-buffer (insert contents)
2095 (org-table-align)
2096 (buffer-string))
2097 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2098 (reverse (org-element-property :tblfm table))
2099 "\n"))))
2102 ;;;; Table Row
2104 (defun org-element-table-row-parser (limit)
2105 "Parse table row at point.
2107 LIMIT bounds the search.
2109 Return a list whose CAR is `table-row' and CDR is a plist
2110 containing `:begin', `:end', `:contents-begin', `:contents-end',
2111 `:type' and `:post-blank' keywords."
2112 (save-excursion
2113 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2114 (begin (point))
2115 ;; A table rule has no contents. In that case, ensure
2116 ;; CONTENTS-BEGIN matches CONTENTS-END.
2117 (contents-begin (and (eq type 'standard)
2118 (search-forward "|")
2119 (point)))
2120 (contents-end (and (eq type 'standard)
2121 (progn
2122 (end-of-line)
2123 (skip-chars-backward " \t")
2124 (point))))
2125 (end (progn (forward-line) (point))))
2126 (list 'table-row
2127 (list :type type
2128 :begin begin
2129 :end end
2130 :contents-begin contents-begin
2131 :contents-end contents-end
2132 :post-blank 0)))))
2134 (defun org-element-table-row-interpreter (table-row contents)
2135 "Interpret TABLE-ROW element as Org syntax.
2136 CONTENTS is the contents of the table row."
2137 (if (eq (org-element-property :type table-row) 'rule) "|-"
2138 (concat "| " contents)))
2141 ;;;; Verse Block
2143 (defun org-element-verse-block-parser (limit)
2144 "Parse a verse block.
2146 LIMIT bounds the search.
2148 Return a list whose CAR is `verse-block' and CDR is a plist
2149 containing `:begin', `:end', `:contents-begin', `:contents-end',
2150 `:hiddenp' and `:post-blank' keywords.
2152 Assume point is at beginning of the block."
2153 (let ((case-fold-search t))
2154 (if (not (save-excursion
2155 (re-search-forward "^[ \t]*#\\+END_VERSE" limit t)))
2156 ;; Incomplete block: parse it as a comment.
2157 (org-element-paragraph-parser limit)
2158 (let ((contents-end (match-beginning 0)))
2159 (save-excursion
2160 (let* ((keywords (org-element--collect-affiliated-keywords))
2161 (begin (car keywords))
2162 (hidden (progn (forward-line) (org-invisible-p2)))
2163 (contents-begin (point))
2164 (pos-before-blank (progn (goto-char contents-end)
2165 (forward-line)
2166 (point)))
2167 (end (progn (skip-chars-forward " \r\t\n" limit)
2168 (if (eobp) (point) (point-at-bol)))))
2169 (list 'verse-block
2170 (nconc
2171 (list :begin begin
2172 :end end
2173 :contents-begin contents-begin
2174 :contents-end contents-end
2175 :hiddenp hidden
2176 :post-blank (count-lines pos-before-blank end))
2177 (cadr keywords)))))))))
2179 (defun org-element-verse-block-interpreter (verse-block contents)
2180 "Interpret VERSE-BLOCK element as Org syntax.
2181 CONTENTS is verse block contents."
2182 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2186 ;;; Objects
2188 ;; Unlike to elements, interstices can be found between objects.
2189 ;; That's why, along with the parser, successor functions are provided
2190 ;; for each object. Some objects share the same successor (i.e. `code'
2191 ;; and `verbatim' objects).
2193 ;; A successor must accept a single argument bounding the search. It
2194 ;; will return either a cons cell whose CAR is the object's type, as
2195 ;; a symbol, and CDR the position of its next occurrence, or nil.
2197 ;; Successors follow the naming convention:
2198 ;; org-element-NAME-successor, where NAME is the name of the
2199 ;; successor, as defined in `org-element-all-successors'.
2201 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2202 ;; object types they can contain will be specified in
2203 ;; `org-element-object-restrictions'.
2205 ;; Adding a new type of object is simple. Implement a successor,
2206 ;; a parser, and an interpreter for it, all following the naming
2207 ;; convention. Register type in `org-element-all-objects' and
2208 ;; successor in `org-element-all-successors'. Maybe tweak
2209 ;; restrictions about it, and that's it.
2212 ;;;; Bold
2214 (defun org-element-bold-parser ()
2215 "Parse bold object at point.
2217 Return a list whose CAR is `bold' and CDR is a plist with
2218 `:begin', `:end', `:contents-begin' and `:contents-end' and
2219 `:post-blank' keywords.
2221 Assume point is at the first star marker."
2222 (save-excursion
2223 (unless (bolp) (backward-char 1))
2224 (looking-at org-emph-re)
2225 (let ((begin (match-beginning 2))
2226 (contents-begin (match-beginning 4))
2227 (contents-end (match-end 4))
2228 (post-blank (progn (goto-char (match-end 2))
2229 (skip-chars-forward " \t")))
2230 (end (point)))
2231 (list 'bold
2232 (list :begin begin
2233 :end end
2234 :contents-begin contents-begin
2235 :contents-end contents-end
2236 :post-blank post-blank)))))
2238 (defun org-element-bold-interpreter (bold contents)
2239 "Interpret BOLD object as Org syntax.
2240 CONTENTS is the contents of the object."
2241 (format "*%s*" contents))
2243 (defun org-element-text-markup-successor (limit)
2244 "Search for the next text-markup object.
2246 LIMIT bounds the search.
2248 Return value is a cons cell whose CAR is a symbol among `bold',
2249 `italic', `underline', `strike-through', `code' and `verbatim'
2250 and CDR is beginning position."
2251 (save-excursion
2252 (unless (bolp) (backward-char))
2253 (when (re-search-forward org-emph-re limit t)
2254 (let ((marker (match-string 3)))
2255 (cons (cond
2256 ((equal marker "*") 'bold)
2257 ((equal marker "/") 'italic)
2258 ((equal marker "_") 'underline)
2259 ((equal marker "+") 'strike-through)
2260 ((equal marker "~") 'code)
2261 ((equal marker "=") 'verbatim)
2262 (t (error "Unknown marker at %d" (match-beginning 3))))
2263 (match-beginning 2))))))
2266 ;;;; Code
2268 (defun org-element-code-parser ()
2269 "Parse code object at point.
2271 Return a list whose CAR is `code' and CDR is a plist with
2272 `:value', `:begin', `:end' and `:post-blank' keywords.
2274 Assume point is at the first tilde marker."
2275 (save-excursion
2276 (unless (bolp) (backward-char 1))
2277 (looking-at org-emph-re)
2278 (let ((begin (match-beginning 2))
2279 (value (org-match-string-no-properties 4))
2280 (post-blank (progn (goto-char (match-end 2))
2281 (skip-chars-forward " \t")))
2282 (end (point)))
2283 (list 'code
2284 (list :value value
2285 :begin begin
2286 :end end
2287 :post-blank post-blank)))))
2289 (defun org-element-code-interpreter (code contents)
2290 "Interpret CODE object as Org syntax.
2291 CONTENTS is nil."
2292 (format "~%s~" (org-element-property :value code)))
2295 ;;;; Entity
2297 (defun org-element-entity-parser ()
2298 "Parse entity at point.
2300 Return a list whose CAR is `entity' and CDR a plist with
2301 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2302 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2303 keywords.
2305 Assume point is at the beginning of the entity."
2306 (save-excursion
2307 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2308 (let* ((value (org-entity-get (match-string 1)))
2309 (begin (match-beginning 0))
2310 (bracketsp (string= (match-string 2) "{}"))
2311 (post-blank (progn (goto-char (match-end 1))
2312 (when bracketsp (forward-char 2))
2313 (skip-chars-forward " \t")))
2314 (end (point)))
2315 (list 'entity
2316 (list :name (car value)
2317 :latex (nth 1 value)
2318 :latex-math-p (nth 2 value)
2319 :html (nth 3 value)
2320 :ascii (nth 4 value)
2321 :latin1 (nth 5 value)
2322 :utf-8 (nth 6 value)
2323 :begin begin
2324 :end end
2325 :use-brackets-p bracketsp
2326 :post-blank post-blank)))))
2328 (defun org-element-entity-interpreter (entity contents)
2329 "Interpret ENTITY object as Org syntax.
2330 CONTENTS is nil."
2331 (concat "\\"
2332 (org-element-property :name entity)
2333 (when (org-element-property :use-brackets-p entity) "{}")))
2335 (defun org-element-latex-or-entity-successor (limit)
2336 "Search for the next latex-fragment or entity object.
2338 LIMIT bounds the search.
2340 Return value is a cons cell whose CAR is `entity' or
2341 `latex-fragment' and CDR is beginning position."
2342 (save-excursion
2343 (let ((matchers (plist-get org-format-latex-options :matchers))
2344 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2345 (entity-re
2346 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2347 (when (re-search-forward
2348 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
2349 matchers "\\|")
2350 "\\|" entity-re)
2351 limit t)
2352 (goto-char (match-beginning 0))
2353 (if (looking-at entity-re)
2354 ;; Determine if it's a real entity or a LaTeX command.
2355 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2356 (match-beginning 0))
2357 ;; No entity nor command: point is at a LaTeX fragment.
2358 ;; Determine its type to get the correct beginning position.
2359 (cons 'latex-fragment
2360 (catch 'return
2361 (mapc (lambda (e)
2362 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
2363 (throw 'return
2364 (match-beginning
2365 (nth 2 (assoc e org-latex-regexps))))))
2366 matchers)
2367 (point))))))))
2370 ;;;; Export Snippet
2372 (defun org-element-export-snippet-parser ()
2373 "Parse export snippet at point.
2375 Return a list whose CAR is `export-snippet' and CDR a plist with
2376 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2377 keywords.
2379 Assume point is at the beginning of the snippet."
2380 (save-excursion
2381 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2382 (let* ((begin (match-beginning 0))
2383 (back-end (org-match-string-no-properties 1))
2384 (value (buffer-substring-no-properties
2385 (point)
2386 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2387 (post-blank (skip-chars-forward " \t"))
2388 (end (point)))
2389 (list 'export-snippet
2390 (list :back-end back-end
2391 :value value
2392 :begin begin
2393 :end end
2394 :post-blank post-blank)))))
2396 (defun org-element-export-snippet-interpreter (export-snippet contents)
2397 "Interpret EXPORT-SNIPPET object as Org syntax.
2398 CONTENTS is nil."
2399 (format "@@%s:%s@@"
2400 (org-element-property :back-end export-snippet)
2401 (org-element-property :value export-snippet)))
2403 (defun org-element-export-snippet-successor (limit)
2404 "Search for the next export-snippet object.
2406 LIMIT bounds the search.
2408 Return value is a cons cell whose CAR is `export-snippet' and CDR
2409 its beginning position."
2410 (save-excursion
2411 (let (beg)
2412 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" limit t)
2413 (setq beg (match-beginning 0))
2414 (re-search-forward "@@" limit t))
2415 (cons 'export-snippet beg)))))
2418 ;;;; Footnote Reference
2420 (defun org-element-footnote-reference-parser ()
2421 "Parse footnote reference at point.
2423 Return a list whose CAR is `footnote-reference' and CDR a plist
2424 with `:label', `:type', `:inline-definition', `:begin', `:end'
2425 and `:post-blank' as keywords."
2426 (save-excursion
2427 (looking-at org-footnote-re)
2428 (let* ((begin (point))
2429 (label (or (org-match-string-no-properties 2)
2430 (org-match-string-no-properties 3)
2431 (and (match-string 1)
2432 (concat "fn:" (org-match-string-no-properties 1)))))
2433 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2434 (inner-begin (match-end 0))
2435 (inner-end
2436 (let ((count 1))
2437 (forward-char)
2438 (while (and (> count 0) (re-search-forward "[][]" nil t))
2439 (if (equal (match-string 0) "[") (incf count) (decf count)))
2440 (1- (point))))
2441 (post-blank (progn (goto-char (1+ inner-end))
2442 (skip-chars-forward " \t")))
2443 (end (point))
2444 (footnote-reference
2445 (list 'footnote-reference
2446 (list :label label
2447 :type type
2448 :begin begin
2449 :end end
2450 :post-blank post-blank))))
2451 (org-element-put-property
2452 footnote-reference :inline-definition
2453 (and (eq type 'inline)
2454 (org-element-parse-secondary-string
2455 (buffer-substring inner-begin inner-end)
2456 (org-element-restriction 'footnote-reference)
2457 footnote-reference))))))
2459 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2460 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2461 CONTENTS is nil."
2462 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2463 (def
2464 (let ((inline-def
2465 (org-element-property :inline-definition footnote-reference)))
2466 (if (not inline-def) ""
2467 (concat ":" (org-element-interpret-data inline-def))))))
2468 (format "[%s]" (concat label def))))
2470 (defun org-element-footnote-reference-successor (limit)
2471 "Search for the next footnote-reference object.
2473 LIMIT bounds the search.
2475 Return value is a cons cell whose CAR is `footnote-reference' and
2476 CDR is beginning position."
2477 (save-excursion
2478 (catch 'exit
2479 (while (re-search-forward org-footnote-re limit t)
2480 (save-excursion
2481 (let ((beg (match-beginning 0))
2482 (count 1))
2483 (backward-char)
2484 (while (re-search-forward "[][]" limit t)
2485 (if (equal (match-string 0) "[") (incf count) (decf count))
2486 (when (zerop count)
2487 (throw 'exit (cons 'footnote-reference beg))))))))))
2490 ;;;; Inline Babel Call
2492 (defun org-element-inline-babel-call-parser ()
2493 "Parse inline babel call at point.
2495 Return a list whose CAR is `inline-babel-call' and CDR a plist
2496 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2498 Assume point is at the beginning of the babel call."
2499 (save-excursion
2500 (unless (bolp) (backward-char))
2501 (looking-at org-babel-inline-lob-one-liner-regexp)
2502 (let ((info (save-match-data (org-babel-lob-get-info)))
2503 (begin (match-end 1))
2504 (post-blank (progn (goto-char (match-end 0))
2505 (skip-chars-forward " \t")))
2506 (end (point)))
2507 (list 'inline-babel-call
2508 (list :begin begin
2509 :end end
2510 :info info
2511 :post-blank post-blank)))))
2513 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2514 "Interpret INLINE-BABEL-CALL object as Org syntax.
2515 CONTENTS is nil."
2516 (let* ((babel-info (org-element-property :info inline-babel-call))
2517 (main-source (car babel-info))
2518 (post-options (nth 1 babel-info)))
2519 (concat "call_"
2520 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2521 ;; Remove redundant square brackets.
2522 (replace-match
2523 (match-string 1 main-source) nil nil main-source)
2524 main-source)
2525 (and post-options (format "[%s]" post-options)))))
2527 (defun org-element-inline-babel-call-successor (limit)
2528 "Search for the next inline-babel-call object.
2530 LIMIT bounds the search.
2532 Return value is a cons cell whose CAR is `inline-babel-call' and
2533 CDR is beginning position."
2534 (save-excursion
2535 ;; Use a simplified version of
2536 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
2537 (when (re-search-forward
2538 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
2539 limit t)
2540 (cons 'inline-babel-call (match-beginning 0)))))
2543 ;;;; Inline Src Block
2545 (defun org-element-inline-src-block-parser ()
2546 "Parse inline source block at point.
2548 LIMIT bounds the search.
2550 Return a list whose CAR is `inline-src-block' and CDR a plist
2551 with `:begin', `:end', `:language', `:value', `:parameters' and
2552 `:post-blank' as keywords.
2554 Assume point is at the beginning of the inline src block."
2555 (save-excursion
2556 (unless (bolp) (backward-char))
2557 (looking-at org-babel-inline-src-block-regexp)
2558 (let ((begin (match-beginning 1))
2559 (language (org-match-string-no-properties 2))
2560 (parameters (org-match-string-no-properties 4))
2561 (value (org-match-string-no-properties 5))
2562 (post-blank (progn (goto-char (match-end 0))
2563 (skip-chars-forward " \t")))
2564 (end (point)))
2565 (list 'inline-src-block
2566 (list :language language
2567 :value value
2568 :parameters parameters
2569 :begin begin
2570 :end end
2571 :post-blank post-blank)))))
2573 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2574 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2575 CONTENTS is nil."
2576 (let ((language (org-element-property :language inline-src-block))
2577 (arguments (org-element-property :parameters inline-src-block))
2578 (body (org-element-property :value inline-src-block)))
2579 (format "src_%s%s{%s}"
2580 language
2581 (if arguments (format "[%s]" arguments) "")
2582 body)))
2584 (defun org-element-inline-src-block-successor (limit)
2585 "Search for the next inline-babel-call element.
2587 LIMIT bounds the search.
2589 Return value is a cons cell whose CAR is `inline-babel-call' and
2590 CDR is beginning position."
2591 (save-excursion
2592 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
2593 (cons 'inline-src-block (match-beginning 1)))))
2595 ;;;; Italic
2597 (defun org-element-italic-parser ()
2598 "Parse italic object at point.
2600 Return a list whose CAR is `italic' and CDR is a plist with
2601 `:begin', `:end', `:contents-begin' and `:contents-end' and
2602 `:post-blank' keywords.
2604 Assume point is at the first slash marker."
2605 (save-excursion
2606 (unless (bolp) (backward-char 1))
2607 (looking-at org-emph-re)
2608 (let ((begin (match-beginning 2))
2609 (contents-begin (match-beginning 4))
2610 (contents-end (match-end 4))
2611 (post-blank (progn (goto-char (match-end 2))
2612 (skip-chars-forward " \t")))
2613 (end (point)))
2614 (list 'italic
2615 (list :begin begin
2616 :end end
2617 :contents-begin contents-begin
2618 :contents-end contents-end
2619 :post-blank post-blank)))))
2621 (defun org-element-italic-interpreter (italic contents)
2622 "Interpret ITALIC object as Org syntax.
2623 CONTENTS is the contents of the object."
2624 (format "/%s/" contents))
2627 ;;;; Latex Fragment
2629 (defun org-element-latex-fragment-parser ()
2630 "Parse latex fragment at point.
2632 Return a list whose CAR is `latex-fragment' and CDR a plist with
2633 `:value', `:begin', `:end', and `:post-blank' as keywords.
2635 Assume point is at the beginning of the latex fragment."
2636 (save-excursion
2637 (let* ((begin (point))
2638 (substring-match
2639 (catch 'exit
2640 (mapc (lambda (e)
2641 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2642 (when (or (looking-at latex-regexp)
2643 (and (not (bobp))
2644 (save-excursion
2645 (backward-char)
2646 (looking-at latex-regexp))))
2647 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2648 (plist-get org-format-latex-options :matchers))
2649 ;; None found: it's a macro.
2650 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2652 (value (match-string-no-properties substring-match))
2653 (post-blank (progn (goto-char (match-end substring-match))
2654 (skip-chars-forward " \t")))
2655 (end (point)))
2656 (list 'latex-fragment
2657 (list :value value
2658 :begin begin
2659 :end end
2660 :post-blank post-blank)))))
2662 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2663 "Interpret LATEX-FRAGMENT object as Org syntax.
2664 CONTENTS is nil."
2665 (org-element-property :value latex-fragment))
2667 ;;;; Line Break
2669 (defun org-element-line-break-parser ()
2670 "Parse line break at point.
2672 Return a list whose CAR is `line-break', and CDR a plist with
2673 `:begin', `:end' and `:post-blank' keywords.
2675 Assume point is at the beginning of the line break."
2676 (list 'line-break (list :begin (point) :end (point-at-eol) :post-blank 0)))
2678 (defun org-element-line-break-interpreter (line-break contents)
2679 "Interpret LINE-BREAK object as Org syntax.
2680 CONTENTS is nil."
2681 "\\\\")
2683 (defun org-element-line-break-successor (limit)
2684 "Search for the next line-break object.
2686 LIMIT bounds the search.
2688 Return value is a cons cell whose CAR is `line-break' and CDR is
2689 beginning position."
2690 (save-excursion
2691 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2692 (goto-char (match-beginning 1)))))
2693 ;; A line break can only happen on a non-empty line.
2694 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2695 (cons 'line-break beg)))))
2698 ;;;; Link
2700 (defun org-element-link-parser ()
2701 "Parse link at point.
2703 Return a list whose CAR is `link' and CDR a plist with `:type',
2704 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
2705 `:contents-end' and `:post-blank' as keywords.
2707 Assume point is at the beginning of the link."
2708 (save-excursion
2709 (let ((begin (point))
2710 end contents-begin contents-end link-end post-blank path type
2711 raw-link link)
2712 (cond
2713 ;; Type 1: Text targeted from a radio target.
2714 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2715 (setq type "radio"
2716 link-end (match-end 0)
2717 path (org-match-string-no-properties 0)))
2718 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2719 ((looking-at org-bracket-link-regexp)
2720 (setq contents-begin (match-beginning 3)
2721 contents-end (match-end 3)
2722 link-end (match-end 0)
2723 ;; RAW-LINK is the original link.
2724 raw-link (org-match-string-no-properties 1)
2725 link (org-translate-link
2726 (org-link-expand-abbrev
2727 (org-link-unescape raw-link))))
2728 ;; Determine TYPE of link and set PATH accordingly.
2729 (cond
2730 ;; File type.
2731 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2732 (setq type "file" path link))
2733 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2734 ((string-match org-link-re-with-space3 link)
2735 (setq type (match-string 1 link) path (match-string 2 link)))
2736 ;; Id type: PATH is the id.
2737 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2738 (setq type "id" path (match-string 1 link)))
2739 ;; Code-ref type: PATH is the name of the reference.
2740 ((string-match "^(\\(.*\\))$" link)
2741 (setq type "coderef" path (match-string 1 link)))
2742 ;; Custom-id type: PATH is the name of the custom id.
2743 ((= (aref link 0) ?#)
2744 (setq type "custom-id" path (substring link 1)))
2745 ;; Fuzzy type: Internal link either matches a target, an
2746 ;; headline name or nothing. PATH is the target or
2747 ;; headline's name.
2748 (t (setq type "fuzzy" path link))))
2749 ;; Type 3: Plain link, i.e. http://orgmode.org
2750 ((looking-at org-plain-link-re)
2751 (setq raw-link (org-match-string-no-properties 0)
2752 type (org-match-string-no-properties 1)
2753 path (org-match-string-no-properties 2)
2754 link-end (match-end 0)))
2755 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2756 ((looking-at org-angle-link-re)
2757 (setq raw-link (buffer-substring-no-properties
2758 (match-beginning 1) (match-end 2))
2759 type (org-match-string-no-properties 1)
2760 path (org-match-string-no-properties 2)
2761 link-end (match-end 0))))
2762 ;; In any case, deduce end point after trailing white space from
2763 ;; LINK-END variable.
2764 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2765 end (point))
2766 (list 'link
2767 (list :type type
2768 :path path
2769 :raw-link (or raw-link path)
2770 :begin begin
2771 :end end
2772 :contents-begin contents-begin
2773 :contents-end contents-end
2774 :post-blank post-blank)))))
2776 (defun org-element-link-interpreter (link contents)
2777 "Interpret LINK object as Org syntax.
2778 CONTENTS is the contents of the object, or nil."
2779 (let ((type (org-element-property :type link))
2780 (raw-link (org-element-property :raw-link link)))
2781 (if (string= type "radio") raw-link
2782 (format "[[%s]%s]"
2783 raw-link
2784 (if contents (format "[%s]" contents) "")))))
2786 (defun org-element-link-successor (limit)
2787 "Search for the next link object.
2789 LIMIT bounds the search.
2791 Return value is a cons cell whose CAR is `link' and CDR is
2792 beginning position."
2793 (save-excursion
2794 (let ((link-regexp
2795 (if (not org-target-link-regexp) org-any-link-re
2796 (concat org-any-link-re "\\|" org-target-link-regexp))))
2797 (when (re-search-forward link-regexp limit t)
2798 (cons 'link (match-beginning 0))))))
2801 ;;;; Macro
2803 (defun org-element-macro-parser ()
2804 "Parse macro at point.
2806 Return a list whose CAR is `macro' and CDR a plist with `:key',
2807 `:args', `:begin', `:end', `:value' and `:post-blank' as
2808 keywords.
2810 Assume point is at the macro."
2811 (save-excursion
2812 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2813 (let ((begin (point))
2814 (key (downcase (org-match-string-no-properties 1)))
2815 (value (org-match-string-no-properties 0))
2816 (post-blank (progn (goto-char (match-end 0))
2817 (skip-chars-forward " \t")))
2818 (end (point))
2819 (args (let ((args (org-match-string-no-properties 3)) args2)
2820 (when args
2821 (setq args (org-split-string args ","))
2822 (while args
2823 (while (string-match "\\\\\\'" (car args))
2824 ;; Repair bad splits.
2825 (setcar (cdr args) (concat (substring (car args) 0 -1)
2826 "," (nth 1 args)))
2827 (pop args))
2828 (push (pop args) args2))
2829 (mapcar 'org-trim (nreverse args2))))))
2830 (list 'macro
2831 (list :key key
2832 :value value
2833 :args args
2834 :begin begin
2835 :end end
2836 :post-blank post-blank)))))
2838 (defun org-element-macro-interpreter (macro contents)
2839 "Interpret MACRO object as Org syntax.
2840 CONTENTS is nil."
2841 (org-element-property :value macro))
2843 (defun org-element-macro-successor (limit)
2844 "Search for the next macro object.
2846 LIMIT bounds the search.
2848 Return value is cons cell whose CAR is `macro' and CDR is
2849 beginning position."
2850 (save-excursion
2851 (when (re-search-forward
2852 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2853 limit t)
2854 (cons 'macro (match-beginning 0)))))
2857 ;;;; Radio-target
2859 (defun org-element-radio-target-parser ()
2860 "Parse radio target at point.
2862 Return a list whose CAR is `radio-target' and CDR a plist with
2863 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2864 and `:post-blank' as keywords.
2866 Assume point is at the radio target."
2867 (save-excursion
2868 (looking-at org-radio-target-regexp)
2869 (let ((begin (point))
2870 (contents-begin (match-beginning 1))
2871 (contents-end (match-end 1))
2872 (value (org-match-string-no-properties 1))
2873 (post-blank (progn (goto-char (match-end 0))
2874 (skip-chars-forward " \t")))
2875 (end (point)))
2876 (list 'radio-target
2877 (list :begin begin
2878 :end end
2879 :contents-begin contents-begin
2880 :contents-end contents-end
2881 :post-blank post-blank
2882 :value value)))))
2884 (defun org-element-radio-target-interpreter (target contents)
2885 "Interpret TARGET object as Org syntax.
2886 CONTENTS is the contents of the object."
2887 (concat "<<<" contents ">>>"))
2889 (defun org-element-radio-target-successor (limit)
2890 "Search for the next radio-target object.
2892 LIMIT bounds the search.
2894 Return value is a cons cell whose CAR is `radio-target' and CDR
2895 is beginning position."
2896 (save-excursion
2897 (when (re-search-forward org-radio-target-regexp limit t)
2898 (cons 'radio-target (match-beginning 0)))))
2901 ;;;; Statistics Cookie
2903 (defun org-element-statistics-cookie-parser ()
2904 "Parse statistics cookie at point.
2906 Return a list whose CAR is `statistics-cookie', and CDR a plist
2907 with `:begin', `:end', `:value' and `:post-blank' keywords.
2909 Assume point is at the beginning of the statistics-cookie."
2910 (save-excursion
2911 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2912 (let* ((begin (point))
2913 (value (buffer-substring-no-properties
2914 (match-beginning 0) (match-end 0)))
2915 (post-blank (progn (goto-char (match-end 0))
2916 (skip-chars-forward " \t")))
2917 (end (point)))
2918 (list 'statistics-cookie
2919 (list :begin begin
2920 :end end
2921 :value value
2922 :post-blank post-blank)))))
2924 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2925 "Interpret STATISTICS-COOKIE object as Org syntax.
2926 CONTENTS is nil."
2927 (org-element-property :value statistics-cookie))
2929 (defun org-element-statistics-cookie-successor (limit)
2930 "Search for the next statistics cookie object.
2932 LIMIT bounds the search.
2934 Return value is a cons cell whose CAR is `statistics-cookie' and
2935 CDR is beginning position."
2936 (save-excursion
2937 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2938 (cons 'statistics-cookie (match-beginning 0)))))
2941 ;;;; Strike-Through
2943 (defun org-element-strike-through-parser ()
2944 "Parse strike-through object at point.
2946 Return a list whose CAR is `strike-through' and CDR is a plist
2947 with `:begin', `:end', `:contents-begin' and `:contents-end' and
2948 `:post-blank' keywords.
2950 Assume point is at the first plus sign marker."
2951 (save-excursion
2952 (unless (bolp) (backward-char 1))
2953 (looking-at org-emph-re)
2954 (let ((begin (match-beginning 2))
2955 (contents-begin (match-beginning 4))
2956 (contents-end (match-end 4))
2957 (post-blank (progn (goto-char (match-end 2))
2958 (skip-chars-forward " \t")))
2959 (end (point)))
2960 (list 'strike-through
2961 (list :begin begin
2962 :end end
2963 :contents-begin contents-begin
2964 :contents-end contents-end
2965 :post-blank post-blank)))))
2967 (defun org-element-strike-through-interpreter (strike-through contents)
2968 "Interpret STRIKE-THROUGH object as Org syntax.
2969 CONTENTS is the contents of the object."
2970 (format "+%s+" contents))
2973 ;;;; Subscript
2975 (defun org-element-subscript-parser ()
2976 "Parse subscript at point.
2978 Return a list whose CAR is `subscript' and CDR a plist with
2979 `:begin', `:end', `:contents-begin', `:contents-end',
2980 `:use-brackets-p' and `:post-blank' as keywords.
2982 Assume point is at the underscore."
2983 (save-excursion
2984 (unless (bolp) (backward-char))
2985 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2987 (not (looking-at org-match-substring-regexp))))
2988 (begin (match-beginning 2))
2989 (contents-begin (or (match-beginning 5)
2990 (match-beginning 3)))
2991 (contents-end (or (match-end 5) (match-end 3)))
2992 (post-blank (progn (goto-char (match-end 0))
2993 (skip-chars-forward " \t")))
2994 (end (point)))
2995 (list 'subscript
2996 (list :begin begin
2997 :end end
2998 :use-brackets-p bracketsp
2999 :contents-begin contents-begin
3000 :contents-end contents-end
3001 :post-blank post-blank)))))
3003 (defun org-element-subscript-interpreter (subscript contents)
3004 "Interpret SUBSCRIPT object as Org syntax.
3005 CONTENTS is the contents of the object."
3006 (format
3007 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3008 contents))
3010 (defun org-element-sub/superscript-successor (limit)
3011 "Search for the next sub/superscript object.
3013 LIMIT bounds the search.
3015 Return value is a cons cell whose CAR is either `subscript' or
3016 `superscript' and CDR is beginning position."
3017 (save-excursion
3018 (when (re-search-forward org-match-substring-regexp limit t)
3019 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3020 (match-beginning 2)))))
3023 ;;;; Superscript
3025 (defun org-element-superscript-parser ()
3026 "Parse superscript at point.
3028 Return a list whose CAR is `superscript' and CDR a plist with
3029 `:begin', `:end', `:contents-begin', `:contents-end',
3030 `:use-brackets-p' and `:post-blank' as keywords.
3032 Assume point is at the caret."
3033 (save-excursion
3034 (unless (bolp) (backward-char))
3035 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3036 (not (looking-at org-match-substring-regexp))))
3037 (begin (match-beginning 2))
3038 (contents-begin (or (match-beginning 5)
3039 (match-beginning 3)))
3040 (contents-end (or (match-end 5) (match-end 3)))
3041 (post-blank (progn (goto-char (match-end 0))
3042 (skip-chars-forward " \t")))
3043 (end (point)))
3044 (list 'superscript
3045 (list :begin begin
3046 :end end
3047 :use-brackets-p bracketsp
3048 :contents-begin contents-begin
3049 :contents-end contents-end
3050 :post-blank post-blank)))))
3052 (defun org-element-superscript-interpreter (superscript contents)
3053 "Interpret SUPERSCRIPT object as Org syntax.
3054 CONTENTS is the contents of the object."
3055 (format
3056 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3057 contents))
3060 ;;;; Table Cell
3062 (defun org-element-table-cell-parser ()
3063 "Parse table cell at point.
3065 Return a list whose CAR is `table-cell' and CDR is a plist
3066 containing `:begin', `:end', `:contents-begin', `:contents-end'
3067 and `:post-blank' keywords."
3068 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3069 (let* ((begin (match-beginning 0))
3070 (end (match-end 0))
3071 (contents-begin (match-beginning 1))
3072 (contents-end (match-end 1)))
3073 (list 'table-cell
3074 (list :begin begin
3075 :end end
3076 :contents-begin contents-begin
3077 :contents-end contents-end
3078 :post-blank 0))))
3080 (defun org-element-table-cell-interpreter (table-cell contents)
3081 "Interpret TABLE-CELL element as Org syntax.
3082 CONTENTS is the contents of the cell, or nil."
3083 (concat " " contents " |"))
3085 (defun org-element-table-cell-successor (limit)
3086 "Search for the next table-cell object.
3088 LIMIT bounds the search.
3090 Return value is a cons cell whose CAR is `table-cell' and CDR is
3091 beginning position."
3092 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
3095 ;;;; Target
3097 (defun org-element-target-parser ()
3098 "Parse target at point.
3100 Return a list whose CAR is `target' and CDR a plist with
3101 `:begin', `:end', `:value' and `:post-blank' as keywords.
3103 Assume point is at the target."
3104 (save-excursion
3105 (looking-at org-target-regexp)
3106 (let ((begin (point))
3107 (value (org-match-string-no-properties 1))
3108 (post-blank (progn (goto-char (match-end 0))
3109 (skip-chars-forward " \t")))
3110 (end (point)))
3111 (list 'target
3112 (list :begin begin
3113 :end end
3114 :value value
3115 :post-blank post-blank)))))
3117 (defun org-element-target-interpreter (target contents)
3118 "Interpret TARGET object as Org syntax.
3119 CONTENTS is nil."
3120 (format "<<%s>>" (org-element-property :value target)))
3122 (defun org-element-target-successor (limit)
3123 "Search for the next target object.
3125 LIMIT bounds the search.
3127 Return value is a cons cell whose CAR is `target' and CDR is
3128 beginning position."
3129 (save-excursion
3130 (when (re-search-forward org-target-regexp limit t)
3131 (cons 'target (match-beginning 0)))))
3134 ;;;; Timestamp
3136 (defun org-element-timestamp-parser ()
3137 "Parse time stamp at point.
3139 Return a list whose CAR is `timestamp', and CDR a plist with
3140 `:type', `:begin', `:end', `:value' and `:post-blank' keywords.
3142 Assume point is at the beginning of the timestamp."
3143 (save-excursion
3144 (let* ((begin (point))
3145 (activep (eq (char-after) ?<))
3146 (main-value
3147 (progn
3148 (looking-at "[<[]\\(\\(%%\\)?.*?\\)[]>]\\(?:--[<[]\\(.*?\\)[]>]\\)?")
3149 (match-string-no-properties 1)))
3150 (range-end (match-string-no-properties 3))
3151 (type (cond ((match-string 2) 'diary)
3152 ((and activep range-end) 'active-range)
3153 (activep 'active)
3154 (range-end 'inactive-range)
3155 (t 'inactive)))
3156 (post-blank (progn (goto-char (match-end 0))
3157 (skip-chars-forward " \t")))
3158 (end (point)))
3159 (list 'timestamp
3160 (list :type type
3161 :value main-value
3162 :range-end range-end
3163 :begin begin
3164 :end end
3165 :post-blank post-blank)))))
3167 (defun org-element-timestamp-interpreter (timestamp contents)
3168 "Interpret TIMESTAMP object as Org syntax.
3169 CONTENTS is nil."
3170 (let ((type (org-element-property :type timestamp) ))
3171 (concat
3172 (format (if (memq type '(inactive inactive-range)) "[%s]" "<%s>")
3173 (org-element-property :value timestamp))
3174 (let ((range-end (org-element-property :range-end timestamp)))
3175 (when range-end
3176 (concat "--"
3177 (format (if (eq type 'inactive-range) "[%s]" "<%s>")
3178 range-end)))))))
3180 (defun org-element-timestamp-successor (limit)
3181 "Search for the next timestamp object.
3183 LIMIT bounds the search.
3185 Return value is a cons cell whose CAR is `timestamp' and CDR is
3186 beginning position."
3187 (save-excursion
3188 (when (re-search-forward
3189 (concat org-ts-regexp-both
3190 "\\|"
3191 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3192 "\\|"
3193 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3194 limit t)
3195 (cons 'timestamp (match-beginning 0)))))
3198 ;;;; Underline
3200 (defun org-element-underline-parser ()
3201 "Parse underline object at point.
3203 Return a list whose CAR is `underline' and CDR is a plist with
3204 `:begin', `:end', `:contents-begin' and `:contents-end' and
3205 `:post-blank' keywords.
3207 Assume point is at the first underscore marker."
3208 (save-excursion
3209 (unless (bolp) (backward-char 1))
3210 (looking-at org-emph-re)
3211 (let ((begin (match-beginning 2))
3212 (contents-begin (match-beginning 4))
3213 (contents-end (match-end 4))
3214 (post-blank (progn (goto-char (match-end 2))
3215 (skip-chars-forward " \t")))
3216 (end (point)))
3217 (list 'underline
3218 (list :begin begin
3219 :end end
3220 :contents-begin contents-begin
3221 :contents-end contents-end
3222 :post-blank post-blank)))))
3224 (defun org-element-underline-interpreter (underline contents)
3225 "Interpret UNDERLINE object as Org syntax.
3226 CONTENTS is the contents of the object."
3227 (format "_%s_" contents))
3230 ;;;; Verbatim
3232 (defun org-element-verbatim-parser ()
3233 "Parse verbatim object at point.
3235 Return a list whose CAR is `verbatim' and CDR is a plist with
3236 `:value', `:begin', `:end' and `:post-blank' keywords.
3238 Assume point is at the first equal sign marker."
3239 (save-excursion
3240 (unless (bolp) (backward-char 1))
3241 (looking-at org-emph-re)
3242 (let ((begin (match-beginning 2))
3243 (value (org-match-string-no-properties 4))
3244 (post-blank (progn (goto-char (match-end 2))
3245 (skip-chars-forward " \t")))
3246 (end (point)))
3247 (list 'verbatim
3248 (list :value value
3249 :begin begin
3250 :end end
3251 :post-blank post-blank)))))
3253 (defun org-element-verbatim-interpreter (verbatim contents)
3254 "Interpret VERBATIM object as Org syntax.
3255 CONTENTS is nil."
3256 (format "=%s=" (org-element-property :value verbatim)))
3260 ;;; Parsing Element Starting At Point
3262 ;; `org-element--current-element' is the core function of this section.
3263 ;; It returns the Lisp representation of the element starting at
3264 ;; point.
3266 ;; `org-element--current-element' makes use of special modes. They
3267 ;; are activated for fixed element chaining (i.e. `plain-list' >
3268 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3269 ;; `section'). Special modes are: `first-section', `section',
3270 ;; `quote-section', `item' and `table-row'.
3272 (defun org-element--current-element
3273 (limit &optional granularity special structure)
3274 "Parse the element starting at point.
3276 LIMIT bounds the search.
3278 Return value is a list like (TYPE PROPS) where TYPE is the type
3279 of the element and PROPS a plist of properties associated to the
3280 element.
3282 Possible types are defined in `org-element-all-elements'.
3284 Optional argument GRANULARITY determines the depth of the
3285 recursion. Allowed values are `headline', `greater-element',
3286 `element', `object' or nil. When it is broader than `object' (or
3287 nil), secondary values will not be parsed, since they only
3288 contain objects.
3290 Optional argument SPECIAL, when non-nil, can be either
3291 `first-section', `section', `quote-section', `table-row' and
3292 `item'.
3294 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3295 be computed.
3297 This function assumes point is always at the beginning of the
3298 element it has to parse."
3299 (save-excursion
3300 ;; If point is at an affiliated keyword, try moving to the
3301 ;; beginning of the associated element. If none is found, the
3302 ;; keyword is orphaned and will be treated as plain text.
3303 (when (looking-at org-element--affiliated-re)
3304 (let ((opoint (point)))
3305 (while (looking-at org-element--affiliated-re) (forward-line))
3306 (when (looking-at "[ \t]*$") (goto-char opoint))))
3307 (let ((case-fold-search t)
3308 ;; Determine if parsing depth allows for secondary strings
3309 ;; parsing. It only applies to elements referenced in
3310 ;; `org-element-secondary-value-alist'.
3311 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3312 (cond
3313 ;; Item.
3314 ((eq special 'item)
3315 (org-element-item-parser limit structure raw-secondary-p))
3316 ;; Quote Section.
3317 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3318 ;; Table Row.
3319 ((eq special 'table-row) (org-element-table-row-parser limit))
3320 ;; Headline.
3321 ((org-with-limited-levels (org-at-heading-p))
3322 (org-element-headline-parser limit raw-secondary-p))
3323 ;; Section (must be checked after headline).
3324 ((eq special 'section) (org-element-section-parser limit))
3325 ((eq special 'first-section)
3326 (org-element-section-parser
3327 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3328 limit)))
3329 ;; Planning and Clock.
3330 ((and (looking-at org-planning-or-clock-line-re))
3331 (if (equal (match-string 1) org-clock-string)
3332 (org-element-clock-parser limit)
3333 (org-element-planning-parser limit)))
3334 ;; Inlinetask.
3335 ((org-at-heading-p)
3336 (org-element-inlinetask-parser limit raw-secondary-p))
3337 ;; LaTeX Environment.
3338 ((looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}")
3339 (if (save-excursion
3340 (re-search-forward
3341 (format "[ \t]*\\\\end{%s}[ \t]*"
3342 (regexp-quote (match-string 1)))
3343 nil t))
3344 (org-element-latex-environment-parser limit)
3345 (org-element-paragraph-parser limit)))
3346 ;; Drawer and Property Drawer.
3347 ((looking-at org-drawer-regexp)
3348 (let ((name (match-string 1)))
3349 (cond
3350 ((not (save-excursion
3351 (re-search-forward "^[ \t]*:END:[ \t]*$" nil t)))
3352 (org-element-paragraph-parser limit))
3353 ((equal "PROPERTIES" name)
3354 (org-element-property-drawer-parser limit))
3355 (t (org-element-drawer-parser limit)))))
3356 ;; Fixed Width
3357 ((looking-at "[ \t]*:\\( \\|$\\)")
3358 (org-element-fixed-width-parser limit))
3359 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3360 ;; Keywords.
3361 ((looking-at "[ \t]*#")
3362 (goto-char (match-end 0))
3363 (cond ((looking-at "\\(?: \\|$\\)")
3364 (beginning-of-line)
3365 (org-element-comment-parser limit))
3366 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3367 (beginning-of-line)
3368 (let ((parser (assoc (upcase (match-string 1))
3369 org-element-block-name-alist)))
3370 (if parser (funcall (cdr parser) limit)
3371 (org-element-special-block-parser limit))))
3372 ((looking-at "\\+CALL:")
3373 (beginning-of-line)
3374 (org-element-babel-call-parser limit))
3375 ((looking-at "\\+BEGIN:? ")
3376 (beginning-of-line)
3377 (org-element-dynamic-block-parser limit))
3378 ((looking-at "\\+\\S-+:")
3379 (beginning-of-line)
3380 (org-element-keyword-parser limit))
3382 (beginning-of-line)
3383 (org-element-paragraph-parser limit))))
3384 ;; Footnote Definition.
3385 ((looking-at org-footnote-definition-re)
3386 (org-element-footnote-definition-parser limit))
3387 ;; Horizontal Rule.
3388 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3389 (org-element-horizontal-rule-parser limit))
3390 ;; Table.
3391 ((org-at-table-p t) (org-element-table-parser limit))
3392 ;; List.
3393 ((looking-at (org-item-re))
3394 (org-element-plain-list-parser limit (or structure (org-list-struct))))
3395 ;; Default element: Paragraph.
3396 (t (org-element-paragraph-parser limit))))))
3399 ;; Most elements can have affiliated keywords. When looking for an
3400 ;; element beginning, we want to move before them, as they belong to
3401 ;; that element, and, in the meantime, collect information they give
3402 ;; into appropriate properties. Hence the following function.
3404 ;; Usage of optional arguments may not be obvious at first glance:
3406 ;; - TRANS-LIST is used to polish keywords names that have evolved
3407 ;; during Org history. In example, even though =result= and
3408 ;; =results= coexist, we want to have them under the same =result=
3409 ;; property. It's also true for "srcname" and "name", where the
3410 ;; latter seems to be preferred nowadays (thus the "name" property).
3412 ;; - CONSED allows to regroup multi-lines keywords under the same
3413 ;; property, while preserving their own identity. This is mostly
3414 ;; used for "attr_latex" and al.
3416 ;; - PARSED prepares a keyword value for export. This is useful for
3417 ;; "caption". Objects restrictions for such keywords are defined in
3418 ;; `org-element-object-restrictions'.
3420 ;; - DUALS is used to take care of keywords accepting a main and an
3421 ;; optional secondary values. For example "results" has its
3422 ;; source's name as the main value, and may have an hash string in
3423 ;; optional square brackets as the secondary one.
3425 ;; A keyword may belong to more than one category.
3427 (defun org-element--collect-affiliated-keywords
3428 (&optional key-re trans-list consed parsed duals)
3429 "Collect affiliated keywords before point.
3431 Optional argument KEY-RE is a regexp matching keywords, which
3432 puts matched keyword in group 1. It defaults to
3433 `org-element--affiliated-re'.
3435 TRANS-LIST is an alist where key is the keyword and value the
3436 property name it should be translated to, without the colons. It
3437 defaults to `org-element-keyword-translation-alist'.
3439 CONSED is a list of strings. Any keyword belonging to that list
3440 will have its value consed. The check is done after keyword
3441 translation. It defaults to `org-element-multiple-keywords'.
3443 PARSED is a list of strings. Any keyword member of this list
3444 will have its value parsed. The check is done after keyword
3445 translation. If a keyword is a member of both CONSED and PARSED,
3446 it's value will be a list of parsed strings. It defaults to
3447 `org-element-parsed-keywords'.
3449 DUALS is a list of strings. Any keyword member of this list can
3450 have two parts: one mandatory and one optional. Its value is
3451 a cons cell whose CAR is the former, and the CDR the latter. If
3452 a keyword is a member of both PARSED and DUALS, both values will
3453 be parsed. It defaults to `org-element-dual-keywords'.
3455 Return a list whose CAR is the position at the first of them and
3456 CDR a plist of keywords and values."
3457 (save-excursion
3458 (let ((case-fold-search t)
3459 (key-re (or key-re org-element--affiliated-re))
3460 (trans-list (or trans-list org-element-keyword-translation-alist))
3461 (consed (or consed org-element-multiple-keywords))
3462 (parsed (or parsed org-element-parsed-keywords))
3463 (duals (or duals org-element-dual-keywords))
3464 ;; RESTRICT is the list of objects allowed in parsed
3465 ;; keywords value.
3466 (restrict (org-element-restriction 'keyword))
3467 output)
3468 (unless (bobp)
3469 (while (and (not (bobp)) (progn (forward-line -1) (looking-at key-re)))
3470 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3471 ;; Apply translation to RAW-KWD. From there, KWD is
3472 ;; the official keyword.
3473 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3474 ;; Find main value for any keyword.
3475 (value
3476 (save-match-data
3477 (org-trim
3478 (buffer-substring-no-properties
3479 (match-end 0) (point-at-eol)))))
3480 ;; If KWD is a dual keyword, find its secondary
3481 ;; value. Maybe parse it.
3482 (dual-value
3483 (and (member kwd duals)
3484 (let ((sec (org-match-string-no-properties 3)))
3485 (if (or (not sec) (not (member kwd parsed))) sec
3486 (org-element-parse-secondary-string sec restrict)))))
3487 ;; Attribute a property name to KWD.
3488 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3489 ;; Now set final shape for VALUE.
3490 (when (member kwd parsed)
3491 (setq value (org-element-parse-secondary-string value restrict)))
3492 (when (member kwd duals)
3493 ;; VALUE is mandatory. Set it to nil if there is none.
3494 (setq value (and value (cons value dual-value))))
3495 ;; Attributes are always consed.
3496 (when (or (member kwd consed) (string-match "^ATTR_" kwd))
3497 (setq value (cons value (plist-get output kwd-sym))))
3498 ;; Eventually store the new value in OUTPUT.
3499 (setq output (plist-put output kwd-sym value))))
3500 (unless (looking-at key-re) (forward-line 1)))
3501 (list (point) output))))
3505 ;;; The Org Parser
3507 ;; The two major functions here are `org-element-parse-buffer', which
3508 ;; parses Org syntax inside the current buffer, taking into account
3509 ;; region, narrowing, or even visibility if specified, and
3510 ;; `org-element-parse-secondary-string', which parses objects within
3511 ;; a given string.
3513 ;; The (almost) almighty `org-element-map' allows to apply a function
3514 ;; on elements or objects matching some type, and accumulate the
3515 ;; resulting values. In an export situation, it also skips unneeded
3516 ;; parts of the parse tree.
3518 (defun org-element-parse-buffer (&optional granularity visible-only)
3519 "Recursively parse the buffer and return structure.
3520 If narrowing is in effect, only parse the visible part of the
3521 buffer.
3523 Optional argument GRANULARITY determines the depth of the
3524 recursion. It can be set to the following symbols:
3526 `headline' Only parse headlines.
3527 `greater-element' Don't recurse into greater elements excepted
3528 headlines and sections. Thus, elements
3529 parsed are the top-level ones.
3530 `element' Parse everything but objects and plain text.
3531 `object' Parse the complete buffer (default).
3533 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3534 elements.
3536 Assume buffer is in Org mode."
3537 (save-excursion
3538 (goto-char (point-min))
3539 (org-skip-whitespace)
3540 (org-element--parse-elements
3541 (point-at-bol) (point-max)
3542 ;; Start in `first-section' mode so text before the first
3543 ;; headline belongs to a section.
3544 'first-section nil granularity visible-only (list 'org-data nil))))
3546 (defun org-element-parse-secondary-string (string restriction &optional parent)
3547 "Recursively parse objects in STRING and return structure.
3549 RESTRICTION is a symbol limiting the object types that will be
3550 looked after.
3552 Optional argument PARENT, when non-nil, is the element or object
3553 containing the secondary string. It is used to set correctly
3554 `:parent' property within the string."
3555 (with-temp-buffer
3556 (insert string)
3557 (let ((secondary (org-element--parse-objects
3558 (point-min) (point-max) nil restriction)))
3559 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
3560 secondary))))
3562 (defun org-element-map (data types fun &optional info first-match no-recursion)
3563 "Map a function on selected elements or objects.
3565 DATA is the parsed tree, as returned by, i.e,
3566 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3567 of elements or objects types. FUN is the function called on the
3568 matching element or object. It must accept one arguments: the
3569 element or object itself.
3571 When optional argument INFO is non-nil, it should be a plist
3572 holding export options. In that case, parts of the parse tree
3573 not exportable according to that property list will be skipped.
3575 When optional argument FIRST-MATCH is non-nil, stop at the first
3576 match for which FUN doesn't return nil, and return that value.
3578 Optional argument NO-RECURSION is a symbol or a list of symbols
3579 representing elements or objects types. `org-element-map' won't
3580 enter any recursive element or object whose type belongs to that
3581 list. Though, FUN can still be applied on them.
3583 Nil values returned from FUN do not appear in the results."
3584 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3585 (unless (listp types) (setq types (list types)))
3586 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3587 ;; Recursion depth is determined by --CATEGORY.
3588 (let* ((--category
3589 (catch 'found
3590 (let ((category 'greater-elements))
3591 (mapc (lambda (type)
3592 (cond ((or (memq type org-element-all-objects)
3593 (eq type 'plain-text))
3594 ;; If one object is found, the function
3595 ;; has to recurse into every object.
3596 (throw 'found 'objects))
3597 ((not (memq type org-element-greater-elements))
3598 ;; If one regular element is found, the
3599 ;; function has to recurse, at lest, into
3600 ;; every element it encounters.
3601 (and (not (eq category 'elements))
3602 (setq category 'elements)))))
3603 types)
3604 category)))
3605 --acc
3606 --walk-tree
3607 (--walk-tree
3608 (function
3609 (lambda (--data)
3610 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3611 ;; holding contextual information.
3612 (let ((--type (org-element-type --data)))
3613 (cond
3614 ((not --data))
3615 ;; Ignored element in an export context.
3616 ((and info (memq --data (plist-get info :ignore-list))))
3617 ;; Secondary string: only objects can be found there.
3618 ((not --type)
3619 (when (eq --category 'objects) (mapc --walk-tree --data)))
3620 ;; Unconditionally enter parse trees.
3621 ((eq --type 'org-data)
3622 (mapc --walk-tree (org-element-contents --data)))
3624 ;; Check if TYPE is matching among TYPES. If so,
3625 ;; apply FUN to --DATA and accumulate return value
3626 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3627 (when (memq --type types)
3628 (let ((result (funcall fun --data)))
3629 (cond ((not result))
3630 (first-match (throw '--map-first-match result))
3631 (t (push result --acc)))))
3632 ;; If --DATA has a secondary string that can contain
3633 ;; objects with their type among TYPES, look into it.
3634 (when (eq --category 'objects)
3635 (let ((sec-prop
3636 (assq --type org-element-secondary-value-alist)))
3637 (when sec-prop
3638 (funcall --walk-tree
3639 (org-element-property (cdr sec-prop) --data)))))
3640 ;; Determine if a recursion into --DATA is possible.
3641 (cond
3642 ;; --TYPE is explicitly removed from recursion.
3643 ((memq --type no-recursion))
3644 ;; --DATA has no contents.
3645 ((not (org-element-contents --data)))
3646 ;; Looking for greater elements but --DATA is simply
3647 ;; an element or an object.
3648 ((and (eq --category 'greater-elements)
3649 (not (memq --type org-element-greater-elements))))
3650 ;; Looking for elements but --DATA is an object.
3651 ((and (eq --category 'elements)
3652 (memq --type org-element-all-objects)))
3653 ;; In any other case, map contents.
3654 (t (mapc --walk-tree (org-element-contents --data)))))))))))
3655 (catch '--map-first-match
3656 (funcall --walk-tree data)
3657 ;; Return value in a proper order.
3658 (nreverse --acc))))
3660 ;; The following functions are internal parts of the parser.
3662 ;; The first one, `org-element--parse-elements' acts at the element's
3663 ;; level.
3665 ;; The second one, `org-element--parse-objects' applies on all objects
3666 ;; of a paragraph or a secondary string. It uses
3667 ;; `org-element--get-next-object-candidates' to optimize the search of
3668 ;; the next object in the buffer.
3670 ;; More precisely, that function looks for every allowed object type
3671 ;; first. Then, it discards failed searches, keeps further matches,
3672 ;; and searches again types matched behind point, for subsequent
3673 ;; calls. Thus, searching for a given type fails only once, and every
3674 ;; object is searched only once at top level (but sometimes more for
3675 ;; nested types).
3677 (defun org-element--parse-elements
3678 (beg end special structure granularity visible-only acc)
3679 "Parse elements between BEG and END positions.
3681 SPECIAL prioritize some elements over the others. It can be set
3682 to `first-section', `quote-section', `section' `item' or
3683 `table-row'.
3685 When value is `item', STRUCTURE will be used as the current list
3686 structure.
3688 GRANULARITY determines the depth of the recursion. See
3689 `org-element-parse-buffer' for more information.
3691 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3692 elements.
3694 Elements are accumulated into ACC."
3695 (save-excursion
3696 (goto-char beg)
3697 ;; When parsing only headlines, skip any text before first one.
3698 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3699 (org-with-limited-levels (outline-next-heading)))
3700 ;; Main loop start.
3701 (while (< (point) end)
3702 ;; Find current element's type and parse it accordingly to
3703 ;; its category.
3704 (let* ((element (org-element--current-element
3705 end granularity special structure))
3706 (type (org-element-type element))
3707 (cbeg (org-element-property :contents-begin element)))
3708 (goto-char (org-element-property :end element))
3709 ;; Fill ELEMENT contents by side-effect.
3710 (cond
3711 ;; If VISIBLE-ONLY is true and element is hidden or if it has
3712 ;; no contents, don't modify it.
3713 ((or (and visible-only (org-element-property :hiddenp element))
3714 (not cbeg)))
3715 ;; Greater element: parse it between `contents-begin' and
3716 ;; `contents-end'. Make sure GRANULARITY allows the
3717 ;; recursion, or ELEMENT is an headline, in which case going
3718 ;; inside is mandatory, in order to get sub-level headings.
3719 ((and (memq type org-element-greater-elements)
3720 (or (memq granularity '(element object nil))
3721 (and (eq granularity 'greater-element)
3722 (eq type 'section))
3723 (eq type 'headline)))
3724 (org-element--parse-elements
3725 cbeg (org-element-property :contents-end element)
3726 ;; Possibly switch to a special mode.
3727 (case type
3728 (headline
3729 (if (org-element-property :quotedp element) 'quote-section
3730 'section))
3731 (plain-list 'item)
3732 (table 'table-row))
3733 (org-element-property :structure element)
3734 granularity visible-only element))
3735 ;; ELEMENT has contents. Parse objects inside, if
3736 ;; GRANULARITY allows it.
3737 ((memq granularity '(object nil))
3738 (org-element--parse-objects
3739 cbeg (org-element-property :contents-end element) element
3740 (org-element-restriction type))))
3741 (org-element-adopt-element acc element t)))
3742 ;; Return result.
3743 acc))
3745 (defun org-element--parse-objects (beg end acc restriction)
3746 "Parse objects between BEG and END and return recursive structure.
3748 Objects are accumulated in ACC.
3750 RESTRICTION is a list of object types which are allowed in the
3751 current object."
3752 (let (candidates)
3753 (save-excursion
3754 (goto-char beg)
3755 (while (and (< (point) end)
3756 (setq candidates (org-element--get-next-object-candidates
3757 end restriction candidates)))
3758 (let ((next-object
3759 (let ((pos (apply 'min (mapcar 'cdr candidates))))
3760 (save-excursion
3761 (goto-char pos)
3762 (funcall (intern (format "org-element-%s-parser"
3763 (car (rassq pos candidates)))))))))
3764 ;; 1. Text before any object. Untabify it.
3765 (let ((obj-beg (org-element-property :begin next-object)))
3766 (unless (= (point) obj-beg)
3767 (setq acc
3768 (org-element-adopt-element
3770 (replace-regexp-in-string
3771 "\t" (make-string tab-width ? )
3772 (buffer-substring-no-properties (point) obj-beg)) t))))
3773 ;; 2. Object...
3774 (let ((obj-end (org-element-property :end next-object))
3775 (cont-beg (org-element-property :contents-begin next-object)))
3776 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
3777 ;; a recursive type.
3778 (when (and cont-beg
3779 (memq (car next-object) org-element-recursive-objects))
3780 (save-restriction
3781 (narrow-to-region
3782 cont-beg
3783 (org-element-property :contents-end next-object))
3784 (org-element--parse-objects
3785 (point-min) (point-max) next-object
3786 (org-element-restriction next-object))))
3787 (setq acc (org-element-adopt-element acc next-object t))
3788 (goto-char obj-end))))
3789 ;; 3. Text after last object. Untabify it.
3790 (unless (= (point) end)
3791 (setq acc
3792 (org-element-adopt-element
3794 (replace-regexp-in-string
3795 "\t" (make-string tab-width ? )
3796 (buffer-substring-no-properties (point) end)) t)))
3797 ;; Result.
3798 acc)))
3800 (defun org-element--get-next-object-candidates (limit restriction objects)
3801 "Return an alist of candidates for the next object.
3803 LIMIT bounds the search, and RESTRICTION narrows candidates to
3804 some object types.
3806 Return value is an alist whose CAR is position and CDR the object
3807 type, as a symbol.
3809 OBJECTS is the previous candidates alist."
3810 (let (next-candidates types-to-search)
3811 ;; If no previous result, search every object type in RESTRICTION.
3812 ;; Otherwise, keep potential candidates (old objects located after
3813 ;; point) and ask to search again those which had matched before.
3814 (if (not objects) (setq types-to-search restriction)
3815 (mapc (lambda (obj)
3816 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3817 (push obj next-candidates)))
3818 objects))
3819 ;; Call the appropriate successor function for each type to search
3820 ;; and accumulate matches.
3821 (mapc
3822 (lambda (type)
3823 (let* ((successor-fun
3824 (intern
3825 (format "org-element-%s-successor"
3826 (or (cdr (assq type org-element-object-successor-alist))
3827 type))))
3828 (obj (funcall successor-fun limit)))
3829 (and obj (push obj next-candidates))))
3830 types-to-search)
3831 ;; Return alist.
3832 next-candidates))
3836 ;;; Towards A Bijective Process
3838 ;; The parse tree obtained with `org-element-parse-buffer' is really
3839 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3840 ;; interpreted and expanded into a string with canonical Org syntax.
3841 ;; Hence `org-element-interpret-data'.
3843 ;; The function relies internally on
3844 ;; `org-element--interpret-affiliated-keywords'.
3846 (defun org-element-interpret-data (data &optional parent)
3847 "Interpret DATA as Org syntax.
3849 DATA is a parse tree, an element, an object or a secondary string
3850 to interpret.
3852 Optional argument PARENT is used for recursive calls. It contains
3853 the element or object containing data, or nil.
3855 Return Org syntax as a string."
3856 (let* ((type (org-element-type data))
3857 (results
3858 (cond
3859 ;; Secondary string.
3860 ((not type)
3861 (mapconcat
3862 (lambda (obj) (org-element-interpret-data obj parent))
3863 data ""))
3864 ;; Full Org document.
3865 ((eq type 'org-data)
3866 (mapconcat
3867 (lambda (obj) (org-element-interpret-data obj parent))
3868 (org-element-contents data) ""))
3869 ;; Plain text.
3870 ((stringp data) data)
3871 ;; Element/Object without contents.
3872 ((not (org-element-contents data))
3873 (funcall (intern (format "org-element-%s-interpreter" type))
3874 data nil))
3875 ;; Element/Object with contents.
3877 (let* ((greaterp (memq type org-element-greater-elements))
3878 (objectp (and (not greaterp)
3879 (memq type org-element-recursive-objects)))
3880 (contents
3881 (mapconcat
3882 (lambda (obj) (org-element-interpret-data obj data))
3883 (org-element-contents
3884 (if (or greaterp objectp) data
3885 ;; Elements directly containing objects must
3886 ;; have their indentation normalized first.
3887 (org-element-normalize-contents
3888 data
3889 ;; When normalizing first paragraph of an
3890 ;; item or a footnote-definition, ignore
3891 ;; first line's indentation.
3892 (and (eq type 'paragraph)
3893 (equal data (car (org-element-contents parent)))
3894 (memq (org-element-type parent)
3895 '(footnote-definiton item))))))
3896 "")))
3897 (funcall (intern (format "org-element-%s-interpreter" type))
3898 data
3899 (if greaterp (org-element-normalize-contents contents)
3900 contents)))))))
3901 (if (memq type '(org-data plain-text nil)) results
3902 ;; Build white spaces. If no `:post-blank' property is
3903 ;; specified, assume its value is 0.
3904 (let ((post-blank (or (org-element-property :post-blank data) 0)))
3905 (if (memq type org-element-all-objects)
3906 (concat results (make-string post-blank 32))
3907 (concat
3908 (org-element--interpret-affiliated-keywords data)
3909 (org-element-normalize-string results)
3910 (make-string post-blank 10)))))))
3912 (defun org-element--interpret-affiliated-keywords (element)
3913 "Return ELEMENT's affiliated keywords as Org syntax.
3914 If there is no affiliated keyword, return the empty string."
3915 (let ((keyword-to-org
3916 (function
3917 (lambda (key value)
3918 (let (dual)
3919 (when (member key org-element-dual-keywords)
3920 (setq dual (cdr value) value (car value)))
3921 (concat "#+" key
3922 (and dual
3923 (format "[%s]" (org-element-interpret-data dual)))
3924 ": "
3925 (if (member key org-element-parsed-keywords)
3926 (org-element-interpret-data value)
3927 value)
3928 "\n"))))))
3929 (mapconcat
3930 (lambda (prop)
3931 (let ((value (org-element-property prop element))
3932 (keyword (upcase (substring (symbol-name prop) 1))))
3933 (when value
3934 (if (or (member keyword org-element-multiple-keywords)
3935 ;; All attribute keywords can have multiple lines.
3936 (string-match "^ATTR_" keyword))
3937 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
3938 value
3940 (funcall keyword-to-org keyword value)))))
3941 ;; List all ELEMENT's properties matching an attribute line or an
3942 ;; affiliated keyword, but ignore translated keywords since they
3943 ;; cannot belong to the property list.
3944 (loop for prop in (nth 1 element) by 'cddr
3945 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
3946 (or (string-match "^ATTR_" keyword)
3947 (and
3948 (member keyword org-element-affiliated-keywords)
3949 (not (assoc keyword
3950 org-element-keyword-translation-alist)))))
3951 collect prop)
3952 "")))
3954 ;; Because interpretation of the parse tree must return the same
3955 ;; number of blank lines between elements and the same number of white
3956 ;; space after objects, some special care must be given to white
3957 ;; spaces.
3959 ;; The first function, `org-element-normalize-string', ensures any
3960 ;; string different from the empty string will end with a single
3961 ;; newline character.
3963 ;; The second function, `org-element-normalize-contents', removes
3964 ;; global indentation from the contents of the current element.
3966 (defun org-element-normalize-string (s)
3967 "Ensure string S ends with a single newline character.
3969 If S isn't a string return it unchanged. If S is the empty
3970 string, return it. Otherwise, return a new string with a single
3971 newline character at its end."
3972 (cond
3973 ((not (stringp s)) s)
3974 ((string= "" s) "")
3975 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3976 (replace-match "\n" nil nil s)))))
3978 (defun org-element-normalize-contents (element &optional ignore-first)
3979 "Normalize plain text in ELEMENT's contents.
3981 ELEMENT must only contain plain text and objects.
3983 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3984 indentation to compute maximal common indentation.
3986 Return the normalized element that is element with global
3987 indentation removed from its contents. The function assumes that
3988 indentation is not done with TAB characters."
3989 (let* (ind-list ; for byte-compiler
3990 collect-inds ; for byte-compiler
3991 (collect-inds
3992 (function
3993 ;; Return list of indentations within BLOB. This is done by
3994 ;; walking recursively BLOB and updating IND-LIST along the
3995 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3996 ;; been seen yet. It is required as this string is the only
3997 ;; one whose indentation doesn't happen after a newline
3998 ;; character.
3999 (lambda (blob first-flag)
4000 (mapc
4001 (lambda (object)
4002 (when (and first-flag (stringp object))
4003 (setq first-flag nil)
4004 (string-match "\\`\\( *\\)" object)
4005 (let ((len (length (match-string 1 object))))
4006 ;; An indentation of zero means no string will be
4007 ;; modified. Quit the process.
4008 (if (zerop len) (throw 'zero (setq ind-list nil))
4009 (push len ind-list))))
4010 (cond
4011 ((stringp object)
4012 (let ((start 0))
4013 ;; Avoid matching blank or empty lines.
4014 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4015 (not (equal (match-string 2 object) " ")))
4016 (setq start (match-end 0))
4017 (push (length (match-string 1 object)) ind-list))))
4018 ((memq (org-element-type object) org-element-recursive-objects)
4019 (funcall collect-inds object first-flag))))
4020 (org-element-contents blob))))))
4021 ;; Collect indentation list in ELEMENT. Possibly remove first
4022 ;; value if IGNORE-FIRST is non-nil.
4023 (catch 'zero (funcall collect-inds element (not ignore-first)))
4024 (if (not ind-list) element
4025 ;; Build ELEMENT back, replacing each string with the same
4026 ;; string minus common indentation.
4027 (let* (build ; For byte compiler.
4028 (build
4029 (function
4030 (lambda (blob mci first-flag)
4031 ;; Return BLOB with all its strings indentation
4032 ;; shortened from MCI white spaces. FIRST-FLAG is
4033 ;; non-nil when the first string hasn't been seen
4034 ;; yet.
4035 (setcdr (cdr blob)
4036 (mapcar
4037 (lambda (object)
4038 (when (and first-flag (stringp object))
4039 (setq first-flag nil)
4040 (setq object
4041 (replace-regexp-in-string
4042 (format "\\` \\{%d\\}" mci) "" object)))
4043 (cond
4044 ((stringp object)
4045 (replace-regexp-in-string
4046 (format "\n \\{%d\\}" mci) "\n" object))
4047 ((memq (org-element-type object)
4048 org-element-recursive-objects)
4049 (funcall build object mci first-flag))
4050 (t object)))
4051 (org-element-contents blob)))
4052 blob))))
4053 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4057 ;;; The Toolbox
4059 ;; The first move is to implement a way to obtain the smallest element
4060 ;; containing point. This is the job of `org-element-at-point'. It
4061 ;; basically jumps back to the beginning of section containing point
4062 ;; and moves, element after element, with
4063 ;; `org-element--current-element' until the container is found. Note:
4064 ;; When using `org-element-at-point', secondary values are never
4065 ;; parsed since the function focuses on elements, not on objects.
4067 ;; At a deeper level, `org-element-context' lists all elements and
4068 ;; objects containing point.
4070 ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
4071 ;; internally by navigation and manipulation tools.
4073 ;;;###autoload
4074 (defun org-element-at-point (&optional keep-trail)
4075 "Determine closest element around point.
4077 Return value is a list like (TYPE PROPS) where TYPE is the type
4078 of the element and PROPS a plist of properties associated to the
4079 element.
4081 Possible types are defined in `org-element-all-elements'.
4082 Properties depend on element or object type, but always
4083 include :begin, :end, :parent and :post-blank properties.
4085 As a special case, if point is at the very beginning of a list or
4086 sub-list, returned element will be that list instead of the first
4087 item. In the same way, if point is at the beginning of the first
4088 row of a table, returned element will be the table instead of the
4089 first row.
4091 If optional argument KEEP-TRAIL is non-nil, the function returns
4092 a list of of elements leading to element at point. The list's
4093 CAR is always the element at point. Following positions contain
4094 element's siblings, then parents, siblings of parents, until the
4095 first element of current section."
4096 (org-with-wide-buffer
4097 ;; If at an headline, parse it. It is the sole element that
4098 ;; doesn't require to know about context. Be sure to disallow
4099 ;; secondary string parsing, though.
4100 (if (org-with-limited-levels (org-at-heading-p))
4101 (progn
4102 (beginning-of-line)
4103 (if (not keep-trail) (org-element-headline-parser (point-max) t)
4104 (list (org-element-headline-parser (point-max) t))))
4105 ;; Otherwise move at the beginning of the section containing
4106 ;; point.
4107 (let ((origin (point))
4108 (end (save-excursion
4109 (org-with-limited-levels (outline-next-heading)) (point)))
4110 element type special-flag trail struct prevs parent)
4111 (org-with-limited-levels
4112 (if (org-with-limited-levels (org-before-first-heading-p))
4113 (goto-char (point-min))
4114 (org-back-to-heading)
4115 (forward-line)))
4116 (org-skip-whitespace)
4117 (beginning-of-line)
4118 ;; Parse successively each element, skipping those ending
4119 ;; before original position.
4120 (catch 'exit
4121 (while t
4122 (setq element
4123 (org-element--current-element end 'element special-flag struct)
4124 type (car element))
4125 (org-element-put-property element :parent parent)
4126 (when keep-trail (push element trail))
4127 (cond
4128 ;; 1. Skip any element ending before point. Also skip
4129 ;; element ending at point when we're sure that another
4130 ;; element has started.
4131 ((let ((elem-end (org-element-property :end element)))
4132 (when (or (< elem-end origin)
4133 (and (= elem-end origin) (/= elem-end end)))
4134 (goto-char elem-end))))
4135 ;; 2. An element containing point is always the element at
4136 ;; point.
4137 ((not (memq type org-element-greater-elements))
4138 (throw 'exit (if keep-trail trail element)))
4139 ;; 3. At any other greater element type, if point is
4140 ;; within contents, move into it.
4142 (let ((cbeg (org-element-property :contents-begin element))
4143 (cend (org-element-property :contents-end element)))
4144 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
4145 ;; Create an anchor for tables and plain lists:
4146 ;; when point is at the very beginning of these
4147 ;; elements, ignoring affiliated keywords,
4148 ;; target them instead of their contents.
4149 (and (= cbeg origin) (memq type '(plain-list table)))
4150 ;; When point is at contents end, do not move
4151 ;; into elements with an explicit ending, but
4152 ;; return that element instead.
4153 (and (= cend origin)
4154 (memq type
4155 '(center-block
4156 drawer dynamic-block inlinetask item
4157 plain-list quote-block special-block))))
4158 (throw 'exit (if keep-trail trail element))
4159 (setq parent element)
4160 (case type
4161 (plain-list
4162 (setq special-flag 'item
4163 struct (org-element-property :structure element)))
4164 (table (setq special-flag 'table-row))
4165 (otherwise (setq special-flag nil)))
4166 (setq end cend)
4167 (goto-char cbeg)))))))))))
4169 (defun org-element-context ()
4170 "Return closest element or object around point.
4172 Return value is a list like (TYPE PROPS) where TYPE is the type
4173 of the element or object and PROPS a plist of properties
4174 associated to it.
4176 Possible types are defined in `org-element-all-elements' and
4177 `org-element-all-objects'. Properties depend on element or
4178 object type, but always include :begin, :end, :parent
4179 and :post-blank properties."
4180 (org-with-wide-buffer
4181 (let* ((origin (point))
4182 (element (org-element-at-point))
4183 (type (car element))
4184 end)
4185 ;; Check if point is inside an element containing objects or at
4186 ;; a secondary string. In that case, move to beginning of the
4187 ;; element or secondary string and set END to the other side.
4188 (if (not (or (and (eq type 'item)
4189 (let ((tag (org-element-property :tag element)))
4190 (and tag
4191 (progn
4192 (beginning-of-line)
4193 (search-forward tag (point-at-eol))
4194 (goto-char (match-beginning 0))
4195 (and (>= origin (point))
4196 (<= origin
4197 ;; `1+' is required so some
4198 ;; successors can match
4199 ;; properly their object.
4200 (setq end (1+ (match-end 0)))))))))
4201 (and (memq type '(headline inlinetask))
4202 (progn (beginning-of-line)
4203 (skip-chars-forward "* ")
4204 (setq end (point-at-eol))))
4205 (and (memq type '(paragraph table-cell verse-block))
4206 (let ((cbeg (org-element-property
4207 :contents-begin element))
4208 (cend (org-element-property
4209 :contents-end element)))
4210 (and (>= origin cbeg)
4211 (<= origin cend)
4212 (progn (goto-char cbeg) (setq end cend)))))))
4213 element
4214 (let ((restriction (org-element-restriction element))
4215 (parent element)
4216 candidates)
4217 (catch 'exit
4218 (while (setq candidates (org-element--get-next-object-candidates
4219 end restriction candidates))
4220 (let ((closest-cand (rassq (apply 'min (mapcar 'cdr candidates))
4221 candidates)))
4222 ;; If ORIGIN is before next object in element, there's
4223 ;; no point in looking further.
4224 (if (> (cdr closest-cand) origin) (throw 'exit element)
4225 (let* ((object
4226 (progn (goto-char (cdr closest-cand))
4227 (funcall (intern (format "org-element-%s-parser"
4228 (car closest-cand))))))
4229 (cbeg (org-element-property :contents-begin object))
4230 (cend (org-element-property :contents-end object)))
4231 (cond
4232 ;; ORIGIN is after OBJECT, so skip it.
4233 ((< (org-element-property :end object) origin)
4234 (goto-char (org-element-property :end object)))
4235 ;; ORIGIN is within a non-recursive object or at an
4236 ;; object boundaries: Return that object.
4237 ((or (not cbeg) (> cbeg origin) (< cend origin))
4238 (throw 'exit
4239 (org-element-put-property object :parent parent)))
4240 ;; Otherwise, move within current object and restrict
4241 ;; search to the end of its contents.
4242 (t (goto-char cbeg)
4243 (org-element-put-property object :parent parent)
4244 (setq parent object end cend)))))))
4245 parent))))))
4247 (defsubst org-element-nested-p (elem-A elem-B)
4248 "Non-nil when elements ELEM-A and ELEM-B are nested."
4249 (let ((beg-A (org-element-property :begin elem-A))
4250 (beg-B (org-element-property :begin elem-B))
4251 (end-A (org-element-property :end elem-A))
4252 (end-B (org-element-property :end elem-B)))
4253 (or (and (>= beg-A beg-B) (<= end-A end-B))
4254 (and (>= beg-B beg-A) (<= end-B end-A)))))
4256 (defun org-element-swap-A-B (elem-A elem-B)
4257 "Swap elements ELEM-A and ELEM-B.
4258 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
4259 end of ELEM-A."
4260 (goto-char (org-element-property :begin elem-A))
4261 ;; There are two special cases when an element doesn't start at bol:
4262 ;; the first paragraph in an item or in a footnote definition.
4263 (let ((specialp (not (bolp))))
4264 ;; Only a paragraph without any affiliated keyword can be moved at
4265 ;; ELEM-A position in such a situation. Note that the case of
4266 ;; a footnote definition is impossible: it cannot contain two
4267 ;; paragraphs in a row because it cannot contain a blank line.
4268 (if (and specialp
4269 (or (not (eq (org-element-type elem-B) 'paragraph))
4270 (/= (org-element-property :begin elem-B)
4271 (org-element-property :contents-begin elem-B))))
4272 (error "Cannot swap elements"))
4273 ;; In a special situation, ELEM-A will have no indentation. We'll
4274 ;; give it ELEM-B's (which will in, in turn, have no indentation).
4275 (let* ((ind-B (when specialp
4276 (goto-char (org-element-property :begin elem-B))
4277 (org-get-indentation)))
4278 (beg-A (org-element-property :begin elem-A))
4279 (end-A (save-excursion
4280 (goto-char (org-element-property :end elem-A))
4281 (skip-chars-backward " \r\t\n")
4282 (point-at-eol)))
4283 (beg-B (org-element-property :begin elem-B))
4284 (end-B (save-excursion
4285 (goto-char (org-element-property :end elem-B))
4286 (skip-chars-backward " \r\t\n")
4287 (point-at-eol)))
4288 ;; Store overlays responsible for visibility status. We
4289 ;; also need to store their boundaries as they will be
4290 ;; removed from buffer.
4291 (overlays
4292 (cons
4293 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4294 (overlays-in beg-A end-A))
4295 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
4296 (overlays-in beg-B end-B))))
4297 ;; Get contents.
4298 (body-A (buffer-substring beg-A end-A))
4299 (body-B (delete-and-extract-region beg-B end-B)))
4300 (goto-char beg-B)
4301 (when specialp
4302 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
4303 (org-indent-to-column ind-B))
4304 (insert body-A)
4305 ;; Restore ex ELEM-A overlays.
4306 (let ((offset (- beg-B beg-A)))
4307 (mapc (lambda (ov)
4308 (move-overlay
4309 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
4310 (car overlays))
4311 (goto-char beg-A)
4312 (delete-region beg-A end-A)
4313 (insert body-B)
4314 ;; Restore ex ELEM-B overlays.
4315 (mapc (lambda (ov)
4316 (move-overlay
4317 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
4318 (cdr overlays)))
4319 (goto-char (org-element-property :end elem-B)))))
4322 (provide 'org-element)
4323 ;;; org-element.el ends here