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