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