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