testing: allow to select tests
[org-mode/org-tableheadings.git] / lisp / org-element.el
blob57e26ffb5cd630c634f6f0bf9060d0f3c44576e3
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'. A simple cache mechanism is also
115 ;; provided for these functions.
118 ;;; Code:
120 (eval-when-compile (require 'cl))
121 (require 'org)
125 ;;; Definitions And Rules
127 ;; Define elements, greater elements and specify recursive objects,
128 ;; along with the affiliated keywords recognized. Also set up
129 ;; restrictions on recursive objects combinations.
131 ;; These variables really act as a control center for the parsing
132 ;; process.
134 (defconst org-element-paragraph-separate
135 (concat "^\\(?:"
136 ;; Headlines, inlinetasks.
137 org-outline-regexp "\\|"
138 ;; Footnote definitions.
139 "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
140 ;; Diary sexps.
141 "%%(" "\\|"
142 "[ \t]*\\(?:"
143 ;; Empty lines.
144 "$" "\\|"
145 ;; Tables (any type).
146 "\\(?:|\\|\\+-[-+]\\)" "\\|"
147 ;; Blocks (any type), Babel calls, drawers (any type),
148 ;; fixed-width areas and keywords. Note: this is only an
149 ;; indication and need some thorough check.
150 "[#:]" "\\|"
151 ;; Horizontal rules.
152 "-\\{5,\\}[ \t]*$" "\\|"
153 ;; LaTeX environments.
154 "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
155 ;; Planning and Clock lines.
156 (regexp-opt (list org-scheduled-string
157 org-deadline-string
158 org-closed-string
159 org-clock-string))
160 "\\|"
161 ;; Lists.
162 (let ((term (case org-plain-list-ordered-item-terminator
163 (?\) ")") (?. "\\.") (otherwise "[.)]")))
164 (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
165 (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
166 "\\(?:[ \t]\\|$\\)"))
167 "\\)\\)")
168 "Regexp to separate paragraphs in an Org buffer.
169 In the case of lines starting with \"#\" and \":\", this regexp
170 is not sufficient to know if point is at a paragraph ending. See
171 `org-element-paragraph-parser' for more information.")
173 (defconst org-element-all-elements
174 '(babel-call center-block clock comment comment-block diary-sexp drawer
175 dynamic-block example-block export-block fixed-width
176 footnote-definition headline horizontal-rule inlinetask item
177 keyword latex-environment node-property paragraph plain-list
178 planning property-drawer quote-block quote-section section
179 special-block src-block table table-row verse-block)
180 "Complete list of element types.")
182 (defconst org-element-greater-elements
183 '(center-block drawer dynamic-block footnote-definition headline inlinetask
184 item plain-list property-drawer quote-block section
185 special-block table)
186 "List of recursive element types aka Greater Elements.")
188 (defconst org-element-all-successors
189 '(export-snippet footnote-reference inline-babel-call inline-src-block
190 latex-or-entity line-break link macro plain-link radio-target
191 statistics-cookie sub/superscript table-cell target
192 text-markup timestamp)
193 "Complete list of successors.")
195 (defconst org-element-object-successor-alist
196 '((subscript . sub/superscript) (superscript . sub/superscript)
197 (bold . text-markup) (code . text-markup) (italic . text-markup)
198 (strike-through . text-markup) (underline . text-markup)
199 (verbatim . text-markup) (entity . latex-or-entity)
200 (latex-fragment . latex-or-entity))
201 "Alist of translations between object type and successor name.
202 Sharing the same successor comes handy when, for example, the
203 regexp matching one object can also match the other object.")
205 (defconst org-element-all-objects
206 '(bold code entity export-snippet footnote-reference inline-babel-call
207 inline-src-block italic line-break latex-fragment link macro
208 radio-target statistics-cookie strike-through subscript superscript
209 table-cell target timestamp underline verbatim)
210 "Complete list of object types.")
212 (defconst org-element-recursive-objects
213 '(bold italic link subscript radio-target strike-through superscript
214 table-cell underline)
215 "List of recursive object types.")
217 (defvar org-element-block-name-alist
218 '(("CENTER" . org-element-center-block-parser)
219 ("COMMENT" . org-element-comment-block-parser)
220 ("EXAMPLE" . org-element-example-block-parser)
221 ("QUOTE" . org-element-quote-block-parser)
222 ("SRC" . org-element-src-block-parser)
223 ("VERSE" . org-element-verse-block-parser))
224 "Alist between block names and the associated parsing function.
225 Names must be uppercase. Any block whose name has no association
226 is parsed with `org-element-special-block-parser'.")
228 (defconst org-element-link-type-is-file
229 '("file" "file+emacs" "file+sys" "docview")
230 "List of link types equivalent to \"file\".
231 Only these types can accept search options and an explicit
232 application to open them.")
234 (defconst org-element-affiliated-keywords
235 '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
236 "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
237 "List of affiliated keywords as strings.
238 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
239 are affiliated keywords and need not to be in this list.")
241 (defconst org-element--affiliated-re
242 (format "[ \t]*#\\+%s:"
243 ;; Regular affiliated keywords.
244 (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
245 (regexp-opt org-element-affiliated-keywords)))
246 "Regexp matching any affiliated keyword.
248 Keyword name is put in match group 1. Moreover, if keyword
249 belongs to `org-element-dual-keywords', put the dual value in
250 match group 2.
252 Don't modify it, set `org-element-affiliated-keywords' instead.")
254 (defconst org-element-keyword-translation-alist
255 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
256 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
257 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
258 "Alist of usual translations for keywords.
259 The key is the old name and the value the new one. The property
260 holding their value will be named after the translated name.")
262 (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
263 "List of affiliated keywords that can occur more than once in an element.
265 Their value will be consed into a list of strings, which will be
266 returned as the value of the property.
268 This list is checked after translations have been applied. See
269 `org-element-keyword-translation-alist'.
271 By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
272 allow multiple occurrences and need not to be in this list.")
274 (defconst org-element-parsed-keywords '("CAPTION")
275 "List of affiliated keywords whose value can be parsed.
277 Their value will be stored as a secondary string: a list of
278 strings and objects.
280 This list is checked after translations have been applied. See
281 `org-element-keyword-translation-alist'.")
283 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
284 "List of affiliated keywords which can have a secondary value.
286 In Org syntax, they can be written with optional square brackets
287 before the colons. For example, RESULTS keyword can be
288 associated to a hash value with the following:
290 #+RESULTS[hash-string]: some-source
292 This list is checked after translations have been applied. See
293 `org-element-keyword-translation-alist'.")
295 (defconst org-element-document-properties '("AUTHOR" "DATE" "TITLE")
296 "List of properties associated to the whole document.
297 Any keyword in this list will have its value parsed and stored as
298 a secondary string.")
300 (defconst org-element-object-restrictions
301 (let* ((standard-set
302 (remq 'plain-link (remq 'table-cell org-element-all-successors)))
303 (standard-set-no-line-break (remq 'line-break standard-set)))
304 `((bold ,@standard-set)
305 (footnote-reference ,@standard-set)
306 (headline ,@standard-set-no-line-break)
307 (inlinetask ,@standard-set-no-line-break)
308 (italic ,@standard-set)
309 (item ,@standard-set-no-line-break)
310 (keyword ,@standard-set)
311 ;; Ignore all links excepted plain links in a link description.
312 ;; Also ignore radio-targets and line breaks.
313 (link export-snippet inline-babel-call inline-src-block latex-or-entity
314 macro plain-link statistics-cookie sub/superscript text-markup)
315 (paragraph ,@standard-set)
316 ;; Remove any variable object from radio target as it would
317 ;; prevent it from being properly recognized.
318 (radio-target latex-or-entity sub/superscript)
319 (strike-through ,@standard-set)
320 (subscript ,@standard-set)
321 (superscript ,@standard-set)
322 ;; Ignore inline babel call and inline src block as formulas are
323 ;; possible. Also ignore line breaks and statistics cookies.
324 (table-cell export-snippet footnote-reference latex-or-entity link macro
325 radio-target sub/superscript target text-markup timestamp)
326 (table-row table-cell)
327 (underline ,@standard-set)
328 (verse-block ,@standard-set)))
329 "Alist of objects restrictions.
331 CAR is an element or object type containing objects and CDR is
332 a list of successors that will be called within an element or
333 object of such type.
335 For example, in a `radio-target' object, one can only find
336 entities, latex-fragments, subscript and superscript.
338 This alist also applies to secondary string. For example, an
339 `headline' type element doesn't directly contain objects, but
340 still has an entry since one of its properties (`:title') does.")
342 (defconst org-element-secondary-value-alist
343 '((headline . :title)
344 (inlinetask . :title)
345 (item . :tag)
346 (footnote-reference . :inline-definition))
347 "Alist between element types and location of secondary value.")
349 (defconst org-element-object-variables '(org-link-abbrev-alist-local)
350 "List of buffer-local variables used when parsing objects.
351 These variables are copied to the temporary buffer created by
352 `org-export-secondary-string'.")
356 ;;; Accessors and Setters
358 ;; Provide four accessors: `org-element-type', `org-element-property'
359 ;; `org-element-contents' and `org-element-restriction'.
361 ;; Setter functions allow to modify elements by side effect. There is
362 ;; `org-element-put-property', `org-element-set-contents',
363 ;; `org-element-set-element' and `org-element-adopt-element'. Note
364 ;; that `org-element-set-element' and `org-element-adopt-elements' are
365 ;; higher level functions since also update `:parent' property.
367 (defsubst org-element-type (element)
368 "Return type of ELEMENT.
370 The function returns the type of the element or object provided.
371 It can also return the following special value:
372 `plain-text' for a string
373 `org-data' for a complete document
374 nil in any other case."
375 (cond
376 ((not (consp element)) (and (stringp element) 'plain-text))
377 ((symbolp (car element)) (car element))))
379 (defsubst org-element-property (property element)
380 "Extract the value from the PROPERTY of an ELEMENT."
381 (if (stringp element) (get-text-property 0 property element)
382 (plist-get (nth 1 element) property)))
384 (defsubst org-element-contents (element)
385 "Extract contents from an ELEMENT."
386 (cond ((not (consp element)) nil)
387 ((symbolp (car element)) (nthcdr 2 element))
388 (t element)))
390 (defsubst org-element-restriction (element)
391 "Return restriction associated to ELEMENT.
392 ELEMENT can be an element, an object or a symbol representing an
393 element or object type."
394 (cdr (assq (if (symbolp element) element (org-element-type element))
395 org-element-object-restrictions)))
397 (defsubst org-element-put-property (element property value)
398 "In ELEMENT set PROPERTY to VALUE.
399 Return modified element."
400 (if (stringp element) (org-add-props element nil property value)
401 (setcar (cdr element) (plist-put (nth 1 element) property value))
402 element))
404 (defsubst org-element-set-contents (element &rest contents)
405 "Set ELEMENT contents to CONTENTS.
406 Return modified element."
407 (cond ((not element) (list contents))
408 ((not (symbolp (car element))) contents)
409 ((cdr element) (setcdr (cdr element) contents))
410 (t (nconc element contents))))
412 (defsubst org-element-set-element (old new)
413 "Replace element or object OLD with element or object NEW.
414 The function takes care of setting `:parent' property for NEW."
415 ;; Since OLD is going to be changed into NEW by side-effect, first
416 ;; make sure that every element or object within NEW has OLD as
417 ;; parent.
418 (mapc (lambda (blob) (org-element-put-property blob :parent old))
419 (org-element-contents new))
420 ;; Transfer contents.
421 (apply 'org-element-set-contents old (org-element-contents new))
422 ;; Ensure NEW has same parent as OLD, then overwrite OLD properties
423 ;; with NEW's.
424 (org-element-put-property new :parent (org-element-property :parent old))
425 (setcar (cdr old) (nth 1 new))
426 ;; Transfer type.
427 (setcar old (car new)))
429 (defsubst org-element-adopt-elements (parent &rest children)
430 "Append elements to the contents of another element.
432 PARENT is an element or object. CHILDREN can be elements,
433 objects, or a strings.
435 The function takes care of setting `:parent' property for CHILD.
436 Return parent element."
437 ;; Link every child to PARENT. If PARENT is nil, it is a secondary
438 ;; string: parent is the list itself.
439 (mapc (lambda (child)
440 (org-element-put-property child :parent (or parent children)))
441 children)
442 ;; Add CHILDREN at the end of PARENT contents.
443 (when parent
444 (apply 'org-element-set-contents
445 parent
446 (nconc (org-element-contents parent) children)))
447 ;; Return modified PARENT element.
448 (or parent children))
452 ;;; Greater elements
454 ;; For each greater element type, we define a parser and an
455 ;; interpreter.
457 ;; A parser returns the element or object as the list described above.
458 ;; Most of them accepts no argument. Though, exceptions exist. Hence
459 ;; every element containing a secondary string (see
460 ;; `org-element-secondary-value-alist') will accept an optional
461 ;; argument to toggle parsing of that secondary string. Moreover,
462 ;; `item' parser requires current list's structure as its first
463 ;; element.
465 ;; An interpreter accepts two arguments: the list representation of
466 ;; the element or object, and its contents. The latter may be nil,
467 ;; depending on the element or object considered. It returns the
468 ;; appropriate Org syntax, as a string.
470 ;; Parsing functions must follow the naming convention:
471 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
472 ;; defined in `org-element-greater-elements'.
474 ;; Similarly, interpreting functions must follow the naming
475 ;; convention: org-element-TYPE-interpreter.
477 ;; With the exception of `headline' and `item' types, greater elements
478 ;; cannot contain other greater elements of their own type.
480 ;; Beside implementing a parser and an interpreter, adding a new
481 ;; greater element requires to tweak `org-element--current-element'.
482 ;; Moreover, the newly defined type must be added to both
483 ;; `org-element-all-elements' and `org-element-greater-elements'.
486 ;;;; Center Block
488 (defun org-element-center-block-parser (limit affiliated)
489 "Parse a center block.
491 LIMIT bounds the search. AFFILIATED is a list of which CAR is
492 the buffer position at the beginning of the first affiliated
493 keyword and CDR is a plist of affiliated keywords along with
494 their value.
496 Return a list whose CAR is `center-block' and CDR is a plist
497 containing `:begin', `:end', `:contents-begin', `:contents-end',
498 `:post-blank' and `:post-affiliated' keywords.
500 Assume point is at the beginning of the block."
501 (let ((case-fold-search t))
502 (if (not (save-excursion
503 (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
504 ;; Incomplete block: parse it as a paragraph.
505 (org-element-paragraph-parser limit affiliated)
506 (let ((block-end-line (match-beginning 0)))
507 (let* ((begin (car affiliated))
508 (post-affiliated (point))
509 ;; Empty blocks have no contents.
510 (contents-begin (progn (forward-line)
511 (and (< (point) block-end-line)
512 (point))))
513 (contents-end (and contents-begin block-end-line))
514 (pos-before-blank (progn (goto-char block-end-line)
515 (forward-line)
516 (point)))
517 (end (save-excursion
518 (skip-chars-forward " \r\t\n" limit)
519 (if (eobp) (point) (line-beginning-position)))))
520 (list 'center-block
521 (nconc
522 (list :begin begin
523 :end end
524 :contents-begin contents-begin
525 :contents-end contents-end
526 :post-blank (count-lines pos-before-blank end)
527 :post-affiliated post-affiliated)
528 (cdr affiliated))))))))
530 (defun org-element-center-block-interpreter (center-block contents)
531 "Interpret CENTER-BLOCK element as Org syntax.
532 CONTENTS is the contents of the element."
533 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
536 ;;;; Drawer
538 (defun org-element-drawer-parser (limit affiliated)
539 "Parse a drawer.
541 LIMIT bounds the search. AFFILIATED is a list of which CAR is
542 the buffer position at the beginning of the first affiliated
543 keyword and CDR is a plist of affiliated keywords along with
544 their value.
546 Return a list whose CAR is `drawer' and CDR is a plist containing
547 `:drawer-name', `:begin', `:end', `:contents-begin',
548 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
550 Assume point is at beginning of drawer."
551 (let ((case-fold-search t))
552 (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
553 ;; Incomplete drawer: parse it as a paragraph.
554 (org-element-paragraph-parser limit affiliated)
555 (save-excursion
556 (let* ((drawer-end-line (match-beginning 0))
557 (name (progn (looking-at org-drawer-regexp)
558 (org-match-string-no-properties 1)))
559 (begin (car affiliated))
560 (post-affiliated (point))
561 ;; Empty drawers have no contents.
562 (contents-begin (progn (forward-line)
563 (and (< (point) drawer-end-line)
564 (point))))
565 (contents-end (and contents-begin drawer-end-line))
566 (pos-before-blank (progn (goto-char drawer-end-line)
567 (forward-line)
568 (point)))
569 (end (progn (skip-chars-forward " \r\t\n" limit)
570 (if (eobp) (point) (line-beginning-position)))))
571 (list 'drawer
572 (nconc
573 (list :begin begin
574 :end end
575 :drawer-name name
576 :contents-begin contents-begin
577 :contents-end contents-end
578 :post-blank (count-lines pos-before-blank end)
579 :post-affiliated post-affiliated)
580 (cdr affiliated))))))))
582 (defun org-element-drawer-interpreter (drawer contents)
583 "Interpret DRAWER element as Org syntax.
584 CONTENTS is the contents of the element."
585 (format ":%s:\n%s:END:"
586 (org-element-property :drawer-name drawer)
587 contents))
590 ;;;; Dynamic Block
592 (defun org-element-dynamic-block-parser (limit affiliated)
593 "Parse a dynamic block.
595 LIMIT bounds the search. AFFILIATED is a list of which CAR is
596 the buffer position at the beginning of the first affiliated
597 keyword and CDR is a plist of affiliated keywords along with
598 their value.
600 Return a list whose CAR is `dynamic-block' and CDR is a plist
601 containing `:block-name', `:begin', `:end', `:contents-begin',
602 `:contents-end', `:arguments', `:post-blank' and
603 `:post-affiliated' keywords.
605 Assume point is at beginning of dynamic block."
606 (let ((case-fold-search t))
607 (if (not (save-excursion
608 (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
609 ;; Incomplete block: parse it as a paragraph.
610 (org-element-paragraph-parser limit affiliated)
611 (let ((block-end-line (match-beginning 0)))
612 (save-excursion
613 (let* ((name (progn (looking-at org-dblock-start-re)
614 (org-match-string-no-properties 1)))
615 (arguments (org-match-string-no-properties 3))
616 (begin (car affiliated))
617 (post-affiliated (point))
618 ;; Empty blocks have no contents.
619 (contents-begin (progn (forward-line)
620 (and (< (point) block-end-line)
621 (point))))
622 (contents-end (and contents-begin block-end-line))
623 (pos-before-blank (progn (goto-char block-end-line)
624 (forward-line)
625 (point)))
626 (end (progn (skip-chars-forward " \r\t\n" limit)
627 (if (eobp) (point) (line-beginning-position)))))
628 (list 'dynamic-block
629 (nconc
630 (list :begin begin
631 :end end
632 :block-name name
633 :arguments arguments
634 :contents-begin contents-begin
635 :contents-end contents-end
636 :post-blank (count-lines pos-before-blank end)
637 :post-affiliated post-affiliated)
638 (cdr affiliated)))))))))
640 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
641 "Interpret DYNAMIC-BLOCK element as Org syntax.
642 CONTENTS is the contents of the element."
643 (format "#+BEGIN: %s%s\n%s#+END:"
644 (org-element-property :block-name dynamic-block)
645 (let ((args (org-element-property :arguments dynamic-block)))
646 (and args (concat " " args)))
647 contents))
650 ;;;; Footnote Definition
652 (defun org-element-footnote-definition-parser (limit affiliated)
653 "Parse a footnote definition.
655 LIMIT bounds the search. AFFILIATED is a list of which CAR is
656 the buffer position at the beginning of the first affiliated
657 keyword and CDR is a plist of affiliated keywords along with
658 their value.
660 Return a list whose CAR is `footnote-definition' and CDR is
661 a plist containing `:label', `:begin' `:end', `:contents-begin',
662 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
664 Assume point is at the beginning of the footnote definition."
665 (save-excursion
666 (let* ((label (progn (looking-at org-footnote-definition-re)
667 (org-match-string-no-properties 1)))
668 (begin (car affiliated))
669 (post-affiliated (point))
670 (ending (save-excursion
671 (if (progn
672 (end-of-line)
673 (re-search-forward
674 (concat org-outline-regexp-bol "\\|"
675 org-footnote-definition-re "\\|"
676 "^\\([ \t]*\n\\)\\{2,\\}") limit 'move))
677 (match-beginning 0)
678 (point))))
679 (contents-begin (progn
680 (search-forward "]")
681 (skip-chars-forward " \r\t\n" ending)
682 (cond ((= (point) ending) nil)
683 ((= (line-beginning-position) begin) (point))
684 (t (line-beginning-position)))))
685 (contents-end (and contents-begin ending))
686 (end (progn (goto-char ending)
687 (skip-chars-forward " \r\t\n" limit)
688 (if (eobp) (point) (line-beginning-position)))))
689 (list 'footnote-definition
690 (nconc
691 (list :label label
692 :begin begin
693 :end end
694 :contents-begin contents-begin
695 :contents-end contents-end
696 :post-blank (count-lines ending end)
697 :post-affiliated post-affiliated)
698 (cdr affiliated))))))
700 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
701 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
702 CONTENTS is the contents of the footnote-definition."
703 (concat (format "[%s]" (org-element-property :label footnote-definition))
705 contents))
708 ;;;; Headline
710 (defun org-element-headline-parser (limit &optional raw-secondary-p)
711 "Parse a headline.
713 Return a list whose CAR is `headline' and CDR is a plist
714 containing `:raw-value', `:title', `:alt-title', `:begin',
715 `:end', `:pre-blank', `:contents-begin' and `:contents-end',
716 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
717 `:scheduled', `:deadline', `:closed', `:quotedp', `:archivedp',
718 `:commentedp' and `:footnote-section-p' keywords.
720 The plist also contains any property set in the property drawer,
721 with its name in upper cases and colons added at the
722 beginning (i.e. `:CUSTOM_ID').
724 When RAW-SECONDARY-P is non-nil, headline's title will not be
725 parsed as a secondary string, but as a plain string instead.
727 Assume point is at beginning of the headline."
728 (save-excursion
729 (let* ((components (org-heading-components))
730 (level (nth 1 components))
731 (todo (nth 2 components))
732 (todo-type
733 (and todo (if (member todo org-done-keywords) 'done 'todo)))
734 (tags (let ((raw-tags (nth 5 components)))
735 (and raw-tags (org-split-string raw-tags ":"))))
736 (raw-value (or (nth 4 components) ""))
737 (quotedp
738 (let ((case-fold-search nil))
739 (string-match (format "^%s\\( \\|$\\)" org-quote-string)
740 raw-value)))
741 (commentedp
742 (let ((case-fold-search nil))
743 (string-match (format "^%s\\( \\|$\\)" org-comment-string)
744 raw-value)))
745 (archivedp (member org-archive-tag tags))
746 (footnote-section-p (and org-footnote-section
747 (string= org-footnote-section raw-value)))
748 ;; Upcase property names. It avoids confusion between
749 ;; properties obtained through property drawer and default
750 ;; properties from the parser (e.g. `:end' and :END:)
751 (standard-props
752 (let (plist)
753 (mapc
754 (lambda (p)
755 (setq plist
756 (plist-put plist
757 (intern (concat ":" (upcase (car p))))
758 (cdr p))))
759 (org-entry-properties nil 'standard))
760 plist))
761 (time-props
762 ;; Read time properties on the line below the headline.
763 (save-excursion
764 (when (progn (forward-line)
765 (looking-at org-planning-or-clock-line-re))
766 (let ((end (line-end-position)) plist)
767 (while (re-search-forward
768 org-keyword-time-not-clock-regexp end t)
769 (goto-char (match-end 1))
770 (skip-chars-forward " \t")
771 (let ((keyword (match-string 1))
772 (time (org-element-timestamp-parser)))
773 (cond ((equal keyword org-scheduled-string)
774 (setq plist (plist-put plist :scheduled time)))
775 ((equal keyword org-deadline-string)
776 (setq plist (plist-put plist :deadline time)))
777 (t (setq plist (plist-put plist :closed time))))))
778 plist))))
779 (begin (point))
780 (end (save-excursion (goto-char (org-end-of-subtree t t))))
781 (pos-after-head (progn (forward-line) (point)))
782 (contents-begin (save-excursion
783 (skip-chars-forward " \r\t\n" end)
784 (and (/= (point) end) (line-beginning-position))))
785 (contents-end (and contents-begin
786 (progn (goto-char end)
787 (skip-chars-backward " \r\t\n")
788 (forward-line)
789 (point)))))
790 ;; Clean RAW-VALUE from any quote or comment string.
791 (when (or quotedp commentedp)
792 (let ((case-fold-search nil))
793 (setq raw-value
794 (replace-regexp-in-string
795 (concat
796 (regexp-opt (list org-quote-string org-comment-string))
797 "\\(?: \\|$\\)")
799 raw-value))))
800 ;; Clean TAGS from archive tag, if any.
801 (when archivedp (setq tags (delete org-archive-tag tags)))
802 (let ((headline
803 (list 'headline
804 (nconc
805 (list :raw-value raw-value
806 :begin begin
807 :end end
808 :pre-blank
809 (if (not contents-begin) 0
810 (count-lines pos-after-head contents-begin))
811 :contents-begin contents-begin
812 :contents-end contents-end
813 :level level
814 :priority (nth 3 components)
815 :tags tags
816 :todo-keyword todo
817 :todo-type todo-type
818 :post-blank (count-lines
819 (if (not contents-end) pos-after-head
820 (goto-char contents-end)
821 (forward-line)
822 (point))
823 end)
824 :footnote-section-p footnote-section-p
825 :archivedp archivedp
826 :commentedp commentedp
827 :quotedp quotedp)
828 time-props
829 standard-props))))
830 (let ((alt-title (org-element-property :ALT_TITLE headline)))
831 (when alt-title
832 (org-element-put-property
833 headline :alt-title
834 (if raw-secondary-p alt-title
835 (org-element-parse-secondary-string
836 alt-title (org-element-restriction 'headline) headline)))))
837 (org-element-put-property
838 headline :title
839 (if raw-secondary-p raw-value
840 (org-element-parse-secondary-string
841 raw-value (org-element-restriction 'headline) headline)))))))
843 (defun org-element-headline-interpreter (headline contents)
844 "Interpret HEADLINE element as Org syntax.
845 CONTENTS is the contents of the element."
846 (let* ((level (org-element-property :level headline))
847 (todo (org-element-property :todo-keyword headline))
848 (priority (org-element-property :priority headline))
849 (title (org-element-interpret-data
850 (org-element-property :title headline)))
851 (tags (let ((tag-list (if (org-element-property :archivedp headline)
852 (cons org-archive-tag
853 (org-element-property :tags headline))
854 (org-element-property :tags headline))))
855 (and tag-list
856 (format ":%s:" (mapconcat 'identity tag-list ":")))))
857 (commentedp (org-element-property :commentedp headline))
858 (quotedp (org-element-property :quotedp headline))
859 (pre-blank (or (org-element-property :pre-blank headline) 0))
860 (heading (concat (make-string (org-reduced-level level) ?*)
861 (and todo (concat " " todo))
862 (and quotedp (concat " " org-quote-string))
863 (and commentedp (concat " " org-comment-string))
864 (and priority
865 (format " [#%s]" (char-to-string priority)))
866 (cond ((and org-footnote-section
867 (org-element-property
868 :footnote-section-p headline))
869 (concat " " org-footnote-section))
870 (title (concat " " title))))))
871 (concat heading
872 ;; Align tags.
873 (when tags
874 (cond
875 ((zerop org-tags-column) (format " %s" tags))
876 ((< org-tags-column 0)
877 (concat
878 (make-string
879 (max (- (+ org-tags-column (length heading) (length tags))) 1)
881 tags))
883 (concat
884 (make-string (max (- org-tags-column (length heading)) 1) ? )
885 tags))))
886 (make-string (1+ pre-blank) 10)
887 contents)))
890 ;;;; Inlinetask
892 (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
893 "Parse an inline task.
895 Return a list whose CAR is `inlinetask' and CDR is a plist
896 containing `:title', `:begin', `:end', `:contents-begin' and
897 `:contents-end', `:level', `:priority', `:raw-value', `:tags',
898 `:todo-keyword', `:todo-type', `:scheduled', `:deadline',
899 `:closed' and `:post-blank' keywords.
901 The plist also contains any property set in the property drawer,
902 with its name in upper cases and colons added at the
903 beginning (i.e. `:CUSTOM_ID').
905 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
906 title will not be parsed as a secondary string, but as a plain
907 string instead.
909 Assume point is at beginning of the inline task."
910 (save-excursion
911 (let* ((begin (point))
912 (components (org-heading-components))
913 (todo (nth 2 components))
914 (todo-type (and todo
915 (if (member todo org-done-keywords) 'done 'todo)))
916 (tags (let ((raw-tags (nth 5 components)))
917 (and raw-tags (org-split-string raw-tags ":"))))
918 (raw-value (or (nth 4 components) ""))
919 ;; Upcase property names. It avoids confusion between
920 ;; properties obtained through property drawer and default
921 ;; properties from the parser (e.g. `:end' and :END:)
922 (standard-props
923 (let (plist)
924 (mapc
925 (lambda (p)
926 (setq plist
927 (plist-put plist
928 (intern (concat ":" (upcase (car p))))
929 (cdr p))))
930 (org-entry-properties nil 'standard))
931 plist))
932 (time-props
933 ;; Read time properties on the line below the inlinetask
934 ;; opening string.
935 (save-excursion
936 (when (progn (forward-line)
937 (looking-at org-planning-or-clock-line-re))
938 (let ((end (line-end-position)) plist)
939 (while (re-search-forward
940 org-keyword-time-not-clock-regexp end t)
941 (goto-char (match-end 1))
942 (skip-chars-forward " \t")
943 (let ((keyword (match-string 1))
944 (time (org-element-timestamp-parser)))
945 (cond ((equal keyword org-scheduled-string)
946 (setq plist (plist-put plist :scheduled time)))
947 ((equal keyword org-deadline-string)
948 (setq plist (plist-put plist :deadline time)))
949 (t (setq plist (plist-put plist :closed time))))))
950 plist))))
951 (task-end (save-excursion
952 (end-of-line)
953 (and (re-search-forward "^\\*+ END" limit t)
954 (match-beginning 0))))
955 (contents-begin (progn (forward-line)
956 (and task-end (< (point) task-end) (point))))
957 (contents-end (and contents-begin task-end))
958 (before-blank (if (not task-end) (point)
959 (goto-char task-end)
960 (forward-line)
961 (point)))
962 (end (progn (skip-chars-forward " \r\t\n" limit)
963 (if (eobp) (point) (line-beginning-position))))
964 (inlinetask
965 (list 'inlinetask
966 (nconc
967 (list :raw-value raw-value
968 :begin begin
969 :end end
970 :contents-begin contents-begin
971 :contents-end contents-end
972 :level (nth 1 components)
973 :priority (nth 3 components)
974 :tags tags
975 :todo-keyword todo
976 :todo-type todo-type
977 :post-blank (count-lines before-blank end))
978 time-props
979 standard-props))))
980 (org-element-put-property
981 inlinetask :title
982 (if raw-secondary-p raw-value
983 (org-element-parse-secondary-string
984 raw-value
985 (org-element-restriction 'inlinetask)
986 inlinetask))))))
988 (defun org-element-inlinetask-interpreter (inlinetask contents)
989 "Interpret INLINETASK element as Org syntax.
990 CONTENTS is the contents of inlinetask."
991 (let* ((level (org-element-property :level inlinetask))
992 (todo (org-element-property :todo-keyword inlinetask))
993 (priority (org-element-property :priority inlinetask))
994 (title (org-element-interpret-data
995 (org-element-property :title inlinetask)))
996 (tags (let ((tag-list (org-element-property :tags inlinetask)))
997 (and tag-list
998 (format ":%s:" (mapconcat 'identity tag-list ":")))))
999 (task (concat (make-string level ?*)
1000 (and todo (concat " " todo))
1001 (and priority
1002 (format " [#%s]" (char-to-string priority)))
1003 (and title (concat " " title)))))
1004 (concat task
1005 ;; Align tags.
1006 (when tags
1007 (cond
1008 ((zerop org-tags-column) (format " %s" tags))
1009 ((< org-tags-column 0)
1010 (concat
1011 (make-string
1012 (max (- (+ org-tags-column (length task) (length tags))) 1)
1014 tags))
1016 (concat
1017 (make-string (max (- org-tags-column (length task)) 1) ? )
1018 tags))))
1019 ;; Prefer degenerate inlinetasks when there are no
1020 ;; contents.
1021 (when contents
1022 (concat "\n"
1023 contents
1024 (make-string level ?*) " END")))))
1027 ;;;; Item
1029 (defun org-element-item-parser (limit struct &optional raw-secondary-p)
1030 "Parse an item.
1032 STRUCT is the structure of the plain list.
1034 Return a list whose CAR is `item' and CDR is a plist containing
1035 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
1036 `:checkbox', `:counter', `:tag', `:structure' and `:post-blank'
1037 keywords.
1039 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
1040 any, will not be parsed as a secondary string, but as a plain
1041 string instead.
1043 Assume point is at the beginning of the item."
1044 (save-excursion
1045 (beginning-of-line)
1046 (looking-at org-list-full-item-re)
1047 (let* ((begin (point))
1048 (bullet (org-match-string-no-properties 1))
1049 (checkbox (let ((box (org-match-string-no-properties 3)))
1050 (cond ((equal "[ ]" box) 'off)
1051 ((equal "[X]" box) 'on)
1052 ((equal "[-]" box) 'trans))))
1053 (counter (let ((c (org-match-string-no-properties 2)))
1054 (save-match-data
1055 (cond
1056 ((not c) nil)
1057 ((string-match "[A-Za-z]" c)
1058 (- (string-to-char (upcase (match-string 0 c)))
1059 64))
1060 ((string-match "[0-9]+" c)
1061 (string-to-number (match-string 0 c)))))))
1062 (end (progn (goto-char (nth 6 (assq (point) struct)))
1063 (unless (bolp) (forward-line))
1064 (point)))
1065 (contents-begin
1066 (progn (goto-char
1067 ;; Ignore tags in un-ordered lists: they are just
1068 ;; a part of item's body.
1069 (if (and (match-beginning 4)
1070 (save-match-data (string-match "[.)]" bullet)))
1071 (match-beginning 4)
1072 (match-end 0)))
1073 (skip-chars-forward " \r\t\n" limit)
1074 ;; If first line isn't empty, contents really start
1075 ;; at the text after item's meta-data.
1076 (if (= (point-at-bol) begin) (point) (point-at-bol))))
1077 (contents-end (progn (goto-char end)
1078 (skip-chars-backward " \r\t\n")
1079 (forward-line)
1080 (point)))
1081 (item
1082 (list 'item
1083 (list :bullet bullet
1084 :begin begin
1085 :end end
1086 ;; CONTENTS-BEGIN and CONTENTS-END may be
1087 ;; mixed up in the case of an empty item
1088 ;; separated from the next by a blank line.
1089 ;; Thus ensure the former is always the
1090 ;; smallest.
1091 :contents-begin (min contents-begin contents-end)
1092 :contents-end (max contents-begin contents-end)
1093 :checkbox checkbox
1094 :counter counter
1095 :structure struct
1096 :post-blank (count-lines contents-end end)))))
1097 (org-element-put-property
1098 item :tag
1099 (let ((raw-tag (org-list-get-tag begin struct)))
1100 (and raw-tag
1101 (if raw-secondary-p raw-tag
1102 (org-element-parse-secondary-string
1103 raw-tag (org-element-restriction 'item) item))))))))
1105 (defun org-element-item-interpreter (item contents)
1106 "Interpret ITEM element as Org syntax.
1107 CONTENTS is the contents of the element."
1108 (let* ((bullet (let ((bullet (org-element-property :bullet item)))
1109 (org-list-bullet-string
1110 (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
1111 ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
1112 (t "1.")))))
1113 (checkbox (org-element-property :checkbox item))
1114 (counter (org-element-property :counter item))
1115 (tag (let ((tag (org-element-property :tag item)))
1116 (and tag (org-element-interpret-data tag))))
1117 ;; Compute indentation.
1118 (ind (make-string (length bullet) 32))
1119 (item-starts-with-par-p
1120 (eq (org-element-type (car (org-element-contents item)))
1121 'paragraph)))
1122 ;; Indent contents.
1123 (concat
1124 bullet
1125 (and counter (format "[@%d] " counter))
1126 (case checkbox
1127 (on "[X] ")
1128 (off "[ ] ")
1129 (trans "[-] "))
1130 (and tag (format "%s :: " tag))
1131 (when contents
1132 (let ((contents (replace-regexp-in-string
1133 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
1134 (if item-starts-with-par-p (org-trim contents)
1135 (concat "\n" contents)))))))
1138 ;;;; Plain List
1140 (defun org-element--list-struct (limit)
1141 ;; Return structure of list at point. Internal function. See
1142 ;; `org-list-struct' for details.
1143 (let ((case-fold-search t)
1144 (top-ind limit)
1145 (item-re (org-item-re))
1146 (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
1147 items struct)
1148 (save-excursion
1149 (catch 'exit
1150 (while t
1151 (cond
1152 ;; At limit: end all items.
1153 ((>= (point) limit)
1154 (throw 'exit
1155 (let ((end (progn (skip-chars-backward " \r\t\n")
1156 (forward-line)
1157 (point))))
1158 (dolist (item items (sort (nconc items struct)
1159 'car-less-than-car))
1160 (setcar (nthcdr 6 item) end)))))
1161 ;; At list end: end all items.
1162 ((looking-at org-list-end-re)
1163 (throw 'exit (dolist (item items (sort (nconc items struct)
1164 'car-less-than-car))
1165 (setcar (nthcdr 6 item) (point)))))
1166 ;; At a new item: end previous sibling.
1167 ((looking-at item-re)
1168 (let ((ind (save-excursion (skip-chars-forward " \t")
1169 (current-column))))
1170 (setq top-ind (min top-ind ind))
1171 (while (and items (<= ind (nth 1 (car items))))
1172 (let ((item (pop items)))
1173 (setcar (nthcdr 6 item) (point))
1174 (push item struct)))
1175 (push (progn (looking-at org-list-full-item-re)
1176 (let ((bullet (match-string-no-properties 1)))
1177 (list (point)
1179 bullet
1180 (match-string-no-properties 2) ; counter
1181 (match-string-no-properties 3) ; checkbox
1182 ;; Description tag.
1183 (and (save-match-data
1184 (string-match "[-+*]" bullet))
1185 (match-string-no-properties 4))
1186 ;; Ending position, unknown so far.
1187 nil)))
1188 items))
1189 (forward-line 1))
1190 ;; Skip empty lines.
1191 ((looking-at "^[ \t]*$") (forward-line))
1192 ;; Skip inline tasks and blank lines along the way.
1193 ((and inlinetask-re (looking-at inlinetask-re))
1194 (forward-line)
1195 (let ((origin (point)))
1196 (when (re-search-forward inlinetask-re limit t)
1197 (if (looking-at "^\\*+ END[ \t]*$") (forward-line)
1198 (goto-char origin)))))
1199 ;; At some text line. Check if it ends any previous item.
1201 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
1202 (when (<= ind top-ind)
1203 (skip-chars-backward " \r\t\n")
1204 (forward-line))
1205 (while (<= ind (nth 1 (car items)))
1206 (let ((item (pop items)))
1207 (setcar (nthcdr 6 item) (line-beginning-position))
1208 (push item struct)
1209 (unless items
1210 (throw 'exit (sort struct 'car-less-than-car))))))
1211 ;; Skip blocks (any type) and drawers contents.
1212 (cond
1213 ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
1214 (re-search-forward
1215 (format "^[ \t]*#\\+END%s[ \t]*$"
1216 (org-match-string-no-properties 1))
1217 limit t)))
1218 ((and (looking-at org-drawer-regexp)
1219 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
1220 (forward-line))))))))
1222 (defun org-element-plain-list-parser (limit affiliated structure)
1223 "Parse a plain list.
1225 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1226 the buffer position at the beginning of the first affiliated
1227 keyword and CDR is a plist of affiliated keywords along with
1228 their value. STRUCTURE is the structure of the plain list being
1229 parsed.
1231 Return a list whose CAR is `plain-list' and CDR is a plist
1232 containing `:type', `:begin', `:end', `:contents-begin' and
1233 `:contents-end', `:structure', `:post-blank' and
1234 `:post-affiliated' keywords.
1236 Assume point is at the beginning of the list."
1237 (save-excursion
1238 (let* ((struct (or structure (org-element--list-struct limit)))
1239 (type (cond ((org-looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
1240 ((nth 5 (assq (point) struct)) 'descriptive)
1241 (t 'unordered)))
1242 (contents-begin (point))
1243 (begin (car affiliated))
1244 (contents-end (let* ((item (assq contents-begin struct))
1245 (ind (nth 1 item))
1246 (pos (nth 6 item)))
1247 (while (and (setq item (assq pos struct))
1248 (= (nth 1 item) ind))
1249 (setq pos (nth 6 item)))
1250 pos))
1251 (end (progn (goto-char contents-end)
1252 (skip-chars-forward " \r\t\n" limit)
1253 (if (= (point) limit) limit (line-beginning-position)))))
1254 ;; Return value.
1255 (list 'plain-list
1256 (nconc
1257 (list :type type
1258 :begin begin
1259 :end end
1260 :contents-begin contents-begin
1261 :contents-end contents-end
1262 :structure struct
1263 :post-blank (count-lines contents-end end)
1264 :post-affiliated contents-begin)
1265 (cdr affiliated))))))
1267 (defun org-element-plain-list-interpreter (plain-list contents)
1268 "Interpret PLAIN-LIST element as Org syntax.
1269 CONTENTS is the contents of the element."
1270 (with-temp-buffer
1271 (insert contents)
1272 (goto-char (point-min))
1273 (org-list-repair)
1274 (buffer-string)))
1277 ;;;; Property Drawer
1279 (defun org-element-property-drawer-parser (limit affiliated)
1280 "Parse a property drawer.
1282 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1283 the buffer position at the beginning of the first affiliated
1284 keyword and CDR is a plist of affiliated keywords along with
1285 their value.
1287 Return a list whose CAR is `property-drawer' and CDR is a plist
1288 containing `:begin', `:end', `:contents-begin', `:contents-end',
1289 `:post-blank' and `:post-affiliated' keywords.
1291 Assume point is at the beginning of the property drawer."
1292 (save-excursion
1293 (let ((case-fold-search t))
1294 (if (not (save-excursion
1295 (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
1296 ;; Incomplete drawer: parse it as a paragraph.
1297 (org-element-paragraph-parser limit affiliated)
1298 (save-excursion
1299 (let* ((drawer-end-line (match-beginning 0))
1300 (begin (car affiliated))
1301 (post-affiliated (point))
1302 (contents-begin (progn (forward-line)
1303 (and (< (point) drawer-end-line)
1304 (point))))
1305 (contents-end (and contents-begin drawer-end-line))
1306 (pos-before-blank (progn (goto-char drawer-end-line)
1307 (forward-line)
1308 (point)))
1309 (end (progn (skip-chars-forward " \r\t\n" limit)
1310 (if (eobp) (point) (line-beginning-position)))))
1311 (list 'property-drawer
1312 (nconc
1313 (list :begin begin
1314 :end end
1315 :contents-begin contents-begin
1316 :contents-end contents-end
1317 :post-blank (count-lines pos-before-blank end)
1318 :post-affiliated post-affiliated)
1319 (cdr affiliated)))))))))
1321 (defun org-element-property-drawer-interpreter (property-drawer contents)
1322 "Interpret PROPERTY-DRAWER element as Org syntax.
1323 CONTENTS is the properties within the drawer."
1324 (format ":PROPERTIES:\n%s:END:" contents))
1327 ;;;; Quote Block
1329 (defun org-element-quote-block-parser (limit affiliated)
1330 "Parse a quote block.
1332 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1333 the buffer position at the beginning of the first affiliated
1334 keyword and CDR is a plist of affiliated keywords along with
1335 their value.
1337 Return a list whose CAR is `quote-block' and CDR is a plist
1338 containing `:begin', `:end', `:contents-begin', `:contents-end',
1339 `:post-blank' and `:post-affiliated' keywords.
1341 Assume point is at the beginning of the block."
1342 (let ((case-fold-search t))
1343 (if (not (save-excursion
1344 (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1345 ;; Incomplete block: parse it as a paragraph.
1346 (org-element-paragraph-parser limit affiliated)
1347 (let ((block-end-line (match-beginning 0)))
1348 (save-excursion
1349 (let* ((begin (car affiliated))
1350 (post-affiliated (point))
1351 ;; Empty blocks have no contents.
1352 (contents-begin (progn (forward-line)
1353 (and (< (point) block-end-line)
1354 (point))))
1355 (contents-end (and contents-begin block-end-line))
1356 (pos-before-blank (progn (goto-char block-end-line)
1357 (forward-line)
1358 (point)))
1359 (end (progn (skip-chars-forward " \r\t\n" limit)
1360 (if (eobp) (point) (line-beginning-position)))))
1361 (list 'quote-block
1362 (nconc
1363 (list :begin begin
1364 :end end
1365 :contents-begin contents-begin
1366 :contents-end contents-end
1367 :post-blank (count-lines pos-before-blank end)
1368 :post-affiliated post-affiliated)
1369 (cdr affiliated)))))))))
1371 (defun org-element-quote-block-interpreter (quote-block contents)
1372 "Interpret QUOTE-BLOCK element as Org syntax.
1373 CONTENTS is the contents of the element."
1374 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
1377 ;;;; Section
1379 (defun org-element-section-parser (limit)
1380 "Parse a section.
1382 LIMIT bounds the search.
1384 Return a list whose CAR is `section' and CDR is a plist
1385 containing `:begin', `:end', `:contents-begin', `contents-end'
1386 and `:post-blank' keywords."
1387 (save-excursion
1388 ;; Beginning of section is the beginning of the first non-blank
1389 ;; line after previous headline.
1390 (let ((begin (point))
1391 (end (progn (org-with-limited-levels (outline-next-heading))
1392 (point)))
1393 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1394 (forward-line)
1395 (point))))
1396 (list 'section
1397 (list :begin begin
1398 :end end
1399 :contents-begin begin
1400 :contents-end pos-before-blank
1401 :post-blank (count-lines pos-before-blank end))))))
1403 (defun org-element-section-interpreter (section contents)
1404 "Interpret SECTION element as Org syntax.
1405 CONTENTS is the contents of the element."
1406 contents)
1409 ;;;; Special Block
1411 (defun org-element-special-block-parser (limit affiliated)
1412 "Parse a special block.
1414 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1415 the buffer position at the beginning of the first affiliated
1416 keyword and CDR is a plist of affiliated keywords along with
1417 their value.
1419 Return a list whose CAR is `special-block' and CDR is a plist
1420 containing `:type', `:begin', `:end', `:contents-begin',
1421 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
1423 Assume point is at the beginning of the block."
1424 (let* ((case-fold-search t)
1425 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1426 (upcase (match-string-no-properties 1)))))
1427 (if (not (save-excursion
1428 (re-search-forward
1429 (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
1430 limit t)))
1431 ;; Incomplete block: parse it as a paragraph.
1432 (org-element-paragraph-parser limit affiliated)
1433 (let ((block-end-line (match-beginning 0)))
1434 (save-excursion
1435 (let* ((begin (car affiliated))
1436 (post-affiliated (point))
1437 ;; Empty blocks have no contents.
1438 (contents-begin (progn (forward-line)
1439 (and (< (point) block-end-line)
1440 (point))))
1441 (contents-end (and contents-begin block-end-line))
1442 (pos-before-blank (progn (goto-char block-end-line)
1443 (forward-line)
1444 (point)))
1445 (end (progn (skip-chars-forward " \r\t\n" limit)
1446 (if (eobp) (point) (line-beginning-position)))))
1447 (list 'special-block
1448 (nconc
1449 (list :type type
1450 :begin begin
1451 :end end
1452 :contents-begin contents-begin
1453 :contents-end contents-end
1454 :post-blank (count-lines pos-before-blank end)
1455 :post-affiliated post-affiliated)
1456 (cdr affiliated)))))))))
1458 (defun org-element-special-block-interpreter (special-block contents)
1459 "Interpret SPECIAL-BLOCK element as Org syntax.
1460 CONTENTS is the contents of the element."
1461 (let ((block-type (org-element-property :type special-block)))
1462 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
1466 ;;; Elements
1468 ;; For each element, a parser and an interpreter are also defined.
1469 ;; Both follow the same naming convention used for greater elements.
1471 ;; Also, as for greater elements, adding a new element type is done
1472 ;; through the following steps: implement a parser and an interpreter,
1473 ;; tweak `org-element--current-element' so that it recognizes the new
1474 ;; type and add that new type to `org-element-all-elements'.
1476 ;; As a special case, when the newly defined type is a block type,
1477 ;; `org-element-block-name-alist' has to be modified accordingly.
1480 ;;;; Babel Call
1482 (defun org-element-babel-call-parser (limit affiliated)
1483 "Parse a babel call.
1485 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1486 the buffer position at the beginning of the first affiliated
1487 keyword and CDR is a plist of affiliated keywords along with
1488 their value.
1490 Return a list whose CAR is `babel-call' and CDR is a plist
1491 containing `:begin', `:end', `:value', `:post-blank' and
1492 `:post-affiliated' as keywords."
1493 (save-excursion
1494 (let ((begin (car affiliated))
1495 (post-affiliated (point))
1496 (value (progn (let ((case-fold-search t))
1497 (re-search-forward "call:[ \t]*" nil t))
1498 (buffer-substring-no-properties (point)
1499 (line-end-position))))
1500 (pos-before-blank (progn (forward-line) (point)))
1501 (end (progn (skip-chars-forward " \r\t\n" limit)
1502 (if (eobp) (point) (line-beginning-position)))))
1503 (list 'babel-call
1504 (nconc
1505 (list :begin begin
1506 :end end
1507 :value value
1508 :post-blank (count-lines pos-before-blank end)
1509 :post-affiliated post-affiliated)
1510 (cdr affiliated))))))
1512 (defun org-element-babel-call-interpreter (babel-call contents)
1513 "Interpret BABEL-CALL element as Org syntax.
1514 CONTENTS is nil."
1515 (concat "#+CALL: " (org-element-property :value babel-call)))
1518 ;;;; Clock
1520 (defun org-element-clock-parser (limit)
1521 "Parse a clock.
1523 LIMIT bounds the search.
1525 Return a list whose CAR is `clock' and CDR is a plist containing
1526 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
1527 as keywords."
1528 (save-excursion
1529 (let* ((case-fold-search nil)
1530 (begin (point))
1531 (value (progn (search-forward org-clock-string (line-end-position) t)
1532 (skip-chars-forward " \t")
1533 (org-element-timestamp-parser)))
1534 (duration (and (search-forward " => " (line-end-position) t)
1535 (progn (skip-chars-forward " \t")
1536 (looking-at "\\(\\S-+\\)[ \t]*$"))
1537 (org-match-string-no-properties 1)))
1538 (status (if duration 'closed 'running))
1539 (post-blank (let ((before-blank (progn (forward-line) (point))))
1540 (skip-chars-forward " \r\t\n" limit)
1541 (skip-chars-backward " \t")
1542 (unless (bolp) (end-of-line))
1543 (count-lines before-blank (point))))
1544 (end (point)))
1545 (list 'clock
1546 (list :status status
1547 :value value
1548 :duration duration
1549 :begin begin
1550 :end end
1551 :post-blank post-blank)))))
1553 (defun org-element-clock-interpreter (clock contents)
1554 "Interpret CLOCK element as Org syntax.
1555 CONTENTS is nil."
1556 (concat org-clock-string " "
1557 (org-element-timestamp-interpreter
1558 (org-element-property :value clock) nil)
1559 (let ((duration (org-element-property :duration clock)))
1560 (and duration
1561 (concat " => "
1562 (apply 'format
1563 "%2s:%02s"
1564 (org-split-string duration ":")))))))
1567 ;;;; Comment
1569 (defun org-element-comment-parser (limit affiliated)
1570 "Parse a comment.
1572 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1573 the buffer position at the beginning of the first affiliated
1574 keyword and CDR is a plist of affiliated keywords along with
1575 their value.
1577 Return a list whose CAR is `comment' and CDR is a plist
1578 containing `:begin', `:end', `:value', `:post-blank',
1579 `:post-affiliated' keywords.
1581 Assume point is at comment beginning."
1582 (save-excursion
1583 (let* ((begin (car affiliated))
1584 (post-affiliated (point))
1585 (value (prog2 (looking-at "[ \t]*# ?")
1586 (buffer-substring-no-properties
1587 (match-end 0) (line-end-position))
1588 (forward-line)))
1589 (com-end
1590 ;; Get comments ending.
1591 (progn
1592 (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
1593 ;; Accumulate lines without leading hash and first
1594 ;; whitespace.
1595 (setq value
1596 (concat value
1597 "\n"
1598 (buffer-substring-no-properties
1599 (match-end 0) (line-end-position))))
1600 (forward-line))
1601 (point)))
1602 (end (progn (goto-char com-end)
1603 (skip-chars-forward " \r\t\n" limit)
1604 (if (eobp) (point) (line-beginning-position)))))
1605 (list 'comment
1606 (nconc
1607 (list :begin begin
1608 :end end
1609 :value value
1610 :post-blank (count-lines com-end end)
1611 :post-affiliated post-affiliated)
1612 (cdr affiliated))))))
1614 (defun org-element-comment-interpreter (comment contents)
1615 "Interpret COMMENT element as Org syntax.
1616 CONTENTS is nil."
1617 (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
1620 ;;;; Comment Block
1622 (defun org-element-comment-block-parser (limit affiliated)
1623 "Parse an export block.
1625 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1626 the buffer position at the beginning of the first affiliated
1627 keyword and CDR is a plist of affiliated keywords along with
1628 their value.
1630 Return a list whose CAR is `comment-block' and CDR is a plist
1631 containing `:begin', `:end', `:value', `:post-blank' and
1632 `:post-affiliated' keywords.
1634 Assume point is at comment block beginning."
1635 (let ((case-fold-search t))
1636 (if (not (save-excursion
1637 (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1638 ;; Incomplete block: parse it as a paragraph.
1639 (org-element-paragraph-parser limit affiliated)
1640 (let ((contents-end (match-beginning 0)))
1641 (save-excursion
1642 (let* ((begin (car affiliated))
1643 (post-affiliated (point))
1644 (contents-begin (progn (forward-line) (point)))
1645 (pos-before-blank (progn (goto-char contents-end)
1646 (forward-line)
1647 (point)))
1648 (end (progn (skip-chars-forward " \r\t\n" limit)
1649 (if (eobp) (point) (line-beginning-position))))
1650 (value (buffer-substring-no-properties
1651 contents-begin contents-end)))
1652 (list 'comment-block
1653 (nconc
1654 (list :begin begin
1655 :end end
1656 :value value
1657 :post-blank (count-lines pos-before-blank end)
1658 :post-affiliated post-affiliated)
1659 (cdr affiliated)))))))))
1661 (defun org-element-comment-block-interpreter (comment-block contents)
1662 "Interpret COMMENT-BLOCK element as Org syntax.
1663 CONTENTS is nil."
1664 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1665 (org-remove-indentation (org-element-property :value comment-block))))
1668 ;;;; Diary Sexp
1670 (defun org-element-diary-sexp-parser (limit affiliated)
1671 "Parse a diary sexp.
1673 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1674 the buffer position at the beginning of the first affiliated
1675 keyword and CDR is a plist of affiliated keywords along with
1676 their value.
1678 Return a list whose CAR is `diary-sexp' and CDR is a plist
1679 containing `:begin', `:end', `:value', `:post-blank' and
1680 `:post-affiliated' keywords."
1681 (save-excursion
1682 (let ((begin (car affiliated))
1683 (post-affiliated (point))
1684 (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
1685 (org-match-string-no-properties 1)))
1686 (pos-before-blank (progn (forward-line) (point)))
1687 (end (progn (skip-chars-forward " \r\t\n" limit)
1688 (if (eobp) (point) (line-beginning-position)))))
1689 (list 'diary-sexp
1690 (nconc
1691 (list :value value
1692 :begin begin
1693 :end end
1694 :post-blank (count-lines pos-before-blank end)
1695 :post-affiliated post-affiliated)
1696 (cdr affiliated))))))
1698 (defun org-element-diary-sexp-interpreter (diary-sexp contents)
1699 "Interpret DIARY-SEXP as Org syntax.
1700 CONTENTS is nil."
1701 (org-element-property :value diary-sexp))
1704 ;;;; Example Block
1706 (defun org-element-example-block-parser (limit affiliated)
1707 "Parse an example block.
1709 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1710 the buffer position at the beginning of the first affiliated
1711 keyword and CDR is a plist of affiliated keywords along with
1712 their value.
1714 Return a list whose CAR is `example-block' and CDR is a plist
1715 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1716 `:retain-labels', `:use-labels', `:label-fmt', `:switches',
1717 `:value', `:post-blank' and `:post-affiliated' keywords."
1718 (let ((case-fold-search t))
1719 (if (not (save-excursion
1720 (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1721 ;; Incomplete block: parse it as a paragraph.
1722 (org-element-paragraph-parser limit affiliated)
1723 (let ((contents-end (match-beginning 0)))
1724 (save-excursion
1725 (let* ((switches
1726 (progn
1727 (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1728 (org-match-string-no-properties 1)))
1729 ;; Switches analysis
1730 (number-lines
1731 (cond ((not switches) nil)
1732 ((string-match "-n\\>" switches) 'new)
1733 ((string-match "+n\\>" switches) 'continued)))
1734 (preserve-indent
1735 (and switches (string-match "-i\\>" switches)))
1736 ;; Should labels be retained in (or stripped from) example
1737 ;; blocks?
1738 (retain-labels
1739 (or (not switches)
1740 (not (string-match "-r\\>" switches))
1741 (and number-lines (string-match "-k\\>" switches))))
1742 ;; What should code-references use - labels or
1743 ;; line-numbers?
1744 (use-labels
1745 (or (not switches)
1746 (and retain-labels
1747 (not (string-match "-k\\>" switches)))))
1748 (label-fmt
1749 (and switches
1750 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1751 (match-string 1 switches)))
1752 ;; Standard block parsing.
1753 (begin (car affiliated))
1754 (post-affiliated (point))
1755 (block-ind (progn (skip-chars-forward " \t") (current-column)))
1756 (contents-begin (progn (forward-line) (point)))
1757 (value (org-element-remove-indentation
1758 (org-unescape-code-in-string
1759 (buffer-substring-no-properties
1760 contents-begin contents-end))
1761 block-ind))
1762 (pos-before-blank (progn (goto-char contents-end)
1763 (forward-line)
1764 (point)))
1765 (end (progn (skip-chars-forward " \r\t\n" limit)
1766 (if (eobp) (point) (line-beginning-position)))))
1767 (list 'example-block
1768 (nconc
1769 (list :begin begin
1770 :end end
1771 :value value
1772 :switches switches
1773 :number-lines number-lines
1774 :preserve-indent preserve-indent
1775 :retain-labels retain-labels
1776 :use-labels use-labels
1777 :label-fmt label-fmt
1778 :post-blank (count-lines pos-before-blank end)
1779 :post-affiliated post-affiliated)
1780 (cdr affiliated)))))))))
1782 (defun org-element-example-block-interpreter (example-block contents)
1783 "Interpret EXAMPLE-BLOCK element as Org syntax.
1784 CONTENTS is nil."
1785 (let ((switches (org-element-property :switches example-block))
1786 (value (org-element-property :value example-block)))
1787 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1788 (org-escape-code-in-string
1789 (if (or org-src-preserve-indentation
1790 (org-element-property :preserve-indent example-block))
1791 value
1792 (org-element-remove-indentation value)))
1793 "#+END_EXAMPLE")))
1796 ;;;; Export Block
1798 (defun org-element-export-block-parser (limit affiliated)
1799 "Parse an export block.
1801 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1802 the buffer position at the beginning of the first affiliated
1803 keyword and CDR is a plist of affiliated keywords along with
1804 their value.
1806 Return a list whose CAR is `export-block' and CDR is a plist
1807 containing `:begin', `:end', `:type', `:value', `:post-blank' and
1808 `:post-affiliated' keywords.
1810 Assume point is at export-block beginning."
1811 (let* ((case-fold-search t)
1812 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
1813 (upcase (org-match-string-no-properties 1)))))
1814 (if (not (save-excursion
1815 (re-search-forward
1816 (format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1817 ;; Incomplete block: parse it as a paragraph.
1818 (org-element-paragraph-parser limit affiliated)
1819 (let ((contents-end (match-beginning 0)))
1820 (save-excursion
1821 (let* ((begin (car affiliated))
1822 (post-affiliated (point))
1823 (contents-begin (progn (forward-line) (point)))
1824 (pos-before-blank (progn (goto-char contents-end)
1825 (forward-line)
1826 (point)))
1827 (end (progn (skip-chars-forward " \r\t\n" limit)
1828 (if (eobp) (point) (line-beginning-position))))
1829 (value (buffer-substring-no-properties contents-begin
1830 contents-end)))
1831 (list 'export-block
1832 (nconc
1833 (list :begin begin
1834 :end end
1835 :type type
1836 :value value
1837 :post-blank (count-lines pos-before-blank end)
1838 :post-affiliated post-affiliated)
1839 (cdr affiliated)))))))))
1841 (defun org-element-export-block-interpreter (export-block contents)
1842 "Interpret EXPORT-BLOCK element as Org syntax.
1843 CONTENTS is nil."
1844 (let ((type (org-element-property :type export-block)))
1845 (concat (format "#+BEGIN_%s\n" type)
1846 (org-element-property :value export-block)
1847 (format "#+END_%s" type))))
1850 ;;;; Fixed-width
1852 (defun org-element-fixed-width-parser (limit affiliated)
1853 "Parse a fixed-width section.
1855 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1856 the buffer position at the beginning of the first affiliated
1857 keyword and CDR is a plist of affiliated keywords along with
1858 their value.
1860 Return a list whose CAR is `fixed-width' and CDR is a plist
1861 containing `:begin', `:end', `:value', `:post-blank' and
1862 `:post-affiliated' keywords.
1864 Assume point is at the beginning of the fixed-width area."
1865 (save-excursion
1866 (let* ((begin (car affiliated))
1867 (post-affiliated (point))
1868 value
1869 (end-area
1870 (progn
1871 (while (and (< (point) limit)
1872 (looking-at "[ \t]*:\\( \\|$\\)"))
1873 ;; Accumulate text without starting colons.
1874 (setq value
1875 (concat value
1876 (buffer-substring-no-properties
1877 (match-end 0) (point-at-eol))
1878 "\n"))
1879 (forward-line))
1880 (point)))
1881 (end (progn (skip-chars-forward " \r\t\n" limit)
1882 (if (eobp) (point) (line-beginning-position)))))
1883 (list 'fixed-width
1884 (nconc
1885 (list :begin begin
1886 :end end
1887 :value value
1888 :post-blank (count-lines end-area end)
1889 :post-affiliated post-affiliated)
1890 (cdr affiliated))))))
1892 (defun org-element-fixed-width-interpreter (fixed-width contents)
1893 "Interpret FIXED-WIDTH element as Org syntax.
1894 CONTENTS is nil."
1895 (let ((value (org-element-property :value fixed-width)))
1896 (and value
1897 (replace-regexp-in-string
1898 "^" ": "
1899 (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
1902 ;;;; Horizontal Rule
1904 (defun org-element-horizontal-rule-parser (limit affiliated)
1905 "Parse an horizontal rule.
1907 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1908 the buffer position at the beginning of the first affiliated
1909 keyword and CDR is a plist of affiliated keywords along with
1910 their value.
1912 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1913 containing `:begin', `:end', `:post-blank' and `:post-affiliated'
1914 keywords."
1915 (save-excursion
1916 (let ((begin (car affiliated))
1917 (post-affiliated (point))
1918 (post-hr (progn (forward-line) (point)))
1919 (end (progn (skip-chars-forward " \r\t\n" limit)
1920 (if (eobp) (point) (line-beginning-position)))))
1921 (list 'horizontal-rule
1922 (nconc
1923 (list :begin begin
1924 :end end
1925 :post-blank (count-lines post-hr end)
1926 :post-affiliated post-affiliated)
1927 (cdr affiliated))))))
1929 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1930 "Interpret HORIZONTAL-RULE element as Org syntax.
1931 CONTENTS is nil."
1932 "-----")
1935 ;;;; Keyword
1937 (defun org-element-keyword-parser (limit affiliated)
1938 "Parse a keyword at point.
1940 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1941 the buffer position at the beginning of the first affiliated
1942 keyword and CDR is a plist of affiliated keywords along with
1943 their value.
1945 Return a list whose CAR is `keyword' and CDR is a plist
1946 containing `:key', `:value', `:begin', `:end', `:post-blank' and
1947 `:post-affiliated' keywords."
1948 (save-excursion
1949 (let ((begin (car affiliated))
1950 (post-affiliated (point))
1951 (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
1952 (upcase (org-match-string-no-properties 1))))
1953 (value (org-trim (buffer-substring-no-properties
1954 (match-end 0) (point-at-eol))))
1955 (pos-before-blank (progn (forward-line) (point)))
1956 (end (progn (skip-chars-forward " \r\t\n" limit)
1957 (if (eobp) (point) (line-beginning-position)))))
1958 (list 'keyword
1959 (nconc
1960 (list :key key
1961 :value value
1962 :begin begin
1963 :end end
1964 :post-blank (count-lines pos-before-blank end)
1965 :post-affiliated post-affiliated)
1966 (cdr affiliated))))))
1968 (defun org-element-keyword-interpreter (keyword contents)
1969 "Interpret KEYWORD element as Org syntax.
1970 CONTENTS is nil."
1971 (format "#+%s: %s"
1972 (org-element-property :key keyword)
1973 (org-element-property :value keyword)))
1976 ;;;; Latex Environment
1978 (defun org-element-latex-environment-parser (limit affiliated)
1979 "Parse a LaTeX environment.
1981 LIMIT bounds the search. AFFILIATED is a list of which CAR is
1982 the buffer position at the beginning of the first affiliated
1983 keyword and CDR is a plist of affiliated keywords along with
1984 their value.
1986 Return a list whose CAR is `latex-environment' and CDR is a plist
1987 containing `:begin', `:end', `:value', `:post-blank' and
1988 `:post-affiliated' keywords.
1990 Assume point is at the beginning of the latex environment."
1991 (save-excursion
1992 (let ((case-fold-search t)
1993 (code-begin (point)))
1994 (looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
1995 (if (not (re-search-forward (format "^[ \t]*\\\\end{%s}[ \t]*$"
1996 (regexp-quote (match-string 1)))
1997 limit t))
1998 ;; Incomplete latex environment: parse it as a paragraph.
1999 (org-element-paragraph-parser limit affiliated)
2000 (let* ((code-end (progn (forward-line) (point)))
2001 (begin (car affiliated))
2002 (value (buffer-substring-no-properties code-begin code-end))
2003 (end (progn (skip-chars-forward " \r\t\n" limit)
2004 (if (eobp) (point) (line-beginning-position)))))
2005 (list 'latex-environment
2006 (nconc
2007 (list :begin begin
2008 :end end
2009 :value value
2010 :post-blank (count-lines code-end end)
2011 :post-affiliated code-begin)
2012 (cdr affiliated))))))))
2014 (defun org-element-latex-environment-interpreter (latex-environment contents)
2015 "Interpret LATEX-ENVIRONMENT element as Org syntax.
2016 CONTENTS is nil."
2017 (org-element-property :value latex-environment))
2020 ;;;; Node Property
2022 (defun org-element-node-property-parser (limit)
2023 "Parse a node-property at point.
2025 LIMIT bounds the search.
2027 Return a list whose CAR is `node-property' and CDR is a plist
2028 containing `:key', `:value', `:begin', `:end' and `:post-blank'
2029 keywords."
2030 (save-excursion
2031 (looking-at org-property-re)
2032 (let ((case-fold-search t)
2033 (begin (point))
2034 (key (org-match-string-no-properties 2))
2035 (value (org-match-string-no-properties 3))
2036 (pos-before-blank (progn (forward-line) (point)))
2037 (end (progn (skip-chars-forward " \r\t\n" limit)
2038 (if (eobp) (point) (point-at-bol)))))
2039 (list 'node-property
2040 (list :key key
2041 :value value
2042 :begin begin
2043 :end end
2044 :post-blank (count-lines pos-before-blank end))))))
2046 (defun org-element-node-property-interpreter (node-property contents)
2047 "Interpret NODE-PROPERTY element as Org syntax.
2048 CONTENTS is nil."
2049 (format org-property-format
2050 (format ":%s:" (org-element-property :key node-property))
2051 (org-element-property :value node-property)))
2054 ;;;; Paragraph
2056 (defun org-element-paragraph-parser (limit affiliated)
2057 "Parse a paragraph.
2059 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2060 the buffer position at the beginning of the first affiliated
2061 keyword and CDR is a plist of affiliated keywords along with
2062 their value.
2064 Return a list whose CAR is `paragraph' and CDR is a plist
2065 containing `:begin', `:end', `:contents-begin' and
2066 `:contents-end', `:post-blank' and `:post-affiliated' keywords.
2068 Assume point is at the beginning of the paragraph."
2069 (save-excursion
2070 (let* ((begin (car affiliated))
2071 (contents-begin (point))
2072 (before-blank
2073 (let ((case-fold-search t))
2074 (end-of-line)
2075 (if (not (re-search-forward
2076 org-element-paragraph-separate limit 'm))
2077 limit
2078 ;; A matching `org-element-paragraph-separate' is not
2079 ;; necessarily the end of the paragraph. In
2080 ;; particular, lines starting with # or : as a first
2081 ;; non-space character are ambiguous. We have check
2082 ;; if they are valid Org syntax (i.e. not an
2083 ;; incomplete keyword).
2084 (beginning-of-line)
2085 (while (not
2087 ;; There's no ambiguity for other symbols or
2088 ;; empty lines: stop here.
2089 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
2090 ;; Stop at valid fixed-width areas.
2091 (looking-at "[ \t]*:\\(?: \\|$\\)")
2092 ;; Stop at drawers.
2093 (and (looking-at org-drawer-regexp)
2094 (save-excursion
2095 (re-search-forward
2096 "^[ \t]*:END:[ \t]*$" limit t)))
2097 ;; Stop at valid comments.
2098 (looking-at "[ \t]*#\\(?: \\|$\\)")
2099 ;; Stop at valid dynamic blocks.
2100 (and (looking-at org-dblock-start-re)
2101 (save-excursion
2102 (re-search-forward
2103 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
2104 ;; Stop at valid blocks.
2105 (and (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
2106 (save-excursion
2107 (re-search-forward
2108 (format "^[ \t]*#\\+END_%s[ \t]*$"
2109 (regexp-quote
2110 (org-match-string-no-properties 1)))
2111 limit t)))
2112 ;; Stop at valid latex environments.
2113 (and (looking-at
2114 "[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
2115 (save-excursion
2116 (re-search-forward
2117 (format "^[ \t]*\\\\end{%s}[ \t]*$"
2118 (regexp-quote
2119 (org-match-string-no-properties 1)))
2120 limit t)))
2121 ;; Stop at valid keywords.
2122 (looking-at "[ \t]*#\\+\\S-+:")
2123 ;; Skip everything else.
2124 (not
2125 (progn
2126 (end-of-line)
2127 (re-search-forward org-element-paragraph-separate
2128 limit 'm)))))
2129 (beginning-of-line)))
2130 (if (= (point) limit) limit
2131 (goto-char (line-beginning-position)))))
2132 (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
2133 (forward-line)
2134 (point)))
2135 (end (progn (skip-chars-forward " \r\t\n" limit)
2136 (if (eobp) (point) (line-beginning-position)))))
2137 (list 'paragraph
2138 (nconc
2139 (list :begin begin
2140 :end end
2141 :contents-begin contents-begin
2142 :contents-end contents-end
2143 :post-blank (count-lines before-blank end)
2144 :post-affiliated contents-begin)
2145 (cdr affiliated))))))
2147 (defun org-element-paragraph-interpreter (paragraph contents)
2148 "Interpret PARAGRAPH element as Org syntax.
2149 CONTENTS is the contents of the element."
2150 contents)
2153 ;;;; Planning
2155 (defun org-element-planning-parser (limit)
2156 "Parse a planning.
2158 LIMIT bounds the search.
2160 Return a list whose CAR is `planning' and CDR is a plist
2161 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
2162 and `:post-blank' keywords."
2163 (save-excursion
2164 (let* ((case-fold-search nil)
2165 (begin (point))
2166 (post-blank (let ((before-blank (progn (forward-line) (point))))
2167 (skip-chars-forward " \r\t\n" limit)
2168 (skip-chars-backward " \t")
2169 (unless (bolp) (end-of-line))
2170 (count-lines before-blank (point))))
2171 (end (point))
2172 closed deadline scheduled)
2173 (goto-char begin)
2174 (while (re-search-forward org-keyword-time-not-clock-regexp end t)
2175 (goto-char (match-end 1))
2176 (skip-chars-forward " \t" end)
2177 (let ((keyword (match-string 1))
2178 (time (org-element-timestamp-parser)))
2179 (cond ((equal keyword org-closed-string) (setq closed time))
2180 ((equal keyword org-deadline-string) (setq deadline time))
2181 (t (setq scheduled time)))))
2182 (list 'planning
2183 (list :closed closed
2184 :deadline deadline
2185 :scheduled scheduled
2186 :begin begin
2187 :end end
2188 :post-blank post-blank)))))
2190 (defun org-element-planning-interpreter (planning contents)
2191 "Interpret PLANNING element as Org syntax.
2192 CONTENTS is nil."
2193 (mapconcat
2194 'identity
2195 (delq nil
2196 (list (let ((deadline (org-element-property :deadline planning)))
2197 (when deadline
2198 (concat org-deadline-string " "
2199 (org-element-timestamp-interpreter deadline nil))))
2200 (let ((scheduled (org-element-property :scheduled planning)))
2201 (when scheduled
2202 (concat org-scheduled-string " "
2203 (org-element-timestamp-interpreter scheduled nil))))
2204 (let ((closed (org-element-property :closed planning)))
2205 (when closed
2206 (concat org-closed-string " "
2207 (org-element-timestamp-interpreter closed nil))))))
2208 " "))
2211 ;;;; Quote Section
2213 (defun org-element-quote-section-parser (limit)
2214 "Parse a quote section.
2216 LIMIT bounds the search.
2218 Return a list whose CAR is `quote-section' and CDR is a plist
2219 containing `:begin', `:end', `:value' and `:post-blank' keywords.
2221 Assume point is at beginning of the section."
2222 (save-excursion
2223 (let* ((begin (point))
2224 (end (progn (org-with-limited-levels (outline-next-heading))
2225 (point)))
2226 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
2227 (forward-line)
2228 (point)))
2229 (value (buffer-substring-no-properties begin pos-before-blank)))
2230 (list 'quote-section
2231 (list :begin begin
2232 :end end
2233 :value value
2234 :post-blank (count-lines pos-before-blank end))))))
2236 (defun org-element-quote-section-interpreter (quote-section contents)
2237 "Interpret QUOTE-SECTION element as Org syntax.
2238 CONTENTS is nil."
2239 (org-element-property :value quote-section))
2242 ;;;; Src Block
2244 (defun org-element-src-block-parser (limit affiliated)
2245 "Parse a src block.
2247 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2248 the buffer position at the beginning of the first affiliated
2249 keyword and CDR is a plist of affiliated keywords along with
2250 their value.
2252 Return a list whose CAR is `src-block' and CDR is a plist
2253 containing `:language', `:switches', `:parameters', `:begin',
2254 `:end', `:number-lines', `:retain-labels', `:use-labels',
2255 `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
2256 `:post-affiliated' keywords.
2258 Assume point is at the beginning of the block."
2259 (let ((case-fold-search t))
2260 (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
2261 limit t)))
2262 ;; Incomplete block: parse it as a paragraph.
2263 (org-element-paragraph-parser limit affiliated)
2264 (let ((contents-end (match-beginning 0)))
2265 (save-excursion
2266 (let* ((begin (car affiliated))
2267 (post-affiliated (point))
2268 ;; Get language as a string.
2269 (language
2270 (progn
2271 (looking-at
2272 (concat "^[ \t]*#\\+BEGIN_SRC"
2273 "\\(?: +\\(\\S-+\\)\\)?"
2274 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
2275 "\\(.*\\)[ \t]*$"))
2276 (org-match-string-no-properties 1)))
2277 ;; Get switches.
2278 (switches (org-match-string-no-properties 2))
2279 ;; Get parameters.
2280 (parameters (org-match-string-no-properties 3))
2281 ;; Switches analysis
2282 (number-lines
2283 (cond ((not switches) nil)
2284 ((string-match "-n\\>" switches) 'new)
2285 ((string-match "+n\\>" switches) 'continued)))
2286 (preserve-indent (and switches
2287 (string-match "-i\\>" switches)))
2288 (label-fmt
2289 (and switches
2290 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2291 (match-string 1 switches)))
2292 ;; Should labels be retained in (or stripped from)
2293 ;; src blocks?
2294 (retain-labels
2295 (or (not switches)
2296 (not (string-match "-r\\>" switches))
2297 (and number-lines (string-match "-k\\>" switches))))
2298 ;; What should code-references use - labels or
2299 ;; line-numbers?
2300 (use-labels
2301 (or (not switches)
2302 (and retain-labels
2303 (not (string-match "-k\\>" switches)))))
2304 ;; Indentation.
2305 (block-ind (progn (skip-chars-forward " \t") (current-column)))
2306 ;; Retrieve code.
2307 (value (org-element-remove-indentation
2308 (org-unescape-code-in-string
2309 (buffer-substring-no-properties
2310 (progn (forward-line) (point)) contents-end))
2311 block-ind))
2312 (pos-before-blank (progn (goto-char contents-end)
2313 (forward-line)
2314 (point)))
2315 ;; Get position after ending blank lines.
2316 (end (progn (skip-chars-forward " \r\t\n" limit)
2317 (if (eobp) (point) (line-beginning-position)))))
2318 (list 'src-block
2319 (nconc
2320 (list :language language
2321 :switches (and (org-string-nw-p switches)
2322 (org-trim switches))
2323 :parameters (and (org-string-nw-p parameters)
2324 (org-trim parameters))
2325 :begin begin
2326 :end end
2327 :number-lines number-lines
2328 :preserve-indent preserve-indent
2329 :retain-labels retain-labels
2330 :use-labels use-labels
2331 :label-fmt label-fmt
2332 :value value
2333 :post-blank (count-lines pos-before-blank end)
2334 :post-affiliated post-affiliated)
2335 (cdr affiliated)))))))))
2337 (defun org-element-src-block-interpreter (src-block contents)
2338 "Interpret SRC-BLOCK element as Org syntax.
2339 CONTENTS is nil."
2340 (let ((lang (org-element-property :language src-block))
2341 (switches (org-element-property :switches src-block))
2342 (params (org-element-property :parameters src-block))
2343 (value
2344 (let ((val (org-element-property :value src-block)))
2345 (cond
2346 ((or org-src-preserve-indentation
2347 (org-element-property :preserve-indent src-block))
2348 val)
2349 ((zerop org-edit-src-content-indentation) val)
2351 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
2352 (replace-regexp-in-string
2353 "\\(^\\)[ \t]*\\S-" ind val nil nil 1)))))))
2354 (concat (format "#+BEGIN_SRC%s\n"
2355 (concat (and lang (concat " " lang))
2356 (and switches (concat " " switches))
2357 (and params (concat " " params))))
2358 (org-escape-code-in-string value)
2359 "#+END_SRC")))
2362 ;;;; Table
2364 (defun org-element-table-parser (limit affiliated)
2365 "Parse a table at point.
2367 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2368 the buffer position at the beginning of the first affiliated
2369 keyword and CDR is a plist of affiliated keywords along with
2370 their value.
2372 Return a list whose CAR is `table' and CDR is a plist containing
2373 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
2374 `:contents-end', `:value', `:post-blank' and `:post-affiliated'
2375 keywords.
2377 Assume point is at the beginning of the table."
2378 (save-excursion
2379 (let* ((case-fold-search t)
2380 (table-begin (point))
2381 (type (if (org-at-table.el-p) 'table.el 'org))
2382 (begin (car affiliated))
2383 (table-end
2384 (if (re-search-forward org-table-any-border-regexp limit 'm)
2385 (goto-char (match-beginning 0))
2386 (point)))
2387 (tblfm (let (acc)
2388 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
2389 (push (org-match-string-no-properties 1) acc)
2390 (forward-line))
2391 acc))
2392 (pos-before-blank (point))
2393 (end (progn (skip-chars-forward " \r\t\n" limit)
2394 (if (eobp) (point) (line-beginning-position)))))
2395 (list 'table
2396 (nconc
2397 (list :begin begin
2398 :end end
2399 :type type
2400 :tblfm tblfm
2401 ;; Only `org' tables have contents. `table.el' tables
2402 ;; use a `:value' property to store raw table as
2403 ;; a string.
2404 :contents-begin (and (eq type 'org) table-begin)
2405 :contents-end (and (eq type 'org) table-end)
2406 :value (and (eq type 'table.el)
2407 (buffer-substring-no-properties
2408 table-begin table-end))
2409 :post-blank (count-lines pos-before-blank end)
2410 :post-affiliated table-begin)
2411 (cdr affiliated))))))
2413 (defun org-element-table-interpreter (table contents)
2414 "Interpret TABLE element as Org syntax.
2415 CONTENTS is nil."
2416 (if (eq (org-element-property :type table) 'table.el)
2417 (org-remove-indentation (org-element-property :value table))
2418 (concat (with-temp-buffer (insert contents)
2419 (org-table-align)
2420 (buffer-string))
2421 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
2422 (reverse (org-element-property :tblfm table))
2423 "\n"))))
2426 ;;;; Table Row
2428 (defun org-element-table-row-parser (limit)
2429 "Parse table row at point.
2431 LIMIT bounds the search.
2433 Return a list whose CAR is `table-row' and CDR is a plist
2434 containing `:begin', `:end', `:contents-begin', `:contents-end',
2435 `:type' and `:post-blank' keywords."
2436 (save-excursion
2437 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
2438 (begin (point))
2439 ;; A table rule has no contents. In that case, ensure
2440 ;; CONTENTS-BEGIN matches CONTENTS-END.
2441 (contents-begin (and (eq type 'standard)
2442 (search-forward "|")
2443 (point)))
2444 (contents-end (and (eq type 'standard)
2445 (progn
2446 (end-of-line)
2447 (skip-chars-backward " \t")
2448 (point))))
2449 (end (progn (forward-line) (point))))
2450 (list 'table-row
2451 (list :type type
2452 :begin begin
2453 :end end
2454 :contents-begin contents-begin
2455 :contents-end contents-end
2456 :post-blank 0)))))
2458 (defun org-element-table-row-interpreter (table-row contents)
2459 "Interpret TABLE-ROW element as Org syntax.
2460 CONTENTS is the contents of the table row."
2461 (if (eq (org-element-property :type table-row) 'rule) "|-"
2462 (concat "| " contents)))
2465 ;;;; Verse Block
2467 (defun org-element-verse-block-parser (limit affiliated)
2468 "Parse a verse block.
2470 LIMIT bounds the search. AFFILIATED is a list of which CAR is
2471 the buffer position at the beginning of the first affiliated
2472 keyword and CDR is a plist of affiliated keywords along with
2473 their value.
2475 Return a list whose CAR is `verse-block' and CDR is a plist
2476 containing `:begin', `:end', `:contents-begin', `:contents-end',
2477 `:post-blank' and `:post-affiliated' keywords.
2479 Assume point is at beginning of the block."
2480 (let ((case-fold-search t))
2481 (if (not (save-excursion
2482 (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
2483 ;; Incomplete block: parse it as a paragraph.
2484 (org-element-paragraph-parser limit affiliated)
2485 (let ((contents-end (match-beginning 0)))
2486 (save-excursion
2487 (let* ((begin (car affiliated))
2488 (post-affiliated (point))
2489 (contents-begin (progn (forward-line) (point)))
2490 (pos-before-blank (progn (goto-char contents-end)
2491 (forward-line)
2492 (point)))
2493 (end (progn (skip-chars-forward " \r\t\n" limit)
2494 (if (eobp) (point) (line-beginning-position)))))
2495 (list 'verse-block
2496 (nconc
2497 (list :begin begin
2498 :end end
2499 :contents-begin contents-begin
2500 :contents-end contents-end
2501 :post-blank (count-lines pos-before-blank end)
2502 :post-affiliated post-affiliated)
2503 (cdr affiliated)))))))))
2505 (defun org-element-verse-block-interpreter (verse-block contents)
2506 "Interpret VERSE-BLOCK element as Org syntax.
2507 CONTENTS is verse block contents."
2508 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
2512 ;;; Objects
2514 ;; Unlike to elements, interstices can be found between objects.
2515 ;; That's why, along with the parser, successor functions are provided
2516 ;; for each object. Some objects share the same successor (i.e. `code'
2517 ;; and `verbatim' objects).
2519 ;; A successor must accept a single argument bounding the search. It
2520 ;; will return either a cons cell whose CAR is the object's type, as
2521 ;; a symbol, and CDR the position of its next occurrence, or nil.
2523 ;; Successors follow the naming convention:
2524 ;; org-element-NAME-successor, where NAME is the name of the
2525 ;; successor, as defined in `org-element-all-successors'.
2527 ;; Some object types (i.e. `italic') are recursive. Restrictions on
2528 ;; object types they can contain will be specified in
2529 ;; `org-element-object-restrictions'.
2531 ;; Adding a new type of object is simple. Implement a successor,
2532 ;; a parser, and an interpreter for it, all following the naming
2533 ;; convention. Register type in `org-element-all-objects' and
2534 ;; successor in `org-element-all-successors'. Maybe tweak
2535 ;; restrictions about it, and that's it.
2538 ;;;; Bold
2540 (defun org-element-bold-parser ()
2541 "Parse bold object at point.
2543 Return a list whose CAR is `bold' and CDR is a plist with
2544 `:begin', `:end', `:contents-begin' and `:contents-end' and
2545 `:post-blank' keywords.
2547 Assume point is at the first star marker."
2548 (save-excursion
2549 (unless (bolp) (backward-char 1))
2550 (looking-at org-emph-re)
2551 (let ((begin (match-beginning 2))
2552 (contents-begin (match-beginning 4))
2553 (contents-end (match-end 4))
2554 (post-blank (progn (goto-char (match-end 2))
2555 (skip-chars-forward " \t")))
2556 (end (point)))
2557 (list 'bold
2558 (list :begin begin
2559 :end end
2560 :contents-begin contents-begin
2561 :contents-end contents-end
2562 :post-blank post-blank)))))
2564 (defun org-element-bold-interpreter (bold contents)
2565 "Interpret BOLD object as Org syntax.
2566 CONTENTS is the contents of the object."
2567 (format "*%s*" contents))
2569 (defun org-element-text-markup-successor ()
2570 "Search for the next text-markup object.
2572 Return value is a cons cell whose CAR is a symbol among `bold',
2573 `italic', `underline', `strike-through', `code' and `verbatim'
2574 and CDR is beginning position."
2575 (save-excursion
2576 (unless (bolp) (backward-char))
2577 (when (re-search-forward org-emph-re nil t)
2578 (let ((marker (match-string 3)))
2579 (cons (cond
2580 ((equal marker "*") 'bold)
2581 ((equal marker "/") 'italic)
2582 ((equal marker "_") 'underline)
2583 ((equal marker "+") 'strike-through)
2584 ((equal marker "~") 'code)
2585 ((equal marker "=") 'verbatim)
2586 (t (error "Unknown marker at %d" (match-beginning 3))))
2587 (match-beginning 2))))))
2590 ;;;; Code
2592 (defun org-element-code-parser ()
2593 "Parse code object at point.
2595 Return a list whose CAR is `code' and CDR is a plist with
2596 `:value', `:begin', `:end' and `:post-blank' keywords.
2598 Assume point is at the first tilde marker."
2599 (save-excursion
2600 (unless (bolp) (backward-char 1))
2601 (looking-at org-emph-re)
2602 (let ((begin (match-beginning 2))
2603 (value (org-match-string-no-properties 4))
2604 (post-blank (progn (goto-char (match-end 2))
2605 (skip-chars-forward " \t")))
2606 (end (point)))
2607 (list 'code
2608 (list :value value
2609 :begin begin
2610 :end end
2611 :post-blank post-blank)))))
2613 (defun org-element-code-interpreter (code contents)
2614 "Interpret CODE object as Org syntax.
2615 CONTENTS is nil."
2616 (format "~%s~" (org-element-property :value code)))
2619 ;;;; Entity
2621 (defun org-element-entity-parser ()
2622 "Parse entity at point.
2624 Return a list whose CAR is `entity' and CDR a plist with
2625 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
2626 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
2627 keywords.
2629 Assume point is at the beginning of the entity."
2630 (save-excursion
2631 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
2632 (let* ((value (org-entity-get (match-string 1)))
2633 (begin (match-beginning 0))
2634 (bracketsp (string= (match-string 2) "{}"))
2635 (post-blank (progn (goto-char (match-end 1))
2636 (when bracketsp (forward-char 2))
2637 (skip-chars-forward " \t")))
2638 (end (point)))
2639 (list 'entity
2640 (list :name (car value)
2641 :latex (nth 1 value)
2642 :latex-math-p (nth 2 value)
2643 :html (nth 3 value)
2644 :ascii (nth 4 value)
2645 :latin1 (nth 5 value)
2646 :utf-8 (nth 6 value)
2647 :begin begin
2648 :end end
2649 :use-brackets-p bracketsp
2650 :post-blank post-blank)))))
2652 (defun org-element-entity-interpreter (entity contents)
2653 "Interpret ENTITY object as Org syntax.
2654 CONTENTS is nil."
2655 (concat "\\"
2656 (org-element-property :name entity)
2657 (when (org-element-property :use-brackets-p entity) "{}")))
2659 (defun org-element-latex-or-entity-successor ()
2660 "Search for the next latex-fragment or entity object.
2662 Return value is a cons cell whose CAR is `entity' or
2663 `latex-fragment' and CDR is beginning position."
2664 (save-excursion
2665 (unless (bolp) (backward-char))
2666 (let ((matchers (cdr org-latex-regexps))
2667 ;; ENTITY-RE matches both LaTeX commands and Org entities.
2668 (entity-re
2669 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
2670 (when (re-search-forward
2671 (concat (mapconcat #'cadr matchers "\\|") "\\|" entity-re) nil t)
2672 (goto-char (match-beginning 0))
2673 (if (looking-at entity-re)
2674 ;; Determine if it's a real entity or a LaTeX command.
2675 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
2676 (match-beginning 0))
2677 ;; No entity nor command: point is at a LaTeX fragment.
2678 ;; Determine its type to get the correct beginning position.
2679 (cons 'latex-fragment
2680 (catch 'return
2681 (dolist (e matchers)
2682 (when (looking-at (nth 1 e))
2683 (throw 'return (match-beginning (nth 2 e)))))
2684 (point))))))))
2687 ;;;; Export Snippet
2689 (defun org-element-export-snippet-parser ()
2690 "Parse export snippet at point.
2692 Return a list whose CAR is `export-snippet' and CDR a plist with
2693 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
2694 keywords.
2696 Assume point is at the beginning of the snippet."
2697 (save-excursion
2698 (re-search-forward "@@\\([-A-Za-z0-9]+\\):" nil t)
2699 (let* ((begin (match-beginning 0))
2700 (back-end (org-match-string-no-properties 1))
2701 (value (buffer-substring-no-properties
2702 (point)
2703 (progn (re-search-forward "@@" nil t) (match-beginning 0))))
2704 (post-blank (skip-chars-forward " \t"))
2705 (end (point)))
2706 (list 'export-snippet
2707 (list :back-end back-end
2708 :value value
2709 :begin begin
2710 :end end
2711 :post-blank post-blank)))))
2713 (defun org-element-export-snippet-interpreter (export-snippet contents)
2714 "Interpret EXPORT-SNIPPET object as Org syntax.
2715 CONTENTS is nil."
2716 (format "@@%s:%s@@"
2717 (org-element-property :back-end export-snippet)
2718 (org-element-property :value export-snippet)))
2720 (defun org-element-export-snippet-successor ()
2721 "Search for the next export-snippet object.
2723 Return value is a cons cell whose CAR is `export-snippet' and CDR
2724 its beginning position."
2725 (save-excursion
2726 (let (beg)
2727 (when (and (re-search-forward "@@[-A-Za-z0-9]+:" nil t)
2728 (setq beg (match-beginning 0))
2729 (search-forward "@@" nil t))
2730 (cons 'export-snippet beg)))))
2733 ;;;; Footnote Reference
2735 (defun org-element-footnote-reference-parser ()
2736 "Parse footnote reference at point.
2738 Return a list whose CAR is `footnote-reference' and CDR a plist
2739 with `:label', `:type', `:inline-definition', `:begin', `:end'
2740 and `:post-blank' as keywords."
2741 (save-excursion
2742 (looking-at org-footnote-re)
2743 (let* ((begin (point))
2744 (label (or (org-match-string-no-properties 2)
2745 (org-match-string-no-properties 3)
2746 (and (match-string 1)
2747 (concat "fn:" (org-match-string-no-properties 1)))))
2748 (type (if (or (not label) (match-string 1)) 'inline 'standard))
2749 (inner-begin (match-end 0))
2750 (inner-end
2751 (let ((count 1))
2752 (forward-char)
2753 (while (and (> count 0) (re-search-forward "[][]" nil t))
2754 (if (equal (match-string 0) "[") (incf count) (decf count)))
2755 (1- (point))))
2756 (post-blank (progn (goto-char (1+ inner-end))
2757 (skip-chars-forward " \t")))
2758 (end (point))
2759 (footnote-reference
2760 (list 'footnote-reference
2761 (list :label label
2762 :type type
2763 :begin begin
2764 :end end
2765 :post-blank post-blank))))
2766 (org-element-put-property
2767 footnote-reference :inline-definition
2768 (and (eq type 'inline)
2769 (org-element-parse-secondary-string
2770 (buffer-substring inner-begin inner-end)
2771 (org-element-restriction 'footnote-reference)
2772 footnote-reference))))))
2774 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
2775 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
2776 CONTENTS is nil."
2777 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
2778 (def
2779 (let ((inline-def
2780 (org-element-property :inline-definition footnote-reference)))
2781 (if (not inline-def) ""
2782 (concat ":" (org-element-interpret-data inline-def))))))
2783 (format "[%s]" (concat label def))))
2785 (defun org-element-footnote-reference-successor ()
2786 "Search for the next footnote-reference object.
2788 Return value is a cons cell whose CAR is `footnote-reference' and
2789 CDR is beginning position."
2790 (save-excursion
2791 (catch 'exit
2792 (while (re-search-forward org-footnote-re nil t)
2793 (save-excursion
2794 (let ((beg (match-beginning 0))
2795 (count 1))
2796 (backward-char)
2797 (while (re-search-forward "[][]" nil t)
2798 (if (equal (match-string 0) "[") (incf count) (decf count))
2799 (when (zerop count)
2800 (throw 'exit (cons 'footnote-reference beg))))))))))
2803 ;;;; Inline Babel Call
2805 (defun org-element-inline-babel-call-parser ()
2806 "Parse inline babel call at point.
2808 Return a list whose CAR is `inline-babel-call' and CDR a plist
2809 with `:begin', `:end', `:value' and `:post-blank' as keywords.
2811 Assume point is at the beginning of the babel call."
2812 (save-excursion
2813 (unless (bolp) (backward-char))
2814 (let ((case-fold-search t))
2815 (looking-at org-babel-inline-lob-one-liner-regexp))
2816 (let ((begin (match-end 1))
2817 (value (buffer-substring-no-properties (match-end 1) (match-end 0)))
2818 (post-blank (progn (goto-char (match-end 0))
2819 (skip-chars-forward " \t")))
2820 (end (point)))
2821 (list 'inline-babel-call
2822 (list :begin begin
2823 :end end
2824 :value value
2825 :post-blank post-blank)))))
2827 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2828 "Interpret INLINE-BABEL-CALL object as Org syntax.
2829 CONTENTS is nil."
2830 (org-element-property :value inline-babel-call))
2832 (defun org-element-inline-babel-call-successor ()
2833 "Search for the next inline-babel-call object.
2835 Return value is a cons cell whose CAR is `inline-babel-call' and
2836 CDR is beginning position."
2837 (save-excursion
2838 ;; Use a simplified version of
2839 ;; `org-babel-inline-lob-one-liner-regexp'.
2840 (when (re-search-forward
2841 "call_\\([^()\n]+?\\)\\(?:\\[.*?\\]\\)?([^\n]*?)\\(\\[.*?\\]\\)?"
2842 nil t)
2843 (cons 'inline-babel-call (match-beginning 0)))))
2846 ;;;; Inline Src Block
2848 (defun org-element-inline-src-block-parser ()
2849 "Parse inline source block at point.
2851 Return a list whose CAR is `inline-src-block' and CDR a plist
2852 with `:begin', `:end', `:language', `:value', `:parameters' and
2853 `:post-blank' as keywords.
2855 Assume point is at the beginning of the inline src block."
2856 (save-excursion
2857 (unless (bolp) (backward-char))
2858 (looking-at org-babel-inline-src-block-regexp)
2859 (let ((begin (match-beginning 1))
2860 (language (org-match-string-no-properties 2))
2861 (parameters (org-match-string-no-properties 4))
2862 (value (org-match-string-no-properties 5))
2863 (post-blank (progn (goto-char (match-end 0))
2864 (skip-chars-forward " \t")))
2865 (end (point)))
2866 (list 'inline-src-block
2867 (list :language language
2868 :value value
2869 :parameters parameters
2870 :begin begin
2871 :end end
2872 :post-blank post-blank)))))
2874 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2875 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2876 CONTENTS is nil."
2877 (let ((language (org-element-property :language inline-src-block))
2878 (arguments (org-element-property :parameters inline-src-block))
2879 (body (org-element-property :value inline-src-block)))
2880 (format "src_%s%s{%s}"
2881 language
2882 (if arguments (format "[%s]" arguments) "")
2883 body)))
2885 (defun org-element-inline-src-block-successor ()
2886 "Search for the next inline-babel-call element.
2888 Return value is a cons cell whose CAR is `inline-babel-call' and
2889 CDR is beginning position."
2890 (save-excursion
2891 (unless (bolp) (backward-char))
2892 (when (re-search-forward org-babel-inline-src-block-regexp nil t)
2893 (cons 'inline-src-block (match-beginning 1)))))
2895 ;;;; Italic
2897 (defun org-element-italic-parser ()
2898 "Parse italic object at point.
2900 Return a list whose CAR is `italic' and CDR is a plist with
2901 `:begin', `:end', `:contents-begin' and `:contents-end' and
2902 `:post-blank' keywords.
2904 Assume point is at the first slash marker."
2905 (save-excursion
2906 (unless (bolp) (backward-char 1))
2907 (looking-at org-emph-re)
2908 (let ((begin (match-beginning 2))
2909 (contents-begin (match-beginning 4))
2910 (contents-end (match-end 4))
2911 (post-blank (progn (goto-char (match-end 2))
2912 (skip-chars-forward " \t")))
2913 (end (point)))
2914 (list 'italic
2915 (list :begin begin
2916 :end end
2917 :contents-begin contents-begin
2918 :contents-end contents-end
2919 :post-blank post-blank)))))
2921 (defun org-element-italic-interpreter (italic contents)
2922 "Interpret ITALIC object as Org syntax.
2923 CONTENTS is the contents of the object."
2924 (format "/%s/" contents))
2927 ;;;; Latex Fragment
2929 (defun org-element-latex-fragment-parser ()
2930 "Parse LaTeX fragment at point.
2932 Return a list whose CAR is `latex-fragment' and CDR a plist with
2933 `:value', `:begin', `:end', and `:post-blank' as keywords.
2935 Assume point is at the beginning of the LaTeX fragment."
2936 (save-excursion
2937 (let* ((begin (point))
2938 (substring-match
2939 (catch 'exit
2940 (dolist (e (cdr org-latex-regexps))
2941 (let ((latex-regexp (nth 1 e)))
2942 (when (or (looking-at latex-regexp)
2943 (and (not (bobp))
2944 (save-excursion
2945 (backward-char)
2946 (looking-at latex-regexp))))
2947 (throw 'exit (nth 2 e)))))
2948 ;; None found: it's a macro.
2949 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2951 (value (org-match-string-no-properties substring-match))
2952 (post-blank (progn (goto-char (match-end substring-match))
2953 (skip-chars-forward " \t")))
2954 (end (point)))
2955 (list 'latex-fragment
2956 (list :value value
2957 :begin begin
2958 :end end
2959 :post-blank post-blank)))))
2961 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2962 "Interpret LATEX-FRAGMENT object as Org syntax.
2963 CONTENTS is nil."
2964 (org-element-property :value latex-fragment))
2966 ;;;; Line Break
2968 (defun org-element-line-break-parser ()
2969 "Parse line break at point.
2971 Return a list whose CAR is `line-break', and CDR a plist with
2972 `:begin', `:end' and `:post-blank' keywords.
2974 Assume point is at the beginning of the line break."
2975 (list 'line-break
2976 (list :begin (point)
2977 :end (progn (forward-line) (point))
2978 :post-blank 0)))
2980 (defun org-element-line-break-interpreter (line-break contents)
2981 "Interpret LINE-BREAK object as Org syntax.
2982 CONTENTS is nil."
2983 "\\\\\n")
2985 (defun org-element-line-break-successor ()
2986 "Search for the next line-break object.
2988 Return value is a cons cell whose CAR is `line-break' and CDR is
2989 beginning position."
2990 (save-excursion
2991 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" nil t)
2992 (goto-char (match-beginning 1)))))
2993 ;; A line break can only happen on a non-empty line.
2994 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2995 (cons 'line-break beg)))))
2998 ;;;; Link
3000 (defun org-element-link-parser ()
3001 "Parse link at point.
3003 Return a list whose CAR is `link' and CDR a plist with `:type',
3004 `:path', `:raw-link', `:application', `:search-option', `:begin',
3005 `:end', `:contents-begin', `:contents-end' and `:post-blank' as
3006 keywords.
3008 Assume point is at the beginning of the link."
3009 (save-excursion
3010 (let ((begin (point))
3011 end contents-begin contents-end link-end post-blank path type
3012 raw-link link search-option application)
3013 (cond
3014 ;; Type 1: Text targeted from a radio target.
3015 ((and org-target-link-regexp (looking-at org-target-link-regexp))
3016 (setq type "radio"
3017 link-end (match-end 0)
3018 path (org-match-string-no-properties 0)))
3019 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
3020 ((looking-at org-bracket-link-regexp)
3021 (setq contents-begin (match-beginning 3)
3022 contents-end (match-end 3)
3023 link-end (match-end 0)
3024 ;; RAW-LINK is the original link. Expand any
3025 ;; abbreviation in it.
3026 raw-link (org-translate-link
3027 (org-link-expand-abbrev
3028 (org-match-string-no-properties 1))))
3029 ;; Determine TYPE of link and set PATH accordingly.
3030 (cond
3031 ;; File type.
3032 ((or (file-name-absolute-p raw-link)
3033 (string-match "^\\.\\.?/" raw-link))
3034 (setq type "file" path raw-link))
3035 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
3036 ((string-match org-link-re-with-space3 raw-link)
3037 (setq type (match-string 1 raw-link) path (match-string 2 raw-link)))
3038 ;; Id type: PATH is the id.
3039 ((string-match "^id:\\([-a-f0-9]+\\)" raw-link)
3040 (setq type "id" path (match-string 1 raw-link)))
3041 ;; Code-ref type: PATH is the name of the reference.
3042 ((string-match "^(\\(.*\\))$" raw-link)
3043 (setq type "coderef" path (match-string 1 raw-link)))
3044 ;; Custom-id type: PATH is the name of the custom id.
3045 ((= (aref raw-link 0) ?#)
3046 (setq type "custom-id" path (substring raw-link 1)))
3047 ;; Fuzzy type: Internal link either matches a target, an
3048 ;; headline name or nothing. PATH is the target or
3049 ;; headline's name.
3050 (t (setq type "fuzzy" path raw-link))))
3051 ;; Type 3: Plain link, i.e. http://orgmode.org
3052 ((looking-at org-plain-link-re)
3053 (setq raw-link (org-match-string-no-properties 0)
3054 type (org-match-string-no-properties 1)
3055 link-end (match-end 0)
3056 path (org-match-string-no-properties 2)))
3057 ;; Type 4: Angular link, i.e. <http://orgmode.org>
3058 ((looking-at org-angle-link-re)
3059 (setq raw-link (buffer-substring-no-properties
3060 (match-beginning 1) (match-end 2))
3061 type (org-match-string-no-properties 1)
3062 link-end (match-end 0)
3063 path (org-match-string-no-properties 2))))
3064 ;; In any case, deduce end point after trailing white space from
3065 ;; LINK-END variable.
3066 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
3067 end (point))
3068 ;; Extract search option and opening application out of
3069 ;; "file"-type links.
3070 (when (member type org-element-link-type-is-file)
3071 ;; Application.
3072 (cond ((string-match "^file\\+\\(.*\\)$" type)
3073 (setq application (match-string 1 type)))
3074 ((not (string-match "^file" type))
3075 (setq application type)))
3076 ;; Extract search option from PATH.
3077 (when (string-match "::\\(.*\\)$" path)
3078 (setq search-option (match-string 1 path)
3079 path (replace-match "" nil nil path)))
3080 ;; Make sure TYPE always reports "file".
3081 (setq type "file"))
3082 (list 'link
3083 (list :type type
3084 :path path
3085 :raw-link (or raw-link path)
3086 :application application
3087 :search-option search-option
3088 :begin begin
3089 :end end
3090 :contents-begin contents-begin
3091 :contents-end contents-end
3092 :post-blank post-blank)))))
3094 (defun org-element-link-interpreter (link contents)
3095 "Interpret LINK object as Org syntax.
3096 CONTENTS is the contents of the object, or nil."
3097 (let ((type (org-element-property :type link))
3098 (raw-link (org-element-property :raw-link link)))
3099 (if (string= type "radio") raw-link
3100 (format "[[%s]%s]"
3101 raw-link
3102 (if contents (format "[%s]" contents) "")))))
3104 (defun org-element-link-successor ()
3105 "Search for the next link object.
3107 Return value is a cons cell whose CAR is `link' and CDR is
3108 beginning position."
3109 (save-excursion
3110 (let ((link-regexp
3111 (if (not org-target-link-regexp) org-any-link-re
3112 (concat org-any-link-re "\\|" org-target-link-regexp))))
3113 (when (re-search-forward link-regexp nil t)
3114 (cons 'link (match-beginning 0))))))
3116 (defun org-element-plain-link-successor ()
3117 "Search for the next plain link object.
3119 Return value is a cons cell whose CAR is `link' and CDR is
3120 beginning position."
3121 (and (save-excursion (re-search-forward org-plain-link-re nil t))
3122 (cons 'link (match-beginning 0))))
3125 ;;;; Macro
3127 (defun org-element-macro-parser ()
3128 "Parse macro at point.
3130 Return a list whose CAR is `macro' and CDR a plist with `:key',
3131 `:args', `:begin', `:end', `:value' and `:post-blank' as
3132 keywords.
3134 Assume point is at the macro."
3135 (save-excursion
3136 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
3137 (let ((begin (point))
3138 (key (downcase (org-match-string-no-properties 1)))
3139 (value (org-match-string-no-properties 0))
3140 (post-blank (progn (goto-char (match-end 0))
3141 (skip-chars-forward " \t")))
3142 (end (point))
3143 (args (let ((args (org-match-string-no-properties 3)))
3144 (when args
3145 ;; Do not use `org-split-string' since empty
3146 ;; strings are meaningful here.
3147 (split-string
3148 (replace-regexp-in-string
3149 "\\(\\\\*\\)\\(,\\)"
3150 (lambda (str)
3151 (let ((len (length (match-string 1 str))))
3152 (concat (make-string (/ len 2) ?\\)
3153 (if (zerop (mod len 2)) "\000" ","))))
3154 args nil t)
3155 "\000")))))
3156 (list 'macro
3157 (list :key key
3158 :value value
3159 :args args
3160 :begin begin
3161 :end end
3162 :post-blank post-blank)))))
3164 (defun org-element-macro-interpreter (macro contents)
3165 "Interpret MACRO object as Org syntax.
3166 CONTENTS is nil."
3167 (org-element-property :value macro))
3169 (defun org-element-macro-successor ()
3170 "Search for the next macro object.
3172 Return value is cons cell whose CAR is `macro' and CDR is
3173 beginning position."
3174 (save-excursion
3175 (when (re-search-forward
3176 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
3177 nil t)
3178 (cons 'macro (match-beginning 0)))))
3181 ;;;; Radio-target
3183 (defun org-element-radio-target-parser ()
3184 "Parse radio target at point.
3186 Return a list whose CAR is `radio-target' and CDR a plist with
3187 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
3188 and `:post-blank' as keywords.
3190 Assume point is at the radio target."
3191 (save-excursion
3192 (looking-at org-radio-target-regexp)
3193 (let ((begin (point))
3194 (contents-begin (match-beginning 1))
3195 (contents-end (match-end 1))
3196 (value (org-match-string-no-properties 1))
3197 (post-blank (progn (goto-char (match-end 0))
3198 (skip-chars-forward " \t")))
3199 (end (point)))
3200 (list 'radio-target
3201 (list :begin begin
3202 :end end
3203 :contents-begin contents-begin
3204 :contents-end contents-end
3205 :post-blank post-blank
3206 :value value)))))
3208 (defun org-element-radio-target-interpreter (target contents)
3209 "Interpret TARGET object as Org syntax.
3210 CONTENTS is the contents of the object."
3211 (concat "<<<" contents ">>>"))
3213 (defun org-element-radio-target-successor ()
3214 "Search for the next radio-target object.
3216 Return value is a cons cell whose CAR is `radio-target' and CDR
3217 is beginning position."
3218 (save-excursion
3219 (when (re-search-forward org-radio-target-regexp nil t)
3220 (cons 'radio-target (match-beginning 0)))))
3223 ;;;; Statistics Cookie
3225 (defun org-element-statistics-cookie-parser ()
3226 "Parse statistics cookie at point.
3228 Return a list whose CAR is `statistics-cookie', and CDR a plist
3229 with `:begin', `:end', `:value' and `:post-blank' keywords.
3231 Assume point is at the beginning of the statistics-cookie."
3232 (save-excursion
3233 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
3234 (let* ((begin (point))
3235 (value (buffer-substring-no-properties
3236 (match-beginning 0) (match-end 0)))
3237 (post-blank (progn (goto-char (match-end 0))
3238 (skip-chars-forward " \t")))
3239 (end (point)))
3240 (list 'statistics-cookie
3241 (list :begin begin
3242 :end end
3243 :value value
3244 :post-blank post-blank)))))
3246 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
3247 "Interpret STATISTICS-COOKIE object as Org syntax.
3248 CONTENTS is nil."
3249 (org-element-property :value statistics-cookie))
3251 (defun org-element-statistics-cookie-successor ()
3252 "Search for the next statistics cookie object.
3254 Return value is a cons cell whose CAR is `statistics-cookie' and
3255 CDR is beginning position."
3256 (save-excursion
3257 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" nil t)
3258 (cons 'statistics-cookie (match-beginning 0)))))
3261 ;;;; Strike-Through
3263 (defun org-element-strike-through-parser ()
3264 "Parse strike-through object at point.
3266 Return a list whose CAR is `strike-through' and CDR is a plist
3267 with `:begin', `:end', `:contents-begin' and `:contents-end' and
3268 `:post-blank' keywords.
3270 Assume point is at the first plus sign marker."
3271 (save-excursion
3272 (unless (bolp) (backward-char 1))
3273 (looking-at org-emph-re)
3274 (let ((begin (match-beginning 2))
3275 (contents-begin (match-beginning 4))
3276 (contents-end (match-end 4))
3277 (post-blank (progn (goto-char (match-end 2))
3278 (skip-chars-forward " \t")))
3279 (end (point)))
3280 (list 'strike-through
3281 (list :begin begin
3282 :end end
3283 :contents-begin contents-begin
3284 :contents-end contents-end
3285 :post-blank post-blank)))))
3287 (defun org-element-strike-through-interpreter (strike-through contents)
3288 "Interpret STRIKE-THROUGH object as Org syntax.
3289 CONTENTS is the contents of the object."
3290 (format "+%s+" contents))
3293 ;;;; Subscript
3295 (defun org-element-subscript-parser ()
3296 "Parse subscript at point.
3298 Return a list whose CAR is `subscript' and CDR a plist with
3299 `:begin', `:end', `:contents-begin', `:contents-end',
3300 `:use-brackets-p' and `:post-blank' as keywords.
3302 Assume point is at the underscore."
3303 (save-excursion
3304 (unless (bolp) (backward-char))
3305 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
3307 (not (looking-at org-match-substring-regexp))))
3308 (begin (match-beginning 2))
3309 (contents-begin (or (match-beginning 5)
3310 (match-beginning 3)))
3311 (contents-end (or (match-end 5) (match-end 3)))
3312 (post-blank (progn (goto-char (match-end 0))
3313 (skip-chars-forward " \t")))
3314 (end (point)))
3315 (list 'subscript
3316 (list :begin begin
3317 :end end
3318 :use-brackets-p bracketsp
3319 :contents-begin contents-begin
3320 :contents-end contents-end
3321 :post-blank post-blank)))))
3323 (defun org-element-subscript-interpreter (subscript contents)
3324 "Interpret SUBSCRIPT object as Org syntax.
3325 CONTENTS is the contents of the object."
3326 (format
3327 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
3328 contents))
3330 (defun org-element-sub/superscript-successor ()
3331 "Search for the next sub/superscript object.
3333 Return value is a cons cell whose CAR is either `subscript' or
3334 `superscript' and CDR is beginning position."
3335 (save-excursion
3336 (unless (bolp) (backward-char))
3337 (when (re-search-forward org-match-substring-regexp nil t)
3338 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
3339 (match-beginning 2)))))
3342 ;;;; Superscript
3344 (defun org-element-superscript-parser ()
3345 "Parse superscript at point.
3347 Return a list whose CAR is `superscript' and CDR a plist with
3348 `:begin', `:end', `:contents-begin', `:contents-end',
3349 `:use-brackets-p' and `:post-blank' as keywords.
3351 Assume point is at the caret."
3352 (save-excursion
3353 (unless (bolp) (backward-char))
3354 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
3355 (not (looking-at org-match-substring-regexp))))
3356 (begin (match-beginning 2))
3357 (contents-begin (or (match-beginning 5)
3358 (match-beginning 3)))
3359 (contents-end (or (match-end 5) (match-end 3)))
3360 (post-blank (progn (goto-char (match-end 0))
3361 (skip-chars-forward " \t")))
3362 (end (point)))
3363 (list 'superscript
3364 (list :begin begin
3365 :end end
3366 :use-brackets-p bracketsp
3367 :contents-begin contents-begin
3368 :contents-end contents-end
3369 :post-blank post-blank)))))
3371 (defun org-element-superscript-interpreter (superscript contents)
3372 "Interpret SUPERSCRIPT object as Org syntax.
3373 CONTENTS is the contents of the object."
3374 (format
3375 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
3376 contents))
3379 ;;;; Table Cell
3381 (defun org-element-table-cell-parser ()
3382 "Parse table cell at point.
3384 Return a list whose CAR is `table-cell' and CDR is a plist
3385 containing `:begin', `:end', `:contents-begin', `:contents-end'
3386 and `:post-blank' keywords."
3387 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
3388 (let* ((begin (match-beginning 0))
3389 (end (match-end 0))
3390 (contents-begin (match-beginning 1))
3391 (contents-end (match-end 1)))
3392 (list 'table-cell
3393 (list :begin begin
3394 :end end
3395 :contents-begin contents-begin
3396 :contents-end contents-end
3397 :post-blank 0))))
3399 (defun org-element-table-cell-interpreter (table-cell contents)
3400 "Interpret TABLE-CELL element as Org syntax.
3401 CONTENTS is the contents of the cell, or nil."
3402 (concat " " contents " |"))
3404 (defun org-element-table-cell-successor ()
3405 "Search for the next table-cell object.
3407 Return value is a cons cell whose CAR is `table-cell' and CDR is
3408 beginning position."
3409 (when (looking-at "[ \t]*.*?[ \t]*|") (cons 'table-cell (point))))
3412 ;;;; Target
3414 (defun org-element-target-parser ()
3415 "Parse target at point.
3417 Return a list whose CAR is `target' and CDR a plist with
3418 `:begin', `:end', `:value' and `:post-blank' as keywords.
3420 Assume point is at the target."
3421 (save-excursion
3422 (looking-at org-target-regexp)
3423 (let ((begin (point))
3424 (value (org-match-string-no-properties 1))
3425 (post-blank (progn (goto-char (match-end 0))
3426 (skip-chars-forward " \t")))
3427 (end (point)))
3428 (list 'target
3429 (list :begin begin
3430 :end end
3431 :value value
3432 :post-blank post-blank)))))
3434 (defun org-element-target-interpreter (target contents)
3435 "Interpret TARGET object as Org syntax.
3436 CONTENTS is nil."
3437 (format "<<%s>>" (org-element-property :value target)))
3439 (defun org-element-target-successor ()
3440 "Search for the next target object.
3442 Return value is a cons cell whose CAR is `target' and CDR is
3443 beginning position."
3444 (save-excursion
3445 (when (re-search-forward org-target-regexp nil t)
3446 (cons 'target (match-beginning 0)))))
3449 ;;;; Timestamp
3451 (defun org-element-timestamp-parser ()
3452 "Parse time stamp at point.
3454 Return a list whose CAR is `timestamp', and CDR a plist with
3455 `:type', `:raw-value', `:year-start', `:month-start',
3456 `:day-start', `:hour-start', `:minute-start', `:year-end',
3457 `:month-end', `:day-end', `:hour-end', `:minute-end',
3458 `:repeater-type', `:repeater-value', `:repeater-unit',
3459 `:warning-type', `:warning-value', `:warning-unit', `:begin',
3460 `:end', `:value' and `:post-blank' keywords.
3462 Assume point is at the beginning of the timestamp."
3463 (save-excursion
3464 (let* ((begin (point))
3465 (activep (eq (char-after) ?<))
3466 (raw-value
3467 (progn
3468 (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
3469 (match-string-no-properties 0)))
3470 (date-start (match-string-no-properties 1))
3471 (date-end (match-string 3))
3472 (diaryp (match-beginning 2))
3473 (post-blank (progn (goto-char (match-end 0))
3474 (skip-chars-forward " \t")))
3475 (end (point))
3476 (time-range
3477 (and (not diaryp)
3478 (string-match
3479 "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
3480 date-start)
3481 (cons (string-to-number (match-string 2 date-start))
3482 (string-to-number (match-string 3 date-start)))))
3483 (type (cond (diaryp 'diary)
3484 ((and activep (or date-end time-range)) 'active-range)
3485 (activep 'active)
3486 ((or date-end time-range) 'inactive-range)
3487 (t 'inactive)))
3488 (repeater-props
3489 (and (not diaryp)
3490 (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
3491 raw-value)
3492 (list
3493 :repeater-type
3494 (let ((type (match-string 1 raw-value)))
3495 (cond ((equal "++" type) 'catch-up)
3496 ((equal ".+" type) 'restart)
3497 (t 'cumulate)))
3498 :repeater-value (string-to-number (match-string 2 raw-value))
3499 :repeater-unit
3500 (case (string-to-char (match-string 3 raw-value))
3501 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3502 (warning-props
3503 (and (not diaryp)
3504 (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
3505 (list
3506 :warning-type (if (match-string 1 raw-value) 'first 'all)
3507 :warning-value (string-to-number (match-string 2 raw-value))
3508 :warning-unit
3509 (case (string-to-char (match-string 3 raw-value))
3510 (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (t 'year)))))
3511 year-start month-start day-start hour-start minute-start year-end
3512 month-end day-end hour-end minute-end)
3513 ;; Parse date-start.
3514 (unless diaryp
3515 (let ((date (org-parse-time-string date-start t)))
3516 (setq year-start (nth 5 date)
3517 month-start (nth 4 date)
3518 day-start (nth 3 date)
3519 hour-start (nth 2 date)
3520 minute-start (nth 1 date))))
3521 ;; Compute date-end. It can be provided directly in time-stamp,
3522 ;; or extracted from time range. Otherwise, it defaults to the
3523 ;; same values as date-start.
3524 (unless diaryp
3525 (let ((date (and date-end (org-parse-time-string date-end t))))
3526 (setq year-end (or (nth 5 date) year-start)
3527 month-end (or (nth 4 date) month-start)
3528 day-end (or (nth 3 date) day-start)
3529 hour-end (or (nth 2 date) (car time-range) hour-start)
3530 minute-end (or (nth 1 date) (cdr time-range) minute-start))))
3531 (list 'timestamp
3532 (nconc (list :type type
3533 :raw-value raw-value
3534 :year-start year-start
3535 :month-start month-start
3536 :day-start day-start
3537 :hour-start hour-start
3538 :minute-start minute-start
3539 :year-end year-end
3540 :month-end month-end
3541 :day-end day-end
3542 :hour-end hour-end
3543 :minute-end minute-end
3544 :begin begin
3545 :end end
3546 :post-blank post-blank)
3547 repeater-props
3548 warning-props)))))
3550 (defun org-element-timestamp-interpreter (timestamp contents)
3551 "Interpret TIMESTAMP object as Org syntax.
3552 CONTENTS is nil."
3553 (let* ((repeat-string
3554 (concat
3555 (case (org-element-property :repeater-type timestamp)
3556 (cumulate "+") (catch-up "++") (restart ".+"))
3557 (let ((val (org-element-property :repeater-value timestamp)))
3558 (and val (number-to-string val)))
3559 (case (org-element-property :repeater-unit timestamp)
3560 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3561 (warning-string
3562 (concat
3563 (case (org-element-property :warning-type timestamp)
3564 (first "--")
3565 (all "-"))
3566 (let ((val (org-element-property :warning-value timestamp)))
3567 (and val (number-to-string val)))
3568 (case (org-element-property :warning-unit timestamp)
3569 (hour "h") (day "d") (week "w") (month "m") (year "y"))))
3570 (build-ts-string
3571 ;; Build an Org timestamp string from TIME. ACTIVEP is
3572 ;; non-nil when time stamp is active. If WITH-TIME-P is
3573 ;; non-nil, add a time part. HOUR-END and MINUTE-END
3574 ;; specify a time range in the timestamp. REPEAT-STRING is
3575 ;; the repeater string, if any.
3576 (lambda (time activep &optional with-time-p hour-end minute-end)
3577 (let ((ts (format-time-string
3578 (funcall (if with-time-p 'cdr 'car)
3579 org-time-stamp-formats)
3580 time)))
3581 (when (and hour-end minute-end)
3582 (string-match "[012]?[0-9]:[0-5][0-9]" ts)
3583 (setq ts
3584 (replace-match
3585 (format "\\&-%02d:%02d" hour-end minute-end)
3586 nil nil ts)))
3587 (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
3588 (dolist (s (list repeat-string warning-string))
3589 (when (org-string-nw-p s)
3590 (setq ts (concat (substring ts 0 -1)
3593 (substring ts -1)))))
3594 ;; Return value.
3595 ts)))
3596 (type (org-element-property :type timestamp)))
3597 (case type
3598 ((active inactive)
3599 (let* ((minute-start (org-element-property :minute-start timestamp))
3600 (minute-end (org-element-property :minute-end timestamp))
3601 (hour-start (org-element-property :hour-start timestamp))
3602 (hour-end (org-element-property :hour-end timestamp))
3603 (time-range-p (and hour-start hour-end minute-start minute-end
3604 (or (/= hour-start hour-end)
3605 (/= minute-start minute-end)))))
3606 (funcall
3607 build-ts-string
3608 (encode-time 0
3609 (or minute-start 0)
3610 (or hour-start 0)
3611 (org-element-property :day-start timestamp)
3612 (org-element-property :month-start timestamp)
3613 (org-element-property :year-start timestamp))
3614 (eq type 'active)
3615 (and hour-start minute-start)
3616 (and time-range-p hour-end)
3617 (and time-range-p minute-end))))
3618 ((active-range inactive-range)
3619 (let ((minute-start (org-element-property :minute-start timestamp))
3620 (minute-end (org-element-property :minute-end timestamp))
3621 (hour-start (org-element-property :hour-start timestamp))
3622 (hour-end (org-element-property :hour-end timestamp)))
3623 (concat
3624 (funcall
3625 build-ts-string (encode-time
3627 (or minute-start 0)
3628 (or hour-start 0)
3629 (org-element-property :day-start timestamp)
3630 (org-element-property :month-start timestamp)
3631 (org-element-property :year-start timestamp))
3632 (eq type 'active-range)
3633 (and hour-start minute-start))
3634 "--"
3635 (funcall build-ts-string
3636 (encode-time 0
3637 (or minute-end 0)
3638 (or hour-end 0)
3639 (org-element-property :day-end timestamp)
3640 (org-element-property :month-end timestamp)
3641 (org-element-property :year-end timestamp))
3642 (eq type 'active-range)
3643 (and hour-end minute-end))))))))
3645 (defun org-element-timestamp-successor ()
3646 "Search for the next timestamp object.
3648 Return value is a cons cell whose CAR is `timestamp' and CDR is
3649 beginning position."
3650 (save-excursion
3651 (when (re-search-forward
3652 (concat org-ts-regexp-both
3653 "\\|"
3654 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
3655 "\\|"
3656 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
3657 nil t)
3658 (cons 'timestamp (match-beginning 0)))))
3661 ;;;; Underline
3663 (defun org-element-underline-parser ()
3664 "Parse underline object at point.
3666 Return a list whose CAR is `underline' and CDR is a plist with
3667 `:begin', `:end', `:contents-begin' and `:contents-end' and
3668 `:post-blank' keywords.
3670 Assume point is at the first underscore marker."
3671 (save-excursion
3672 (unless (bolp) (backward-char 1))
3673 (looking-at org-emph-re)
3674 (let ((begin (match-beginning 2))
3675 (contents-begin (match-beginning 4))
3676 (contents-end (match-end 4))
3677 (post-blank (progn (goto-char (match-end 2))
3678 (skip-chars-forward " \t")))
3679 (end (point)))
3680 (list 'underline
3681 (list :begin begin
3682 :end end
3683 :contents-begin contents-begin
3684 :contents-end contents-end
3685 :post-blank post-blank)))))
3687 (defun org-element-underline-interpreter (underline contents)
3688 "Interpret UNDERLINE object as Org syntax.
3689 CONTENTS is the contents of the object."
3690 (format "_%s_" contents))
3693 ;;;; Verbatim
3695 (defun org-element-verbatim-parser ()
3696 "Parse verbatim object at point.
3698 Return a list whose CAR is `verbatim' and CDR is a plist with
3699 `:value', `:begin', `:end' and `:post-blank' keywords.
3701 Assume point is at the first equal sign marker."
3702 (save-excursion
3703 (unless (bolp) (backward-char 1))
3704 (looking-at org-emph-re)
3705 (let ((begin (match-beginning 2))
3706 (value (org-match-string-no-properties 4))
3707 (post-blank (progn (goto-char (match-end 2))
3708 (skip-chars-forward " \t")))
3709 (end (point)))
3710 (list 'verbatim
3711 (list :value value
3712 :begin begin
3713 :end end
3714 :post-blank post-blank)))))
3716 (defun org-element-verbatim-interpreter (verbatim contents)
3717 "Interpret VERBATIM object as Org syntax.
3718 CONTENTS is nil."
3719 (format "=%s=" (org-element-property :value verbatim)))
3723 ;;; Parsing Element Starting At Point
3725 ;; `org-element--current-element' is the core function of this section.
3726 ;; It returns the Lisp representation of the element starting at
3727 ;; point.
3729 ;; `org-element--current-element' makes use of special modes. They
3730 ;; are activated for fixed element chaining (i.e. `plain-list' >
3731 ;; `item') or fixed conditional element chaining (i.e. `headline' >
3732 ;; `section'). Special modes are: `first-section', `item',
3733 ;; `node-property', `quote-section', `section' and `table-row'.
3735 (defun org-element--current-element
3736 (limit &optional granularity special structure)
3737 "Parse the element starting at point.
3739 Return value is a list like (TYPE PROPS) where TYPE is the type
3740 of the element and PROPS a plist of properties associated to the
3741 element.
3743 Possible types are defined in `org-element-all-elements'.
3745 LIMIT bounds the search.
3747 Optional argument GRANULARITY determines the depth of the
3748 recursion. Allowed values are `headline', `greater-element',
3749 `element', `object' or nil. When it is broader than `object' (or
3750 nil), secondary values will not be parsed, since they only
3751 contain objects.
3753 Optional argument SPECIAL, when non-nil, can be either
3754 `first-section', `item', `node-property', `quote-section',
3755 `section', and `table-row'.
3757 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3758 be computed.
3760 This function assumes point is always at the beginning of the
3761 element it has to parse."
3762 (save-excursion
3763 (let ((case-fold-search t)
3764 ;; Determine if parsing depth allows for secondary strings
3765 ;; parsing. It only applies to elements referenced in
3766 ;; `org-element-secondary-value-alist'.
3767 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3768 (cond
3769 ;; Item.
3770 ((eq special 'item)
3771 (org-element-item-parser limit structure raw-secondary-p))
3772 ;; Table Row.
3773 ((eq special 'table-row) (org-element-table-row-parser limit))
3774 ;; Node Property.
3775 ((eq special 'node-property) (org-element-node-property-parser limit))
3776 ;; Headline.
3777 ((org-with-limited-levels (org-at-heading-p))
3778 (org-element-headline-parser limit raw-secondary-p))
3779 ;; Sections (must be checked after headline).
3780 ((eq special 'section) (org-element-section-parser limit))
3781 ((eq special 'quote-section) (org-element-quote-section-parser limit))
3782 ((eq special 'first-section)
3783 (org-element-section-parser
3784 (or (save-excursion (org-with-limited-levels (outline-next-heading)))
3785 limit)))
3786 ;; When not at bol, point is at the beginning of an item or
3787 ;; a footnote definition: next item is always a paragraph.
3788 ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
3789 ;; Planning and Clock.
3790 ((looking-at org-planning-or-clock-line-re)
3791 (if (equal (match-string 1) org-clock-string)
3792 (org-element-clock-parser limit)
3793 (org-element-planning-parser limit)))
3794 ;; Inlinetask.
3795 ((org-at-heading-p)
3796 (org-element-inlinetask-parser limit raw-secondary-p))
3797 ;; From there, elements can have affiliated keywords.
3798 (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
3799 (cond
3800 ;; Jumping over affiliated keywords put point off-limits.
3801 ;; Parse them as regular keywords.
3802 ((and (cdr affiliated) (>= (point) limit))
3803 (goto-char (car affiliated))
3804 (org-element-keyword-parser limit nil))
3805 ;; LaTeX Environment.
3806 ((looking-at
3807 "[ \t]*\\\\begin{[A-Za-z0-9*]+}\\(\\[.*?\\]\\|{.*?}\\)*[ \t]*$")
3808 (org-element-latex-environment-parser limit affiliated))
3809 ;; Drawer and Property Drawer.
3810 ((looking-at org-drawer-regexp)
3811 (if (equal (match-string 1) "PROPERTIES")
3812 (org-element-property-drawer-parser limit affiliated)
3813 (org-element-drawer-parser limit affiliated)))
3814 ;; Fixed Width
3815 ((looking-at "[ \t]*:\\( \\|$\\)")
3816 (org-element-fixed-width-parser limit affiliated))
3817 ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
3818 ;; Keywords.
3819 ((looking-at "[ \t]*#")
3820 (goto-char (match-end 0))
3821 (cond ((looking-at "\\(?: \\|$\\)")
3822 (beginning-of-line)
3823 (org-element-comment-parser limit affiliated))
3824 ((looking-at "\\+BEGIN_\\(\\S-+\\)")
3825 (beginning-of-line)
3826 (let ((parser (assoc (upcase (match-string 1))
3827 org-element-block-name-alist)))
3828 (if parser (funcall (cdr parser) limit affiliated)
3829 (org-element-special-block-parser limit affiliated))))
3830 ((looking-at "\\+CALL:")
3831 (beginning-of-line)
3832 (org-element-babel-call-parser limit affiliated))
3833 ((looking-at "\\+BEGIN:? ")
3834 (beginning-of-line)
3835 (org-element-dynamic-block-parser limit affiliated))
3836 ((looking-at "\\+\\S-+:")
3837 (beginning-of-line)
3838 (org-element-keyword-parser limit affiliated))
3840 (beginning-of-line)
3841 (org-element-paragraph-parser limit affiliated))))
3842 ;; Footnote Definition.
3843 ((looking-at org-footnote-definition-re)
3844 (org-element-footnote-definition-parser limit affiliated))
3845 ;; Horizontal Rule.
3846 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3847 (org-element-horizontal-rule-parser limit affiliated))
3848 ;; Diary Sexp.
3849 ((looking-at "%%(")
3850 (org-element-diary-sexp-parser limit affiliated))
3851 ;; Table.
3852 ((org-at-table-p t) (org-element-table-parser limit affiliated))
3853 ;; List.
3854 ((looking-at (org-item-re))
3855 (org-element-plain-list-parser
3856 limit affiliated
3857 (or structure (org-element--list-struct limit))))
3858 ;; Default element: Paragraph.
3859 (t (org-element-paragraph-parser limit affiliated)))))))))
3862 ;; Most elements can have affiliated keywords. When looking for an
3863 ;; element beginning, we want to move before them, as they belong to
3864 ;; that element, and, in the meantime, collect information they give
3865 ;; into appropriate properties. Hence the following function.
3867 (defun org-element--collect-affiliated-keywords (limit)
3868 "Collect affiliated keywords from point down to LIMIT.
3870 Return a list whose CAR is the position at the first of them and
3871 CDR a plist of keywords and values and move point to the
3872 beginning of the first line after them.
3874 As a special case, if element doesn't start at the beginning of
3875 the line (i.e. a paragraph starting an item), CAR is current
3876 position of point and CDR is nil."
3877 (if (not (bolp)) (list (point))
3878 (let ((case-fold-search t)
3879 (origin (point))
3880 ;; RESTRICT is the list of objects allowed in parsed
3881 ;; keywords value.
3882 (restrict (org-element-restriction 'keyword))
3883 output)
3884 (while (and (< (point) limit) (looking-at org-element--affiliated-re))
3885 (let* ((raw-kwd (upcase (match-string 1)))
3886 ;; Apply translation to RAW-KWD. From there, KWD is
3887 ;; the official keyword.
3888 (kwd (or (cdr (assoc raw-kwd
3889 org-element-keyword-translation-alist))
3890 raw-kwd))
3891 ;; Find main value for any keyword.
3892 (value
3893 (save-match-data
3894 (org-trim
3895 (buffer-substring-no-properties
3896 (match-end 0) (point-at-eol)))))
3897 ;; PARSEDP is non-nil when keyword should have its
3898 ;; value parsed.
3899 (parsedp (member kwd org-element-parsed-keywords))
3900 ;; If KWD is a dual keyword, find its secondary
3901 ;; value. Maybe parse it.
3902 (dualp (member kwd org-element-dual-keywords))
3903 (dual-value
3904 (and dualp
3905 (let ((sec (org-match-string-no-properties 2)))
3906 (if (or (not sec) (not parsedp)) sec
3907 (org-element-parse-secondary-string sec restrict)))))
3908 ;; Attribute a property name to KWD.
3909 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3910 ;; Now set final shape for VALUE.
3911 (when parsedp
3912 (setq value (org-element-parse-secondary-string value restrict)))
3913 (when dualp
3914 (setq value (and (or value dual-value) (cons value dual-value))))
3915 (when (or (member kwd org-element-multiple-keywords)
3916 ;; Attributes can always appear on multiple lines.
3917 (string-match "^ATTR_" kwd))
3918 (setq value (cons value (plist-get output kwd-sym))))
3919 ;; Eventually store the new value in OUTPUT.
3920 (setq output (plist-put output kwd-sym value))
3921 ;; Move to next keyword.
3922 (forward-line)))
3923 ;; If affiliated keywords are orphaned: move back to first one.
3924 ;; They will be parsed as a paragraph.
3925 (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
3926 ;; Return value.
3927 (cons origin output))))
3931 ;;; The Org Parser
3933 ;; The two major functions here are `org-element-parse-buffer', which
3934 ;; parses Org syntax inside the current buffer, taking into account
3935 ;; region, narrowing, or even visibility if specified, and
3936 ;; `org-element-parse-secondary-string', which parses objects within
3937 ;; a given string.
3939 ;; The (almost) almighty `org-element-map' allows to apply a function
3940 ;; on elements or objects matching some type, and accumulate the
3941 ;; resulting values. In an export situation, it also skips unneeded
3942 ;; parts of the parse tree.
3944 (defun org-element-parse-buffer (&optional granularity visible-only)
3945 "Recursively parse the buffer and return structure.
3946 If narrowing is in effect, only parse the visible part of the
3947 buffer.
3949 Optional argument GRANULARITY determines the depth of the
3950 recursion. It can be set to the following symbols:
3952 `headline' Only parse headlines.
3953 `greater-element' Don't recurse into greater elements excepted
3954 headlines and sections. Thus, elements
3955 parsed are the top-level ones.
3956 `element' Parse everything but objects and plain text.
3957 `object' Parse the complete buffer (default).
3959 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3960 elements.
3962 An element or an objects is represented as a list with the
3963 pattern (TYPE PROPERTIES CONTENTS), where :
3965 TYPE is a symbol describing the element or object. See
3966 `org-element-all-elements' and `org-element-all-objects' for an
3967 exhaustive list of such symbols. One can retrieve it with
3968 `org-element-type' function.
3970 PROPERTIES is the list of attributes attached to the element or
3971 object, as a plist. Although most of them are specific to the
3972 element or object type, all types share `:begin', `:end',
3973 `:post-blank' and `:parent' properties, which respectively
3974 refer to buffer position where the element or object starts,
3975 ends, the number of white spaces or blank lines after it, and
3976 the element or object containing it. Properties values can be
3977 obtained by using `org-element-property' function.
3979 CONTENTS is a list of elements, objects or raw strings
3980 contained in the current element or object, when applicable.
3981 One can access them with `org-element-contents' function.
3983 The Org buffer has `org-data' as type and nil as properties.
3984 `org-element-map' function can be used to find specific elements
3985 or objects within the parse tree.
3987 This function assumes that current major mode is `org-mode'."
3988 (save-excursion
3989 (goto-char (point-min))
3990 (org-skip-whitespace)
3991 (org-element--parse-elements
3992 (point-at-bol) (point-max)
3993 ;; Start in `first-section' mode so text before the first
3994 ;; headline belongs to a section.
3995 'first-section nil granularity visible-only (list 'org-data nil))))
3997 (defun org-element-parse-secondary-string (string restriction &optional parent)
3998 "Recursively parse objects in STRING and return structure.
4000 RESTRICTION is a symbol limiting the object types that will be
4001 looked after.
4003 Optional argument PARENT, when non-nil, is the element or object
4004 containing the secondary string. It is used to set correctly
4005 `:parent' property within the string."
4006 ;; Copy buffer-local variables listed in
4007 ;; `org-element-object-variables' into temporary buffer. This is
4008 ;; required since object parsing is dependent on these variables.
4009 (let ((pairs (delq nil (mapcar (lambda (var)
4010 (when (boundp var)
4011 (cons var (symbol-value var))))
4012 org-element-object-variables))))
4013 (with-temp-buffer
4014 (mapc (lambda (pair) (org-set-local (car pair) (cdr pair))) pairs)
4015 (insert string)
4016 (let ((secondary (org-element--parse-objects
4017 (point-min) (point-max) nil restriction)))
4018 (when parent
4019 (mapc (lambda (obj) (org-element-put-property obj :parent parent))
4020 secondary))
4021 secondary))))
4023 (defun org-element-map
4024 (data types fun &optional info first-match no-recursion with-affiliated)
4025 "Map a function on selected elements or objects.
4027 DATA is a parse tree, an element, an object, a string, or a list
4028 of such constructs. TYPES is a symbol or list of symbols of
4029 elements or objects types (see `org-element-all-elements' and
4030 `org-element-all-objects' for a complete list of types). FUN is
4031 the function called on the matching element or object. It has to
4032 accept one argument: the element or object itself.
4034 When optional argument INFO is non-nil, it should be a plist
4035 holding export options. In that case, parts of the parse tree
4036 not exportable according to that property list will be skipped.
4038 When optional argument FIRST-MATCH is non-nil, stop at the first
4039 match for which FUN doesn't return nil, and return that value.
4041 Optional argument NO-RECURSION is a symbol or a list of symbols
4042 representing elements or objects types. `org-element-map' won't
4043 enter any recursive element or object whose type belongs to that
4044 list. Though, FUN can still be applied on them.
4046 When optional argument WITH-AFFILIATED is non-nil, FUN will also
4047 apply to matching objects within parsed affiliated keywords (see
4048 `org-element-parsed-keywords').
4050 Nil values returned from FUN do not appear in the results.
4053 Examples:
4054 ---------
4056 Assuming TREE is a variable containing an Org buffer parse tree,
4057 the following example will return a flat list of all `src-block'
4058 and `example-block' elements in it:
4060 \(org-element-map tree '(example-block src-block) 'identity)
4062 The following snippet will find the first headline with a level
4063 of 1 and a \"phone\" tag, and will return its beginning position:
4065 \(org-element-map tree 'headline
4066 \(lambda (hl)
4067 \(and (= (org-element-property :level hl) 1)
4068 \(member \"phone\" (org-element-property :tags hl))
4069 \(org-element-property :begin hl)))
4070 nil t)
4072 The next example will return a flat list of all `plain-list' type
4073 elements in TREE that are not a sub-list themselves:
4075 \(org-element-map tree 'plain-list 'identity nil nil 'plain-list)
4077 Eventually, this example will return a flat list of all `bold'
4078 type objects containing a `latex-snippet' type object, even
4079 looking into captions:
4081 \(org-element-map tree 'bold
4082 \(lambda (b)
4083 \(and (org-element-map b 'latex-snippet 'identity nil t) b))
4084 nil nil nil t)"
4085 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
4086 (unless (listp types) (setq types (list types)))
4087 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
4088 ;; Recursion depth is determined by --CATEGORY.
4089 (let* ((--category
4090 (catch 'found
4091 (let ((category 'greater-elements))
4092 (mapc (lambda (type)
4093 (cond ((or (memq type org-element-all-objects)
4094 (eq type 'plain-text))
4095 ;; If one object is found, the function
4096 ;; has to recurse into every object.
4097 (throw 'found 'objects))
4098 ((not (memq type org-element-greater-elements))
4099 ;; If one regular element is found, the
4100 ;; function has to recurse, at least,
4101 ;; into every element it encounters.
4102 (and (not (eq category 'elements))
4103 (setq category 'elements)))))
4104 types)
4105 category)))
4106 ;; Compute properties for affiliated keywords if necessary.
4107 (--affiliated-alist
4108 (and with-affiliated
4109 (mapcar (lambda (kwd)
4110 (cons kwd (intern (concat ":" (downcase kwd)))))
4111 org-element-affiliated-keywords)))
4112 --acc
4113 --walk-tree
4114 (--walk-tree
4115 (function
4116 (lambda (--data)
4117 ;; Recursively walk DATA. INFO, if non-nil, is a plist
4118 ;; holding contextual information.
4119 (let ((--type (org-element-type --data)))
4120 (cond
4121 ((not --data))
4122 ;; Ignored element in an export context.
4123 ((and info (memq --data (plist-get info :ignore-list))))
4124 ;; List of elements or objects.
4125 ((not --type) (mapc --walk-tree --data))
4126 ;; Unconditionally enter parse trees.
4127 ((eq --type 'org-data)
4128 (mapc --walk-tree (org-element-contents --data)))
4130 ;; Check if TYPE is matching among TYPES. If so,
4131 ;; apply FUN to --DATA and accumulate return value
4132 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
4133 (when (memq --type types)
4134 (let ((result (funcall fun --data)))
4135 (cond ((not result))
4136 (first-match (throw '--map-first-match result))
4137 (t (push result --acc)))))
4138 ;; If --DATA has a secondary string that can contain
4139 ;; objects with their type among TYPES, look into it.
4140 (when (and (eq --category 'objects) (not (stringp --data)))
4141 (let ((sec-prop
4142 (assq --type org-element-secondary-value-alist)))
4143 (when sec-prop
4144 (funcall --walk-tree
4145 (org-element-property (cdr sec-prop) --data)))))
4146 ;; If --DATA has any affiliated keywords and
4147 ;; WITH-AFFILIATED is non-nil, look for objects in
4148 ;; them.
4149 (when (and with-affiliated
4150 (eq --category 'objects)
4151 (memq --type org-element-all-elements))
4152 (mapc (lambda (kwd-pair)
4153 (let ((kwd (car kwd-pair))
4154 (value (org-element-property
4155 (cdr kwd-pair) --data)))
4156 ;; Pay attention to the type of value.
4157 ;; Preserve order for multiple keywords.
4158 (cond
4159 ((not value))
4160 ((and (member kwd org-element-multiple-keywords)
4161 (member kwd org-element-dual-keywords))
4162 (mapc (lambda (line)
4163 (funcall --walk-tree (cdr line))
4164 (funcall --walk-tree (car line)))
4165 (reverse value)))
4166 ((member kwd org-element-multiple-keywords)
4167 (mapc (lambda (line) (funcall --walk-tree line))
4168 (reverse value)))
4169 ((member kwd org-element-dual-keywords)
4170 (funcall --walk-tree (cdr value))
4171 (funcall --walk-tree (car value)))
4172 (t (funcall --walk-tree value)))))
4173 --affiliated-alist))
4174 ;; Determine if a recursion into --DATA is possible.
4175 (cond
4176 ;; --TYPE is explicitly removed from recursion.
4177 ((memq --type no-recursion))
4178 ;; --DATA has no contents.
4179 ((not (org-element-contents --data)))
4180 ;; Looking for greater elements but --DATA is simply
4181 ;; an element or an object.
4182 ((and (eq --category 'greater-elements)
4183 (not (memq --type org-element-greater-elements))))
4184 ;; Looking for elements but --DATA is an object.
4185 ((and (eq --category 'elements)
4186 (memq --type org-element-all-objects)))
4187 ;; In any other case, map contents.
4188 (t (mapc --walk-tree (org-element-contents --data)))))))))))
4189 (catch '--map-first-match
4190 (funcall --walk-tree data)
4191 ;; Return value in a proper order.
4192 (nreverse --acc))))
4193 (put 'org-element-map 'lisp-indent-function 2)
4195 ;; The following functions are internal parts of the parser.
4197 ;; The first one, `org-element--parse-elements' acts at the element's
4198 ;; level.
4200 ;; The second one, `org-element--parse-objects' applies on all objects
4201 ;; of a paragraph or a secondary string. It uses
4202 ;; `org-element--get-next-object-candidates' to optimize the search of
4203 ;; the next object in the buffer.
4205 ;; More precisely, that function looks for every allowed object type
4206 ;; first. Then, it discards failed searches, keeps further matches,
4207 ;; and searches again types matched behind point, for subsequent
4208 ;; calls. Thus, searching for a given type fails only once, and every
4209 ;; object is searched only once at top level (but sometimes more for
4210 ;; nested types).
4212 (defun org-element--parse-elements
4213 (beg end special structure granularity visible-only acc)
4214 "Parse elements between BEG and END positions.
4216 SPECIAL prioritize some elements over the others. It can be set
4217 to `first-section', `quote-section', `section' `item' or
4218 `table-row'.
4220 When value is `item', STRUCTURE will be used as the current list
4221 structure.
4223 GRANULARITY determines the depth of the recursion. See
4224 `org-element-parse-buffer' for more information.
4226 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
4227 elements.
4229 Elements are accumulated into ACC."
4230 (save-excursion
4231 (goto-char beg)
4232 ;; Visible only: skip invisible parts at the beginning of the
4233 ;; element.
4234 (when (and visible-only (org-invisible-p2))
4235 (goto-char (min (1+ (org-find-visible)) end)))
4236 ;; When parsing only headlines, skip any text before first one.
4237 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
4238 (org-with-limited-levels (outline-next-heading)))
4239 ;; Main loop start.
4240 (while (< (point) end)
4241 ;; Find current element's type and parse it accordingly to
4242 ;; its category.
4243 (let* ((element (org-element--current-element
4244 end granularity special structure))
4245 (type (org-element-type element))
4246 (cbeg (org-element-property :contents-begin element)))
4247 (goto-char (org-element-property :end element))
4248 ;; Visible only: skip invisible parts between siblings.
4249 (when (and visible-only (org-invisible-p2))
4250 (goto-char (min (1+ (org-find-visible)) end)))
4251 ;; Fill ELEMENT contents by side-effect.
4252 (cond
4253 ;; If element has no contents, don't modify it.
4254 ((not cbeg))
4255 ;; Greater element: parse it between `contents-begin' and
4256 ;; `contents-end'. Make sure GRANULARITY allows the
4257 ;; recursion, or ELEMENT is a headline, in which case going
4258 ;; inside is mandatory, in order to get sub-level headings.
4259 ((and (memq type org-element-greater-elements)
4260 (or (memq granularity '(element object nil))
4261 (and (eq granularity 'greater-element)
4262 (eq type 'section))
4263 (eq type 'headline)))
4264 (org-element--parse-elements
4265 cbeg (org-element-property :contents-end element)
4266 ;; Possibly switch to a special mode.
4267 (case type
4268 (headline
4269 (if (org-element-property :quotedp element) 'quote-section
4270 'section))
4271 (plain-list 'item)
4272 (property-drawer 'node-property)
4273 (table 'table-row))
4274 (and (memq type '(item plain-list))
4275 (org-element-property :structure element))
4276 granularity visible-only element))
4277 ;; ELEMENT has contents. Parse objects inside, if
4278 ;; GRANULARITY allows it.
4279 ((memq granularity '(object nil))
4280 (org-element--parse-objects
4281 cbeg (org-element-property :contents-end element) element
4282 (org-element-restriction type))))
4283 (org-element-adopt-elements acc element)))
4284 ;; Return result.
4285 acc))
4287 (defun org-element--parse-objects (beg end acc restriction)
4288 "Parse objects between BEG and END and return recursive structure.
4290 Objects are accumulated in ACC.
4292 RESTRICTION is a list of object successors which are allowed in
4293 the current object."
4294 (let ((candidates 'initial))
4295 (save-excursion
4296 (save-restriction
4297 (narrow-to-region beg end)
4298 (goto-char (point-min))
4299 (while (and (not (eobp))
4300 (setq candidates
4301 (org-element--get-next-object-candidates
4302 restriction candidates)))
4303 (let ((next-object
4304 (let ((pos (apply 'min (mapcar 'cdr candidates))))
4305 (save-excursion
4306 (goto-char pos)
4307 (funcall (intern (format "org-element-%s-parser"
4308 (car (rassq pos candidates)))))))))
4309 ;; 1. Text before any object. Untabify it.
4310 (let ((obj-beg (org-element-property :begin next-object)))
4311 (unless (= (point) obj-beg)
4312 (setq acc
4313 (org-element-adopt-elements
4315 (replace-regexp-in-string
4316 "\t" (make-string tab-width ? )
4317 (buffer-substring-no-properties (point) obj-beg))))))
4318 ;; 2. Object...
4319 (let ((obj-end (org-element-property :end next-object))
4320 (cont-beg (org-element-property :contents-begin next-object)))
4321 ;; Fill contents of NEXT-OBJECT by side-effect, if it has
4322 ;; a recursive type.
4323 (when (and cont-beg
4324 (memq (car next-object) org-element-recursive-objects))
4325 (org-element--parse-objects
4326 cont-beg (org-element-property :contents-end next-object)
4327 next-object (org-element-restriction next-object)))
4328 (setq acc (org-element-adopt-elements acc next-object))
4329 (goto-char obj-end))))
4330 ;; 3. Text after last object. Untabify it.
4331 (unless (eobp)
4332 (setq acc
4333 (org-element-adopt-elements
4335 (replace-regexp-in-string
4336 "\t" (make-string tab-width ? )
4337 (buffer-substring-no-properties (point) end)))))
4338 ;; Result.
4339 acc))))
4341 (defun org-element--get-next-object-candidates (restriction objects)
4342 "Return an alist of candidates for the next object.
4344 RESTRICTION is a list of object types, as symbols. Only
4345 candidates with such types are looked after.
4347 OBJECTS is the previous candidates alist. If it is set to
4348 `initial', no search has been done before, and all symbols in
4349 RESTRICTION should be looked after.
4351 Return value is an alist whose CAR is the object type and CDR its
4352 beginning position."
4353 (delq
4355 (if (eq objects 'initial)
4356 ;; When searching for the first time, look for every successor
4357 ;; allowed in RESTRICTION.
4358 (mapcar
4359 (lambda (res)
4360 (funcall (intern (format "org-element-%s-successor" res))))
4361 restriction)
4362 ;; Focus on objects returned during last search. Keep those
4363 ;; still after point. Search again objects before it.
4364 (mapcar
4365 (lambda (obj)
4366 (if (>= (cdr obj) (point)) obj
4367 (let* ((type (car obj))
4368 (succ (or (cdr (assq type org-element-object-successor-alist))
4369 type)))
4370 (and succ
4371 (funcall (intern (format "org-element-%s-successor" succ)))))))
4372 objects))))
4376 ;;; Towards A Bijective Process
4378 ;; The parse tree obtained with `org-element-parse-buffer' is really
4379 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
4380 ;; interpreted and expanded into a string with canonical Org syntax.
4381 ;; Hence `org-element-interpret-data'.
4383 ;; The function relies internally on
4384 ;; `org-element--interpret-affiliated-keywords'.
4386 ;;;###autoload
4387 (defun org-element-interpret-data (data &optional pseudo-objects)
4388 "Interpret DATA as Org syntax.
4390 DATA is a parse tree, an element, an object or a secondary string
4391 to interpret.
4393 Optional argument PSEUDO-OBJECTS is a list of symbols defining
4394 new types that should be treated as objects. An unknown type not
4395 belonging to this list is seen as a pseudo-element instead. Both
4396 pseudo-objects and pseudo-elements are transparent entities, i.e.
4397 only their contents are interpreted.
4399 Return Org syntax as a string."
4400 (org-element--interpret-data-1 data nil pseudo-objects))
4402 (defun org-element--interpret-data-1 (data parent pseudo-objects)
4403 "Interpret DATA as Org syntax.
4405 DATA is a parse tree, an element, an object or a secondary string
4406 to interpret. PARENT is used for recursive calls. It contains
4407 the element or object containing data, or nil. PSEUDO-OBJECTS
4408 are list of symbols defining new element or object types.
4409 Unknown types that don't belong to this list are treated as
4410 pseudo-elements instead.
4412 Return Org syntax as a string."
4413 (let* ((type (org-element-type data))
4414 ;; Find interpreter for current object or element. If it
4415 ;; doesn't exist (e.g. this is a pseudo object or element),
4416 ;; return contents, if any.
4417 (interpret
4418 (let ((fun (intern (format "org-element-%s-interpreter" type))))
4419 (if (fboundp fun) fun (lambda (data contents) contents))))
4420 (results
4421 (cond
4422 ;; Secondary string.
4423 ((not type)
4424 (mapconcat
4425 (lambda (obj)
4426 (org-element--interpret-data-1 obj parent pseudo-objects))
4427 data ""))
4428 ;; Full Org document.
4429 ((eq type 'org-data)
4430 (mapconcat
4431 (lambda (obj)
4432 (org-element--interpret-data-1 obj parent pseudo-objects))
4433 (org-element-contents data) ""))
4434 ;; Plain text: remove `:parent' text property from output.
4435 ((stringp data) (org-no-properties data))
4436 ;; Element or object without contents.
4437 ((not (org-element-contents data)) (funcall interpret data nil))
4438 ;; Element or object with contents.
4440 (funcall interpret data
4441 ;; Recursively interpret contents.
4442 (mapconcat
4443 (lambda (obj)
4444 (org-element--interpret-data-1 obj data pseudo-objects))
4445 (org-element-contents
4446 (if (not (memq type '(paragraph verse-block)))
4447 data
4448 ;; Fix indentation of elements containing
4449 ;; objects. We ignore `table-row' elements
4450 ;; as they are one line long anyway.
4451 (org-element-normalize-contents
4452 data
4453 ;; When normalizing first paragraph of an
4454 ;; item or a footnote-definition, ignore
4455 ;; first line's indentation.
4456 (and (eq type 'paragraph)
4457 (equal data (car (org-element-contents parent)))
4458 (memq (org-element-type parent)
4459 '(footnote-definition item))))))
4460 ""))))))
4461 (if (memq type '(org-data plain-text nil)) results
4462 ;; Build white spaces. If no `:post-blank' property is
4463 ;; specified, assume its value is 0.
4464 (let ((post-blank (or (org-element-property :post-blank data) 0)))
4465 (if (or (memq type org-element-all-objects)
4466 (memq type pseudo-objects))
4467 (concat results (make-string post-blank ?\s))
4468 (concat
4469 (org-element--interpret-affiliated-keywords data)
4470 (org-element-normalize-string results)
4471 (make-string post-blank ?\n)))))))
4473 (defun org-element--interpret-affiliated-keywords (element)
4474 "Return ELEMENT's affiliated keywords as Org syntax.
4475 If there is no affiliated keyword, return the empty string."
4476 (let ((keyword-to-org
4477 (function
4478 (lambda (key value)
4479 (let (dual)
4480 (when (member key org-element-dual-keywords)
4481 (setq dual (cdr value) value (car value)))
4482 (concat "#+" key
4483 (and dual
4484 (format "[%s]" (org-element-interpret-data dual)))
4485 ": "
4486 (if (member key org-element-parsed-keywords)
4487 (org-element-interpret-data value)
4488 value)
4489 "\n"))))))
4490 (mapconcat
4491 (lambda (prop)
4492 (let ((value (org-element-property prop element))
4493 (keyword (upcase (substring (symbol-name prop) 1))))
4494 (when value
4495 (if (or (member keyword org-element-multiple-keywords)
4496 ;; All attribute keywords can have multiple lines.
4497 (string-match "^ATTR_" keyword))
4498 (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
4499 (reverse value)
4501 (funcall keyword-to-org keyword value)))))
4502 ;; List all ELEMENT's properties matching an attribute line or an
4503 ;; affiliated keyword, but ignore translated keywords since they
4504 ;; cannot belong to the property list.
4505 (loop for prop in (nth 1 element) by 'cddr
4506 when (let ((keyword (upcase (substring (symbol-name prop) 1))))
4507 (or (string-match "^ATTR_" keyword)
4508 (and
4509 (member keyword org-element-affiliated-keywords)
4510 (not (assoc keyword
4511 org-element-keyword-translation-alist)))))
4512 collect prop)
4513 "")))
4515 ;; Because interpretation of the parse tree must return the same
4516 ;; number of blank lines between elements and the same number of white
4517 ;; space after objects, some special care must be given to white
4518 ;; spaces.
4520 ;; The first function, `org-element-normalize-string', ensures any
4521 ;; string different from the empty string will end with a single
4522 ;; newline character.
4524 ;; The second function, `org-element-normalize-contents', removes
4525 ;; global indentation from the contents of the current element.
4527 (defun org-element-normalize-string (s)
4528 "Ensure string S ends with a single newline character.
4530 If S isn't a string return it unchanged. If S is the empty
4531 string, return it. Otherwise, return a new string with a single
4532 newline character at its end."
4533 (cond
4534 ((not (stringp s)) s)
4535 ((string= "" s) "")
4536 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
4537 (replace-match "\n" nil nil s)))))
4539 (defun org-element-normalize-contents (element &optional ignore-first)
4540 "Normalize plain text in ELEMENT's contents.
4542 ELEMENT must only contain plain text and objects.
4544 If optional argument IGNORE-FIRST is non-nil, ignore first line's
4545 indentation to compute maximal common indentation.
4547 Return the normalized element that is element with global
4548 indentation removed from its contents. The function assumes that
4549 indentation is not done with TAB characters."
4550 (let* (ind-list ; for byte-compiler
4551 collect-inds ; for byte-compiler
4552 (collect-inds
4553 (function
4554 ;; Return list of indentations within BLOB. This is done by
4555 ;; walking recursively BLOB and updating IND-LIST along the
4556 ;; way. FIRST-FLAG is non-nil when the first string hasn't
4557 ;; been seen yet. It is required as this string is the only
4558 ;; one whose indentation doesn't happen after a newline
4559 ;; character.
4560 (lambda (blob first-flag)
4561 (mapc
4562 (lambda (object)
4563 (when (and first-flag (stringp object))
4564 (setq first-flag nil)
4565 (string-match "\\`\\( *\\)" object)
4566 (let ((len (length (match-string 1 object))))
4567 ;; An indentation of zero means no string will be
4568 ;; modified. Quit the process.
4569 (if (zerop len) (throw 'zero (setq ind-list nil))
4570 (push len ind-list))))
4571 (cond
4572 ((stringp object)
4573 (let ((start 0))
4574 ;; Avoid matching blank or empty lines.
4575 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
4576 (not (equal (match-string 2 object) " ")))
4577 (setq start (match-end 0))
4578 (push (length (match-string 1 object)) ind-list))))
4579 ((memq (org-element-type object) org-element-recursive-objects)
4580 (funcall collect-inds object first-flag))))
4581 (org-element-contents blob))))))
4582 ;; Collect indentation list in ELEMENT. Possibly remove first
4583 ;; value if IGNORE-FIRST is non-nil.
4584 (catch 'zero (funcall collect-inds element (not ignore-first)))
4585 (if (not ind-list) element
4586 ;; Build ELEMENT back, replacing each string with the same
4587 ;; string minus common indentation.
4588 (let* (build ; For byte compiler.
4589 (build
4590 (function
4591 (lambda (blob mci first-flag)
4592 ;; Return BLOB with all its strings indentation
4593 ;; shortened from MCI white spaces. FIRST-FLAG is
4594 ;; non-nil when the first string hasn't been seen
4595 ;; yet.
4596 (setcdr (cdr blob)
4597 (mapcar
4598 (lambda (object)
4599 (when (and first-flag (stringp object))
4600 (setq first-flag nil)
4601 (setq object
4602 (replace-regexp-in-string
4603 (format "\\` \\{%d\\}" mci) "" object)))
4604 (cond
4605 ((stringp object)
4606 (replace-regexp-in-string
4607 (format "\n \\{%d\\}" mci) "\n" object))
4608 ((memq (org-element-type object)
4609 org-element-recursive-objects)
4610 (funcall build object mci first-flag))
4611 (t object)))
4612 (org-element-contents blob)))
4613 blob))))
4614 (funcall build element (apply 'min ind-list) (not ignore-first))))))
4618 ;;; The Toolbox
4620 ;; The first move is to implement a way to obtain the smallest element
4621 ;; containing point. This is the job of `org-element-at-point'. It
4622 ;; basically jumps back to the beginning of section containing point
4623 ;; and proceed, one element after the other, with
4624 ;; `org-element--current-element' until the container is found. Note:
4625 ;; When using `org-element-at-point', secondary values are never
4626 ;; parsed since the function focuses on elements, not on objects.
4628 ;; At a deeper level, `org-element-context' lists all elements and
4629 ;; objects containing point.
4631 ;; Both functions benefit from a simple caching mechanism. It is
4632 ;; enabled by default, but can be disabled globally with
4633 ;; `org-element-use-cache'. Also `org-element-cache-reset' clears or
4634 ;; initializes cache for current buffer. Values are retrieved and put
4635 ;; into cache with respectively, `org-element-cache-get' and
4636 ;; `org-element-cache-put'. `org-element--cache-sync-idle-time' and
4637 ;; `org-element--cache-merge-changes-threshold' are used internally to
4638 ;; control caching behaviour.
4640 ;; Eventually `org-element-nested-p' and `org-element-swap-A-B' may be
4641 ;; used internally by navigation and manipulation tools.
4643 (defvar org-element-use-cache t
4644 "Non nil when Org parser should cache its results.")
4646 (defvar org-element--cache nil
4647 "Hash table used as a cache for parser.
4648 Key is a buffer position and value is a cons cell with the
4649 pattern:
4651 \(ELEMENT . OBJECTS-DATA)
4653 where ELEMENT is the element starting at the key and OBJECTS-DATA
4654 is an alist where each association is:
4656 \(POS CANDIDATES . OBJECTS)
4658 where POS is a buffer position, CANDIDATES is the last know list
4659 of successors (see `org-element--get-next-object-candidates') in
4660 container starting at POS and OBJECTS is a list of objects known
4661 to live within that container, from farthest to closest.
4663 In the following example, \\alpha, bold object and \\beta start
4664 at, respectively, positions 1, 7 and 8,
4666 \\alpha *\\beta*
4668 If the paragraph is completely parsed, OBJECTS-DATA will be
4670 \((1 nil BOLD-OBJECT ENTITY-OBJECT)
4671 \(8 nil ENTITY-OBJECT))
4673 whereas in a partially parsed paragraph, it could be
4675 \((1 ((entity . 1) (bold . 7)) ENTITY-OBJECT))
4677 This cache is used in both `org-element-at-point' and
4678 `org-element-context'. The former uses ELEMENT only and the
4679 latter OBJECTS-DATA only.")
4681 (defvar org-element--cache-sync-idle-time 0.5
4682 "Number of seconds of idle time wait before syncing buffer cache.
4683 Syncing also happens when current modification is too distant
4684 from the stored one (for more information, see
4685 `org-element--cache-merge-changes-threshold').")
4687 (defvar org-element--cache-merge-changes-threshold 200
4688 "Number of characters triggering cache syncing.
4690 The cache mechanism only stores one buffer modification at any
4691 given time. When another change happens, it replaces it with
4692 a change containing both the stored modification and the current
4693 one. This is a trade-off, as merging them prevents another
4694 syncing, but every element between them is then lost.
4696 This variable determines the maximum size, in characters, we
4697 accept to lose in order to avoid syncing the cache.")
4699 (defvar org-element--cache-status nil
4700 "Contains data about cache validity for current buffer.
4702 Value is a vector of seven elements,
4704 [ACTIVEP BEGIN END OFFSET TIMER PREVIOUS-STATE]
4706 ACTIVEP is a boolean non-nil when changes described in the other
4707 slots are valid for current buffer.
4709 BEGIN and END are the beginning and ending position of the area
4710 for which cache cannot be trusted.
4712 OFFSET it an integer specifying the number to add to position of
4713 elements after that area.
4715 TIMER is a timer used to apply these changes to cache when Emacs
4716 is idle.
4718 PREVIOUS-STATE is a symbol referring to the state of the buffer
4719 before a change happens. It is used to know if sensitive
4720 areas (block boundaries, headlines) were modified. It can be set
4721 to nil, `headline' or `other'.")
4723 ;;;###autoload
4724 (defun org-element-cache-reset (&optional all)
4725 "Reset cache in current buffer.
4726 When optional argument ALL is non-nil, reset cache in all Org
4727 buffers. This function will do nothing if
4728 `org-element-use-cache' is nil."
4729 (interactive "P")
4730 (when org-element-use-cache
4731 (dolist (buffer (if all (buffer-list) (list (current-buffer))))
4732 (with-current-buffer buffer
4733 (when (derived-mode-p 'org-mode)
4734 (if (org-bound-and-true-p org-element--cache)
4735 (clrhash org-element--cache)
4736 (org-set-local 'org-element--cache
4737 (make-hash-table :size 5003 :test 'eq)))
4738 (org-set-local 'org-element--cache-status (make-vector 6 nil))
4739 (add-hook 'before-change-functions
4740 'org-element--cache-before-change nil t)
4741 (add-hook 'after-change-functions
4742 'org-element--cache-record-change nil t))))))
4744 (defsubst org-element--cache-pending-changes-p ()
4745 "Non-nil when changes are not integrated in cache yet."
4746 (and org-element--cache-status
4747 (aref org-element--cache-status 0)))
4749 (defsubst org-element--cache-push-change (beg end offset)
4750 "Push change to current buffer staging area.
4751 BEG and END and the beginning and ending position of the
4752 modification area. OFFSET is the size of the change, as an
4753 integer."
4754 (aset org-element--cache-status 1 beg)
4755 (aset org-element--cache-status 2 end)
4756 (aset org-element--cache-status 3 offset)
4757 (let ((timer (aref org-element--cache-status 4)))
4758 (if timer (timer-activate-when-idle timer t)
4759 (aset org-element--cache-status 4
4760 (run-with-idle-timer org-element--cache-sync-idle-time
4762 #'org-element--cache-sync
4763 (current-buffer)))))
4764 (aset org-element--cache-status 0 t))
4766 (defsubst org-element--cache-cancel-changes ()
4767 "Remove any cache change set for current buffer."
4768 (let ((timer (aref org-element--cache-status 4)))
4769 (and timer (cancel-timer timer)))
4770 (aset org-element--cache-status 0 nil))
4772 (defsubst org-element--cache-get-key (element)
4773 "Return expected key for ELEMENT in cache."
4774 (let ((begin (org-element-property :begin element)))
4775 (if (and (memq (org-element-type element) '(item table-row))
4776 (= (org-element-property :contents-begin
4777 (org-element-property :parent element))
4778 begin))
4779 ;; Special key for first item (resp. table-row) in a plain
4780 ;; list (resp. table).
4781 (1+ begin)
4782 begin)))
4784 (defsubst org-element-cache-get (pos &optional type)
4785 "Return data stored at key POS in current buffer cache.
4786 When optional argument TYPE is `element', retrieve the element
4787 starting at POS. When it is `objects', return the list of object
4788 types along with their beginning position within that element.
4789 Otherwise, return the full data. In any case, return nil if no
4790 data is found, or if caching is not allowed."
4791 (when (and org-element-use-cache org-element--cache)
4792 ;; If there are pending changes, first sync them.
4793 (when (org-element--cache-pending-changes-p)
4794 (org-element--cache-sync (current-buffer)))
4795 (let ((data (gethash pos org-element--cache)))
4796 (case type
4797 (element (car data))
4798 (objects (cdr data))
4799 (otherwise data)))))
4801 (defsubst org-element-cache-put (pos data)
4802 "Store data in current buffer's cache, if allowed.
4803 POS is a buffer position, which will be used as a key. DATA is
4804 the value to store. Nothing will be stored if
4805 `org-element-use-cache' is nil. Return DATA in any case."
4806 (if (not org-element-use-cache) data
4807 (unless org-element--cache (org-element-cache-reset))
4808 (puthash pos data org-element--cache)))
4810 (defsubst org-element--cache-shift-positions (element offset)
4811 "Shift ELEMENT properties relative to buffer positions by OFFSET.
4812 Properties containing buffer positions are `:begin', `:end',
4813 `:contents-begin', `:contents-end' and `:structure'. They are
4814 modified by side-effect. Return modified element."
4815 (let ((properties (nth 1 element)))
4816 ;; Shift :structure property for the first plain list only: it is
4817 ;; the only one that really matters and it prevents from shifting
4818 ;; it more than once.
4819 (when (and (eq (org-element-type element) 'plain-list)
4820 (not (eq (org-element-type (plist-get properties :parent))
4821 'item)))
4822 (dolist (item (plist-get properties :structure))
4823 (incf (car item) offset)
4824 (incf (nth 6 item) offset)))
4825 (plist-put properties :begin (+ (plist-get properties :begin) offset))
4826 (plist-put properties :end (+ (plist-get properties :end) offset))
4827 (dolist (key '(:contents-begin :contents-end :post-affiliated))
4828 (let ((value (plist-get properties key)))
4829 (and value (plist-put properties key (+ offset value))))))
4830 element)
4832 (defconst org-element--cache-opening-line
4833 (concat "^[ \t]*\\(?:"
4834 "#\\+BEGIN[:_]" "\\|"
4835 "\\\\begin{[A-Za-z0-9]+\\*?}" "\\|"
4836 ":\\S-+:[ \t]*$"
4837 "\\)")
4838 "Regexp matching an element opening line.
4839 When such a line is modified, modifications may propagate after
4840 modified area. In that situation, every element between that
4841 area and next section is removed from cache.")
4843 (defconst org-element--cache-closing-line
4844 (concat "^[ \t]*\\(?:"
4845 "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
4846 "\\\\end{[A-Za-z0-9]+\\*?}[ \t]*$" "\\|"
4847 ":END:[ \t]*$"
4848 "\\)")
4849 "Regexp matching an element closing line.
4850 When such a line is modified, modifications may propagate before
4851 modified area. In that situation, every element between that
4852 area and previous section is removed from cache.")
4854 (defun org-element--cache-before-change (beg end)
4855 "Request extension of area going to be modified if needed.
4856 BEG and END are the beginning and end of the range of changed
4857 text. See `before-change-functions' for more information."
4858 (let ((inhibit-quit t))
4859 (org-with-wide-buffer
4860 (goto-char beg)
4861 (beginning-of-line)
4862 (let ((top (point))
4863 (bottom (save-excursion (goto-char end) (line-end-position)))
4864 (sensitive-re
4865 ;; A sensitive line is a headline or a block (or drawer,
4866 ;; or latex-environment) boundary. Inserting one can
4867 ;; modify buffer drastically both above and below that
4868 ;; line, possibly making cache invalid. Therefore, we
4869 ;; need to pay special attention to changes happening to
4870 ;; them.
4871 (concat
4872 "\\(" (org-with-limited-levels org-outline-regexp-bol) "\\)" "\\|"
4873 org-element--cache-closing-line "\\|"
4874 org-element--cache-opening-line)))
4875 (save-match-data
4876 (aset org-element--cache-status 5
4877 (cond ((not (re-search-forward sensitive-re bottom t)) nil)
4878 ((and (match-beginning 1)
4879 (progn (goto-char bottom)
4880 (or (not (re-search-backward sensitive-re
4881 (match-end 1) t))
4882 (match-beginning 1))))
4883 'headline)
4884 (t 'other))))))))
4886 (defun org-element--cache-record-change (beg end pre)
4887 "Update buffer modifications for current buffer.
4889 BEG and END are the beginning and end of the range of changed
4890 text, and the length in bytes of the pre-change text replaced by
4891 that range. See `after-change-functions' for more information.
4893 If there are already pending changes, try to merge them into
4894 a bigger change record. If that's not possible, the function
4895 will first synchronize cache with previous change and store the
4896 new one."
4897 (let ((inhibit-quit t))
4898 (when (and org-element-use-cache org-element--cache)
4899 (org-with-wide-buffer
4900 (goto-char beg)
4901 (beginning-of-line)
4902 (let ((top (point))
4903 (bottom (save-excursion (goto-char end) (line-end-position))))
4904 (org-with-limited-levels
4905 (save-match-data
4906 ;; Determine if modified area needs to be extended,
4907 ;; according to both previous and current state. We make
4908 ;; a special case for headline editing: if a headline is
4909 ;; modified but not removed, do not extend.
4910 (when (let ((previous-state (aref org-element--cache-status 5))
4911 (sensitive-re
4912 (concat "\\(" org-outline-regexp-bol "\\)" "\\|"
4913 org-element--cache-closing-line "\\|"
4914 org-element--cache-opening-line)))
4915 (cond ((eq previous-state 'other))
4916 ((not (re-search-forward sensitive-re bottom t))
4917 (eq previous-state 'headline))
4918 ((match-beginning 1)
4919 (or (not (eq previous-state 'headline))
4920 (and (progn (goto-char bottom)
4921 (re-search-backward
4922 sensitive-re (match-end 1) t))
4923 (not (match-beginning 1)))))
4924 (t)))
4925 ;; Effectively extend modified area.
4926 (setq top (progn (goto-char top)
4927 (outline-previous-heading)
4928 ;; Headline above is inclusive.
4929 (point)))
4930 (setq bottom (progn (goto-char bottom)
4931 (outline-next-heading)
4932 ;; Headline below is exclusive.
4933 (if (eobp) (point) (1- (point))))))))
4934 ;; Store changes.
4935 (let ((offset (- end beg pre)))
4936 (if (not (org-element--cache-pending-changes-p))
4937 ;; No pending changes. Store the new ones.
4938 (org-element--cache-push-change top (- bottom offset) offset)
4939 (let* ((current-start (aref org-element--cache-status 1))
4940 (current-end (+ (aref org-element--cache-status 2)
4941 (aref org-element--cache-status 3)))
4942 (gap (max (- beg current-end) (- current-start end))))
4943 (if (> gap org-element--cache-merge-changes-threshold)
4944 ;; If we cannot merge two change sets (i.e. they
4945 ;; modify distinct buffer parts) first apply current
4946 ;; change set and store new one. This way, there is
4947 ;; never more than one pending change set, which
4948 ;; avoids handling costly merges.
4949 (progn (org-element--cache-sync (current-buffer))
4950 (org-element--cache-push-change
4951 top (- bottom offset) offset))
4952 ;; Change sets can be merged. We can expand the area
4953 ;; that requires an update, and postpone the sync.
4954 (timer-activate-when-idle (aref org-element--cache-status 4) t)
4955 (aset org-element--cache-status 0 t)
4956 (aset org-element--cache-status 1 (min top current-start))
4957 (aset org-element--cache-status 2
4958 (- (max current-end bottom) offset))
4959 (incf (aref org-element--cache-status 3) offset))))))))))
4961 (defun org-element--cache-sync (buffer)
4962 "Synchronize cache with recent modification in BUFFER.
4963 Elements ending before modification area are kept in cache.
4964 Elements starting after modification area have their position
4965 shifted by the size of the modification. Every other element is
4966 removed from the cache."
4967 (when (buffer-live-p buffer)
4968 (with-current-buffer buffer
4969 (when (org-element--cache-pending-changes-p)
4970 (let ((inhibit-quit t)
4971 (beg (aref org-element--cache-status 1))
4972 (end (aref org-element--cache-status 2))
4973 (offset (aref org-element--cache-status 3))
4974 new-keys)
4975 (maphash
4976 #'(lambda (key value)
4977 (cond
4978 ((memq key new-keys))
4979 ((> key end)
4980 ;; Shift every element starting after END by OFFSET.
4981 ;; We also need to shift keys, since they refer to
4982 ;; buffer positions.
4984 ;; Upon shifting a key a conflict can occur if the
4985 ;; shifted key also refers to some element in the
4986 ;; cache. In this case, we temporarily associate
4987 ;; both elements, as a cons cell, to the shifted key,
4988 ;; following the pattern (SHIFTED . CURRENT).
4990 ;; Such a conflict can only occur if shifted key hash
4991 ;; hasn't been processed by `maphash' yet.
4992 (unless (zerop offset)
4993 (let* ((conflictp (consp (caar value)))
4994 (value-to-shift (if conflictp (cdr value) value)))
4995 ;; Shift element part.
4996 (org-element--cache-shift-positions (car value-to-shift) offset)
4997 ;; Shift objects part.
4998 (dolist (object-data (cdr value-to-shift))
4999 (incf (car object-data) offset)
5000 (dolist (successor (nth 1 object-data))
5001 (incf (cdr successor) offset))
5002 (dolist (object (cddr object-data))
5003 (org-element--cache-shift-positions object offset)))
5004 ;; Shift key-value pair.
5005 (let* ((new-key (+ key offset))
5006 (new-value (gethash new-key org-element--cache)))
5007 ;; Put new value to shifted key.
5009 ;; If one already exists, do not overwrite it:
5010 ;; store it as the car of a cons cell instead,
5011 ;; and handle it when `maphash' reaches
5012 ;; NEW-KEY.
5014 ;; If there is no element stored at NEW-KEY or
5015 ;; if NEW-KEY is going to be removed anyway
5016 ;; (i.e., it is before END), just store new
5017 ;; value there and make sure it will not be
5018 ;; processed again by storing NEW-KEY in
5019 ;; NEW-KEYS.
5020 (puthash new-key
5021 (if (and new-value (> new-key end))
5022 (cons value-to-shift new-value)
5023 (push new-key new-keys)
5024 value-to-shift)
5025 org-element--cache)
5026 ;; If current value contains two elements, car
5027 ;; should be the new value, since cdr has been
5028 ;; shifted already.
5029 (if conflictp
5030 (puthash key (car value) org-element--cache)
5031 (remhash key org-element--cache))))))
5032 ;; Remove every element between BEG and END, since
5033 ;; this is where changes happened.
5034 ((>= key beg) (remhash key org-element--cache))
5035 ;; Preserve any element ending before BEG. If it
5036 ;; overlaps the BEG-END area, remove it.
5038 (let ((element (car value)))
5039 (if (>= (org-element-property :end element) beg)
5040 (remhash key org-element--cache)
5041 ;; Special case: footnote definitions and plain
5042 ;; lists can end with blank lines. Modifying
5043 ;; those can also alter last element inside. We
5044 ;; must therefore remove them from cache.
5045 (let ((parent (org-element-property :parent element)))
5046 (when (and parent (eq (org-element-type parent) 'item))
5047 (setq parent (org-element-property :parent parent)))
5048 (when (and (memq (org-element-type parent)
5049 '(footnote-definition plain-list))
5050 (>= (org-element-property :end parent) beg)
5051 (= (org-element-property :contents-end parent)
5052 (org-element-property :end element)))
5053 (remhash key org-element--cache))))))))
5054 org-element--cache)
5055 ;; Signal cache as up-to-date.
5056 (org-element--cache-cancel-changes))))))
5058 ;;;###autoload
5059 (defun org-element-at-point (&optional keep-trail)
5060 "Determine closest element around point.
5062 Return value is a list like (TYPE PROPS) where TYPE is the type
5063 of the element and PROPS a plist of properties associated to the
5064 element.
5066 Possible types are defined in `org-element-all-elements'.
5067 Properties depend on element or object type, but always include
5068 `:begin', `:end', `:parent' and `:post-blank' properties.
5070 As a special case, if point is at the very beginning of a list or
5071 sub-list, returned element will be that list instead of the first
5072 item. In the same way, if point is at the beginning of the first
5073 row of a table, returned element will be the table instead of the
5074 first row.
5076 If optional argument KEEP-TRAIL is non-nil, the function returns
5077 a list of elements leading to element at point. The list's CAR
5078 is always the element at point. The following positions contain
5079 element's siblings, then parents, siblings of parents, until the
5080 first element of current section."
5081 (org-with-wide-buffer
5082 ;; If at a headline, parse it. It is the sole element that
5083 ;; doesn't require to know about context. Be sure to disallow
5084 ;; secondary string parsing, though.
5085 (if (org-with-limited-levels (org-at-heading-p))
5086 (progn
5087 (beginning-of-line)
5088 (let ((headline
5089 (or (org-element-cache-get (point) 'element)
5090 (car (org-element-cache-put
5091 (point)
5092 (list (org-element-headline-parser
5093 (point-max) t)))))))
5094 (if keep-trail (list headline) headline)))
5095 ;; Otherwise move at the beginning of the section containing
5096 ;; point.
5097 (catch 'exit
5098 (let ((origin (point)))
5099 (if (not (org-with-limited-levels (outline-previous-heading)))
5100 ;; In empty lines at buffer's beginning, return nil.
5101 (progn (goto-char (point-min))
5102 (org-skip-whitespace)
5103 (when (or (eobp) (> (line-beginning-position) origin))
5104 (throw 'exit nil)))
5105 (forward-line)
5106 (org-skip-whitespace)
5107 (when (or (eobp) (> (line-beginning-position) origin))
5108 ;; In blank lines just after the headline, point still
5109 ;; belongs to the headline.
5110 (throw 'exit
5111 (progn
5112 (skip-chars-backward " \r\t\n")
5113 (beginning-of-line)
5114 (let ((headline
5115 (or (org-element-cache-get (point) 'element)
5116 (car (org-element-cache-put
5117 (point)
5118 (list (org-element-headline-parser
5119 (point-max) t)))))))
5120 (if keep-trail (list headline) headline))))))
5121 (beginning-of-line)
5122 (let ((end (save-excursion
5123 (org-with-limited-levels (outline-next-heading)) (point)))
5124 element type special-flag trail struct parent)
5125 ;; Parse successively each element, skipping those ending
5126 ;; before original position.
5127 (while t
5128 (setq element
5129 (let* ((pos (if (and (memq special-flag '(item table-row))
5130 (memq type '(plain-list table)))
5131 ;; First item (resp. row) in plain
5132 ;; list (resp. table) gets
5133 ;; a special key in cache.
5134 (1+ (point))
5135 (point)))
5136 (cached (org-element-cache-get pos 'element)))
5137 (cond
5138 ((not cached)
5139 (let ((element (org-element--current-element
5140 end 'element special-flag struct)))
5141 (when (derived-mode-p 'org-mode)
5142 (org-element-cache-put pos (cons element nil)))
5143 element))
5144 ;; When changes happened in the middle of a list,
5145 ;; its structure ends up being invalid.
5146 ;; Therefore, we make sure to use a valid one.
5147 ((and struct (memq (car cached) '(item plain-list)))
5148 (org-element-put-property cached :structure struct))
5149 (t cached))))
5150 (setq type (org-element-type element))
5151 (org-element-put-property element :parent parent)
5152 (when keep-trail (push element trail))
5153 (cond
5154 ;; 1. Skip any element ending before point. Also skip
5155 ;; element ending at point when we're sure that
5156 ;; another element has started.
5157 ((let ((elem-end (org-element-property :end element)))
5158 (when (or (< elem-end origin)
5159 (and (= elem-end origin) (/= elem-end end)))
5160 (goto-char elem-end))))
5161 ;; 2. An element containing point is always the element at
5162 ;; point.
5163 ((not (memq type org-element-greater-elements))
5164 (throw 'exit (if keep-trail trail element)))
5165 ;; 3. At any other greater element type, if point is
5166 ;; within contents, move into it.
5168 (let ((cbeg (org-element-property :contents-begin element))
5169 (cend (org-element-property :contents-end element)))
5170 (if (or (not cbeg) (not cend) (> cbeg origin) (< cend origin)
5171 ;; Create an anchor for tables and plain
5172 ;; lists: when point is at the very beginning
5173 ;; of these elements, ignoring affiliated
5174 ;; keywords, target them instead of their
5175 ;; contents.
5176 (and (= cbeg origin) (memq type '(plain-list table)))
5177 ;; When point is at contents end, do not move
5178 ;; into elements with an explicit ending, but
5179 ;; return that element instead.
5180 (and (= cend origin)
5181 (or (memq type
5182 '(center-block
5183 drawer dynamic-block inlinetask
5184 property-drawer quote-block
5185 special-block))
5186 ;; Corner case: if a list ends at
5187 ;; the end of a buffer without
5188 ;; a final new line, return last
5189 ;; element in last item instead.
5190 (and (memq type '(item plain-list))
5191 (progn (goto-char cend)
5192 (or (bolp) (not (eobp))))))))
5193 (throw 'exit (if keep-trail trail element))
5194 (setq parent element)
5195 (case type
5196 (plain-list
5197 (setq special-flag 'item
5198 struct (org-element-property :structure element)))
5199 (item (setq special-flag nil))
5200 (property-drawer
5201 (setq special-flag 'node-property struct nil))
5202 (table (setq special-flag 'table-row struct nil))
5203 (otherwise (setq special-flag nil struct nil)))
5204 (setq end cend)
5205 (goto-char cbeg))))))))))))
5207 ;;;###autoload
5208 (defun org-element-context (&optional element)
5209 "Return closest element or object around point.
5211 Return value is a list like (TYPE PROPS) where TYPE is the type
5212 of the element or object and PROPS a plist of properties
5213 associated to it.
5215 Possible types are defined in `org-element-all-elements' and
5216 `org-element-all-objects'. Properties depend on element or
5217 object type, but always include `:begin', `:end', `:parent' and
5218 `:post-blank'.
5220 Optional argument ELEMENT, when non-nil, is the closest element
5221 containing point, as returned by `org-element-at-point'.
5222 Providing it allows for quicker computation."
5223 (catch 'objects-forbidden
5224 (org-with-wide-buffer
5225 (let* ((origin (point))
5226 (element (or element (org-element-at-point)))
5227 (type (org-element-type element)))
5228 ;; If point is inside an element containing objects or
5229 ;; a secondary string, narrow buffer to the container and
5230 ;; proceed with parsing. Otherwise, return ELEMENT.
5231 (cond
5232 ;; At a parsed affiliated keyword, check if we're inside main
5233 ;; or dual value.
5234 ((let ((post (org-element-property :post-affiliated element)))
5235 (and post (< origin post)))
5236 (beginning-of-line)
5237 (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
5238 (cond
5239 ((not (member-ignore-case (match-string 1)
5240 org-element-parsed-keywords))
5241 (throw 'objects-forbidden element))
5242 ((< (match-end 0) origin)
5243 (narrow-to-region (match-end 0) (line-end-position)))
5244 ((and (match-beginning 2)
5245 (>= origin (match-beginning 2))
5246 (< origin (match-end 2)))
5247 (narrow-to-region (match-beginning 2) (match-end 2)))
5248 (t (throw 'objects-forbidden element)))
5249 ;; Also change type to retrieve correct restrictions.
5250 (setq type 'keyword))
5251 ;; At an item, objects can only be located within tag, if any.
5252 ((eq type 'item)
5253 (let ((tag (org-element-property :tag element)))
5254 (if (not tag) (throw 'objects-forbidden element)
5255 (beginning-of-line)
5256 (search-forward tag (line-end-position))
5257 (goto-char (match-beginning 0))
5258 (if (and (>= origin (point)) (< origin (match-end 0)))
5259 (narrow-to-region (point) (match-end 0))
5260 (throw 'objects-forbidden element)))))
5261 ;; At an headline or inlinetask, objects are in title.
5262 ((memq type '(headline inlinetask))
5263 (goto-char (org-element-property :begin element))
5264 (skip-chars-forward "* ")
5265 (if (and (>= origin (point)) (< origin (line-end-position)))
5266 (narrow-to-region (point) (line-end-position))
5267 (throw 'objects-forbidden element)))
5268 ;; At a paragraph, a table-row or a verse block, objects are
5269 ;; located within their contents.
5270 ((memq type '(paragraph table-row verse-block))
5271 (let ((cbeg (org-element-property :contents-begin element))
5272 (cend (org-element-property :contents-end element)))
5273 ;; CBEG is nil for table rules.
5274 (if (and cbeg cend (>= origin cbeg) (< origin cend))
5275 (narrow-to-region cbeg cend)
5276 (throw 'objects-forbidden element))))
5277 ;; At a parsed keyword, objects are located within value.
5278 ((eq type 'keyword)
5279 (if (not (member (org-element-property :key element)
5280 org-element-document-properties))
5281 (throw 'objects-forbidden element)
5282 (beginning-of-line)
5283 (search-forward ":")
5284 (if (and (>= origin (point)) (< origin (line-end-position)))
5285 (narrow-to-region (point) (line-end-position))
5286 (throw 'objects-forbidden element))))
5287 ;; All other locations cannot contain objects: bail out.
5288 (t (throw 'objects-forbidden element)))
5289 (goto-char (point-min))
5290 (let* ((restriction (org-element-restriction type))
5291 (parent element)
5292 (candidates 'initial)
5293 (cache-key (org-element--cache-get-key element))
5294 (cache (org-element-cache-get cache-key 'objects))
5295 objects-data next update-cache-flag)
5296 (prog1
5297 (catch 'exit
5298 (while t
5299 ;; Get list of next object candidates in CANDIDATES.
5300 ;; When entering for the first time PARENT, grab it
5301 ;; from cache, if available, or compute it. Then,
5302 ;; for each subsequent iteration in PARENT, always
5303 ;; compute it since we're beyond cache anyway.
5304 (when (and (not next) org-element-use-cache)
5305 (let ((data (assq (point) cache)))
5306 (if data (setq candidates (nth 1 (setq objects-data data)))
5307 (push (setq objects-data (list (point) 'initial))
5308 cache))))
5309 (when (or next (eq 'initial candidates))
5310 (setq candidates
5311 (org-element--get-next-object-candidates
5312 restriction candidates))
5313 (when org-element-use-cache
5314 (setcar (cdr objects-data) candidates)
5315 (or update-cache-flag (setq update-cache-flag t))))
5316 ;; Compare ORIGIN with next object starting position,
5317 ;; if any.
5319 ;; If ORIGIN is lesser or if there is no object
5320 ;; following, look for a previous object that might
5321 ;; contain it in cache. If there is no cache, we
5322 ;; didn't miss any object so simply return PARENT.
5324 ;; If ORIGIN is greater or equal, parse next
5325 ;; candidate for further processing.
5326 (let ((closest
5327 (and candidates
5328 (rassq (apply #'min (mapcar #'cdr candidates))
5329 candidates))))
5330 (if (or (not closest) (> (cdr closest) origin))
5331 (catch 'found
5332 (dolist (obj (cddr objects-data) (throw 'exit parent))
5333 (when (<= (org-element-property :begin obj) origin)
5334 (if (<= (org-element-property :end obj) origin)
5335 ;; Object ends before ORIGIN and we
5336 ;; know next one in cache starts
5337 ;; after it: bail out.
5338 (throw 'exit parent)
5339 (throw 'found (setq next obj))))))
5340 (goto-char (cdr closest))
5341 (setq next
5342 (funcall (intern (format "org-element-%s-parser"
5343 (car closest)))))
5344 (when org-element-use-cache
5345 (push next (cddr objects-data))
5346 (or update-cache-flag (setq update-cache-flag t)))))
5347 ;; Process NEXT to know if we need to skip it, return
5348 ;; it or move into it.
5349 (let ((cbeg (org-element-property :contents-begin next))
5350 (cend (org-element-property :contents-end next))
5351 (obj-end (org-element-property :end next)))
5352 (cond
5353 ;; ORIGIN is after NEXT, so skip it.
5354 ((<= obj-end origin) (goto-char obj-end))
5355 ;; ORIGIN is within a non-recursive next or
5356 ;; at an object boundaries: Return that object.
5357 ((or (not cbeg) (< origin cbeg) (>= origin cend))
5358 (throw 'exit
5359 (org-element-put-property next :parent parent)))
5360 ;; Otherwise, move into NEXT and reset flags as we
5361 ;; shift parent.
5362 (t (goto-char cbeg)
5363 (narrow-to-region (point) cend)
5364 (org-element-put-property next :parent parent)
5365 (setq parent next
5366 restriction (org-element-restriction next)
5367 next nil
5368 objects-data nil
5369 candidates 'initial))))))
5370 ;; Update cache if required.
5371 (when (and update-cache-flag (derived-mode-p 'org-mode))
5372 (org-element-cache-put cache-key (cons element cache)))))))))
5374 (defun org-element-nested-p (elem-A elem-B)
5375 "Non-nil when elements ELEM-A and ELEM-B are nested."
5376 (let ((beg-A (org-element-property :begin elem-A))
5377 (beg-B (org-element-property :begin elem-B))
5378 (end-A (org-element-property :end elem-A))
5379 (end-B (org-element-property :end elem-B)))
5380 (or (and (>= beg-A beg-B) (<= end-A end-B))
5381 (and (>= beg-B beg-A) (<= end-B end-A)))))
5383 (defun org-element-swap-A-B (elem-A elem-B)
5384 "Swap elements ELEM-A and ELEM-B.
5385 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
5386 end of ELEM-A."
5387 (goto-char (org-element-property :begin elem-A))
5388 ;; There are two special cases when an element doesn't start at bol:
5389 ;; the first paragraph in an item or in a footnote definition.
5390 (let ((specialp (not (bolp))))
5391 ;; Only a paragraph without any affiliated keyword can be moved at
5392 ;; ELEM-A position in such a situation. Note that the case of
5393 ;; a footnote definition is impossible: it cannot contain two
5394 ;; paragraphs in a row because it cannot contain a blank line.
5395 (if (and specialp
5396 (or (not (eq (org-element-type elem-B) 'paragraph))
5397 (/= (org-element-property :begin elem-B)
5398 (org-element-property :contents-begin elem-B))))
5399 (error "Cannot swap elements"))
5400 ;; In a special situation, ELEM-A will have no indentation. We'll
5401 ;; give it ELEM-B's (which will in, in turn, have no indentation).
5402 (let* ((ind-B (when specialp
5403 (goto-char (org-element-property :begin elem-B))
5404 (org-get-indentation)))
5405 (beg-A (org-element-property :begin elem-A))
5406 (end-A (save-excursion
5407 (goto-char (org-element-property :end elem-A))
5408 (skip-chars-backward " \r\t\n")
5409 (point-at-eol)))
5410 (beg-B (org-element-property :begin elem-B))
5411 (end-B (save-excursion
5412 (goto-char (org-element-property :end elem-B))
5413 (skip-chars-backward " \r\t\n")
5414 (point-at-eol)))
5415 ;; Store overlays responsible for visibility status. We
5416 ;; also need to store their boundaries as they will be
5417 ;; removed from buffer.
5418 (overlays
5419 (cons
5420 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5421 (overlays-in beg-A end-A))
5422 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
5423 (overlays-in beg-B end-B))))
5424 ;; Get contents.
5425 (body-A (buffer-substring beg-A end-A))
5426 (body-B (delete-and-extract-region beg-B end-B)))
5427 (goto-char beg-B)
5428 (when specialp
5429 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
5430 (org-indent-to-column ind-B))
5431 (insert body-A)
5432 ;; Restore ex ELEM-A overlays.
5433 (let ((offset (- beg-B beg-A)))
5434 (mapc (lambda (ov)
5435 (move-overlay
5436 (car ov) (+ (nth 1 ov) offset) (+ (nth 2 ov) offset)))
5437 (car overlays))
5438 (goto-char beg-A)
5439 (delete-region beg-A end-A)
5440 (insert body-B)
5441 ;; Restore ex ELEM-B overlays.
5442 (mapc (lambda (ov)
5443 (move-overlay
5444 (car ov) (- (nth 1 ov) offset) (- (nth 2 ov) offset)))
5445 (cdr overlays)))
5446 (goto-char (org-element-property :end elem-B)))))
5448 (defun org-element-remove-indentation (s &optional n)
5449 "Remove maximum common indentation in string S and return it.
5450 When optional argument N is a positive integer, remove exactly
5451 that much characters from indentation, if possible, or return
5452 S as-is otherwise. Unlike to `org-remove-indentation', this
5453 function doesn't call `untabify' on S."
5454 (catch 'exit
5455 (with-temp-buffer
5456 (insert s)
5457 (goto-char (point-min))
5458 ;; Find maximum common indentation, if not specified.
5459 (setq n (or n
5460 (let ((min-ind (point-max)))
5461 (save-excursion
5462 (while (re-search-forward "^[ \t]*\\S-" nil t)
5463 (let ((ind (1- (current-column))))
5464 (if (zerop ind) (throw 'exit s)
5465 (setq min-ind (min min-ind ind))))))
5466 min-ind)))
5467 (if (zerop n) s
5468 ;; Remove exactly N indentation, but give up if not possible.
5469 (while (not (eobp))
5470 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
5471 (cond ((eolp) (delete-region (line-beginning-position) (point)))
5472 ((< ind n) (throw 'exit s))
5473 (t (org-indent-line-to (- ind n))))
5474 (forward-line)))
5475 (buffer-string)))))
5478 (provide 'org-element)
5480 ;; Local variables:
5481 ;; generated-autoload-file: "org-loaddefs.el"
5482 ;; End:
5484 ;;; org-element.el ends here