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