org-element: Verse blocks now contain objects
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-element.el
blobc9be73168902ca28a0cf59231dce6e824f00bcd4
1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; This file is not part of GNU Emacs.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; Elements are related to the structure of the document. Indeed, all
29 ;; elements are a cover for the document: each position within belongs
30 ;; to at least one element.
32 ;; An element always starts and ends at the beginning of a line. With
33 ;; a few exceptions (namely `headline', `item', `section', `keyword',
34 ;; `babel-call' and `property-drawer' types), it can also accept
35 ;; a fixed set of keywords as attributes. Those are called
36 ;; "affiliated keywords" to distinguish them from other keywords,
37 ;; which are full-fledged elements.
39 ;; Element containing other elements (and only elements) are called
40 ;; greater elements. Concerned types are: `center-block', `drawer',
41 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
42 ;; `item', `plain-list', `quote-block', `section' and `special-block'.
44 ;; Other element types are: `babel-call', `comment', `comment-block',
45 ;; `example-block', `export-block', `fixed-width', `horizontal-rule',
46 ;; `keyword', `latex-environment', `paragraph', `property-drawer',
47 ;; `quote-section', `src-block', `table', `table-cell', `table-row'
48 ;; and `verse-blocks'. Among them, `paragraph', `table-cell' and
49 ;; `verse-block' types can contain Org objects and plain text.
51 ;; Objects are related to document's contents. Some of them are
52 ;; recursive. Associated types are of the following: `emphasis',
53 ;; `entity', `export-snippet', `footnote-reference',
54 ;; `inline-babel-call', `inline-src-block', `latex-fragment',
55 ;; `line-break', `link', `macro', `radio-target', `statistics-cookie',
56 ;; `subscript', `superscript', `table-cell', `target', `time-stamp'
57 ;; and `verbatim'.
59 ;; Some elements also have special properties whose value can hold
60 ;; objects themselves (i.e. an item tag or an headline name). Such
61 ;; values are called "secondary strings". Any object belongs to
62 ;; either an element or a secondary string.
64 ;; Notwithstanding affiliated keywords, each greater element, element
65 ;; and object has a fixed set of properties attached to it. Among
66 ;; them, three are shared by all types: `:begin' and `:end', which
67 ;; refer to the beginning and ending buffer positions of the
68 ;; considered element or object, and `:post-blank', which holds the
69 ;; number of blank lines, or white spaces, at its end. Greater
70 ;; elements and elements containing objects will also have
71 ;; `:contents-begin' and `:contents-end' properties to delimit
72 ;; contents.
74 ;; Lisp-wise, an element or an object can be represented as a list.
75 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
76 ;; TYPE is a symbol describing the Org element or object.
77 ;; PROPERTIES is the property list attached to it. See docstring of
78 ;; appropriate parsing function to get an exhaustive
79 ;; list.
80 ;; CONTENTS is a list of elements, objects or raw strings contained
81 ;; in the current element or object, when applicable.
83 ;; An Org buffer is a nested list of such elements and objects, whose
84 ;; type is `org-data' and properties is nil.
86 ;; The first part of this file implements a parser and an interpreter
87 ;; for each type of Org syntax.
89 ;; The next two parts introduce four accessors and a function
90 ;; retrieving the element starting at point (respectively
91 ;; `org-element-type', `org-element-property', `org-element-contents',
92 ;; `org-element-restriction' and `org-element-current-element').
94 ;; The following part creates a fully recursive buffer parser. It
95 ;; also provides a tool to map a function to elements or objects
96 ;; matching some criteria in the parse tree. Functions of interest
97 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
98 ;; extent, `org-element-parse-secondary-string'.
100 ;; The penultimate part is the cradle of an interpreter for the
101 ;; obtained parse tree: `org-element-interpret-data' (and its
102 ;; relative, `org-element-interpret-secondary').
104 ;; The library ends by furnishing a set of interactive tools for
105 ;; element's navigation and manipulation, mostly based on
106 ;; `org-element-at-point' function.
109 ;;; Code:
111 (eval-when-compile (require 'cl))
112 (require 'org)
113 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
116 ;;; Greater elements
118 ;; For each greater element type, we define a parser and an
119 ;; interpreter.
121 ;; A parser returns the element or object as the list described above.
122 ;; Most of them accepts no argument. Though, exceptions exist. Hence
123 ;; every element containing a secondary string (see
124 ;; `org-element-secondary-value-alist') will accept an optional
125 ;; argument to toggle parsing of that secondary string. Moreover,
126 ;; `item' parser requires current list's structure as its first
127 ;; element.
129 ;; An interpreter accepts two arguments: the list representation of
130 ;; the element or object, and its contents. The latter may be nil,
131 ;; depending on the element or object considered. It returns the
132 ;; appropriate Org syntax, as a string.
134 ;; Parsing functions must follow the naming convention:
135 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
136 ;; defined in `org-element-greater-elements'.
138 ;; Similarly, interpreting functions must follow the naming
139 ;; convention: org-element-TYPE-interpreter.
141 ;; With the exception of `headline' and `item' types, greater elements
142 ;; cannot contain other greater elements of their own type.
144 ;; Beside implementing a parser and an interpreter, adding a new
145 ;; greater element requires to tweak `org-element-current-element'.
146 ;; Moreover, the newly defined type must be added to both
147 ;; `org-element-all-elements' and `org-element-greater-elements'.
150 ;;;; Center Block
152 (defun org-element-center-block-parser ()
153 "Parse a center block.
155 Return a list whose car is `center-block' and cdr is a plist
156 containing `:begin', `:end', `:hiddenp', `:contents-begin',
157 `:contents-end' and `:post-blank' keywords.
159 Assume point is at beginning or end of the block."
160 (save-excursion
161 (let* ((case-fold-search t)
162 (keywords (progn
163 (end-of-line)
164 (re-search-backward
165 (concat "^[ \t]*#\\+BEGIN_CENTER") nil t)
166 (org-element-collect-affiliated-keywords)))
167 (begin (car keywords))
168 (contents-begin (progn (forward-line) (point)))
169 (hidden (org-truely-invisible-p))
170 (contents-end (progn (re-search-forward
171 (concat "^[ \t]*#\\+END_CENTER") nil t)
172 (point-at-bol)))
173 (pos-before-blank (progn (forward-line) (point)))
174 (end (progn (org-skip-whitespace)
175 (if (eobp) (point) (point-at-bol)))))
176 `(center-block
177 (:begin ,begin
178 :end ,end
179 :hiddenp ,hidden
180 :contents-begin ,contents-begin
181 :contents-end ,contents-end
182 :post-blank ,(count-lines pos-before-blank end)
183 ,@(cadr keywords))))))
185 (defun org-element-center-block-interpreter (center-block contents)
186 "Interpret CENTER-BLOCK element as Org syntax.
187 CONTENTS is the contents of the element."
188 (format "#+begin_center\n%s#+end_center" contents))
191 ;;;; Drawer
193 (defun org-element-drawer-parser ()
194 "Parse a drawer.
196 Return a list whose car is `drawer' and cdr is a plist containing
197 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
198 `:contents-end' and `:post-blank' keywords.
200 Assume point is at beginning of drawer."
201 (save-excursion
202 (let* ((case-fold-search t)
203 (name (progn (looking-at org-drawer-regexp)
204 (org-match-string-no-properties 1)))
205 (keywords (org-element-collect-affiliated-keywords))
206 (begin (car keywords))
207 (contents-begin (progn (forward-line) (point)))
208 (hidden (org-truely-invisible-p))
209 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
210 (point-at-bol)))
211 (pos-before-blank (progn (forward-line) (point)))
212 (end (progn (org-skip-whitespace)
213 (if (eobp) (point) (point-at-bol)))))
214 `(drawer
215 (:begin ,begin
216 :end ,end
217 :drawer-name ,name
218 :hiddenp ,hidden
219 :contents-begin ,contents-begin
220 :contents-end ,contents-end
221 :post-blank ,(count-lines pos-before-blank end)
222 ,@(cadr keywords))))))
224 (defun org-element-drawer-interpreter (drawer contents)
225 "Interpret DRAWER element as Org syntax.
226 CONTENTS is the contents of the element."
227 (format ":%s:\n%s:END:"
228 (org-element-property :drawer-name drawer)
229 contents))
232 ;;;; Dynamic Block
234 (defun org-element-dynamic-block-parser ()
235 "Parse a dynamic block.
237 Return a list whose car is `dynamic-block' and cdr is a plist
238 containing `:block-name', `:begin', `:end', `:hiddenp',
239 `:contents-begin', `:contents-end', `:arguments' and
240 `:post-blank' keywords.
242 Assume point is at beginning of dynamic block."
243 (save-excursion
244 (let* ((case-fold-search t)
245 (name (progn (looking-at org-dblock-start-re)
246 (org-match-string-no-properties 1)))
247 (arguments (org-match-string-no-properties 3))
248 (keywords (org-element-collect-affiliated-keywords))
249 (begin (car keywords))
250 (contents-begin (progn (forward-line) (point)))
251 (hidden (org-truely-invisible-p))
252 (contents-end (progn (re-search-forward org-dblock-end-re nil t)
253 (point-at-bol)))
254 (pos-before-blank (progn (forward-line) (point)))
255 (end (progn (org-skip-whitespace)
256 (if (eobp) (point) (point-at-bol)))))
257 (list 'dynamic-block
258 `(:begin ,begin
259 :end ,end
260 :block-name ,name
261 :arguments ,arguments
262 :hiddenp ,hidden
263 :contents-begin ,contents-begin
264 :contents-end ,contents-end
265 :post-blank ,(count-lines pos-before-blank end)
266 ,@(cadr keywords))))))
268 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
269 "Interpret DYNAMIC-BLOCK element as Org syntax.
270 CONTENTS is the contents of the element."
271 (format "#+BEGIN: %s%s\n%s#+END:"
272 (org-element-property :block-name dynamic-block)
273 (let ((args (org-element-property :arguments dynamic-block)))
274 (and arg (concat " " args)))
275 contents))
278 ;;;; Footnote Definition
280 (defun org-element-footnote-definition-parser ()
281 "Parse a footnote definition.
283 Return a list whose CAR is `footnote-definition' and CDR is
284 a plist containing `:label', `:begin' `:end', `:contents-begin',
285 `:contents-end' and `:post-blank' keywords.
287 Assume point is at the beginning of the footnote definition."
288 (save-excursion
289 (looking-at org-footnote-definition-re)
290 (let* ((label (org-match-string-no-properties 1))
291 (keywords (org-element-collect-affiliated-keywords))
292 (begin (car keywords))
293 (contents-begin (progn (search-forward "]")
294 (org-skip-whitespace)
295 (point)))
296 (contents-end (if (progn
297 (end-of-line)
298 (re-search-forward
299 (concat org-outline-regexp-bol "\\|"
300 org-footnote-definition-re "\\|"
301 "^[ \t]*$") nil t))
302 (match-beginning 0)
303 (point-max)))
304 (end (progn (org-skip-whitespace)
305 (if (eobp) (point) (point-at-bol)))))
306 `(footnote-definition
307 (:label ,label
308 :begin ,begin
309 :end ,end
310 :contents-begin ,contents-begin
311 :contents-end ,contents-end
312 :post-blank ,(count-lines contents-end end)
313 ,@(cadr keywords))))))
315 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
316 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
317 CONTENTS is the contents of the footnote-definition."
318 (concat (format "[%s]" (org-element-property :label footnote-definition))
320 contents))
323 ;;;; Headline
325 (defun org-element-headline-parser (&optional raw-secondary-p)
326 "Parse an headline.
328 Return a list whose car is `headline' and cdr is a plist
329 containing `:raw-value', `:title', `:begin', `:end',
330 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
331 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
332 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
333 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
334 keywords.
336 The plist also contains any property set in the property drawer,
337 with its name in lowercase, the underscores replaced with hyphens
338 and colons at the beginning (i.e. `:custom-id').
340 When RAW-SECONDARY-P is non-nil, headline's title will not be
341 parsed as a secondary string, but as a plain string instead.
343 Assume point is at beginning of the headline."
344 (save-excursion
345 (let* ((components (org-heading-components))
346 (level (nth 1 components))
347 (todo (nth 2 components))
348 (todo-type
349 (and todo (if (member todo org-done-keywords) 'done 'todo)))
350 (tags (nth 5 components))
351 (raw-value (nth 4 components))
352 (quotedp
353 (let ((case-fold-search nil))
354 (string-match (format "^%s +" org-quote-string) raw-value)))
355 (commentedp
356 (let ((case-fold-search nil))
357 (string-match (format "^%s +" org-comment-string) raw-value)))
358 (archivedp
359 (and tags
360 (let ((case-fold-search nil))
361 (string-match (format ":%s:" org-archive-tag) tags))))
362 (footnote-section-p (and org-footnote-section
363 (string= org-footnote-section raw-value)))
364 (standard-props (let (plist)
365 (mapc
366 (lambda (p)
367 (let ((p-name (downcase (car p))))
368 (while (string-match "_" p-name)
369 (setq p-name
370 (replace-match "-" nil nil p-name)))
371 (setq p-name (intern (concat ":" p-name)))
372 (setq plist
373 (plist-put plist p-name (cdr p)))))
374 (org-entry-properties nil 'standard))
375 plist))
376 (time-props (org-entry-properties nil 'special "CLOCK"))
377 (scheduled (cdr (assoc "SCHEDULED" time-props)))
378 (deadline (cdr (assoc "DEADLINE" time-props)))
379 (clock (cdr (assoc "CLOCK" time-props)))
380 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
381 (begin (point))
382 (pos-after-head (save-excursion (forward-line) (point)))
383 (contents-begin (save-excursion (forward-line)
384 (org-skip-whitespace)
385 (if (eobp) (point) (point-at-bol))))
386 (hidden (save-excursion (forward-line) (org-truely-invisible-p)))
387 (end (progn (goto-char (org-end-of-subtree t t))))
388 (contents-end (progn (skip-chars-backward " \r\t\n")
389 (forward-line)
390 (point)))
391 title)
392 ;; Clean RAW-VALUE from any quote or comment string.
393 (when (or quotedp commentedp)
394 (setq raw-value
395 (replace-regexp-in-string
396 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
398 raw-value)))
399 ;; Clean TAGS from archive tag, if any.
400 (when archivedp
401 (setq tags
402 (and (not (string= tags (format ":%s:" org-archive-tag)))
403 (replace-regexp-in-string
404 (concat org-archive-tag ":") "" tags)))
405 (when (string= tags ":") (setq tags nil)))
406 ;; Then get TITLE.
407 (setq title
408 (if raw-secondary-p raw-value
409 (org-element-parse-secondary-string
410 raw-value (org-element-restriction 'headline))))
411 `(headline
412 (:raw-value ,raw-value
413 :title ,title
414 :begin ,begin
415 :end ,end
416 :pre-blank ,(count-lines pos-after-head contents-begin)
417 :hiddenp ,hidden
418 :contents-begin ,contents-begin
419 :contents-end ,contents-end
420 :level ,level
421 :priority ,(nth 3 components)
422 :tags ,tags
423 :todo-keyword ,todo
424 :todo-type ,todo-type
425 :scheduled ,scheduled
426 :deadline ,deadline
427 :timestamp ,timestamp
428 :clock ,clock
429 :post-blank ,(count-lines contents-end end)
430 :footnote-section-p ,footnote-section-p
431 :archivedp ,archivedp
432 :commentedp ,commentedp
433 :quotedp ,quotedp
434 ,@standard-props)))))
436 (defun org-element-headline-interpreter (headline contents)
437 "Interpret HEADLINE element as Org syntax.
438 CONTENTS is the contents of the element."
439 (let* ((level (org-element-property :level headline))
440 (todo (org-element-property :todo-keyword headline))
441 (priority (org-element-property :priority headline))
442 (title (org-element-interpret-secondary
443 (org-element-property :title headline)))
444 (tags (let ((tag-string (org-element-property :tags headline))
445 (archivedp (org-element-property :archivedp headline)))
446 (cond
447 ((and (not tag-string) archivedp)
448 (format ":%s:" org-archive-tag))
449 (archivedp (concat ":" org-archive-tag tag-string))
450 (t tag-string))))
451 (commentedp (org-element-property :commentedp headline))
452 (quotedp (org-element-property :quotedp headline))
453 (pre-blank (org-element-property :pre-blank headline))
454 (heading (concat (make-string level ?*)
455 (and todo (concat " " todo))
456 (and quotedp (concat " " org-quote-string))
457 (and commentedp (concat " " org-comment-string))
458 (and priority (concat " " priority))
459 (cond ((and org-footnote-section
460 (org-element-property
461 :footnote-section-p headline))
462 (concat " " org-footnote-section))
463 (title (concat " " title)))))
464 ;; Align tags.
465 (tags-fmt (when tags
466 (let ((tags-len (length tags)))
467 (format "%% %ds"
468 (cond
469 ((zerop org-tags-column) (1+ tags-len))
470 ((< org-tags-column 0)
471 (max (- (+ org-tags-column (length heading)))
472 (1+ tags-len)))
473 (t (max (+ (- org-tags-column (length heading))
474 tags-len)
475 (1+ tags-len)))))))))
476 (concat heading (and tags (format tags-fmt tags))
477 (make-string (1+ pre-blank) 10)
478 contents)))
481 ;;;; Inlinetask
483 (defun org-element-inlinetask-parser (&optional raw-secondary-p)
484 "Parse an inline task.
486 Return a list whose car is `inlinetask' and cdr is a plist
487 containing `:title', `:begin', `:end', `:hiddenp',
488 `:contents-begin' and `:contents-end', `:level', `:priority',
489 `:tags', `:todo-keyword', `:todo-type', `:scheduled',
490 `:deadline', `:timestamp', `:clock' and `:post-blank' keywords.
492 The plist also contains any property set in the property drawer,
493 with its name in lowercase, the underscores replaced with hyphens
494 and colons at the beginning (i.e. `:custom-id').
496 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
497 title will not be parsed as a secondary string, but as a plain
498 string instead.
500 Assume point is at beginning of the inline task."
501 (save-excursion
502 (let* ((keywords (org-element-collect-affiliated-keywords))
503 (begin (car keywords))
504 (components (org-heading-components))
505 (todo (nth 2 components))
506 (todo-type (and todo
507 (if (member todo org-done-keywords) 'done 'todo)))
508 (title (if raw-secondary-p (nth 4 components)
509 (org-element-parse-secondary-string
510 (nth 4 components)
511 (org-element-restriction 'inlinetask))))
512 (standard-props (let (plist)
513 (mapc
514 (lambda (p)
515 (let ((p-name (downcase (car p))))
516 (while (string-match "_" p-name)
517 (setq p-name
518 (replace-match "-" nil nil p-name)))
519 (setq p-name (intern (concat ":" p-name)))
520 (setq plist
521 (plist-put plist p-name (cdr p)))))
522 (org-entry-properties nil 'standard))
523 plist))
524 (time-props (org-entry-properties nil 'special "CLOCK"))
525 (scheduled (cdr (assoc "SCHEDULED" time-props)))
526 (deadline (cdr (assoc "DEADLINE" time-props)))
527 (clock (cdr (assoc "CLOCK" time-props)))
528 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
529 (contents-begin (save-excursion (forward-line) (point)))
530 (hidden (org-truely-invisible-p))
531 (pos-before-blank (org-inlinetask-goto-end))
532 ;; In the case of a single line task, CONTENTS-BEGIN and
533 ;; CONTENTS-END might overlap.
534 (contents-end (max contents-begin
535 (save-excursion (forward-line -1) (point))))
536 (end (progn (org-skip-whitespace)
537 (if (eobp) (point) (point-at-bol)))))
538 `(inlinetask
539 (:title ,title
540 :begin ,begin
541 :end ,end
542 :hiddenp ,(and (> contents-end contents-begin) hidden)
543 :contents-begin ,contents-begin
544 :contents-end ,contents-end
545 :level ,(nth 1 components)
546 :priority ,(nth 3 components)
547 :tags ,(nth 5 components)
548 :todo-keyword ,todo
549 :todo-type ,todo-type
550 :scheduled ,scheduled
551 :deadline ,deadline
552 :timestamp ,timestamp
553 :clock ,clock
554 :post-blank ,(count-lines pos-before-blank end)
555 ,@standard-props
556 ,@(cadr keywords))))))
558 (defun org-element-inlinetask-interpreter (inlinetask contents)
559 "Interpret INLINETASK element as Org syntax.
560 CONTENTS is the contents of inlinetask."
561 (let* ((level (org-element-property :level inlinetask))
562 (todo (org-element-property :todo-keyword inlinetask))
563 (priority (org-element-property :priority inlinetask))
564 (title (org-element-interpret-secondary
565 (org-element-property :title inlinetask)))
566 (tags (org-element-property :tags inlinetask))
567 (task (concat (make-string level ?*)
568 (and todo (concat " " todo))
569 (and priority (concat " " priority))
570 (and title (concat " " title))))
571 ;; Align tags.
572 (tags-fmt (when tags
573 (format "%% %ds"
574 (cond
575 ((zerop org-tags-column) 1)
576 ((< 0 org-tags-column)
577 (max (+ org-tags-column
578 (length inlinetask)
579 (length tags))
581 (t (max (- org-tags-column (length inlinetask))
582 1)))))))
583 (concat inlinetask (and tags (format tags-fmt tags) "\n" contents))))
586 ;;;; Item
588 (defun org-element-item-parser (struct &optional raw-secondary-p)
589 "Parse an item.
591 STRUCT is the structure of the plain list.
593 Return a list whose car is `item' and cdr is a plist containing
594 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
595 `:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
596 `:post-blank' keywords.
598 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
599 any, will not be parsed as a secondary string, but as a plain
600 string instead.
602 Assume point is at the beginning of the item."
603 (save-excursion
604 (beginning-of-line)
605 (let* ((begin (point))
606 (bullet (org-list-get-bullet (point) struct))
607 (checkbox (let ((box (org-list-get-checkbox begin struct)))
608 (cond ((equal "[ ]" box) 'off)
609 ((equal "[X]" box) 'on)
610 ((equal "[-]" box) 'trans))))
611 (counter (let ((c (org-list-get-counter begin struct)))
612 (cond
613 ((not c) nil)
614 ((string-match "[A-Za-z]" c)
615 (- (string-to-char (upcase (match-string 0 c)))
616 64))
617 ((string-match "[0-9]+" c)
618 (string-to-number (match-string 0 c))))))
619 (tag
620 (let ((raw-tag (org-list-get-tag begin struct)))
621 (and raw-tag
622 (if raw-secondary-p raw-tag
623 (org-element-parse-secondary-string
624 raw-tag (org-element-restriction 'item))))))
625 (end (org-list-get-item-end begin struct))
626 (contents-begin (progn (looking-at org-list-full-item-re)
627 (goto-char (match-end 0))
628 (org-skip-whitespace)
629 ;; If first line isn't empty,
630 ;; contents really start at the text
631 ;; after item's meta-data.
632 (if (= (point-at-bol) begin) (point)
633 (point-at-bol))))
634 (hidden (progn (forward-line)
635 (and (not (= (point) end))
636 (org-truely-invisible-p))))
637 (contents-end (progn (goto-char end)
638 (skip-chars-backward " \r\t\n")
639 (forward-line)
640 (point))))
641 `(item
642 (:bullet ,bullet
643 :begin ,begin
644 :end ,end
645 ;; CONTENTS-BEGIN and CONTENTS-END may be mixed
646 ;; up in the case of an empty item separated
647 ;; from the next by a blank line. Thus, ensure
648 ;; the former is always the smallest of two.
649 :contents-begin ,(min contents-begin contents-end)
650 :contents-end ,(max contents-begin contents-end)
651 :checkbox ,checkbox
652 :counter ,counter
653 :tag ,tag
654 :hiddenp ,hidden
655 :structure ,struct
656 :post-blank ,(count-lines contents-end end))))))
658 (defun org-element-item-interpreter (item contents)
659 "Interpret ITEM element as Org syntax.
660 CONTENTS is the contents of the element."
661 (let* ((bullet
662 (let* ((beg (org-element-property :begin item))
663 (struct (org-element-property :structure item))
664 (pre (org-list-prevs-alist struct))
665 (bul (org-element-property :bullet item)))
666 (org-list-bullet-string
667 (if (not (eq (org-list-get-list-type beg struct pre) 'ordered)) "-"
668 (let ((num
669 (car
670 (last
671 (org-list-get-item-number
672 beg struct pre (org-list-parents-alist struct))))))
673 (format "%d%s"
675 (if (eq org-plain-list-ordered-item-terminator ?\)) ")"
676 ".")))))))
677 (checkbox (org-element-property :checkbox item))
678 (counter (org-element-property :counter item))
679 (tag (let ((tag (org-element-property :tag item)))
680 (and tag (org-element-interpret-secondary tag))))
681 ;; Compute indentation.
682 (ind (make-string (length bullet) 32)))
683 ;; Indent contents.
684 (concat
685 bullet
686 (and counter (format "[@%d] " counter))
687 (cond
688 ((eq checkbox 'on) "[X] ")
689 ((eq checkbox 'off) "[ ] ")
690 ((eq checkbox 'trans) "[-] "))
691 (and tag (format "%s :: " tag))
692 (org-trim
693 (replace-regexp-in-string "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))))
696 ;;;; Plain List
698 (defun org-element-plain-list-parser (&optional structure)
699 "Parse a plain list.
701 Optional argument STRUCTURE, when non-nil, is the structure of
702 the plain list being parsed.
704 Return a list whose car is `plain-list' and cdr is a plist
705 containing `:type', `:begin', `:end', `:contents-begin' and
706 `:contents-end', `:level', `:structure' and `:post-blank'
707 keywords.
709 Assume point is at one of the list items."
710 (save-excursion
711 (let* ((struct (or structure (org-list-struct)))
712 (prevs (org-list-prevs-alist struct))
713 (parents (org-list-parents-alist struct))
714 (type (org-list-get-list-type (point) struct prevs))
715 (contents-begin (goto-char
716 (org-list-get-list-begin (point) struct prevs)))
717 (keywords (org-element-collect-affiliated-keywords))
718 (begin (car keywords))
719 (contents-end (goto-char
720 (org-list-get-list-end (point) struct prevs)))
721 (end (save-excursion (org-skip-whitespace)
722 (if (eobp) (point) (point-at-bol))))
723 (level 0))
724 ;; Get list level.
725 (let ((item contents-begin))
726 (while (setq item
727 (org-list-get-parent
728 (org-list-get-list-begin item struct prevs)
729 struct parents))
730 (incf level)))
731 ;; Blank lines below list belong to the top-level list only.
732 (when (> level 0)
733 (setq end (min (org-list-get-bottom-point struct)
734 (progn (org-skip-whitespace)
735 (if (eobp) (point) (point-at-bol))))))
736 ;; Return value.
737 `(plain-list
738 (:type ,type
739 :begin ,begin
740 :end ,end
741 :contents-begin ,contents-begin
742 :contents-end ,contents-end
743 :level ,level
744 :structure ,struct
745 :post-blank ,(count-lines contents-end end)
746 ,@(cadr keywords))))))
748 (defun org-element-plain-list-interpreter (plain-list contents)
749 "Interpret PLAIN-LIST element as Org syntax.
750 CONTENTS is the contents of the element."
751 contents)
754 ;;;; Quote Block
756 (defun org-element-quote-block-parser ()
757 "Parse a quote block.
759 Return a list whose car is `quote-block' and cdr is a plist
760 containing `:begin', `:end', `:hiddenp', `:contents-begin',
761 `:contents-end' and `:post-blank' keywords.
763 Assume point is at beginning or end of the block."
764 (save-excursion
765 (let* ((case-fold-search t)
766 (keywords (progn
767 (end-of-line)
768 (re-search-backward
769 (concat "^[ \t]*#\\+BEGIN_QUOTE") nil t)
770 (org-element-collect-affiliated-keywords)))
771 (begin (car keywords))
772 (contents-begin (progn (forward-line) (point)))
773 (hidden (org-truely-invisible-p))
774 (contents-end (progn (re-search-forward
775 (concat "^[ \t]*#\\+END_QUOTE") nil t)
776 (point-at-bol)))
777 (pos-before-blank (progn (forward-line) (point)))
778 (end (progn (org-skip-whitespace)
779 (if (eobp) (point) (point-at-bol)))))
780 `(quote-block
781 (:begin ,begin
782 :end ,end
783 :hiddenp ,hidden
784 :contents-begin ,contents-begin
785 :contents-end ,contents-end
786 :post-blank ,(count-lines pos-before-blank end)
787 ,@(cadr keywords))))))
789 (defun org-element-quote-block-interpreter (quote-block contents)
790 "Interpret QUOTE-BLOCK element as Org syntax.
791 CONTENTS is the contents of the element."
792 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
795 ;;;; Section
797 (defun org-element-section-parser ()
798 "Parse a section.
800 Return a list whose car is `section' and cdr is a plist
801 containing `:begin', `:end', `:contents-begin', `contents-end'
802 and `:post-blank' keywords."
803 (save-excursion
804 ;; Beginning of section is the beginning of the first non-blank
805 ;; line after previous headline.
806 (org-with-limited-levels
807 (let ((begin
808 (save-excursion
809 (outline-previous-heading)
810 (if (not (org-at-heading-p)) (point)
811 (forward-line) (org-skip-whitespace) (point-at-bol))))
812 (end (progn (outline-next-heading) (point)))
813 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
814 (forward-line)
815 (point))))
816 `(section
817 (:begin ,begin
818 :end ,end
819 :contents-begin ,begin
820 :contents-end ,pos-before-blank
821 :post-blank ,(count-lines pos-before-blank end)))))))
823 (defun org-element-section-interpreter (section contents)
824 "Interpret SECTION element as Org syntax.
825 CONTENTS is the contents of the element."
826 contents)
829 ;;;; Special Block
831 (defun org-element-special-block-parser ()
832 "Parse a special block.
834 Return a list whose car is `special-block' and cdr is a plist
835 containing `:type', `:begin', `:end', `:hiddenp',
836 `:contents-begin', `:contents-end' and `:post-blank' keywords.
838 Assume point is at beginning or end of the block."
839 (save-excursion
840 (let* ((case-fold-search t)
841 (type (progn (looking-at
842 "[ \t]*#\\+\\(?:BEGIN\\|END\\)_\\([-A-Za-z0-9]+\\)")
843 (org-match-string-no-properties 1)))
844 (keywords (progn
845 (end-of-line)
846 (re-search-backward
847 (concat "^[ \t]*#\\+BEGIN_" type) nil t)
848 (org-element-collect-affiliated-keywords)))
849 (begin (car keywords))
850 (contents-begin (progn (forward-line) (point)))
851 (hidden (org-truely-invisible-p))
852 (contents-end (progn (re-search-forward
853 (concat "^[ \t]*#\\+END_" type) nil t)
854 (point-at-bol)))
855 (pos-before-blank (progn (forward-line) (point)))
856 (end (progn (org-skip-whitespace)
857 (if (eobp) (point) (point-at-bol)))))
858 `(special-block
859 (:type ,type
860 :begin ,begin
861 :end ,end
862 :hiddenp ,hidden
863 :contents-begin ,contents-begin
864 :contents-end ,contents-end
865 :post-blank ,(count-lines pos-before-blank end)
866 ,@(cadr keywords))))))
868 (defun org-element-special-block-interpreter (special-block contents)
869 "Interpret SPECIAL-BLOCK element as Org syntax.
870 CONTENTS is the contents of the element."
871 (let ((block-type (org-element-property :type special-block)))
872 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
876 ;;; Elements
878 ;; For each element, a parser and an interpreter are also defined.
879 ;; Both follow the same naming convention used for greater elements.
881 ;; Also, as for greater elements, adding a new element type is done
882 ;; through the following steps: implement a parser and an interpreter,
883 ;; tweak `org-element-current-element' so that it recognizes the new
884 ;; type and add that new type to `org-element-all-elements'.
886 ;; As a special case, when the newly defined type is a block type,
887 ;; `org-element-non-recursive-block-alist' has to be modified
888 ;; accordingly.
891 ;;;; Babel Call
893 (defun org-element-babel-call-parser ()
894 "Parse a babel call.
896 Return a list whose car is `babel-call' and cdr is a plist
897 containing `:begin', `:end', `:info' and `:post-blank' as
898 keywords."
899 (save-excursion
900 (let ((info (progn (looking-at org-babel-block-lob-one-liner-regexp)
901 (org-babel-lob-get-info)))
902 (beg (point-at-bol))
903 (pos-before-blank (progn (forward-line) (point)))
904 (end (progn (org-skip-whitespace)
905 (if (eobp) (point) (point-at-bol)))))
906 `(babel-call
907 (:beg ,beg
908 :end ,end
909 :info ,info
910 :post-blank ,(count-lines pos-before-blank end))))))
912 (defun org-element-babel-call-interpreter (inline-babel-call contents)
913 "Interpret INLINE-BABEL-CALL object as Org syntax.
914 CONTENTS is nil."
915 (let* ((babel-info (org-element-property :info inline-babel-call))
916 (main-source (car babel-info))
917 (post-options (nth 1 babel-info)))
918 (concat "#+CALL: "
919 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
920 ;; Remove redundant square brackets.
921 (replace-match
922 (match-string 1 main-source) nil nil main-source)
923 main-source)
924 (and post-options (format "[%s]" post-options)))))
927 ;;;; Comment
929 (defun org-element-comment-parser ()
930 "Parse a comment.
932 Return a list whose car is `comment' and cdr is a plist
933 containing `:begin', `:end', `:value' and `:post-blank'
934 keywords."
935 (let (beg-coms begin end end-coms keywords)
936 (save-excursion
937 (if (looking-at "#")
938 ;; First type of comment: comments at column 0.
939 (let ((comment-re "^\\([^#]\\|#\\+[a-z]\\)"))
940 (save-excursion
941 (re-search-backward comment-re nil 'move)
942 (if (bobp) (setq keywords nil beg-coms (point))
943 (forward-line)
944 (setq keywords (org-element-collect-affiliated-keywords)
945 beg-coms (point))))
946 (re-search-forward comment-re nil 'move)
947 (setq end-coms (if (eobp) (point) (match-beginning 0))))
948 ;; Second type of comment: indented comments.
949 (let ((comment-re "[ \t]*#\\+\\(?: \\|$\\)"))
950 (unless (bobp)
951 (while (and (not (bobp)) (looking-at comment-re))
952 (forward-line -1))
953 (unless (looking-at comment-re) (forward-line)))
954 (setq beg-coms (point))
955 (setq keywords (org-element-collect-affiliated-keywords))
956 ;; Get comments ending. This may not be accurate if
957 ;; commented lines within an item are followed by commented
958 ;; lines outside of the list. Though, parser will always
959 ;; get it right as it already knows surrounding element and
960 ;; has narrowed buffer to its contents.
961 (while (looking-at comment-re) (forward-line))
962 (setq end-coms (point))))
963 ;; Find position after blank.
964 (goto-char end-coms)
965 (org-skip-whitespace)
966 (setq end (if (eobp) (point) (point-at-bol))))
967 `(comment
968 (:begin ,(or (car keywords) beg-coms)
969 :end ,end
970 :value ,(buffer-substring-no-properties beg-coms end-coms)
971 :post-blank ,(count-lines end-coms end)
972 ,@(cadr keywords)))))
974 (defun org-element-comment-interpreter (comment contents)
975 "Interpret COMMENT element as Org syntax.
976 CONTENTS is nil."
977 (org-element-property :value comment))
980 ;;;; Comment Block
982 (defun org-element-comment-block-parser ()
983 "Parse an export block.
985 Return a list whose car is `comment-block' and cdr is a plist
986 containing `:begin', `:end', `:hiddenp', `:value' and
987 `:post-blank' keywords."
988 (save-excursion
989 (end-of-line)
990 (let* ((case-fold-search t)
991 (keywords (progn
992 (re-search-backward "^[ \t]*#\\+BEGIN_COMMENT" nil t)
993 (org-element-collect-affiliated-keywords)))
994 (begin (car keywords))
995 (contents-begin (progn (forward-line) (point)))
996 (hidden (org-truely-invisible-p))
997 (contents-end (progn (re-search-forward
998 "^[ \t]*#\\+END_COMMENT" nil t)
999 (point-at-bol)))
1000 (pos-before-blank (progn (forward-line) (point)))
1001 (end (progn (org-skip-whitespace)
1002 (if (eobp) (point) (point-at-bol))))
1003 (value (buffer-substring-no-properties contents-begin contents-end)))
1004 `(comment-block
1005 (:begin ,begin
1006 :end ,end
1007 :value ,value
1008 :hiddenp ,hidden
1009 :post-blank ,(count-lines pos-before-blank end)
1010 ,@(cadr keywords))))))
1012 (defun org-element-comment-block-interpreter (comment-block contents)
1013 "Interpret COMMENT-BLOCK element as Org syntax.
1014 CONTENTS is nil."
1015 (concat "#+begin_comment\n"
1016 (org-remove-indentation
1017 (org-element-property :value comment-block))
1018 "#+begin_comment"))
1021 ;;;; Example Block
1023 (defun org-element-example-block-parser ()
1024 "Parse an example block.
1026 Return a list whose car is `example-block' and cdr is a plist
1027 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1028 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1029 `:switches', `:value' and `:post-blank' keywords."
1030 (save-excursion
1031 (end-of-line)
1032 (let* ((case-fold-search t)
1033 (switches (progn
1034 (re-search-backward
1035 "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?" nil t)
1036 (org-match-string-no-properties 1)))
1037 ;; Switches analysis
1038 (number-lines (cond ((not switches) nil)
1039 ((string-match "-n\\>" switches) 'new)
1040 ((string-match "+n\\>" switches) 'continued)))
1041 (preserve-indent (and switches (string-match "-i\\>" switches)))
1042 ;; Should labels be retained in (or stripped from) example
1043 ;; blocks?
1044 (retain-labels
1045 (or (not switches)
1046 (not (string-match "-r\\>" switches))
1047 (and number-lines (string-match "-k\\>" switches))))
1048 ;; What should code-references use - labels or
1049 ;; line-numbers?
1050 (use-labels
1051 (or (not switches)
1052 (and retain-labels (not (string-match "-k\\>" switches)))))
1053 (label-fmt (and switches
1054 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1055 (match-string 1 switches)))
1056 ;; Standard block parsing.
1057 (keywords (org-element-collect-affiliated-keywords))
1058 (begin (car keywords))
1059 (contents-begin (progn (forward-line) (point)))
1060 (hidden (org-truely-invisible-p))
1061 (contents-end (progn
1062 (re-search-forward "^[ \t]*#\\+END_EXAMPLE" nil t)
1063 (point-at-bol)))
1064 (value (buffer-substring-no-properties contents-begin contents-end))
1065 (pos-before-blank (progn (forward-line) (point)))
1066 (end (progn (org-skip-whitespace)
1067 (if (eobp) (point) (point-at-bol)))))
1068 `(example-block
1069 (:begin ,begin
1070 :end ,end
1071 :value ,value
1072 :switches ,switches
1073 :number-lines ,number-lines
1074 :preserve-indent ,preserve-indent
1075 :retain-labels ,retain-labels
1076 :use-labels ,use-labels
1077 :label-fmt ,label-fmt
1078 :hiddenp ,hidden
1079 :post-blank ,(count-lines pos-before-blank end)
1080 ,@(cadr keywords))))))
1082 (defun org-element-example-block-interpreter (example-block contents)
1083 "Interpret EXAMPLE-BLOCK element as Org syntax.
1084 CONTENTS is nil."
1085 (let ((options (org-element-property :options example-block)))
1086 (concat "#+BEGIN_EXAMPLE" (and options (concat " " options)) "\n"
1087 (org-remove-indentation
1088 (org-element-property :value example-block))
1089 "#+END_EXAMPLE")))
1092 ;;;; Export Block
1094 (defun org-element-export-block-parser ()
1095 "Parse an export block.
1097 Return a list whose car is `export-block' and cdr is a plist
1098 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1099 `:post-blank' keywords."
1100 (save-excursion
1101 (end-of-line)
1102 (let* ((case-fold-search t)
1103 (contents)
1104 (type (progn (re-search-backward
1105 (concat "[ \t]*#\\+BEGIN_"
1106 (org-re "\\([[:alnum:]]+\\)")))
1107 (upcase (org-match-string-no-properties 1))))
1108 (keywords (org-element-collect-affiliated-keywords))
1109 (begin (car keywords))
1110 (contents-begin (progn (forward-line) (point)))
1111 (hidden (org-truely-invisible-p))
1112 (contents-end (progn (re-search-forward
1113 (concat "^[ \t]*#\\+END_" type) nil t)
1114 (point-at-bol)))
1115 (pos-before-blank (progn (forward-line) (point)))
1116 (end (progn (org-skip-whitespace)
1117 (if (eobp) (point) (point-at-bol))))
1118 (value (buffer-substring-no-properties contents-begin contents-end)))
1119 `(export-block
1120 (:begin ,begin
1121 :end ,end
1122 :type ,type
1123 :value ,value
1124 :hiddenp ,hidden
1125 :post-blank ,(count-lines pos-before-blank end)
1126 ,@(cadr keywords))))))
1128 (defun org-element-export-block-interpreter (export-block contents)
1129 "Interpret EXPORT-BLOCK element as Org syntax.
1130 CONTENTS is nil."
1131 (let ((type (org-element-property :type export-block)))
1132 (concat (format "#+BEGIN_%s\n" type)
1133 (org-element-property :value export-block)
1134 (format "#+END_%s" type))))
1137 ;;;; Fixed-width
1139 (defun org-element-fixed-width-parser ()
1140 "Parse a fixed-width section.
1142 Return a list whose car is `fixed-width' and cdr is a plist
1143 containing `:begin', `:end', `:value' and `:post-blank'
1144 keywords."
1145 (let ((fixed-re "[ \t]*:\\( \\|$\\)")
1146 beg-area begin end value pos-before-blank keywords)
1147 (save-excursion
1148 ;; Move to the beginning of the fixed-width area.
1149 (unless (bobp)
1150 (while (and (not (bobp)) (looking-at fixed-re))
1151 (forward-line -1))
1152 (unless (looking-at fixed-re) (forward-line 1)))
1153 (setq beg-area (point))
1154 ;; Get affiliated keywords, if any.
1155 (setq keywords (org-element-collect-affiliated-keywords))
1156 ;; Store true beginning of element.
1157 (setq begin (car keywords))
1158 ;; Get ending of fixed-width area. If point is in a list,
1159 ;; ensure to not get outside of it.
1160 (let* ((itemp (org-in-item-p))
1161 (max-pos (if itemp
1162 (org-list-get-bottom-point
1163 (save-excursion (goto-char itemp) (org-list-struct)))
1164 (point-max))))
1165 (while (and (looking-at fixed-re) (< (point) max-pos))
1166 (forward-line)))
1167 (setq pos-before-blank (point))
1168 ;; Find position after blank
1169 (org-skip-whitespace)
1170 (setq end (if (eobp) (point) (point-at-bol)))
1171 ;; Extract value.
1172 (setq value (buffer-substring-no-properties beg-area pos-before-blank)))
1173 `(fixed-width
1174 (:begin ,begin
1175 :end ,end
1176 :value ,value
1177 :post-blank ,(count-lines pos-before-blank end)
1178 ,@(cadr keywords)))))
1180 (defun org-element-fixed-width-interpreter (fixed-width contents)
1181 "Interpret FIXED-WIDTH element as Org syntax.
1182 CONTENTS is nil."
1183 (org-remove-indentation (org-element-property :value fixed-width)))
1186 ;;;; Horizontal Rule
1188 (defun org-element-horizontal-rule-parser ()
1189 "Parse an horizontal rule.
1191 Return a list whose car is `horizontal-rule' and cdr is
1192 a plist containing `:begin', `:end' and `:post-blank'
1193 keywords."
1194 (save-excursion
1195 (let* ((keywords (org-element-collect-affiliated-keywords))
1196 (begin (car keywords))
1197 (post-hr (progn (forward-line) (point)))
1198 (end (progn (org-skip-whitespace)
1199 (if (eobp) (point) (point-at-bol)))))
1200 `(horizontal-rule
1201 (:begin ,begin
1202 :end ,end
1203 :post-blank ,(count-lines post-hr end)
1204 ,@(cadr keywords))))))
1206 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1207 "Interpret HORIZONTAL-RULE element as Org syntax.
1208 CONTENTS is nil."
1209 "-----")
1212 ;;;; Keyword
1214 (defun org-element-keyword-parser ()
1215 "Parse a keyword at point.
1217 Return a list whose car is `keyword' and cdr is a plist
1218 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1219 keywords."
1220 (save-excursion
1221 (let* ((begin (point))
1222 (key (progn (looking-at
1223 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1224 (upcase (org-match-string-no-properties 1))))
1225 (value (org-trim (buffer-substring-no-properties
1226 (match-end 0) (point-at-eol))))
1227 (pos-before-blank (progn (forward-line) (point)))
1228 (end (progn (org-skip-whitespace)
1229 (if (eobp) (point) (point-at-bol)))))
1230 `(keyword
1231 (:key ,key
1232 :value ,value
1233 :begin ,begin
1234 :end ,end
1235 :post-blank ,(count-lines pos-before-blank end))))))
1237 (defun org-element-keyword-interpreter (keyword contents)
1238 "Interpret KEYWORD element as Org syntax.
1239 CONTENTS is nil."
1240 (format "#+%s: %s"
1241 (org-element-property :key keyword)
1242 (org-element-property :value keyword)))
1245 ;;;; Latex Environment
1247 (defun org-element-latex-environment-parser ()
1248 "Parse a LaTeX environment.
1250 Return a list whose car is `latex-environment' and cdr is a plist
1251 containing `:begin', `:end', `:value' and `:post-blank' keywords."
1252 (save-excursion
1253 (end-of-line)
1254 (let* ((case-fold-search t)
1255 (contents-begin (re-search-backward "^[ \t]*\\\\begin" nil t))
1256 (keywords (org-element-collect-affiliated-keywords))
1257 (begin (car keywords))
1258 (contents-end (progn (re-search-forward "^[ \t]*\\\\end")
1259 (forward-line)
1260 (point)))
1261 (value (buffer-substring-no-properties contents-begin contents-end))
1262 (end (progn (org-skip-whitespace)
1263 (if (eobp) (point) (point-at-bol)))))
1264 `(latex-environment
1265 (:begin ,begin
1266 :end ,end
1267 :value ,value
1268 :post-blank ,(count-lines contents-end end)
1269 ,@(cadr keywords))))))
1271 (defun org-element-latex-environment-interpreter (latex-environment contents)
1272 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1273 CONTENTS is nil."
1274 (org-element-property :value latex-environment))
1277 ;;;; Paragraph
1279 (defun org-element-paragraph-parser ()
1280 "Parse a paragraph.
1282 Return a list whose car is `paragraph' and cdr is a plist
1283 containing `:begin', `:end', `:contents-begin' and
1284 `:contents-end' and `:post-blank' keywords.
1286 Assume point is at the beginning of the paragraph."
1287 (save-excursion
1288 (let* ((contents-begin (point))
1289 (keywords (org-element-collect-affiliated-keywords))
1290 (begin (car keywords))
1291 (contents-end (progn
1292 (end-of-line)
1293 (if (re-search-forward
1294 org-element-paragraph-separate nil 'm)
1295 (progn (forward-line -1) (end-of-line) (point))
1296 (point))))
1297 (pos-before-blank (progn (forward-line) (point)))
1298 (end (progn (org-skip-whitespace)
1299 (if (eobp) (point) (point-at-bol)))))
1300 `(paragraph
1301 (:begin ,begin
1302 :end ,end
1303 :contents-begin ,contents-begin
1304 :contents-end ,contents-end
1305 :post-blank ,(count-lines pos-before-blank end)
1306 ,@(cadr keywords))))))
1308 (defun org-element-paragraph-interpreter (paragraph contents)
1309 "Interpret PARAGRAPH element as Org syntax.
1310 CONTENTS is the contents of the element."
1311 contents)
1314 ;;;; Property Drawer
1316 (defun org-element-property-drawer-parser ()
1317 "Parse a property drawer.
1319 Return a list whose car is `property-drawer' and cdr is a plist
1320 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1321 `:contents-end', `:properties' and `:post-blank' keywords."
1322 (save-excursion
1323 (let ((case-fold-search t)
1324 (begin (progn (end-of-line)
1325 (re-search-backward org-property-start-re)
1326 (match-beginning 0)))
1327 (contents-begin (progn (forward-line) (point)))
1328 (hidden (org-truely-invisible-p))
1329 (properties (let (val)
1330 (while (not (looking-at "^[ \t]*:END:"))
1331 (when (looking-at
1332 (org-re
1333 "[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):"))
1334 (push (cons (match-string 1)
1335 (org-trim
1336 (buffer-substring
1337 (match-end 0) (point-at-eol))))
1338 val))
1339 (forward-line))
1340 val))
1341 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1342 (point-at-bol)))
1343 (pos-before-blank (progn (forward-line) (point)))
1344 (end (progn (org-skip-whitespace)
1345 (if (eobp) (point) (point-at-bol)))))
1346 `(property-drawer
1347 (:begin ,begin
1348 :end ,end
1349 :hiddenp ,hidden
1350 :properties ,properties
1351 :post-blank ,(count-lines pos-before-blank end))))))
1353 (defun org-element-property-drawer-interpreter (property-drawer contents)
1354 "Interpret PROPERTY-DRAWER element as Org syntax.
1355 CONTENTS is nil."
1356 (let ((props (org-element-property :properties property-drawer)))
1357 (concat
1358 ":PROPERTIES:\n"
1359 (mapconcat (lambda (p)
1360 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1361 (nreverse props) "\n")
1362 "\n:END:")))
1365 ;;;; Quote Section
1367 (defun org-element-quote-section-parser ()
1368 "Parse a quote section.
1370 Return a list whose car is `quote-section' and cdr is a plist
1371 containing `:begin', `:end', `:value' and `:post-blank'
1372 keywords.
1374 Assume point is at beginning of the section."
1375 (save-excursion
1376 (let* ((begin (point))
1377 (end (progn (org-with-limited-levels (outline-next-heading))
1378 (point)))
1379 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1380 (forward-line)
1381 (point)))
1382 (value (buffer-substring-no-properties begin pos-before-blank)))
1383 `(quote-section
1384 (:begin ,begin
1385 :end ,end
1386 :value ,value
1387 :post-blank ,(count-lines pos-before-blank end))))))
1389 (defun org-element-quote-section-interpreter (quote-section contents)
1390 "Interpret QUOTE-SECTION element as Org syntax.
1391 CONTENTS is nil."
1392 (org-element-property :value quote-section))
1395 ;;;; Src Block
1397 (defun org-element-src-block-parser ()
1398 "Parse a src block.
1400 Return a list whose car is `src-block' and cdr is a plist
1401 containing `:language', `:switches', `:parameters', `:begin',
1402 `:end', `:hiddenp', `:contents-begin', `:contents-end',
1403 `:number-lines', `:retain-labels', `:use-labels', `:label-fmt',
1404 `:preserve-indent', `:value' and `:post-blank' keywords."
1405 (save-excursion
1406 (end-of-line)
1407 (let* ((case-fold-search t)
1408 ;; Get position at beginning of block.
1409 (contents-begin
1410 (re-search-backward
1411 (concat
1412 "^[ \t]*#\\+BEGIN_SRC"
1413 "\\(?: +\\(\\S-+\\)\\)?" ; language
1414 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)*\\)" ; switches
1415 "\\(.*\\)[ \t]*$") ; parameters
1416 nil t))
1417 ;; Get language as a string.
1418 (language (org-match-string-no-properties 1))
1419 ;; Get parameters.
1420 (parameters (org-trim (org-match-string-no-properties 3)))
1421 ;; Get switches.
1422 (switches (org-match-string-no-properties 2))
1423 ;; Switches analysis
1424 (number-lines (cond ((not switches) nil)
1425 ((string-match "-n\\>" switches) 'new)
1426 ((string-match "+n\\>" switches) 'continued)))
1427 (preserve-indent (and switches (string-match "-i\\>" switches)))
1428 (label-fmt (and switches
1429 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1430 (match-string 1 switches)))
1431 ;; Should labels be retained in (or stripped from) src
1432 ;; blocks?
1433 (retain-labels
1434 (or (not switches)
1435 (not (string-match "-r\\>" switches))
1436 (and number-lines (string-match "-k\\>" switches))))
1437 ;; What should code-references use - labels or
1438 ;; line-numbers?
1439 (use-labels
1440 (or (not switches)
1441 (and retain-labels (not (string-match "-k\\>" switches)))))
1442 ;; Get affiliated keywords.
1443 (keywords (org-element-collect-affiliated-keywords))
1444 ;; Get beginning position.
1445 (begin (car keywords))
1446 ;; Get position at end of block.
1447 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_SRC" nil t)
1448 (forward-line)
1449 (point)))
1450 ;; Retrieve code.
1451 (value (buffer-substring-no-properties
1452 (save-excursion (goto-char contents-begin)
1453 (forward-line)
1454 (point))
1455 (match-beginning 0)))
1456 ;; Get position after ending blank lines.
1457 (end (progn (org-skip-whitespace)
1458 (if (eobp) (point) (point-at-bol))))
1459 ;; Get visibility status.
1460 (hidden (progn (goto-char contents-begin)
1461 (forward-line)
1462 (org-truely-invisible-p))))
1463 `(src-block
1464 (:language ,language
1465 :switches ,switches
1466 :parameters ,parameters
1467 :begin ,begin
1468 :end ,end
1469 :number-lines ,number-lines
1470 :preserve-indent ,preserve-indent
1471 :retain-labels ,retain-labels
1472 :use-labels ,use-labels
1473 :label-fmt ,label-fmt
1474 :hiddenp ,hidden
1475 :value ,value
1476 :post-blank ,(count-lines contents-end end)
1477 ,@(cadr keywords))))))
1479 (defun org-element-src-block-interpreter (src-block contents)
1480 "Interpret SRC-BLOCK element as Org syntax.
1481 CONTENTS is nil."
1482 (let ((lang (org-element-property :language src-block))
1483 (switches (org-element-property :switches src-block))
1484 (params (org-element-property :parameters src-block))
1485 (value (let ((val (org-element-property :value src-block)))
1486 (cond
1488 (org-src-preserve-indentation val)
1489 ((zerop org-edit-src-content-indentation)
1490 (org-remove-indentation val))
1492 (let ((ind (make-string
1493 org-edit-src-content-indentation 32)))
1494 (replace-regexp-in-string
1495 "\\(^\\)[ \t]*\\S-" ind
1496 (org-remove-indentation val) nil nil 1)))))))
1497 (concat (format "#+BEGIN_SRC%s\n"
1498 (concat (and lang (concat " " lang))
1499 (and switches (concat " " switches))
1500 (and params (concat " " params))))
1501 value
1502 "#+END_SRC")))
1505 ;;;; Table
1507 (defun org-element-table-parser ()
1508 "Parse a table at point.
1510 Return a list whose CAR is `table' and CDR is a plist containing
1511 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
1512 `:contents-end', `:value' and `:post-blank' keywords."
1513 (save-excursion
1514 (let* ((case-fold-search t)
1515 (table-begin (goto-char (org-table-begin t)))
1516 (type (if (org-at-table.el-p) 'table.el 'org))
1517 (keywords (org-element-collect-affiliated-keywords))
1518 (begin (car keywords))
1519 (table-end (goto-char (marker-position (org-table-end t))))
1520 (tblfm (when (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
1521 (prog1 (org-match-string-no-properties 1)
1522 (forward-line))))
1523 (pos-before-blank (point))
1524 (end (progn (org-skip-whitespace)
1525 (if (eobp) (point) (point-at-bol)))))
1526 `(table
1527 (:begin ,begin
1528 :end ,end
1529 :type ,type
1530 :tblfm ,tblfm
1531 ;; Only `org' tables have contents. `table.el'
1532 ;; tables use a `:value' property to store raw
1533 ;; table as a string.
1534 :contents-begin ,(and (eq type 'org) table-begin)
1535 :contents-end ,(and (eq type 'org) table-end)
1536 :value ,(and (eq type 'table.el)
1537 (buffer-substring-no-properties
1538 table-begin table-end))
1539 :post-blank ,(count-lines pos-before-blank end)
1540 ,@(cadr keywords))))))
1542 (defun org-element-table-interpreter (table contents)
1543 "Interpret TABLE element as Org syntax.
1544 CONTENTS is nil."
1545 (if (eq (org-element-property :type table) 'table.el)
1546 (org-remove-indentation (org-element-property :value table))
1547 (concat (with-temp-buffer (insert contents)
1548 (org-table-align)
1549 (buffer-string))
1550 (when (org-element-property :tblfm table)
1551 (format "#+TBLFM: " (org-element-property :tblfm table))))))
1554 ;;;; Table Row
1556 (defun org-element-table-row-parser ()
1557 "Parse table row at point.
1559 Return a list whose CAR is `table-row' and CDR is a plist
1560 containing `:begin', `:end', `:contents-begin', `:contents-end',
1561 `:type' and `:post-blank' keywords."
1562 (save-excursion
1563 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
1564 (begin (point))
1565 ;; A table rule has no contents. In that case, ensure
1566 ;; CONTENTS-BEGIN matches CONTENTS-END.
1567 (contents-begin (if (eq type 'standard)
1568 (progn (search-forward "|") (point))
1569 (end-of-line)
1570 (skip-chars-backward " \r\t\n")
1571 (point)))
1572 (contents-end (progn (end-of-line)
1573 (skip-chars-backward " \r\t\n")
1574 (point)))
1575 (end (progn (forward-line) (point))))
1576 `(table-row
1577 (:type ,type
1578 :begin ,begin
1579 :end ,end
1580 :contents-begin ,contents-begin
1581 :contents-end ,contents-end
1582 :post-blank 0)))))
1584 (defun org-element-table-row-interpreter (table-row contents)
1585 "Interpret TABLE-ROW element as Org syntax.
1586 CONTENTS is the contents of the table row."
1587 (if (eq (org-element-property :type table-row) 'rule) "|-"
1588 (concat "| " contents)))
1591 ;;;; Verse Block
1593 (defun org-element-verse-block-parser ()
1594 "Parse a verse block.
1596 Return a list whose CAR is `verse-block' and CDR is a plist
1597 containing `:begin', `:end', `:contents-begin', `:contents-end',
1598 `:hiddenp' and `:post-blank' keywords.
1600 Assume point is at beginning of the block."
1601 (save-excursion
1602 (let* ((case-fold-search t)
1603 (keywords (org-element-collect-affiliated-keywords))
1604 (begin (car keywords))
1605 (hidden (progn (forward-line) (org-truely-invisible-p)))
1606 (contents-begin (point))
1607 (contents-end
1608 (progn
1609 (re-search-forward (concat "^[ \t]*#\\+END_VERSE") nil t)
1610 (point-at-bol)))
1611 (pos-before-blank (progn (forward-line) (point)))
1612 (end (progn (org-skip-whitespace)
1613 (if (eobp) (point) (point-at-bol)))))
1614 `(verse-block
1615 (:begin ,begin
1616 :end ,end
1617 :contents-begin ,contents-begin
1618 :contents-end ,contents-end
1619 :hiddenp ,hidden
1620 :post-blank ,(count-lines pos-before-blank end)
1621 ,@(cadr keywords))))))
1623 (defun org-element-verse-block-interpreter (verse-block contents)
1624 "Interpret VERSE-BLOCK element as Org syntax.
1625 CONTENTS is verse block contents."
1626 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
1630 ;;; Objects
1632 ;; Unlike to elements, interstices can be found between objects.
1633 ;; That's why, along with the parser, successor functions are provided
1634 ;; for each object. Some objects share the same successor
1635 ;; (i.e. `emphasis' and `verbatim' objects).
1637 ;; A successor must accept a single argument bounding the search. It
1638 ;; will return either a cons cell whose car is the object's type, as
1639 ;; a symbol, and cdr the position of its next occurrence, or nil.
1641 ;; Successors follow the naming convention:
1642 ;; org-element-NAME-successor, where NAME is the name of the
1643 ;; successor, as defined in `org-element-all-successors'.
1645 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1646 ;; object types they can contain will be specified in
1647 ;; `org-element-object-restrictions'.
1649 ;; Adding a new type of object is simple. Implement a successor,
1650 ;; a parser, and an interpreter for it, all following the naming
1651 ;; convention. Register type in `org-element-all-objects' and
1652 ;; successor in `org-element-all-successors'. Maybe tweak
1653 ;; restrictions about it, and that's it.
1655 ;;;; Emphasis
1657 (defun org-element-emphasis-parser ()
1658 "Parse text markup object at point.
1660 Return a list whose car is `emphasis' and cdr is a plist with
1661 `:marker', `:begin', `:end', `:contents-begin' and
1662 `:contents-end' and `:post-blank' keywords.
1664 Assume point is at the first emphasis marker."
1665 (save-excursion
1666 (unless (bolp) (backward-char 1))
1667 (looking-at org-emph-re)
1668 (let ((begin (match-beginning 2))
1669 (marker (org-match-string-no-properties 3))
1670 (contents-begin (match-beginning 4))
1671 (contents-end (match-end 4))
1672 (post-blank (progn (goto-char (match-end 2))
1673 (skip-chars-forward " \t")))
1674 (end (point)))
1675 `(emphasis
1676 (:marker ,marker
1677 :begin ,begin
1678 :end ,end
1679 :contents-begin ,contents-begin
1680 :contents-end ,contents-end
1681 :post-blank ,post-blank)))))
1683 (defun org-element-emphasis-interpreter (emphasis contents)
1684 "Interpret EMPHASIS object as Org syntax.
1685 CONTENTS is the contents of the object."
1686 (let ((marker (org-element-property :marker emphasis)))
1687 (concat marker contents marker)))
1689 (defun org-element-text-markup-successor (limit)
1690 "Search for the next emphasis or verbatim object.
1692 LIMIT bounds the search.
1694 Return value is a cons cell whose car is `emphasis' or
1695 `verbatim' and cdr is beginning position."
1696 (save-excursion
1697 (unless (bolp) (backward-char))
1698 (when (re-search-forward org-emph-re limit t)
1699 (cons (if (nth 4 (assoc (match-string 3) org-emphasis-alist))
1700 'verbatim
1701 'emphasis)
1702 (match-beginning 2)))))
1704 ;;;; Entity
1706 (defun org-element-entity-parser ()
1707 "Parse entity at point.
1709 Return a list whose car is `entity' and cdr a plist with
1710 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1711 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1712 keywords.
1714 Assume point is at the beginning of the entity."
1715 (save-excursion
1716 (looking-at "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1717 (let* ((value (org-entity-get (match-string 1)))
1718 (begin (match-beginning 0))
1719 (bracketsp (string= (match-string 2) "{}"))
1720 (post-blank (progn (goto-char (match-end 1))
1721 (when bracketsp (forward-char 2))
1722 (skip-chars-forward " \t")))
1723 (end (point)))
1724 `(entity
1725 (:name ,(car value)
1726 :latex ,(nth 1 value)
1727 :latex-math-p ,(nth 2 value)
1728 :html ,(nth 3 value)
1729 :ascii ,(nth 4 value)
1730 :latin1 ,(nth 5 value)
1731 :utf-8 ,(nth 6 value)
1732 :begin ,begin
1733 :end ,end
1734 :use-brackets-p ,bracketsp
1735 :post-blank ,post-blank)))))
1737 (defun org-element-entity-interpreter (entity contents)
1738 "Interpret ENTITY object as Org syntax.
1739 CONTENTS is nil."
1740 (concat "\\"
1741 (org-element-property :name entity)
1742 (when (org-element-property :use-brackets-p entity) "{}")))
1744 (defun org-element-latex-or-entity-successor (limit)
1745 "Search for the next latex-fragment or entity object.
1747 LIMIT bounds the search.
1749 Return value is a cons cell whose car is `entity' or
1750 `latex-fragment' and cdr is beginning position."
1751 (save-excursion
1752 (let ((matchers (plist-get org-format-latex-options :matchers))
1753 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1754 (entity-re
1755 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"))
1756 (when (re-search-forward
1757 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1758 matchers "\\|")
1759 "\\|" entity-re)
1760 limit t)
1761 (goto-char (match-beginning 0))
1762 (if (looking-at entity-re)
1763 ;; Determine if it's a real entity or a LaTeX command.
1764 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1765 (match-beginning 0))
1766 ;; No entity nor command: point is at a LaTeX fragment.
1767 ;; Determine its type to get the correct beginning position.
1768 (cons 'latex-fragment
1769 (catch 'return
1770 (mapc (lambda (e)
1771 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1772 (throw 'return
1773 (match-beginning
1774 (nth 2 (assoc e org-latex-regexps))))))
1775 matchers)
1776 (point))))))))
1779 ;;;; Export Snippet
1781 (defun org-element-export-snippet-parser ()
1782 "Parse export snippet at point.
1784 Return a list whose car is `export-snippet' and cdr a plist with
1785 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1786 keywords.
1788 Assume point is at the beginning of the snippet."
1789 (save-excursion
1790 (looking-at "@\\([-A-Za-z0-9]+\\){")
1791 (let* ((begin (point))
1792 (back-end (org-match-string-no-properties 1))
1793 (before-blank (progn (goto-char (scan-sexps (1- (match-end 0)) 1))))
1794 (value (buffer-substring-no-properties
1795 (match-end 0) (1- before-blank)))
1796 (post-blank (skip-chars-forward " \t"))
1797 (end (point)))
1798 `(export-snippet
1799 (:back-end ,back-end
1800 :value ,value
1801 :begin ,begin
1802 :end ,end
1803 :post-blank ,post-blank)))))
1805 (defun org-element-export-snippet-interpreter (export-snippet contents)
1806 "Interpret EXPORT-SNIPPET object as Org syntax.
1807 CONTENTS is nil."
1808 (format "@%s{%s}"
1809 (org-element-property :back-end export-snippet)
1810 (org-element-property :value export-snippet)))
1812 (defun org-element-export-snippet-successor (limit)
1813 "Search for the next export-snippet object.
1815 LIMIT bounds the search.
1817 Return value is a cons cell whose car is `export-snippet' cdr is
1818 its beginning position."
1819 (save-excursion
1820 (catch 'exit
1821 (while (re-search-forward "@[-A-Za-z0-9]+{" limit t)
1822 (when (let ((end (ignore-errors (scan-sexps (1- (point)) 1))))
1823 (and end (eq (char-before end) ?})))
1824 (throw 'exit (cons 'export-snippet (match-beginning 0))))))))
1827 ;;;; Footnote Reference
1829 (defun org-element-footnote-reference-parser ()
1830 "Parse footnote reference at point.
1832 Return a list whose CAR is `footnote-reference' and CDR a plist
1833 with `:label', `:type', `:inline-definition', `:begin', `:end'
1834 and `:post-blank' as keywords."
1835 (save-excursion
1836 (looking-at org-footnote-re)
1837 (let* ((begin (point))
1838 (label (or (org-match-string-no-properties 2)
1839 (org-match-string-no-properties 3)
1840 (and (match-string 1)
1841 (concat "fn:" (org-match-string-no-properties 1)))))
1842 (type (if (or (not label) (match-string 1)) 'inline 'standard))
1843 (inner-begin (match-end 0))
1844 (inner-end
1845 (let ((count 1))
1846 (forward-char)
1847 (while (and (> count 0) (re-search-forward "[][]" nil t))
1848 (if (equal (match-string 0) "[") (incf count) (decf count)))
1849 (1- (point))))
1850 (post-blank (progn (goto-char (1+ inner-end))
1851 (skip-chars-forward " \t")))
1852 (end (point))
1853 (inline-definition
1854 (and (eq type 'inline)
1855 (org-element-parse-secondary-string
1856 (buffer-substring inner-begin inner-end)
1857 (org-element-restriction 'footnote-reference)))))
1858 `(footnote-reference
1859 (:label ,label
1860 :type ,type
1861 :inline-definition ,inline-definition
1862 :begin ,begin
1863 :end ,end
1864 :post-blank ,post-blank)))))
1866 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1867 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1868 CONTENTS is nil."
1869 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
1870 (def
1871 (let ((inline-def
1872 (org-element-property :inline-definition footnote-reference)))
1873 (if (not inline-def) ""
1874 (concat ":" (org-element-interpret-secondary inline-def))))))
1875 (format "[%s]" (concat label def))))
1877 (defun org-element-footnote-reference-successor (limit)
1878 "Search for the next footnote-reference object.
1880 LIMIT bounds the search.
1882 Return value is a cons cell whose CAR is `footnote-reference' and
1883 CDR is beginning position."
1884 (save-excursion
1885 (catch 'exit
1886 (while (re-search-forward org-footnote-re limit t)
1887 (save-excursion
1888 (let ((beg (match-beginning 0))
1889 (count 1))
1890 (backward-char)
1891 (while (re-search-forward "[][]" limit t)
1892 (if (equal (match-string 0) "[") (incf count) (decf count))
1893 (when (zerop count)
1894 (throw 'exit (cons 'footnote-reference beg))))))))))
1897 ;;;; Inline Babel Call
1899 (defun org-element-inline-babel-call-parser ()
1900 "Parse inline babel call at point.
1902 Return a list whose car is `inline-babel-call' and cdr a plist with
1903 `:begin', `:end', `:info' and `:post-blank' as keywords.
1905 Assume point is at the beginning of the babel call."
1906 (save-excursion
1907 (unless (bolp) (backward-char))
1908 (looking-at org-babel-inline-lob-one-liner-regexp)
1909 (let ((info (save-match-data (org-babel-lob-get-info)))
1910 (begin (match-end 1))
1911 (post-blank (progn (goto-char (match-end 0))
1912 (skip-chars-forward " \t")))
1913 (end (point)))
1914 `(inline-babel-call
1915 (:begin ,begin
1916 :end ,end
1917 :info ,info
1918 :post-blank ,post-blank)))))
1920 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
1921 "Interpret INLINE-BABEL-CALL object as Org syntax.
1922 CONTENTS is nil."
1923 (let* ((babel-info (org-element-property :info inline-babel-call))
1924 (main-source (car babel-info))
1925 (post-options (nth 1 babel-info)))
1926 (concat "call_"
1927 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
1928 ;; Remove redundant square brackets.
1929 (replace-match
1930 (match-string 1 main-source) nil nil main-source)
1931 main-source)
1932 (and post-options (format "[%s]" post-options)))))
1934 (defun org-element-inline-babel-call-successor (limit)
1935 "Search for the next inline-babel-call object.
1937 LIMIT bounds the search.
1939 Return value is a cons cell whose car is `inline-babel-call' and
1940 cdr is beginning position."
1941 (save-excursion
1942 ;; Use a simplified version of
1943 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
1944 (when (re-search-forward
1945 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
1946 limit t)
1947 (cons 'inline-babel-call (match-beginning 0)))))
1950 ;;;; Inline Src Block
1952 (defun org-element-inline-src-block-parser ()
1953 "Parse inline source block at point.
1955 Return a list whose car is `inline-src-block' and cdr a plist
1956 with `:begin', `:end', `:language', `:value', `:parameters' and
1957 `:post-blank' as keywords.
1959 Assume point is at the beginning of the inline src block."
1960 (save-excursion
1961 (unless (bolp) (backward-char))
1962 (looking-at org-babel-inline-src-block-regexp)
1963 (let ((begin (match-beginning 1))
1964 (language (org-match-string-no-properties 2))
1965 (parameters (org-match-string-no-properties 4))
1966 (value (org-match-string-no-properties 5))
1967 (post-blank (progn (goto-char (match-end 0))
1968 (skip-chars-forward " \t")))
1969 (end (point)))
1970 `(inline-src-block
1971 (:language ,language
1972 :value ,value
1973 :parameters ,parameters
1974 :begin ,begin
1975 :end ,end
1976 :post-blank ,post-blank)))))
1978 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
1979 "Interpret INLINE-SRC-BLOCK object as Org syntax.
1980 CONTENTS is nil."
1981 (let ((language (org-element-property :language inline-src-block))
1982 (arguments (org-element-property :parameters inline-src-block))
1983 (body (org-element-property :value inline-src-block)))
1984 (format "src_%s%s{%s}"
1985 language
1986 (if arguments (format "[%s]" arguments) "")
1987 body)))
1989 (defun org-element-inline-src-block-successor (limit)
1990 "Search for the next inline-babel-call element.
1992 LIMIT bounds the search.
1994 Return value is a cons cell whose car is `inline-babel-call' and
1995 cdr is beginning position."
1996 (save-excursion
1997 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
1998 (cons 'inline-src-block (match-beginning 1)))))
2001 ;;;; Latex Fragment
2003 (defun org-element-latex-fragment-parser ()
2004 "Parse latex fragment at point.
2006 Return a list whose car is `latex-fragment' and cdr a plist with
2007 `:value', `:begin', `:end', and `:post-blank' as keywords.
2009 Assume point is at the beginning of the latex fragment."
2010 (save-excursion
2011 (let* ((begin (point))
2012 (substring-match
2013 (catch 'exit
2014 (mapc (lambda (e)
2015 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2016 (when (or (looking-at latex-regexp)
2017 (and (not (bobp))
2018 (save-excursion
2019 (backward-char)
2020 (looking-at latex-regexp))))
2021 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2022 (plist-get org-format-latex-options :matchers))
2023 ;; None found: it's a macro.
2024 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2026 (value (match-string-no-properties substring-match))
2027 (post-blank (progn (goto-char (match-end substring-match))
2028 (skip-chars-forward " \t")))
2029 (end (point)))
2030 `(latex-fragment
2031 (:value ,value
2032 :begin ,begin
2033 :end ,end
2034 :post-blank ,post-blank)))))
2036 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2037 "Interpret LATEX-FRAGMENT object as Org syntax.
2038 CONTENTS is nil."
2039 (org-element-property :value latex-fragment))
2041 ;;;; Line Break
2043 (defun org-element-line-break-parser ()
2044 "Parse line break at point.
2046 Return a list whose car is `line-break', and cdr a plist with
2047 `:begin', `:end' and `:post-blank' keywords.
2049 Assume point is at the beginning of the line break."
2050 (let ((begin (point))
2051 (end (save-excursion (forward-line) (point))))
2052 `(line-break (:begin ,begin :end ,end :post-blank 0))))
2054 (defun org-element-line-break-interpreter (line-break contents)
2055 "Interpret LINE-BREAK object as Org syntax.
2056 CONTENTS is nil."
2057 "\\\\\n")
2059 (defun org-element-line-break-successor (limit)
2060 "Search for the next line-break object.
2062 LIMIT bounds the search.
2064 Return value is a cons cell whose car is `line-break' and cdr is
2065 beginning position."
2066 (save-excursion
2067 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2068 (goto-char (match-beginning 1)))))
2069 ;; A line break can only happen on a non-empty line.
2070 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2071 (cons 'line-break beg)))))
2074 ;;;; Link
2076 (defun org-element-link-parser ()
2077 "Parse link at point.
2079 Return a list whose car is `link' and cdr a plist with `:type',
2080 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
2081 `:contents-end' and `:post-blank' as keywords.
2083 Assume point is at the beginning of the link."
2084 (save-excursion
2085 (let ((begin (point))
2086 end contents-begin contents-end link-end post-blank path type
2087 raw-link link)
2088 (cond
2089 ;; Type 1: Text targeted from a radio target.
2090 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2091 (setq type "radio"
2092 link-end (match-end 0)
2093 path (org-match-string-no-properties 0)))
2094 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2095 ((looking-at org-bracket-link-regexp)
2096 (setq contents-begin (match-beginning 3)
2097 contents-end (match-end 3)
2098 link-end (match-end 0)
2099 ;; RAW-LINK is the original link.
2100 raw-link (org-match-string-no-properties 1)
2101 link (org-link-expand-abbrev
2102 (replace-regexp-in-string
2103 " *\n *" " " (org-link-unescape raw-link) t t)))
2104 ;; Determine TYPE of link and set PATH accordingly.
2105 (cond
2106 ;; File type.
2107 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2108 (setq type "file" path link))
2109 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2110 ((string-match org-link-re-with-space3 link)
2111 (setq type (match-string 1 link) path (match-string 2 link)))
2112 ;; Id type: PATH is the id.
2113 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2114 (setq type "id" path (match-string 1 link)))
2115 ;; Code-ref type: PATH is the name of the reference.
2116 ((string-match "^(\\(.*\\))$" link)
2117 (setq type "coderef" path (match-string 1 link)))
2118 ;; Custom-id type: PATH is the name of the custom id.
2119 ((= (aref link 0) ?#)
2120 (setq type "custom-id" path (substring link 1)))
2121 ;; Fuzzy type: Internal link either matches a target, an
2122 ;; headline name or nothing. PATH is the target or headline's
2123 ;; name.
2124 (t (setq type "fuzzy" path link))))
2125 ;; Type 3: Plain link, i.e. http://orgmode.org
2126 ((looking-at org-plain-link-re)
2127 (setq raw-link (org-match-string-no-properties 0)
2128 type (org-match-string-no-properties 1)
2129 path (org-match-string-no-properties 2)
2130 link-end (match-end 0)))
2131 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2132 ((looking-at org-angle-link-re)
2133 (setq raw-link (buffer-substring-no-properties
2134 (match-beginning 1) (match-end 2))
2135 type (org-match-string-no-properties 1)
2136 path (org-match-string-no-properties 2)
2137 link-end (match-end 0))))
2138 ;; In any case, deduce end point after trailing white space from
2139 ;; LINK-END variable.
2140 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2141 end (point))
2142 `(link
2143 (:type ,type
2144 :path ,path
2145 :raw-link ,(or raw-link path)
2146 :begin ,begin
2147 :end ,end
2148 :contents-begin ,contents-begin
2149 :contents-end ,contents-end
2150 :post-blank ,post-blank)))))
2152 (defun org-element-link-interpreter (link contents)
2153 "Interpret LINK object as Org syntax.
2154 CONTENTS is the contents of the object, or nil."
2155 (let ((type (org-element-property :type link))
2156 (raw-link (org-element-property :raw-link link)))
2157 (if (string= type "radio") raw-link
2158 (format "[[%s]%s]"
2159 raw-link
2160 (if contents (format "[%s]" contents) "")))))
2162 (defun org-element-link-successor (limit)
2163 "Search for the next link object.
2165 LIMIT bounds the search.
2167 Return value is a cons cell whose car is `link' and cdr is
2168 beginning position."
2169 (save-excursion
2170 (let ((link-regexp
2171 (if (not org-target-link-regexp) org-any-link-re
2172 (concat org-any-link-re "\\|" org-target-link-regexp))))
2173 (when (re-search-forward link-regexp limit t)
2174 (cons 'link (match-beginning 0))))))
2177 ;;;; Macro
2179 (defun org-element-macro-parser ()
2180 "Parse macro at point.
2182 Return a list whose car is `macro' and cdr a plist with `:key',
2183 `:args', `:begin', `:end', `:value' and `:post-blank' as
2184 keywords.
2186 Assume point is at the macro."
2187 (save-excursion
2188 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2189 (let ((begin (point))
2190 (key (downcase (org-match-string-no-properties 1)))
2191 (value (org-match-string-no-properties 0))
2192 (post-blank (progn (goto-char (match-end 0))
2193 (skip-chars-forward " \t")))
2194 (end (point))
2195 (args (let ((args (org-match-string-no-properties 3)) args2)
2196 (when args
2197 (setq args (org-split-string args ","))
2198 (while args
2199 (while (string-match "\\\\\\'" (car args))
2200 ;; Repair bad splits.
2201 (setcar (cdr args) (concat (substring (car args) 0 -1)
2202 "," (nth 1 args)))
2203 (pop args))
2204 (push (pop args) args2))
2205 (mapcar 'org-trim (nreverse args2))))))
2206 `(macro
2207 (:key ,key
2208 :value ,value
2209 :args ,args
2210 :begin ,begin
2211 :end ,end
2212 :post-blank ,post-blank)))))
2214 (defun org-element-macro-interpreter (macro contents)
2215 "Interpret MACRO object as Org syntax.
2216 CONTENTS is nil."
2217 (org-element-property :value macro))
2219 (defun org-element-macro-successor (limit)
2220 "Search for the next macro object.
2222 LIMIT bounds the search.
2224 Return value is cons cell whose car is `macro' and cdr is
2225 beginning position."
2226 (save-excursion
2227 (when (re-search-forward
2228 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2229 limit t)
2230 (cons 'macro (match-beginning 0)))))
2233 ;;;; Radio-target
2235 (defun org-element-radio-target-parser ()
2236 "Parse radio target at point.
2238 Return a list whose car is `radio-target' and cdr a plist with
2239 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2240 and `:post-blank' as keywords.
2242 Assume point is at the radio target."
2243 (save-excursion
2244 (looking-at org-radio-target-regexp)
2245 (let ((begin (point))
2246 (contents-begin (match-beginning 1))
2247 (contents-end (match-end 1))
2248 (value (org-match-string-no-properties 1))
2249 (post-blank (progn (goto-char (match-end 0))
2250 (skip-chars-forward " \t")))
2251 (end (point)))
2252 `(radio-target
2253 (:begin ,begin
2254 :end ,end
2255 :contents-begin ,contents-begin
2256 :contents-end ,contents-end
2257 :post-blank ,post-blank
2258 :value ,value)))))
2260 (defun org-element-radio-target-interpreter (target contents)
2261 "Interpret TARGET object as Org syntax.
2262 CONTENTS is the contents of the object."
2263 (concat "<<<" contents ">>>"))
2265 (defun org-element-radio-target-successor (limit)
2266 "Search for the next radio-target object.
2268 LIMIT bounds the search.
2270 Return value is a cons cell whose car is `radio-target' and cdr
2271 is beginning position."
2272 (save-excursion
2273 (when (re-search-forward org-radio-target-regexp limit t)
2274 (cons 'radio-target (match-beginning 0)))))
2277 ;;;; Statistics Cookie
2279 (defun org-element-statistics-cookie-parser ()
2280 "Parse statistics cookie at point.
2282 Return a list whose car is `statistics-cookie', and cdr a plist
2283 with `:begin', `:end', `:value' and `:post-blank' keywords.
2285 Assume point is at the beginning of the statistics-cookie."
2286 (save-excursion
2287 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2288 (let* ((begin (point))
2289 (value (buffer-substring-no-properties
2290 (match-beginning 0) (match-end 0)))
2291 (post-blank (progn (goto-char (match-end 0))
2292 (skip-chars-forward " \t")))
2293 (end (point)))
2294 `(statistics-cookie
2295 (:begin ,begin
2296 :end ,end
2297 :value ,value
2298 :post-blank ,post-blank)))))
2300 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2301 "Interpret STATISTICS-COOKIE object as Org syntax.
2302 CONTENTS is nil."
2303 (org-element-property :value statistics-cookie))
2305 (defun org-element-statistics-cookie-successor (limit)
2306 "Search for the next statistics cookie object.
2308 LIMIT bounds the search.
2310 Return value is a cons cell whose car is `statistics-cookie' and
2311 cdr is beginning position."
2312 (save-excursion
2313 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2314 (cons 'statistics-cookie (match-beginning 0)))))
2317 ;;;; Subscript
2319 (defun org-element-subscript-parser ()
2320 "Parse subscript at point.
2322 Return a list whose car is `subscript' and cdr a plist with
2323 `:begin', `:end', `:contents-begin', `:contents-end',
2324 `:use-brackets-p' and `:post-blank' as keywords.
2326 Assume point is at the underscore."
2327 (save-excursion
2328 (unless (bolp) (backward-char))
2329 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2331 (not (looking-at org-match-substring-regexp))))
2332 (begin (match-beginning 2))
2333 (contents-begin (or (match-beginning 5)
2334 (match-beginning 3)))
2335 (contents-end (or (match-end 5) (match-end 3)))
2336 (post-blank (progn (goto-char (match-end 0))
2337 (skip-chars-forward " \t")))
2338 (end (point)))
2339 `(subscript
2340 (:begin ,begin
2341 :end ,end
2342 :use-brackets-p ,bracketsp
2343 :contents-begin ,contents-begin
2344 :contents-end ,contents-end
2345 :post-blank ,post-blank)))))
2347 (defun org-element-subscript-interpreter (subscript contents)
2348 "Interpret SUBSCRIPT object as Org syntax.
2349 CONTENTS is the contents of the object."
2350 (format
2351 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
2352 contents))
2354 (defun org-element-sub/superscript-successor (limit)
2355 "Search for the next sub/superscript object.
2357 LIMIT bounds the search.
2359 Return value is a cons cell whose car is either `subscript' or
2360 `superscript' and cdr is beginning position."
2361 (save-excursion
2362 (when (re-search-forward org-match-substring-regexp limit t)
2363 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2364 (match-beginning 2)))))
2367 ;;;; Superscript
2369 (defun org-element-superscript-parser ()
2370 "Parse superscript at point.
2372 Return a list whose car is `superscript' and cdr a plist with
2373 `:begin', `:end', `:contents-begin', `:contents-end',
2374 `:use-brackets-p' and `:post-blank' as keywords.
2376 Assume point is at the caret."
2377 (save-excursion
2378 (unless (bolp) (backward-char))
2379 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
2380 (not (looking-at org-match-substring-regexp))))
2381 (begin (match-beginning 2))
2382 (contents-begin (or (match-beginning 5)
2383 (match-beginning 3)))
2384 (contents-end (or (match-end 5) (match-end 3)))
2385 (post-blank (progn (goto-char (match-end 0))
2386 (skip-chars-forward " \t")))
2387 (end (point)))
2388 `(superscript
2389 (:begin ,begin
2390 :end ,end
2391 :use-brackets-p ,bracketsp
2392 :contents-begin ,contents-begin
2393 :contents-end ,contents-end
2394 :post-blank ,post-blank)))))
2396 (defun org-element-superscript-interpreter (superscript contents)
2397 "Interpret SUPERSCRIPT object as Org syntax.
2398 CONTENTS is the contents of the object."
2399 (format
2400 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
2401 contents))
2404 ;;;; Table Cell
2406 (defun org-element-table-cell-parser ()
2407 "Parse table cell at point.
2409 Return a list whose CAR is `table-cell' and CDR is a plist
2410 containing `:begin', `:end', `:contents-begin', `:contents-end'
2411 and `:post-blank' keywords."
2412 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
2413 (let* ((begin (match-beginning 0))
2414 (end (match-end 0))
2415 (contents-begin (match-beginning 1))
2416 (contents-end (match-end 1)))
2417 `(table-cell
2418 (:begin ,begin
2419 :end ,end
2420 :contents-begin ,contents-begin
2421 :contents-end ,contents-end
2422 :post-blank 0))))
2424 (defun org-element-table-cell-interpreter (table-cell contents)
2425 "Interpret TABLE-CELL element as Org syntax.
2426 CONTENTS is the contents of the cell, or nil."
2427 (concat " " contents " |"))
2429 (defun org-element-table-cell-successor (limit)
2430 "Search for the next table-cell object.
2432 LIMIT bounds the search.
2434 Return value is a cons cell whose CAR is `table-cell' and CDR is
2435 beginning position."
2436 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
2439 ;;;; Target
2441 (defun org-element-target-parser ()
2442 "Parse target at point.
2444 Return a list whose CAR is `target' and CDR a plist with
2445 `:begin', `:end', `:value' and `:post-blank' as keywords.
2447 Assume point is at the target."
2448 (save-excursion
2449 (looking-at org-target-regexp)
2450 (let ((begin (point))
2451 (value (org-match-string-no-properties 1))
2452 (post-blank (progn (goto-char (match-end 0))
2453 (skip-chars-forward " \t")))
2454 (end (point)))
2455 `(target
2456 (:begin ,begin
2457 :end ,end
2458 :value ,value
2459 :post-blank ,post-blank)))))
2461 (defun org-element-target-interpreter (target contents)
2462 "Interpret TARGET object as Org syntax.
2463 CONTENTS is nil."
2464 (format "<<%s>>" (org-element-property :value target)))
2466 (defun org-element-target-successor (limit)
2467 "Search for the next target object.
2469 LIMIT bounds the search.
2471 Return value is a cons cell whose car is `target' and cdr is
2472 beginning position."
2473 (save-excursion
2474 (when (re-search-forward org-target-regexp limit t)
2475 (cons 'target (match-beginning 0)))))
2478 ;;;; Time-stamp
2480 (defun org-element-time-stamp-parser ()
2481 "Parse time stamp at point.
2483 Return a list whose car is `time-stamp', and cdr a plist with
2484 `:appt-type', `:type', `:begin', `:end', `:value' and
2485 `:post-blank' keywords.
2487 Assume point is at the beginning of the time-stamp."
2488 (save-excursion
2489 (let* ((appt-type (cond
2490 ((looking-at (concat org-deadline-string " +"))
2491 (goto-char (match-end 0))
2492 'deadline)
2493 ((looking-at (concat org-scheduled-string " +"))
2494 (goto-char (match-end 0))
2495 'scheduled)
2496 ((looking-at (concat org-closed-string " +"))
2497 (goto-char (match-end 0))
2498 'closed)))
2499 (begin (and appt-type (match-beginning 0)))
2500 (type (cond
2501 ((looking-at org-tsr-regexp)
2502 (if (match-string 2) 'active-range 'active))
2503 ((looking-at org-tsr-regexp-both)
2504 (if (match-string 2) 'inactive-range 'inactive))
2505 ((looking-at (concat
2506 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2507 "\\|"
2508 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2509 'diary)))
2510 (begin (or begin (match-beginning 0)))
2511 (value (buffer-substring-no-properties
2512 (match-beginning 0) (match-end 0)))
2513 (post-blank (progn (goto-char (match-end 0))
2514 (skip-chars-forward " \t")))
2515 (end (point)))
2516 `(time-stamp
2517 (:appt-type ,appt-type
2518 :type ,type
2519 :value ,value
2520 :begin ,begin
2521 :end ,end
2522 :post-blank ,post-blank)))))
2524 (defun org-element-time-stamp-interpreter (time-stamp contents)
2525 "Interpret TIME-STAMP object as Org syntax.
2526 CONTENTS is nil."
2527 (concat
2528 (case (org-element-property :appt-type time-stamp)
2529 (closed (concat org-closed-string " "))
2530 (deadline (concat org-deadline-string " "))
2531 (scheduled (concat org-scheduled-string " ")))
2532 (org-element-property :value time-stamp)))
2534 (defun org-element-time-stamp-successor (limit)
2535 "Search for the next time-stamp object.
2537 LIMIT bounds the search.
2539 Return value is a cons cell whose car is `time-stamp' and cdr is
2540 beginning position."
2541 (save-excursion
2542 (when (re-search-forward
2543 (concat "\\(?:" org-scheduled-string " +\\|"
2544 org-deadline-string " +\\|" org-closed-string " +\\)?"
2545 org-ts-regexp-both
2546 "\\|"
2547 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2548 "\\|"
2549 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2550 limit t)
2551 (cons 'time-stamp (match-beginning 0)))))
2554 ;;;; Verbatim
2556 (defun org-element-verbatim-parser ()
2557 "Parse verbatim object at point.
2559 Return a list whose car is `verbatim' and cdr is a plist with
2560 `:marker', `:begin', `:end' and `:post-blank' keywords.
2562 Assume point is at the first verbatim marker."
2563 (save-excursion
2564 (unless (bolp) (backward-char 1))
2565 (looking-at org-emph-re)
2566 (let ((begin (match-beginning 2))
2567 (marker (org-match-string-no-properties 3))
2568 (value (org-match-string-no-properties 4))
2569 (post-blank (progn (goto-char (match-end 2))
2570 (skip-chars-forward " \t")))
2571 (end (point)))
2572 `(verbatim
2573 (:marker ,marker
2574 :begin ,begin
2575 :end ,end
2576 :value ,value
2577 :post-blank ,post-blank)))))
2579 (defun org-element-verbatim-interpreter (verbatim contents)
2580 "Interpret VERBATIM object as Org syntax.
2581 CONTENTS is nil."
2582 (let ((marker (org-element-property :marker verbatim))
2583 (value (org-element-property :value verbatim)))
2584 (concat marker value marker)))
2588 ;;; Definitions And Rules
2590 ;; Define elements, greater elements and specify recursive objects,
2591 ;; along with the affiliated keywords recognized. Also set up
2592 ;; restrictions on recursive objects combinations.
2594 ;; These variables really act as a control center for the parsing
2595 ;; process.
2596 (defconst org-element-paragraph-separate
2597 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2598 ;; Headlines and inlinetasks.
2599 org-outline-regexp-bol "\\|"
2600 ;; Comments, blocks (any type), keywords and babel calls.
2601 "^[ \t]*#\\+" "\\|" "^#\\( \\|$\\)" "\\|"
2602 ;; Lists.
2603 (org-item-beginning-re) "\\|"
2604 ;; Fixed-width, drawers (any type) and tables.
2605 "^[ \t]*[:|]" "\\|"
2606 ;; Footnote definitions.
2607 org-footnote-definition-re "\\|"
2608 ;; Horizontal rules.
2609 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2610 ;; LaTeX environments.
2611 "^[ \t]*\\\\\\(begin\\|end\\)")
2612 "Regexp to separate paragraphs in an Org buffer.")
2614 (defconst org-element-all-elements
2615 '(center-block comment comment-block drawer dynamic-block example-block
2616 export-block fixed-width footnote-definition headline
2617 horizontal-rule inlinetask item keyword latex-environment
2618 babel-call paragraph plain-list property-drawer quote-block
2619 quote-section section special-block src-block table table-row
2620 verse-block)
2621 "Complete list of element types.")
2623 (defconst org-element-greater-elements
2624 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2625 item plain-list quote-block section special-block table)
2626 "List of recursive element types aka Greater Elements.")
2628 (defconst org-element-all-successors
2629 '(export-snippet footnote-reference inline-babel-call inline-src-block
2630 latex-or-entity line-break link macro radio-target
2631 statistics-cookie sub/superscript table-cell target
2632 text-markup time-stamp)
2633 "Complete list of successors.")
2635 (defconst org-element-object-successor-alist
2636 '((subscript . sub/superscript) (superscript . sub/superscript)
2637 (emphasis . text-markup) (verbatim . text-markup)
2638 (entity . latex-or-entity) (latex-fragment . latex-or-entity))
2639 "Alist of translations between object type and successor name.
2641 Sharing the same successor comes handy when, for example, the
2642 regexp matching one object can also match the other object.")
2644 (defconst org-element-all-objects
2645 '(emphasis entity export-snippet footnote-reference inline-babel-call
2646 inline-src-block line-break latex-fragment link macro radio-target
2647 statistics-cookie subscript superscript table-cell target
2648 time-stamp verbatim)
2649 "Complete list of object types.")
2651 (defconst org-element-recursive-objects
2652 '(emphasis link macro subscript radio-target superscript table-cell)
2653 "List of recursive object types.")
2655 (defconst org-element-non-recursive-block-alist
2656 '(("ASCII" . export-block)
2657 ("COMMENT" . comment-block)
2658 ("DOCBOOK" . export-block)
2659 ("EXAMPLE" . example-block)
2660 ("HTML" . export-block)
2661 ("LATEX" . export-block)
2662 ("ODT" . export-block)
2663 ("SRC" . src-block)
2664 ("VERSE" . verse-block))
2665 "Alist between non-recursive block name and their element type.")
2667 (defconst org-element-affiliated-keywords
2668 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "CAPTION"
2669 "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT" "RESULTS"
2670 "SOURCE" "SRCNAME" "TBLNAME")
2671 "List of affiliated keywords as strings.")
2673 (defconst org-element-keyword-translation-alist
2674 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
2675 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
2676 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
2677 "Alist of usual translations for keywords.
2678 The key is the old name and the value the new one. The property
2679 holding their value will be named after the translated name.")
2681 (defconst org-element-multiple-keywords
2682 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "HEADER")
2683 "List of affiliated keywords that can occur more that once in an element.
2685 Their value will be consed into a list of strings, which will be
2686 returned as the value of the property.
2688 This list is checked after translations have been applied. See
2689 `org-element-keyword-translation-alist'.")
2691 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "TITLE")
2692 "List of keywords whose value can be parsed.
2694 Their value will be stored as a secondary string: a list of
2695 strings and objects.
2697 This list is checked after translations have been applied. See
2698 `org-element-keyword-translation-alist'.")
2700 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
2701 "List of keywords which can have a secondary value.
2703 In Org syntax, they can be written with optional square brackets
2704 before the colons. For example, results keyword can be
2705 associated to a hash value with the following:
2707 #+RESULTS[hash-string]: some-source
2709 This list is checked after translations have been applied. See
2710 `org-element-keyword-translation-alist'.")
2712 (defconst org-element-object-restrictions
2713 `((emphasis entity export-snippet inline-babel-call inline-src-block link
2714 radio-target sub/superscript target text-markup time-stamp)
2715 (footnote-reference entity export-snippet footnote-reference
2716 inline-babel-call inline-src-block latex-fragment
2717 line-break link macro radio-target sub/superscript
2718 target text-markup time-stamp)
2719 (headline entity inline-babel-call inline-src-block latex-fragment link
2720 macro radio-target statistics-cookie sub/superscript text-markup
2721 time-stamp)
2722 (inlinetask entity inline-babel-call inline-src-block latex-fragment link
2723 macro radio-target sub/superscript text-markup time-stamp)
2724 (item entity inline-babel-call latex-fragment macro radio-target
2725 sub/superscript target text-markup)
2726 (keyword entity latex-fragment macro sub/superscript text-markup)
2727 (link entity export-snippet inline-babel-call inline-src-block
2728 latex-fragment link sub/superscript text-markup)
2729 (macro macro)
2730 (paragraph ,@org-element-all-successors)
2731 (radio-target entity export-snippet latex-fragment sub/superscript)
2732 (subscript entity export-snippet inline-babel-call inline-src-block
2733 latex-fragment sub/superscript text-markup)
2734 (superscript entity export-snippet inline-babel-call inline-src-block
2735 latex-fragment sub/superscript text-markup)
2736 (table-cell entity export-snippet latex-fragment link macro radio-target
2737 sub/superscript target text-markup time-stamp)
2738 (table-row table-cell)
2739 (verse-block entity footnote-reference inline-babel-call inline-src-block
2740 latex-fragment line-break link macro radio-target
2741 sub/superscript target text-markup time-stamp))
2742 "Alist of objects restrictions.
2744 CAR is an element or object type containing objects and CDR is
2745 a list of successors that will be called within an element or
2746 object of such type.
2748 For example, in a `radio-target' object, one can only find
2749 entities, export snippets, latex-fragments, subscript and
2750 superscript.
2752 This alist also applies to secondary string. For example, an
2753 `headline' type element doesn't directly contain objects, but
2754 still has an entry since one of its properties (`:title') does.")
2756 (defconst org-element-secondary-value-alist
2757 '((headline . :title)
2758 (inlinetask . :title)
2759 (item . :tag)
2760 (footnote-reference . :inline-definition))
2761 "Alist between element types and location of secondary value.")
2765 ;;; Accessors
2767 ;; Provide four accessors: `org-element-type', `org-element-property'
2768 ;; `org-element-contents' and `org-element-restriction'.
2770 (defun org-element-type (element)
2771 "Return type of element ELEMENT.
2773 The function returns the type of the element or object provided.
2774 It can also return the following special value:
2775 `plain-text' for a string
2776 `org-data' for a complete document
2777 nil in any other case."
2778 (cond
2779 ((not (consp element)) (and (stringp element) 'plain-text))
2780 ((symbolp (car element)) (car element))))
2782 (defun org-element-property (property element)
2783 "Extract the value from the PROPERTY of an ELEMENT."
2784 (plist-get (nth 1 element) property))
2786 (defun org-element-contents (element)
2787 "Extract contents from an ELEMENT."
2788 (and (consp element) (nthcdr 2 element)))
2790 (defun org-element-restriction (element)
2791 "Return restriction associated to ELEMENT.
2792 ELEMENT can be an element, an object or a symbol representing an
2793 element or object type."
2794 (cdr (assq (if (symbolp element) element (org-element-type element))
2795 org-element-object-restrictions)))
2799 ;;; Parsing Element Starting At Point
2801 ;; `org-element-current-element' is the core function of this section.
2802 ;; It returns the Lisp representation of the element starting at
2803 ;; point. It uses `org-element--element-block-re' for quick access to
2804 ;; a common regexp.
2806 (defconst org-element--element-block-re
2807 (format "[ \t]*#\\+BEGIN_\\(%s\\)\\(?: \\|$\\)"
2808 (mapconcat
2809 'regexp-quote
2810 (mapcar 'car org-element-non-recursive-block-alist) "\\|"))
2811 "Regexp matching the beginning of a non-recursive block type.
2812 Used internally by `org-element-current-element'. Do not modify
2813 it directly, set `org-element-recursive-block-alist' instead.")
2815 (defun org-element-current-element (&optional granularity special structure)
2816 "Parse the element starting at point.
2818 Return value is a list like (TYPE PROPS) where TYPE is the type
2819 of the element and PROPS a plist of properties associated to the
2820 element.
2822 Possible types are defined in `org-element-all-elements'.
2824 Optional argument GRANULARITY determines the depth of the
2825 recursion. Allowed values are `headline', `greater-element',
2826 `element', `object' or nil. When it is broader than `object' (or
2827 nil), secondary values will not be parsed, since they only
2828 contain objects.
2830 Optional argument SPECIAL, when non-nil, can be either `item',
2831 `section', `quote-section' or `table-row'. `item' allows to
2832 parse item wise instead of plain-list wise, using STRUCTURE as
2833 the current list structure. `section' (resp. `quote-section')
2834 will try to parse a section (resp. a quote section) before
2835 anything else.
2837 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
2838 be computed.
2840 Unlike to `org-element-at-point', this function assumes point is
2841 always at the beginning of the element it has to parse. As such,
2842 it is quicker than its counterpart, albeit more restrictive."
2843 (save-excursion
2844 ;; If point is at an affiliated keyword, try moving to the
2845 ;; beginning of the associated element. If none is found, the
2846 ;; keyword is orphaned and will be treated as plain text.
2847 (when (looking-at org-element--affiliated-re)
2848 (let ((opoint (point)))
2849 (while (looking-at org-element--affiliated-re) (forward-line))
2850 (when (looking-at "[ \t]*$") (goto-char opoint))))
2851 (let ((case-fold-search t)
2852 ;; Determine if parsing depth allows for secondary strings
2853 ;; parsing. It only applies to elements referenced in
2854 ;; `org-element-secondary-value-alist'.
2855 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
2856 (cond
2857 ;; Item
2858 ((eq special 'item)
2859 (org-element-item-parser (or structure (org-list-struct))
2860 raw-secondary-p))
2861 ;; Quote section.
2862 ((eq special 'quote-section) (org-element-quote-section-parser))
2863 ;; Table Row
2864 ((eq special 'table-row) (org-element-table-row-parser))
2865 ;; Headline.
2866 ((org-with-limited-levels (org-at-heading-p))
2867 (org-element-headline-parser raw-secondary-p))
2868 ;; Section (must be checked after headline)
2869 ((eq special 'section) (org-element-section-parser))
2870 ;; Non-recursive block.
2871 ((when (looking-at org-element--element-block-re)
2872 (let ((type (upcase (match-string 1))))
2873 (if (save-excursion
2874 (re-search-forward
2875 (format "[ \t]*#\\+END_%s\\(?: \\|$\\)" type) nil t))
2876 (funcall
2877 (intern
2878 (format
2879 "org-element-%s-parser"
2880 (cdr (assoc type org-element-non-recursive-block-alist)))))
2881 (org-element-paragraph-parser)))))
2882 ;; Inlinetask.
2883 ((org-at-heading-p) (org-element-inlinetask-parser raw-secondary-p))
2884 ;; LaTeX Environment or Paragraph if incomplete.
2885 ((looking-at "^[ \t]*\\\\begin{")
2886 (if (save-excursion
2887 (re-search-forward "^[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
2888 (org-element-latex-environment-parser)
2889 (org-element-paragraph-parser)))
2890 ;; Property Drawer.
2891 ((looking-at org-property-start-re)
2892 (if (save-excursion (re-search-forward org-property-end-re nil t))
2893 (org-element-property-drawer-parser)
2894 (org-element-paragraph-parser)))
2895 ;; Recursive Block, or Paragraph if incomplete.
2896 ((looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
2897 (let ((type (upcase (match-string 1))))
2898 (cond
2899 ((not (save-excursion
2900 (re-search-forward
2901 (format "[ \t]*#\\+END_%s\\(?: \\|$\\)" type) nil t)))
2902 (org-element-paragraph-parser))
2903 ((string= type "CENTER") (org-element-center-block-parser))
2904 ((string= type "QUOTE") (org-element-quote-block-parser))
2905 (t (org-element-special-block-parser)))))
2906 ;; Drawer.
2907 ((looking-at org-drawer-regexp)
2908 (if (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t))
2909 (org-element-drawer-parser)
2910 (org-element-paragraph-parser)))
2911 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
2912 ;; Babel Call.
2913 ((looking-at org-babel-block-lob-one-liner-regexp)
2914 (org-element-babel-call-parser))
2915 ;; Keyword, or Paragraph if at an orphaned affiliated keyword.
2916 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
2917 (let ((key (upcase (match-string 1))))
2918 (if (or (string= key "TBLFM")
2919 (member key org-element-affiliated-keywords))
2920 (org-element-paragraph-parser)
2921 (org-element-keyword-parser))))
2922 ;; Footnote definition.
2923 ((looking-at org-footnote-definition-re)
2924 (org-element-footnote-definition-parser))
2925 ;; Dynamic Block or Paragraph if incomplete.
2926 ((looking-at "[ \t]*#\\+BEGIN:\\(?: \\|$\\)")
2927 (if (save-excursion
2928 (re-search-forward "^[ \t]*#\\+END:\\(?: \\|$\\)" nil t))
2929 (org-element-dynamic-block-parser)
2930 (org-element-paragraph-parser)))
2931 ;; Comment.
2932 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
2933 (org-element-comment-parser))
2934 ;; Horizontal Rule.
2935 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
2936 (org-element-horizontal-rule-parser))
2937 ;; Table.
2938 ((org-at-table-p t) (org-element-table-parser))
2939 ;; List or Item.
2940 ((looking-at (org-item-re))
2941 (org-element-plain-list-parser (or structure (org-list-struct))))
2942 ;; Default element: Paragraph.
2943 (t (org-element-paragraph-parser))))))
2946 ;; Most elements can have affiliated keywords. When looking for an
2947 ;; element beginning, we want to move before them, as they belong to
2948 ;; that element, and, in the meantime, collect information they give
2949 ;; into appropriate properties. Hence the following function.
2951 ;; Usage of optional arguments may not be obvious at first glance:
2953 ;; - TRANS-LIST is used to polish keywords names that have evolved
2954 ;; during Org history. In example, even though =result= and
2955 ;; =results= coexist, we want to have them under the same =result=
2956 ;; property. It's also true for "srcname" and "name", where the
2957 ;; latter seems to be preferred nowadays (thus the "name" property).
2959 ;; - CONSED allows to regroup multi-lines keywords under the same
2960 ;; property, while preserving their own identity. This is mostly
2961 ;; used for "attr_latex" and al.
2963 ;; - PARSED prepares a keyword value for export. This is useful for
2964 ;; "caption". Objects restrictions for such keywords are defined in
2965 ;; `org-element-object-restrictions'.
2967 ;; - DUALS is used to take care of keywords accepting a main and an
2968 ;; optional secondary values. For example "results" has its
2969 ;; source's name as the main value, and may have an hash string in
2970 ;; optional square brackets as the secondary one.
2972 ;; A keyword may belong to more than one category.
2974 (defconst org-element--affiliated-re
2975 (format "[ \t]*#\\+\\(%s\\):"
2976 (mapconcat
2977 (lambda (keyword)
2978 (if (member keyword org-element-dual-keywords)
2979 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
2980 (regexp-quote keyword))
2981 (regexp-quote keyword)))
2982 org-element-affiliated-keywords "\\|"))
2983 "Regexp matching any affiliated keyword.
2985 Keyword name is put in match group 1. Moreover, if keyword
2986 belongs to `org-element-dual-keywords', put the dual value in
2987 match group 2.
2989 Don't modify it, set `org-element-affiliated-keywords' instead.")
2991 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
2992 consed parsed duals)
2993 "Collect affiliated keywords before point.
2995 Optional argument KEY-RE is a regexp matching keywords, which
2996 puts matched keyword in group 1. It defaults to
2997 `org-element--affiliated-re'.
2999 TRANS-LIST is an alist where key is the keyword and value the
3000 property name it should be translated to, without the colons. It
3001 defaults to `org-element-keyword-translation-alist'.
3003 CONSED is a list of strings. Any keyword belonging to that list
3004 will have its value consed. The check is done after keyword
3005 translation. It defaults to `org-element-multiple-keywords'.
3007 PARSED is a list of strings. Any keyword member of this list
3008 will have its value parsed. The check is done after keyword
3009 translation. If a keyword is a member of both CONSED and PARSED,
3010 it's value will be a list of parsed strings. It defaults to
3011 `org-element-parsed-keywords'.
3013 DUALS is a list of strings. Any keyword member of this list can
3014 have two parts: one mandatory and one optional. Its value is
3015 a cons cell whose car is the former, and the cdr the latter. If
3016 a keyword is a member of both PARSED and DUALS, both values will
3017 be parsed. It defaults to `org-element-dual-keywords'.
3019 Return a list whose car is the position at the first of them and
3020 cdr a plist of keywords and values."
3021 (save-excursion
3022 (let ((case-fold-search t)
3023 (key-re (or key-re org-element--affiliated-re))
3024 (trans-list (or trans-list org-element-keyword-translation-alist))
3025 (consed (or consed org-element-multiple-keywords))
3026 (parsed (or parsed org-element-parsed-keywords))
3027 (duals (or duals org-element-dual-keywords))
3028 ;; RESTRICT is the list of objects allowed in parsed
3029 ;; keywords value.
3030 (restrict (org-element-restriction 'keyword))
3031 output)
3032 (unless (bobp)
3033 (while (and (not (bobp))
3034 (progn (forward-line -1) (looking-at key-re)))
3035 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3036 ;; Apply translation to RAW-KWD. From there, KWD is
3037 ;; the official keyword.
3038 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3039 ;; Find main value for any keyword.
3040 (value
3041 (save-match-data
3042 (org-trim
3043 (buffer-substring-no-properties
3044 (match-end 0) (point-at-eol)))))
3045 ;; If KWD is a dual keyword, find its secondary
3046 ;; value. Maybe parse it.
3047 (dual-value
3048 (and (member kwd duals)
3049 (let ((sec (org-match-string-no-properties 3)))
3050 (if (or (not sec) (not (member kwd parsed))) sec
3051 (org-element-parse-secondary-string sec restrict)))))
3052 ;; Attribute a property name to KWD.
3053 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3054 ;; Now set final shape for VALUE.
3055 (when (member kwd parsed)
3056 (setq value (org-element-parse-secondary-string value restrict)))
3057 (when (member kwd duals)
3058 ;; VALUE is mandatory. Set it to nil if there is none.
3059 (setq value (and value (cons value dual-value))))
3060 (when (member kwd consed)
3061 (setq value (cons value (plist-get output kwd-sym))))
3062 ;; Eventually store the new value in OUTPUT.
3063 (setq output (plist-put output kwd-sym value))))
3064 (unless (looking-at key-re) (forward-line 1)))
3065 (list (point) output))))
3069 ;;; The Org Parser
3071 ;; The two major functions here are `org-element-parse-buffer', which
3072 ;; parses Org syntax inside the current buffer, taking into account
3073 ;; region, narrowing, or even visibility if specified, and
3074 ;; `org-element-parse-secondary-string', which parses objects within
3075 ;; a given string.
3077 ;; The (almost) almighty `org-element-map' allows to apply a function
3078 ;; on elements or objects matching some type, and accumulate the
3079 ;; resulting values. In an export situation, it also skips unneeded
3080 ;; parts of the parse tree.
3082 (defun org-element-parse-buffer (&optional granularity visible-only)
3083 "Recursively parse the buffer and return structure.
3084 If narrowing is in effect, only parse the visible part of the
3085 buffer.
3087 Optional argument GRANULARITY determines the depth of the
3088 recursion. It can be set to the following symbols:
3090 `headline' Only parse headlines.
3091 `greater-element' Don't recurse into greater elements excepted
3092 headlines and sections. Thus, elements
3093 parsed are the top-level ones.
3094 `element' Parse everything but objects and plain text.
3095 `object' Parse the complete buffer (default).
3097 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3098 elements.
3100 Assume buffer is in Org mode."
3101 (save-excursion
3102 (goto-char (point-min))
3103 (org-skip-whitespace)
3104 (nconc (list 'org-data nil)
3105 (org-element-parse-elements
3106 (point-at-bol) (point-max)
3107 ;; Start is section mode so text before the first headline
3108 ;; belongs to a section.
3109 'section nil granularity visible-only nil))))
3111 (defun org-element-parse-secondary-string (string restriction)
3112 "Recursively parse objects in STRING and return structure.
3114 RESTRICTION, when non-nil, is a symbol limiting the object types
3115 that will be looked after."
3116 (with-temp-buffer
3117 (insert string)
3118 (org-element-parse-objects (point-min) (point-max) nil restriction)))
3120 (defun org-element-map (data types fun &optional info first-match no-recursion)
3121 "Map a function on selected elements or objects.
3123 DATA is the parsed tree, as returned by, i.e,
3124 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3125 of elements or objects types. FUN is the function called on the
3126 matching element or object. It must accept one arguments: the
3127 element or object itself.
3129 When optional argument INFO is non-nil, it should be a plist
3130 holding export options. In that case, parts of the parse tree
3131 not exportable according to that property list will be skipped.
3133 When optional argument FIRST-MATCH is non-nil, stop at the first
3134 match for which FUN doesn't return nil, and return that value.
3136 Optional argument NO-RECURSION is a symbol or a list of symbols
3137 representing elements or objects types. `org-element-map' won't
3138 enter any recursive element or object whose type belongs to that
3139 list. Though, FUN can still be applied on them.
3141 Nil values returned from FUN do not appear in the results."
3142 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3143 (unless (listp types) (setq types (list types)))
3144 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3145 ;; Recursion depth is determined by --CATEGORY.
3146 (let* ((--category
3147 (cond
3148 ((loop for type in types
3149 always (memq type org-element-greater-elements))
3150 'greater-elements)
3151 ((loop for type in types
3152 always (memq type org-element-all-elements))
3153 'elements)
3154 (t 'objects)))
3155 ;; --RESTRICTS is a list of element types whose secondary
3156 ;; string could possibly contain an object with a type among
3157 ;; TYPES.
3158 (--restricts
3159 (and (eq --category 'objects)
3160 (loop for el in org-element-secondary-value-alist
3161 when
3162 (loop for o in types
3163 thereis (memq o (org-element-restriction (car el))))
3164 collect (car el))))
3165 --acc
3166 (--walk-tree
3167 (function
3168 (lambda (--data)
3169 ;; Recursively walk DATA. INFO, if non-nil, is
3170 ;; a plist holding contextual information.
3171 (mapc
3172 (lambda (--blob)
3173 (unless (and info (member --blob (plist-get info :ignore-list)))
3174 (let ((--type (org-element-type --blob)))
3175 ;; Check if TYPE is matching among TYPES. If so,
3176 ;; apply FUN to --BLOB and accumulate return value
3177 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3178 (when (memq --type types)
3179 (let ((result (funcall fun --blob)))
3180 (cond ((not result))
3181 (first-match (throw 'first-match result))
3182 (t (push result --acc)))))
3183 ;; If --BLOB has a secondary string that can
3184 ;; contain objects with their type among TYPES,
3185 ;; look into that string.
3186 (when (memq --type --restricts)
3187 (funcall
3188 --walk-tree
3189 `(org-data
3191 ,@(org-element-property
3192 (cdr (assq --type org-element-secondary-value-alist))
3193 --blob))))
3194 ;; Now determine if a recursion into --BLOB is
3195 ;; possible. If so, do it.
3196 (unless (memq --type no-recursion)
3197 (when (or (and (memq --type org-element-greater-elements)
3198 (not (eq --category 'greater-elements)))
3199 (and (memq --type org-element-all-elements)
3200 (not (eq --category 'elements)))
3201 (org-element-contents --blob))
3202 (funcall --walk-tree --blob))))))
3203 (org-element-contents --data))))))
3204 (catch 'first-match
3205 (funcall --walk-tree data)
3206 ;; Return value in a proper order.
3207 (nreverse --acc))))
3209 ;; The following functions are internal parts of the parser.
3211 ;; The first one, `org-element-parse-elements' acts at the element's
3212 ;; level.
3214 ;; The second one, `org-element-parse-objects' applies on all objects
3215 ;; of a paragraph or a secondary string. It uses
3216 ;; `org-element-get-candidates' to optimize the search of the next
3217 ;; object in the buffer.
3219 ;; More precisely, that function looks for every allowed object type
3220 ;; first. Then, it discards failed searches, keeps further matches,
3221 ;; and searches again types matched behind point, for subsequent
3222 ;; calls. Thus, searching for a given type fails only once, and every
3223 ;; object is searched only once at top level (but sometimes more for
3224 ;; nested types).
3226 (defun org-element-parse-elements
3227 (beg end special structure granularity visible-only acc)
3228 "Parse elements between BEG and END positions.
3230 SPECIAL prioritize some elements over the others. It can be set
3231 to `quote-section', `section' `item' or `table-row', which will
3232 focus search, respectively, on quote sections, sections, items
3233 and table-rows. Moreover, when value is `item', STRUCTURE will
3234 be used as the current list structure.
3236 GRANULARITY determines the depth of the recursion. See
3237 `org-element-parse-buffer' for more information.
3239 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3240 elements.
3242 Elements are accumulated into ACC."
3243 (save-excursion
3244 (save-restriction
3245 (narrow-to-region beg end)
3246 (goto-char beg)
3247 ;; When parsing only headlines, skip any text before first one.
3248 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3249 (org-with-limited-levels (outline-next-heading)))
3250 ;; Main loop start.
3251 (while (not (eobp))
3252 (push
3253 ;; Find current element's type and parse it accordingly to
3254 ;; its category.
3255 (let* ((element (org-element-current-element
3256 granularity special structure))
3257 (type (org-element-type element))
3258 (cbeg (org-element-property :contents-begin element)))
3259 (goto-char (org-element-property :end element))
3260 (cond
3261 ;; Case 1. Simply accumulate element if VISIBLE-ONLY is
3262 ;; true and element is hidden or if it has no contents
3263 ;; anyway.
3264 ((or (and visible-only (org-element-property :hiddenp element))
3265 (not cbeg)) element)
3266 ;; Case 2. Greater element: parse it between
3267 ;; `contents-begin' and `contents-end'. Make sure
3268 ;; GRANULARITY allows the recursion, or ELEMENT is an
3269 ;; headline, in which case going inside is mandatory, in
3270 ;; order to get sub-level headings.
3271 ((and (memq type org-element-greater-elements)
3272 (or (memq granularity '(element object nil))
3273 (and (eq granularity 'greater-element)
3274 (eq type 'section))
3275 (eq type 'headline)))
3276 (org-element-parse-elements
3277 cbeg (org-element-property :contents-end element)
3278 ;; Possibly move to a special mode.
3279 (case type
3280 (headline
3281 (if (org-element-property :quotedp element) 'quote-section
3282 'section))
3283 (table 'table-row)
3284 (plain-list 'item))
3285 (org-element-property :structure element)
3286 granularity visible-only (nreverse element)))
3287 ;; Case 3. ELEMENT has contents. Parse objects inside,
3288 ;; if GRANULARITY allows it.
3289 ((and cbeg (memq granularity '(object nil)))
3290 (org-element-parse-objects
3291 cbeg (org-element-property :contents-end element)
3292 (nreverse element) (org-element-restriction type)))
3293 ;; Case 4. Else, just accumulate ELEMENT.
3294 (t element)))
3295 acc)))
3296 ;; Return result.
3297 (nreverse acc)))
3299 (defun org-element-parse-objects (beg end acc restriction)
3300 "Parse objects between BEG and END and return recursive structure.
3302 Objects are accumulated in ACC.
3304 RESTRICTION is a list of object types which are allowed in the
3305 current object."
3306 (let ((get-next-object
3307 (function
3308 (lambda (cand)
3309 ;; Return the parsing function associated to the nearest
3310 ;; object among list of candidates CAND.
3311 (let ((pos (apply 'min (mapcar 'cdr cand))))
3312 (save-excursion
3313 (goto-char pos)
3314 (funcall
3315 (intern
3316 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3317 next-object candidates)
3318 (save-excursion
3319 (goto-char beg)
3320 (while (setq candidates (org-element-get-next-object-candidates
3321 end restriction candidates))
3322 (setq next-object (funcall get-next-object candidates))
3323 ;; 1. Text before any object. Untabify it.
3324 (let ((obj-beg (org-element-property :begin next-object)))
3325 (unless (= (point) obj-beg)
3326 (push (replace-regexp-in-string
3327 "\t" (make-string tab-width ? )
3328 (buffer-substring-no-properties (point) obj-beg))
3329 acc)))
3330 ;; 2. Object...
3331 (let ((obj-end (org-element-property :end next-object))
3332 (cont-beg (org-element-property :contents-begin next-object)))
3333 (push (if (and (memq (car next-object) org-element-recursive-objects)
3334 cont-beg)
3335 ;; ... recursive. The CONT-BEG check is for
3336 ;; links, as some of them might not be recursive
3337 ;; (i.e. plain links).
3338 (save-restriction
3339 (narrow-to-region
3340 cont-beg
3341 (org-element-property :contents-end next-object))
3342 (org-element-parse-objects
3343 (point-min) (point-max)
3344 (nreverse next-object)
3345 ;; Restrict allowed objects.
3346 (org-element-restriction next-object)))
3347 ;; ... not recursive. Accumulate the object.
3348 next-object)
3349 acc)
3350 (goto-char obj-end)))
3351 ;; 3. Text after last object. Untabify it.
3352 (unless (= (point) end)
3353 (push (replace-regexp-in-string
3354 "\t" (make-string tab-width ? )
3355 (buffer-substring-no-properties (point) end))
3356 acc))
3357 ;; Result.
3358 (nreverse acc))))
3360 (defun org-element-get-next-object-candidates (limit restriction objects)
3361 "Return an alist of candidates for the next object.
3363 LIMIT bounds the search, and RESTRICTION narrows candidates to
3364 some object types.
3366 Return value is an alist whose CAR is position and CDR the object
3367 type, as a symbol.
3369 OBJECTS is the previous candidates alist."
3370 (let (next-candidates types-to-search)
3371 ;; If no previous result, search every object type in RESTRICTION.
3372 ;; Otherwise, keep potential candidates (old objects located after
3373 ;; point) and ask to search again those which had matched before.
3374 (if (not objects) (setq types-to-search restriction)
3375 (mapc (lambda (obj)
3376 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3377 (push obj next-candidates)))
3378 objects))
3379 ;; Call the appropriate successor function for each type to search
3380 ;; and accumulate matches.
3381 (mapc
3382 (lambda (type)
3383 (let* ((successor-fun
3384 (intern
3385 (format "org-element-%s-successor"
3386 (or (cdr (assq type org-element-object-successor-alist))
3387 type))))
3388 (obj (funcall successor-fun limit)))
3389 (and obj (push obj next-candidates))))
3390 types-to-search)
3391 ;; Return alist.
3392 next-candidates))
3396 ;;; Towards A Bijective Process
3398 ;; The parse tree obtained with `org-element-parse-buffer' is really
3399 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3400 ;; interpreted and expanded into a string with canonical Org
3401 ;; syntax. Hence `org-element-interpret-data'.
3403 ;; Data parsed from secondary strings, whose shape is slightly
3404 ;; different than the standard parse tree, is expanded with the
3405 ;; equivalent function `org-element-interpret-secondary'.
3407 ;; Both functions rely internally on
3408 ;; `org-element-interpret--affiliated-keywords'.
3410 (defun org-element-interpret-data (data &optional genealogy previous)
3411 "Interpret a parse tree representing Org data.
3413 DATA is the parse tree to interpret.
3415 Optional arguments GENEALOGY and PREVIOUS are used for recursive
3416 calls:
3417 GENEALOGY is the list of its parents types.
3418 PREVIOUS is the type of the element or object at the same level
3419 interpreted before.
3421 Return Org syntax as a string."
3422 (mapconcat
3423 (lambda (blob)
3424 ;; BLOB can be an element, an object, a string, or nil.
3425 (cond
3426 ((not blob) nil)
3427 ((equal blob "") nil)
3428 ((stringp blob) blob)
3430 (let* ((type (org-element-type blob))
3431 (interpreter
3432 (if (eq type 'org-data) 'identity
3433 (intern (format "org-element-%s-interpreter" type))))
3434 (contents
3435 (cond
3436 ;; Elements or objects without contents.
3437 ((not (org-element-contents blob)) nil)
3438 ;; Full Org document.
3439 ((eq type 'org-data)
3440 (org-element-interpret-data blob genealogy previous))
3441 ;; Greater elements.
3442 ((memq type org-element-greater-elements)
3443 (org-element-interpret-data blob (cons type genealogy) nil))
3445 (org-element-interpret-data
3446 (org-element-normalize-contents
3447 blob
3448 ;; When normalizing first paragraph of an item or
3449 ;; a footnote-definition, ignore first line's
3450 ;; indentation.
3451 (and (eq type 'paragraph)
3452 (not previous)
3453 (memq (car genealogy) '(footnote-definiton item))))
3454 (cons type genealogy) nil))))
3455 (results (funcall interpreter blob contents)))
3456 ;; Update PREVIOUS.
3457 (setq previous type)
3458 ;; Build white spaces. If no `:post-blank' property is
3459 ;; specified, assume its value is 0.
3460 (let ((post-blank (or (org-element-property :post-blank blob) 0)))
3461 (cond
3462 ((eq type 'org-data) results)
3463 ((memq type org-element-all-elements)
3464 (concat
3465 (org-element-interpret--affiliated-keywords blob)
3466 (org-element-normalize-string results)
3467 (make-string post-blank 10)))
3468 (t (concat results (make-string post-blank 32)))))))))
3469 (org-element-contents data) ""))
3471 (defun org-element-interpret-secondary (secondary)
3472 "Interpret SECONDARY string as Org syntax.
3474 SECONDARY-STRING is a nested list as returned by
3475 `org-element-parse-secondary-string'.
3477 Return interpreted string."
3478 ;; Make SECONDARY acceptable for `org-element-interpret-data'.
3479 (let ((s (if (listp secondary) secondary (list secondary))))
3480 (org-element-interpret-data `(org-data nil ,@s) nil nil)))
3482 ;; Both functions internally use `org-element--affiliated-keywords'.
3484 (defun org-element-interpret--affiliated-keywords (element)
3485 "Return ELEMENT's affiliated keywords as Org syntax.
3486 If there is no affiliated keyword, return the empty string."
3487 (let ((keyword-to-org
3488 (function
3489 (lambda (key value)
3490 (let (dual)
3491 (when (member key org-element-dual-keywords)
3492 (setq dual (cdr value) value (car value)))
3493 (concat "#+" key
3494 (and dual
3495 (format "[%s]"
3496 (org-element-interpret-secondary dual)))
3497 ": "
3498 (if (member key org-element-parsed-keywords)
3499 (org-element-interpret-secondary value)
3500 value)
3501 "\n"))))))
3502 (mapconcat
3503 (lambda (key)
3504 (let ((value (org-element-property (intern (concat ":" (downcase key)))
3505 element)))
3506 (when value
3507 (if (member key org-element-multiple-keywords)
3508 (mapconcat (lambda (line)
3509 (funcall keyword-to-org key line))
3510 value "")
3511 (funcall keyword-to-org key value)))))
3512 ;; Remove translated keywords.
3513 (delq nil
3514 (mapcar
3515 (lambda (key)
3516 (and (not (assoc key org-element-keyword-translation-alist)) key))
3517 org-element-affiliated-keywords))
3518 "")))
3520 ;; Because interpretation of the parse tree must return the same
3521 ;; number of blank lines between elements and the same number of white
3522 ;; space after objects, some special care must be given to white
3523 ;; spaces.
3525 ;; The first function, `org-element-normalize-string', ensures any
3526 ;; string different from the empty string will end with a single
3527 ;; newline character.
3529 ;; The second function, `org-element-normalize-contents', removes
3530 ;; global indentation from the contents of the current element.
3532 (defun org-element-normalize-string (s)
3533 "Ensure string S ends with a single newline character.
3535 If S isn't a string return it unchanged. If S is the empty
3536 string, return it. Otherwise, return a new string with a single
3537 newline character at its end."
3538 (cond
3539 ((not (stringp s)) s)
3540 ((string= "" s) "")
3541 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3542 (replace-match "\n" nil nil s)))))
3544 (defun org-element-normalize-contents (element &optional ignore-first)
3545 "Normalize plain text in ELEMENT's contents.
3547 ELEMENT must only contain plain text and objects.
3549 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3550 indentation to compute maximal common indentation.
3552 Return the normalized element that is element with global
3553 indentation removed from its contents. The function assumes that
3554 indentation is not done with TAB characters."
3555 (let (ind-list
3556 (collect-inds
3557 (function
3558 ;; Return list of indentations within BLOB. This is done by
3559 ;; walking recursively BLOB and updating IND-LIST along the
3560 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3561 ;; been seen yet. It is required as this string is the only
3562 ;; one whose indentation doesn't happen after a newline
3563 ;; character.
3564 (lambda (blob first-flag)
3565 (mapc
3566 (lambda (object)
3567 (when (and first-flag (stringp object))
3568 (setq first-flag nil)
3569 (string-match "\\`\\( *\\)" object)
3570 (let ((len (length (match-string 1 object))))
3571 ;; An indentation of zero means no string will be
3572 ;; modified. Quit the process.
3573 (if (zerop len) (throw 'zero (setq ind-list nil))
3574 (push len ind-list))))
3575 (cond
3576 ((stringp object)
3577 (let ((start 0))
3578 ;; Avoid matching blank or empty lines.
3579 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
3580 (not (equal (match-string 2 object) " ")))
3581 (setq start (match-end 0))
3582 (push (length (match-string 1 object)) ind-list))))
3583 ((memq (org-element-type object) org-element-recursive-objects)
3584 (funcall collect-inds object first-flag))))
3585 (org-element-contents blob))))))
3586 ;; Collect indentation list in ELEMENT. Possibly remove first
3587 ;; value if IGNORE-FIRST is non-nil.
3588 (catch 'zero (funcall collect-inds element (not ignore-first)))
3589 (if (not ind-list) element
3590 ;; Build ELEMENT back, replacing each string with the same
3591 ;; string minus common indentation.
3592 (let ((build
3593 (function
3594 (lambda (blob mci first-flag)
3595 ;; Return BLOB with all its strings indentation
3596 ;; shortened from MCI white spaces. FIRST-FLAG is
3597 ;; non-nil when the first string hasn't been seen
3598 ;; yet.
3599 (nconc
3600 (list (org-element-type blob) (nth 1 blob))
3601 (mapcar
3602 (lambda (object)
3603 (when (and first-flag (stringp object))
3604 (setq first-flag nil)
3605 (setq object
3606 (replace-regexp-in-string
3607 (format "\\` \\{%d\\}" mci) "" object)))
3608 (cond
3609 ((stringp object)
3610 (replace-regexp-in-string
3611 (format "\n \\{%d\\}" mci) "\n" object))
3612 ((memq (org-element-type object)
3613 org-element-recursive-objects)
3614 (funcall build object mci first-flag))
3615 (t object)))
3616 (org-element-contents blob)))))))
3617 (funcall build element (apply 'min ind-list) (not ignore-first))))))
3621 ;;; The Toolbox
3623 ;; The first move is to implement a way to obtain the smallest element
3624 ;; containing point. This is the job of `org-element-at-point'. It
3625 ;; basically jumps back to the beginning of section containing point
3626 ;; and moves, element after element, with
3627 ;; `org-element-current-element' until the container is found.
3629 ;; Note: When using `org-element-at-point', secondary values are never
3630 ;; parsed since the function focuses on elements, not on objects.
3632 (defun org-element-at-point (&optional keep-trail)
3633 "Determine closest element around point.
3635 Return value is a list like (TYPE PROPS) where TYPE is the type
3636 of the element and PROPS a plist of properties associated to the
3637 element. Possible types are defined in
3638 `org-element-all-elements'.
3640 As a special case, if point is at the very beginning of a list or
3641 sub-list, returned element will be that list instead of the first
3642 item. In the same way, if point is at the beginning of the first
3643 row of a table, returned element will be the table instead of the
3644 first row.
3646 If optional argument KEEP-TRAIL is non-nil, the function returns
3647 a list of of elements leading to element at point. The list's
3648 CAR is always the element at point. Its last item will be the
3649 element's parent, unless element was either the first in its
3650 section (in which case the last item in the list is the first
3651 element of section) or an headline (in which case the list
3652 contains that headline as its single element). Elements
3653 in-between, if any, are siblings of the element at point."
3654 (org-with-wide-buffer
3655 ;; If at an headline, parse it. It is the sole element that
3656 ;; doesn't require to know about context. Be sure to disallow
3657 ;; secondary string parsing, though.
3658 (if (org-with-limited-levels (org-at-heading-p))
3659 (if (not keep-trail) (org-element-headline-parser t)
3660 (list (org-element-headline-parser t)))
3661 ;; Otherwise move at the beginning of the section containing
3662 ;; point.
3663 (let ((origin (point)) element type special-flag trail struct prevs)
3664 (org-with-limited-levels
3665 (if (org-before-first-heading-p) (goto-char (point-min))
3666 (org-back-to-heading)
3667 (forward-line)))
3668 (org-skip-whitespace)
3669 (beginning-of-line)
3670 ;; Starting parsing successively each element with
3671 ;; `org-element-current-element'. Skip those ending before
3672 ;; original position.
3673 (catch 'exit
3674 (while t
3675 (setq element (org-element-current-element
3676 'element special-flag struct)
3677 type (car element))
3678 (when keep-trail (push element trail))
3679 (cond
3680 ;; 1. Skip any element ending before point or at point.
3681 ((let ((end (org-element-property :end element)))
3682 (when (<= end origin)
3683 (if (> (point-max) end) (goto-char end)
3684 (throw 'exit (or trail element))))))
3685 ;; 2. An element containing point is always the element at
3686 ;; point.
3687 ((not (memq type org-element-greater-elements))
3688 (throw 'exit (if keep-trail trail element)))
3689 ;; 3. At a plain list.
3690 ((eq type 'plain-list)
3691 (setq struct (org-element-property :structure element)
3692 prevs (or prevs (org-list-prevs-alist struct)))
3693 (let ((beg (org-element-property :contents-begin element)))
3694 (if (<= origin beg) (throw 'exit (or trail element))
3695 ;; Find the item at this level containing ORIGIN.
3696 (let ((items (org-list-get-all-items beg struct prevs))
3697 parent)
3698 (catch 'local
3699 (mapc
3700 (lambda (pos)
3701 (cond
3702 ;; Item ends before point: skip it.
3703 ((<= (org-list-get-item-end pos struct) origin))
3704 ;; Item contains point: store is in PARENT.
3705 ((<= pos origin) (setq parent pos))
3706 ;; We went too far: return PARENT.
3707 (t (throw 'local nil)))) items))
3708 ;; No parent: no item contained point, though the
3709 ;; plain list does. Point is in the blank lines
3710 ;; after the list: return plain list.
3711 (if (not parent) (throw 'exit (or trail element))
3712 (setq special-flag 'item)
3713 (goto-char parent))))))
3714 ;; 4. At a table.
3715 ((eq type 'table)
3716 (if (eq (org-element-property :type element) 'table.el)
3717 (throw 'exit (or trail element))
3718 (let ((beg (org-element-property :contents-begin element))
3719 (end (org-element-property :contents-end element)))
3720 (if (or (<= origin beg) (>= origin end))
3721 (throw 'exit (or trail element))
3722 (when keep-trail (setq trail (list element)))
3723 (setq special-flag 'table-row)
3724 (narrow-to-region beg end)))))
3725 ;; 4. At any other greater element type, if point is
3726 ;; within contents, move into it. Otherwise, return
3727 ;; that element.
3729 (when (eq type 'item) (setq special-flag nil))
3730 (let ((beg (org-element-property :contents-begin element))
3731 (end (org-element-property :contents-end element)))
3732 (if (or (not beg) (not end) (> beg origin) (< end origin))
3733 (throw 'exit (or trail element))
3734 ;; Reset trail, since we found a parent.
3735 (when keep-trail (setq trail (list element)))
3736 (narrow-to-region beg end)
3737 (goto-char beg)))))))))))
3740 ;; Once the local structure around point is well understood, it's easy
3741 ;; to implement some replacements for `forward-paragraph'
3742 ;; `backward-paragraph', namely `org-element-forward' and
3743 ;; `org-element-backward'.
3745 ;; Also, `org-transpose-elements' mimics the behaviour of
3746 ;; `transpose-words', at the element's level, whereas
3747 ;; `org-element-drag-forward', `org-element-drag-backward', and
3748 ;; `org-element-up' generalize, respectively, functions
3749 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3751 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3752 ;; smartly remove global indentation from buffer, making it possible
3753 ;; to use Org indent mode on a file created with hard indentation.
3755 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3756 ;; internally by some of the previously cited tools.
3758 (defsubst org-element-nested-p (elem-A elem-B)
3759 "Non-nil when elements ELEM-A and ELEM-B are nested."
3760 (let ((beg-A (org-element-property :begin elem-A))
3761 (beg-B (org-element-property :begin elem-B))
3762 (end-A (org-element-property :end elem-A))
3763 (end-B (org-element-property :end elem-B)))
3764 (or (and (>= beg-A beg-B) (<= end-A end-B))
3765 (and (>= beg-B beg-A) (<= end-B end-A)))))
3767 (defun org-element-swap-A-B (elem-A elem-B)
3768 "Swap elements ELEM-A and ELEM-B.
3770 Leave point at the end of ELEM-A."
3771 (goto-char (org-element-property :begin elem-A))
3772 (let* ((beg-A (org-element-property :begin elem-A))
3773 (end-A (save-excursion
3774 (goto-char (org-element-property :end elem-A))
3775 (skip-chars-backward " \r\t\n")
3776 (point-at-eol)))
3777 (beg-B (org-element-property :begin elem-B))
3778 (end-B (save-excursion
3779 (goto-char (org-element-property :end elem-B))
3780 (skip-chars-backward " \r\t\n")
3781 (point-at-eol)))
3782 (body-A (buffer-substring beg-A end-A))
3783 (body-B (delete-and-extract-region beg-B end-B)))
3784 (goto-char beg-B)
3785 (insert body-A)
3786 (goto-char beg-A)
3787 (delete-region beg-A end-A)
3788 (insert body-B)
3789 (goto-char (org-element-property :end elem-B))))
3791 (defun org-element-backward ()
3792 "Move backward by one element.
3793 Move to the previous element at the same level, when possible."
3794 (interactive)
3795 (if (save-excursion (skip-chars-backward " \r\t\n") (bobp))
3796 (error "Cannot move further up")
3797 (let* ((trail (org-element-at-point 'keep-trail))
3798 (element (car trail))
3799 (beg (org-element-property :begin element)))
3800 ;; Move to beginning of current element if point isn't there.
3801 (if (/= (point) beg) (goto-char beg)
3802 (let ((type (org-element-type element)))
3803 (cond
3804 ;; At an headline: move to previous headline at the same
3805 ;; level, a parent, or BOB.
3806 ((eq type 'headline)
3807 (let ((dest (save-excursion (org-backward-same-level 1) (point))))
3808 (if (= (point-min) dest) (error "Cannot move further up")
3809 (goto-char dest))))
3810 ;; At an item: try to move to the previous item, if any.
3811 ((and (eq type 'item)
3812 (let* ((struct (org-element-property :structure element))
3813 (prev (org-list-get-prev-item
3814 beg struct (org-list-prevs-alist struct))))
3815 (when prev (goto-char prev)))))
3816 ;; In any other case, find the previous element in the
3817 ;; trail and move to its beginning. If no previous element
3818 ;; can be found, move to headline.
3819 (t (let ((prev (nth 1 trail)))
3820 (if prev (goto-char (org-element-property :begin prev))
3821 (org-back-to-heading))))))))))
3823 (defun org-element-drag-backward ()
3824 "Drag backward element at point."
3825 (interactive)
3826 (let* ((pos (point))
3827 (elem (org-element-at-point)))
3828 (when (= (progn (goto-char (point-min))
3829 (org-skip-whitespace)
3830 (point-at-bol))
3831 (org-element-property :end elem))
3832 (error "Cannot drag element backward"))
3833 (goto-char (org-element-property :begin elem))
3834 (org-element-backward)
3835 (let ((prev-elem (org-element-at-point)))
3836 (when (or (org-element-nested-p elem prev-elem)
3837 (and (eq (org-element-type elem) 'headline)
3838 (not (eq (org-element-type prev-elem) 'headline))))
3839 (goto-char pos)
3840 (error "Cannot drag element backward"))
3841 ;; Compute new position of point: it's shifted by PREV-ELEM
3842 ;; body's length.
3843 (let ((size-prev (- (org-element-property :end prev-elem)
3844 (org-element-property :begin prev-elem))))
3845 (org-element-swap-A-B prev-elem elem)
3846 (goto-char (- pos size-prev))))))
3848 (defun org-element-drag-forward ()
3849 "Move forward element at point."
3850 (interactive)
3851 (let* ((pos (point))
3852 (elem (org-element-at-point)))
3853 (when (= (point-max) (org-element-property :end elem))
3854 (error "Cannot drag element forward"))
3855 (goto-char (org-element-property :end elem))
3856 (let ((next-elem (org-element-at-point)))
3857 (when (or (org-element-nested-p elem next-elem)
3858 (and (eq (org-element-type next-elem) 'headline)
3859 (not (eq (org-element-type elem) 'headline))))
3860 (goto-char pos)
3861 (error "Cannot drag element forward"))
3862 ;; Compute new position of point: it's shifted by NEXT-ELEM
3863 ;; body's length (without final blanks) and by the length of
3864 ;; blanks between ELEM and NEXT-ELEM.
3865 (let ((size-next (- (save-excursion
3866 (goto-char (org-element-property :end next-elem))
3867 (skip-chars-backward " \r\t\n")
3868 (forward-line)
3869 (point))
3870 (org-element-property :begin next-elem)))
3871 (size-blank (- (org-element-property :end elem)
3872 (save-excursion
3873 (goto-char (org-element-property :end elem))
3874 (skip-chars-backward " \r\t\n")
3875 (forward-line)
3876 (point)))))
3877 (org-element-swap-A-B elem next-elem)
3878 (goto-char (+ pos size-next size-blank))))))
3880 (defun org-element-forward ()
3881 "Move forward by one element.
3882 Move to the next element at the same level, when possible."
3883 (interactive)
3884 (if (eobp) (error "Cannot move further down")
3885 (let* ((trail (org-element-at-point 'keep-trail))
3886 (element (car trail))
3887 (type (org-element-type element))
3888 (end (org-element-property :end element)))
3889 (cond
3890 ;; At an headline, move to next headline at the same level.
3891 ((eq type 'headline) (goto-char end))
3892 ;; At an item. Move to the next item, if possible.
3893 ((and (eq type 'item)
3894 (let* ((struct (org-element-property :structure element))
3895 (prevs (org-list-prevs-alist struct))
3896 (beg (org-element-property :begin element))
3897 (next-item (org-list-get-next-item beg struct prevs)))
3898 (when next-item (goto-char next-item)))))
3899 ;; In any other case, move to element's end, unless this
3900 ;; position is also the end of its parent's contents, in which
3901 ;; case, directly jump to parent's end.
3903 (let ((parent
3904 ;; Determine if TRAIL contains the real parent of ELEMENT.
3905 (and (> (length trail) 1)
3906 (let* ((parent-candidate (car (last trail))))
3907 (and (memq (org-element-type parent-candidate)
3908 org-element-greater-elements)
3909 (>= (org-element-property
3910 :contents-end parent-candidate) end)
3911 parent-candidate)))))
3912 (cond ((not parent) (goto-char end))
3913 ((= (org-element-property :contents-end parent) end)
3914 (goto-char (org-element-property :end parent)))
3915 (t (goto-char end)))))))))
3917 (defun org-element-mark-element ()
3918 "Put point at beginning of this element, mark at end.
3920 Interactively, if this command is repeated or (in Transient Mark
3921 mode) if the mark is active, it marks the next element after the
3922 ones already marked."
3923 (interactive)
3924 (let (deactivate-mark)
3925 (if (or (and (eq last-command this-command) (mark t))
3926 (and transient-mark-mode mark-active))
3927 (set-mark
3928 (save-excursion
3929 (goto-char (mark))
3930 (goto-char (org-element-property :end (org-element-at-point)))))
3931 (let ((element (org-element-at-point)))
3932 (end-of-line)
3933 (push-mark (org-element-property :end element) t t)
3934 (goto-char (org-element-property :begin element))))))
3936 (defun org-narrow-to-element ()
3937 "Narrow buffer to current element."
3938 (interactive)
3939 (let ((elem (org-element-at-point)))
3940 (cond
3941 ((eq (car elem) 'headline)
3942 (narrow-to-region
3943 (org-element-property :begin elem)
3944 (org-element-property :end elem)))
3945 ((memq (car elem) org-element-greater-elements)
3946 (narrow-to-region
3947 (org-element-property :contents-begin elem)
3948 (org-element-property :contents-end elem)))
3950 (narrow-to-region
3951 (org-element-property :begin elem)
3952 (org-element-property :end elem))))))
3954 (defun org-transpose-elements ()
3955 "Transpose current and previous elements, keeping blank lines between.
3956 Point is moved after both elements."
3957 (interactive)
3958 (org-skip-whitespace)
3959 (let ((pos (point))
3960 (cur (org-element-at-point)))
3961 (when (= (save-excursion (goto-char (point-min))
3962 (org-skip-whitespace)
3963 (point-at-bol))
3964 (org-element-property :begin cur))
3965 (error "No previous element"))
3966 (goto-char (org-element-property :begin cur))
3967 (forward-line -1)
3968 (let ((prev (org-element-at-point)))
3969 (when (org-element-nested-p cur prev)
3970 (goto-char pos)
3971 (error "Cannot transpose nested elements"))
3972 (org-element-swap-A-B prev cur))))
3974 (defun org-element-unindent-buffer ()
3975 "Un-indent the visible part of the buffer.
3976 Relative indentation \(between items, inside blocks, etc.\) isn't
3977 modified."
3978 (interactive)
3979 (unless (eq major-mode 'org-mode)
3980 (error "Cannot un-indent a buffer not in Org mode"))
3981 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
3982 unindent-tree ; For byte-compiler.
3983 (unindent-tree
3984 (function
3985 (lambda (contents)
3986 (mapc (lambda (element)
3987 (if (eq (org-element-type element) 'headline)
3988 (funcall unindent-tree
3989 (org-element-contents element))
3990 (save-excursion
3991 (save-restriction
3992 (narrow-to-region
3993 (org-element-property :begin element)
3994 (org-element-property :end element))
3995 (org-do-remove-indentation)))))
3996 (reverse contents))))))
3997 (funcall unindent-tree (org-element-contents parse-tree))))
3999 (defun org-element-up ()
4000 "Move to upper element."
4001 (interactive)
4002 (cond
4003 ((bobp) (error "No surrounding element"))
4004 ((org-with-limited-levels (org-at-heading-p))
4005 (or (org-up-heading-safe) (error "No surronding element")))
4007 (let* ((trail (org-element-at-point 'keep-trail))
4008 (element (car trail))
4009 (type (org-element-type element)))
4010 (cond
4011 ;; At an item, with a parent in the list: move to that parent.
4012 ((and (eq type 'item)
4013 (let* ((beg (org-element-property :begin element))
4014 (struct (org-element-property :structure element))
4015 (parents (org-list-parents-alist struct))
4016 (parentp (org-list-get-parent beg struct parents)))
4017 (and parentp (goto-char parentp)))))
4018 ;; Determine parent in the trail.
4020 (let ((parent
4021 (and (> (length trail) 1)
4022 (let ((parentp (car (last trail))))
4023 (and (memq (org-element-type parentp)
4024 org-element-greater-elements)
4025 (>= (org-element-property :contents-end parentp)
4026 (org-element-property :end element))
4027 parentp)))))
4028 (cond
4029 ;; When parent is found move to its beginning.
4030 (parent (goto-char (org-element-property :begin parent)))
4031 ;; If no parent was found, move to headline above, if any
4032 ;; or return an error.
4033 ((org-before-first-heading-p) (error "No surrounding element"))
4034 (t (org-back-to-heading))))))))))
4036 (defun org-element-down ()
4037 "Move to inner element."
4038 (interactive)
4039 (let ((element (org-element-at-point)))
4040 (cond
4041 ((memq (org-element-type element) '(plain-list table))
4042 (goto-char (org-element-property :contents-begin element))
4043 (forward-char))
4044 ((memq (org-element-type element) org-element-greater-elements)
4045 ;; If contents are hidden, first disclose them.
4046 (when (org-element-property :hiddenp element) (org-cycle))
4047 (goto-char (org-element-property :contents-begin element)))
4048 (t (error "No inner element")))))
4051 (provide 'org-element)
4052 ;;; org-element.el ends here