org-element: Fix item interpreter when item doesn't start with a paragraph
[org-mode.git] / contrib / lisp / org-element.el
blob15de2a2608f45e6b599299531ac39f3b6fc603f0
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 `babel-call', `clock', `headline', `item',
34 ;; `keyword', `planning', `property-drawer' and `section' types), it
35 ;; can also accept a fixed set of keywords as attributes. Those are
36 ;; called "affiliated keywords" to distinguish them from other
37 ;; keywords, which are full-fledged elements. All affiliated keywords
38 ;; are referenced in `org-element-affiliated-keywords'.
40 ;; Element containing other elements (and only elements) are called
41 ;; greater elements. Concerned types are: `center-block', `drawer',
42 ;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
43 ;; `item', `plain-list', `quote-block', `section' and `special-block'.
45 ;; Other element types are: `babel-call', `clock', `comment',
46 ;; `comment-block', `example-block', `export-block', `fixed-width',
47 ;; `horizontal-rule', `keyword', `latex-environment', `paragraph',
48 ;; `planning', `property-drawer', `quote-section', `src-block',
49 ;; `table', `table-row' and `verse-block'. Among them, `paragraph'
50 ;; and `verse-block' types can contain Org objects and plain text.
52 ;; Objects are related to document's contents. Some of them are
53 ;; recursive. Associated types are of the following: `bold', `code',
54 ;; `entity', `export-snippet', `footnote-reference',
55 ;; `inline-babel-call', `inline-src-block', `italic',
56 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
57 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
58 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
60 ;; Some elements also have special properties whose value can hold
61 ;; objects themselves (i.e. an item tag or an headline name). Such
62 ;; values are called "secondary strings". Any object belongs to
63 ;; either an element or a secondary string.
65 ;; Notwithstanding affiliated keywords, each greater element, element
66 ;; and object has a fixed set of properties attached to it. Among
67 ;; them, four are shared by all types: `:begin' and `:end', which
68 ;; refer to the beginning and ending buffer positions of the
69 ;; considered element or object, `:post-blank', which holds the number
70 ;; of blank lines, or white spaces, at its end and `:parent' which
71 ;; refers to the element or object containing it. Greater elements
72 ;; and elements containing objects will also have `:contents-begin'
73 ;; and `:contents-end' properties to delimit contents.
75 ;; Lisp-wise, an element or an object can be represented as a list.
76 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
77 ;; TYPE is a symbol describing the Org element or object.
78 ;; PROPERTIES is the property list attached to it. See docstring of
79 ;; appropriate parsing function to get an exhaustive
80 ;; list.
81 ;; CONTENTS is a list of elements, objects or raw strings contained
82 ;; in the current element or object, when applicable.
84 ;; An Org buffer is a nested list of such elements and objects, whose
85 ;; type is `org-data' and properties is nil.
87 ;; The first part of this file implements a parser and an interpreter
88 ;; for each type of Org syntax.
90 ;; The next two parts introduce four accessors and a function
91 ;; retrieving the element starting at point (respectively
92 ;; `org-element-type', `org-element-property', `org-element-contents',
93 ;; `org-element-restriction' and `org-element-current-element').
95 ;; The following part creates a fully recursive buffer parser. It
96 ;; also provides a tool to map a function to elements or objects
97 ;; matching some criteria in the parse tree. Functions of interest
98 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
99 ;; extent, `org-element-parse-secondary-string'.
101 ;; The penultimate part is the cradle of an interpreter for the
102 ;; obtained parse tree: `org-element-interpret-data'.
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 the beginning of the block."
160 (save-excursion
161 (let* ((case-fold-search t)
162 (keywords (org-element-collect-affiliated-keywords))
163 (begin (car keywords))
164 (contents-begin (progn (forward-line) (point)))
165 (hidden (org-truely-invisible-p))
166 (contents-end
167 (progn (re-search-forward "^[ \t]*#\\+END_CENTER" nil t)
168 (point-at-bol)))
169 (pos-before-blank (progn (forward-line) (point)))
170 (end (progn (org-skip-whitespace)
171 (if (eobp) (point) (point-at-bol)))))
172 `(center-block
173 (:begin ,begin
174 :end ,end
175 :hiddenp ,hidden
176 :contents-begin ,contents-begin
177 :contents-end ,contents-end
178 :post-blank ,(count-lines pos-before-blank end)
179 ,@(cadr keywords))))))
181 (defun org-element-center-block-interpreter (center-block contents)
182 "Interpret CENTER-BLOCK element as Org syntax.
183 CONTENTS is the contents of the element."
184 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
187 ;;;; Drawer
189 (defun org-element-drawer-parser ()
190 "Parse a drawer.
192 Return a list whose CAR is `drawer' and CDR is a plist containing
193 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
194 `:contents-end' and `:post-blank' keywords.
196 Assume point is at beginning of drawer."
197 (save-excursion
198 (let* ((case-fold-search t)
199 (name (progn (looking-at org-drawer-regexp)
200 (org-match-string-no-properties 1)))
201 (keywords (org-element-collect-affiliated-keywords))
202 (begin (car keywords))
203 (contents-begin (progn (forward-line) (point)))
204 (hidden (org-truely-invisible-p))
205 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
206 (point-at-bol)))
207 (pos-before-blank (progn (forward-line) (point)))
208 (end (progn (org-skip-whitespace)
209 (if (eobp) (point) (point-at-bol)))))
210 `(drawer
211 (:begin ,begin
212 :end ,end
213 :drawer-name ,name
214 :hiddenp ,hidden
215 :contents-begin ,contents-begin
216 :contents-end ,contents-end
217 :post-blank ,(count-lines pos-before-blank end)
218 ,@(cadr keywords))))))
220 (defun org-element-drawer-interpreter (drawer contents)
221 "Interpret DRAWER element as Org syntax.
222 CONTENTS is the contents of the element."
223 (format ":%s:\n%s:END:"
224 (org-element-property :drawer-name drawer)
225 contents))
228 ;;;; Dynamic Block
230 (defun org-element-dynamic-block-parser ()
231 "Parse a dynamic block.
233 Return a list whose CAR is `dynamic-block' and CDR is a plist
234 containing `:block-name', `:begin', `:end', `:hiddenp',
235 `:contents-begin', `:contents-end', `:arguments' and
236 `:post-blank' keywords.
238 Assume point is at beginning of dynamic block."
239 (save-excursion
240 (let* ((case-fold-search t)
241 (name (progn (looking-at org-dblock-start-re)
242 (org-match-string-no-properties 1)))
243 (arguments (org-match-string-no-properties 3))
244 (keywords (org-element-collect-affiliated-keywords))
245 (begin (car keywords))
246 (contents-begin (progn (forward-line) (point)))
247 (hidden (org-truely-invisible-p))
248 (contents-end (progn (re-search-forward org-dblock-end-re nil t)
249 (point-at-bol)))
250 (pos-before-blank (progn (forward-line) (point)))
251 (end (progn (org-skip-whitespace)
252 (if (eobp) (point) (point-at-bol)))))
253 (list 'dynamic-block
254 `(:begin ,begin
255 :end ,end
256 :block-name ,name
257 :arguments ,arguments
258 :hiddenp ,hidden
259 :contents-begin ,contents-begin
260 :contents-end ,contents-end
261 :post-blank ,(count-lines pos-before-blank end)
262 ,@(cadr keywords))))))
264 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
265 "Interpret DYNAMIC-BLOCK element as Org syntax.
266 CONTENTS is the contents of the element."
267 (format "#+BEGIN: %s%s\n%s#+END:"
268 (org-element-property :block-name dynamic-block)
269 (let ((args (org-element-property :arguments dynamic-block)))
270 (and args (concat " " args)))
271 contents))
274 ;;;; Footnote Definition
276 (defun org-element-footnote-definition-parser ()
277 "Parse a footnote definition.
279 Return a list whose CAR is `footnote-definition' and CDR is
280 a plist containing `:label', `:begin' `:end', `:contents-begin',
281 `:contents-end' and `:post-blank' keywords.
283 Assume point is at the beginning of the footnote definition."
284 (save-excursion
285 (looking-at org-footnote-definition-re)
286 (let* ((label (org-match-string-no-properties 1))
287 (keywords (org-element-collect-affiliated-keywords))
288 (begin (car keywords))
289 (contents-begin (progn (search-forward "]")
290 (org-skip-whitespace)
291 (point)))
292 (contents-end (if (progn
293 (end-of-line)
294 (re-search-forward
295 (concat org-outline-regexp-bol "\\|"
296 org-footnote-definition-re "\\|"
297 "^[ \t]*$") nil 'move))
298 (match-beginning 0)
299 (point)))
300 (end (progn (org-skip-whitespace)
301 (if (eobp) (point) (point-at-bol)))))
302 `(footnote-definition
303 (:label ,label
304 :begin ,begin
305 :end ,end
306 :contents-begin ,contents-begin
307 :contents-end ,contents-end
308 :post-blank ,(count-lines contents-end end)
309 ,@(cadr keywords))))))
311 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
312 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
313 CONTENTS is the contents of the footnote-definition."
314 (concat (format "[%s]" (org-element-property :label footnote-definition))
316 contents))
319 ;;;; Headline
321 (defun org-element-headline-parser (&optional raw-secondary-p)
322 "Parse an headline.
324 Return a list whose CAR is `headline' and CDR is a plist
325 containing `:raw-value', `:title', `:begin', `:end',
326 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
327 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
328 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
329 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
330 keywords.
332 The plist also contains any property set in the property drawer,
333 with its name in lowercase, the underscores replaced with hyphens
334 and colons at the beginning (i.e. `:custom-id').
336 When RAW-SECONDARY-P is non-nil, headline's title will not be
337 parsed as a secondary string, but as a plain string instead.
339 Assume point is at beginning of the headline."
340 (save-excursion
341 (let* ((components (org-heading-components))
342 (level (nth 1 components))
343 (todo (nth 2 components))
344 (todo-type
345 (and todo (if (member todo org-done-keywords) 'done 'todo)))
346 (tags (let ((raw-tags (nth 5 components)))
347 (and raw-tags (org-split-string raw-tags ":"))))
348 (raw-value (nth 4 components))
349 (quotedp
350 (let ((case-fold-search nil))
351 (string-match (format "^%s +" org-quote-string) raw-value)))
352 (commentedp
353 (let ((case-fold-search nil))
354 (string-match (format "^%s +" org-comment-string) raw-value)))
355 (archivedp (member org-archive-tag tags))
356 (footnote-section-p (and org-footnote-section
357 (string= org-footnote-section raw-value)))
358 (standard-props (let (plist)
359 (mapc
360 (lambda (p)
361 (let ((p-name (downcase (car p))))
362 (while (string-match "_" p-name)
363 (setq p-name
364 (replace-match "-" nil nil p-name)))
365 (setq p-name (intern (concat ":" p-name)))
366 (setq plist
367 (plist-put plist p-name (cdr p)))))
368 (org-entry-properties nil 'standard))
369 plist))
370 (time-props (org-entry-properties nil 'special "CLOCK"))
371 (scheduled (cdr (assoc "SCHEDULED" time-props)))
372 (deadline (cdr (assoc "DEADLINE" time-props)))
373 (clock (cdr (assoc "CLOCK" time-props)))
374 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
375 (begin (point))
376 (pos-after-head (save-excursion (forward-line) (point)))
377 (contents-begin (save-excursion (forward-line)
378 (org-skip-whitespace)
379 (if (eobp) (point) (point-at-bol))))
380 (hidden (save-excursion (forward-line) (org-truely-invisible-p)))
381 (end (progn (goto-char (org-end-of-subtree t t))))
382 (contents-end (progn (skip-chars-backward " \r\t\n")
383 (forward-line)
384 (point)))
385 title)
386 ;; Clean RAW-VALUE from any quote or comment string.
387 (when (or quotedp commentedp)
388 (setq raw-value
389 (replace-regexp-in-string
390 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
392 raw-value)))
393 ;; Clean TAGS from archive tag, if any.
394 (when archivedp (setq tags (delete org-archive-tag tags)))
395 ;; Then get TITLE.
396 (setq title
397 (if raw-secondary-p raw-value
398 (org-element-parse-secondary-string
399 raw-value (org-element-restriction 'headline))))
400 `(headline
401 (:raw-value ,raw-value
402 :title ,title
403 :begin ,begin
404 :end ,end
405 :pre-blank ,(count-lines pos-after-head contents-begin)
406 :hiddenp ,hidden
407 :contents-begin ,contents-begin
408 :contents-end ,contents-end
409 :level ,level
410 :priority ,(nth 3 components)
411 :tags ,tags
412 :todo-keyword ,todo
413 :todo-type ,todo-type
414 :scheduled ,scheduled
415 :deadline ,deadline
416 :timestamp ,timestamp
417 :clock ,clock
418 :post-blank ,(count-lines contents-end end)
419 :footnote-section-p ,footnote-section-p
420 :archivedp ,archivedp
421 :commentedp ,commentedp
422 :quotedp ,quotedp
423 ,@standard-props)))))
425 (defun org-element-headline-interpreter (headline contents)
426 "Interpret HEADLINE element as Org syntax.
427 CONTENTS is the contents of the element."
428 (let* ((level (org-element-property :level headline))
429 (todo (org-element-property :todo-keyword headline))
430 (priority (org-element-property :priority headline))
431 (title (org-element-interpret-data
432 (org-element-property :title headline)))
433 (tags (let ((tag-list (if (org-element-property :archivedp headline)
434 (cons org-archive-tag
435 (org-element-property :tags headline))
436 (org-element-property :tags headline))))
437 (and tag-list
438 (format ":%s:" (mapconcat 'identity tag-list ":")))))
439 (commentedp (org-element-property :commentedp headline))
440 (quotedp (org-element-property :quotedp headline))
441 (pre-blank (or (org-element-property :pre-blank headline) 0))
442 (heading (concat (make-string level ?*)
443 (and todo (concat " " todo))
444 (and quotedp (concat " " org-quote-string))
445 (and commentedp (concat " " org-comment-string))
446 (and priority
447 (format " [#%s]" (char-to-string priority)))
448 (cond ((and org-footnote-section
449 (org-element-property
450 :footnote-section-p headline))
451 (concat " " org-footnote-section))
452 (title (concat " " title))))))
453 (concat heading
454 ;; Align tags.
455 (when tags
456 (cond
457 ((zerop org-tags-column) (format " %s" tags))
458 ((< org-tags-column 0)
459 (concat
460 (make-string
461 (max (- (+ org-tags-column (length heading) (length tags))) 1)
463 tags))
465 (concat
466 (make-string (max (- org-tags-column (length heading)) 1) ? )
467 tags))))
468 (make-string (1+ pre-blank) 10)
469 contents)))
472 ;;;; Inlinetask
474 (defun org-element-inlinetask-parser (&optional raw-secondary-p)
475 "Parse an inline task.
477 Return a list whose CAR is `inlinetask' and CDR is a plist
478 containing `:title', `:begin', `:end', `:hiddenp',
479 `:contents-begin' and `:contents-end', `:level', `:priority',
480 `:tags', `:todo-keyword', `:todo-type', `:scheduled',
481 `:deadline', `:timestamp', `:clock' and `:post-blank' keywords.
483 The plist also contains any property set in the property drawer,
484 with its name in lowercase, the underscores replaced with hyphens
485 and colons at the beginning (i.e. `:custom-id').
487 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
488 title will not be parsed as a secondary string, but as a plain
489 string instead.
491 Assume point is at beginning of the inline task."
492 (save-excursion
493 (let* ((keywords (org-element-collect-affiliated-keywords))
494 (begin (car keywords))
495 (components (org-heading-components))
496 (todo (nth 2 components))
497 (todo-type (and todo
498 (if (member todo org-done-keywords) 'done 'todo)))
499 (tags (let ((raw-tags (nth 5 components)))
500 (and raw-tags (org-split-string raw-tags ":"))))
501 (title (if raw-secondary-p (nth 4 components)
502 (org-element-parse-secondary-string
503 (nth 4 components)
504 (org-element-restriction 'inlinetask))))
505 (standard-props (let (plist)
506 (mapc
507 (lambda (p)
508 (let ((p-name (downcase (car p))))
509 (while (string-match "_" p-name)
510 (setq p-name
511 (replace-match "-" nil nil p-name)))
512 (setq p-name (intern (concat ":" p-name)))
513 (setq plist
514 (plist-put plist p-name (cdr p)))))
515 (org-entry-properties nil 'standard))
516 plist))
517 (time-props (org-entry-properties nil 'special "CLOCK"))
518 (scheduled (cdr (assoc "SCHEDULED" time-props)))
519 (deadline (cdr (assoc "DEADLINE" time-props)))
520 (clock (cdr (assoc "CLOCK" time-props)))
521 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
522 (contents-begin (save-excursion (forward-line) (point)))
523 (hidden (org-truely-invisible-p))
524 (pos-before-blank (org-inlinetask-goto-end))
525 ;; In the case of a single line task, CONTENTS-BEGIN and
526 ;; CONTENTS-END might overlap.
527 (contents-end (max contents-begin
528 (if (not (bolp)) (point-at-bol)
529 (save-excursion (forward-line -1) (point)))))
530 (end (progn (org-skip-whitespace)
531 (if (eobp) (point) (point-at-bol)))))
532 `(inlinetask
533 (:title ,title
534 :begin ,begin
535 :end ,end
536 :hiddenp ,(and (> contents-end contents-begin) hidden)
537 :contents-begin ,contents-begin
538 :contents-end ,contents-end
539 :level ,(nth 1 components)
540 :priority ,(nth 3 components)
541 :tags ,tags
542 :todo-keyword ,todo
543 :todo-type ,todo-type
544 :scheduled ,scheduled
545 :deadline ,deadline
546 :timestamp ,timestamp
547 :clock ,clock
548 :post-blank ,(count-lines pos-before-blank end)
549 ,@standard-props
550 ,@(cadr keywords))))))
552 (defun org-element-inlinetask-interpreter (inlinetask contents)
553 "Interpret INLINETASK element as Org syntax.
554 CONTENTS is the contents of inlinetask."
555 (let* ((level (org-element-property :level inlinetask))
556 (todo (org-element-property :todo-keyword inlinetask))
557 (priority (org-element-property :priority inlinetask))
558 (title (org-element-interpret-data
559 (org-element-property :title inlinetask)))
560 (tags (let ((tag-list (org-element-property :tags inlinetask)))
561 (and tag-list
562 (format ":%s:" (mapconcat 'identity tag-list ":")))))
563 (task (concat (make-string level ?*)
564 (and todo (concat " " todo))
565 (and priority
566 (format " [#%s]" (char-to-string priority)))
567 (and title (concat " " title)))))
568 (concat task
569 ;; Align tags.
570 (when tags
571 (cond
572 ((zerop org-tags-column) (format " %s" tags))
573 ((< org-tags-column 0)
574 (concat
575 (make-string
576 (max (- (+ org-tags-column (length task) (length tags))) 1)
578 tags))
580 (concat
581 (make-string (max (- org-tags-column (length task)) 1) ? )
582 tags))))
583 ;; Prefer degenerate inlinetasks when there are no
584 ;; contents.
585 (when contents
586 (concat "\n"
587 contents
588 (make-string level ?*) " END")))))
591 ;;;; Item
593 (defun org-element-item-parser (struct &optional raw-secondary-p)
594 "Parse an item.
596 STRUCT is the structure of the plain list.
598 Return a list whose CAR is `item' and CDR is a plist containing
599 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
600 `:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
601 `:post-blank' keywords.
603 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
604 any, will not be parsed as a secondary string, but as a plain
605 string instead.
607 Assume point is at the beginning of the item."
608 (save-excursion
609 (beginning-of-line)
610 (let* ((begin (point))
611 (bullet (org-list-get-bullet (point) struct))
612 (checkbox (let ((box (org-list-get-checkbox begin struct)))
613 (cond ((equal "[ ]" box) 'off)
614 ((equal "[X]" box) 'on)
615 ((equal "[-]" box) 'trans))))
616 (counter (let ((c (org-list-get-counter begin struct)))
617 (cond
618 ((not c) nil)
619 ((string-match "[A-Za-z]" c)
620 (- (string-to-char (upcase (match-string 0 c)))
621 64))
622 ((string-match "[0-9]+" c)
623 (string-to-number (match-string 0 c))))))
624 (tag
625 (let ((raw-tag (org-list-get-tag begin struct)))
626 (and raw-tag
627 (if raw-secondary-p raw-tag
628 (org-element-parse-secondary-string
629 raw-tag (org-element-restriction 'item))))))
630 (end (org-list-get-item-end begin struct))
631 (contents-begin (progn (looking-at org-list-full-item-re)
632 (goto-char (match-end 0))
633 (org-skip-whitespace)
634 ;; If first line isn't empty,
635 ;; contents really start at the text
636 ;; after item's meta-data.
637 (if (= (point-at-bol) begin) (point)
638 (point-at-bol))))
639 (hidden (progn (forward-line)
640 (and (not (= (point) end))
641 (org-truely-invisible-p))))
642 (contents-end (progn (goto-char end)
643 (skip-chars-backward " \r\t\n")
644 (forward-line)
645 (point))))
646 `(item
647 (:bullet ,bullet
648 :begin ,begin
649 :end ,end
650 ;; CONTENTS-BEGIN and CONTENTS-END may be mixed
651 ;; up in the case of an empty item separated
652 ;; from the next by a blank line. Thus, ensure
653 ;; the former is always the smallest of two.
654 :contents-begin ,(min contents-begin contents-end)
655 :contents-end ,(max contents-begin contents-end)
656 :checkbox ,checkbox
657 :counter ,counter
658 :tag ,tag
659 :hiddenp ,hidden
660 :structure ,struct
661 :post-blank ,(count-lines contents-end end))))))
663 (defun org-element-item-interpreter (item contents)
664 "Interpret ITEM element as Org syntax.
665 CONTENTS is the contents of the element."
666 (let* ((bullet
667 (let* ((beg (org-element-property :begin item))
668 (struct (org-element-property :structure item))
669 (pre (org-list-prevs-alist struct))
670 (bul (org-element-property :bullet item)))
671 (org-list-bullet-string
672 (if (not (eq (org-list-get-list-type beg struct pre) 'ordered)) "-"
673 (let ((num
674 (car
675 (last
676 (org-list-get-item-number
677 beg struct pre (org-list-parents-alist struct))))))
678 (format "%d%s"
680 (if (eq org-plain-list-ordered-item-terminator ?\)) ")"
681 ".")))))))
682 (checkbox (org-element-property :checkbox item))
683 (counter (org-element-property :counter item))
684 (tag (let ((tag (org-element-property :tag item)))
685 (and tag (org-element-interpret-data tag))))
686 ;; Compute indentation.
687 (ind (make-string (length bullet) 32))
688 (item-starts-with-par-p
689 (eq (org-element-type (car (org-element-contents item)))
690 'paragraph)))
691 ;; Indent contents.
692 (concat
693 bullet
694 (and counter (format "[@%d] " counter))
695 (cond
696 ((eq checkbox 'on) "[X] ")
697 ((eq checkbox 'off) "[ ] ")
698 ((eq checkbox 'trans) "[-] "))
699 (and tag (format "%s :: " tag))
700 (let ((contents (replace-regexp-in-string
701 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
702 (if item-starts-with-par-p (org-trim contents)
703 (concat "\n" contents))))))
706 ;;;; Plain List
708 (defun org-element-plain-list-parser (&optional structure)
709 "Parse a plain list.
711 Optional argument STRUCTURE, when non-nil, is the structure of
712 the plain list being parsed.
714 Return a list whose CAR is `plain-list' and CDR is a plist
715 containing `:type', `:begin', `:end', `:contents-begin' and
716 `:contents-end', `:structure' and `:post-blank' keywords.
718 Assume point is at the beginning of the list."
719 (save-excursion
720 (let* ((struct (or structure (org-list-struct)))
721 (prevs (org-list-prevs-alist struct))
722 (parents (org-list-parents-alist struct))
723 (type (org-list-get-list-type (point) struct prevs))
724 (contents-begin (point))
725 (keywords (org-element-collect-affiliated-keywords))
726 (begin (car keywords))
727 (contents-end
728 (goto-char (org-list-get-list-end (point) struct prevs)))
729 (end (save-excursion (org-skip-whitespace)
730 (if (eobp) (point) (point-at-bol)))))
731 ;; Blank lines below list belong to the top-level list only.
732 (unless (= (org-list-get-top-point struct) contents-begin)
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 :structure ,struct
744 :post-blank ,(count-lines contents-end end)
745 ,@(cadr keywords))))))
747 (defun org-element-plain-list-interpreter (plain-list contents)
748 "Interpret PLAIN-LIST element as Org syntax.
749 CONTENTS is the contents of the element."
750 contents)
753 ;;;; Quote Block
755 (defun org-element-quote-block-parser ()
756 "Parse a quote block.
758 Return a list whose CAR is `quote-block' and CDR is a plist
759 containing `:begin', `:end', `:hiddenp', `:contents-begin',
760 `:contents-end' and `:post-blank' keywords.
762 Assume point is at the beginning of the block."
763 (save-excursion
764 (let* ((case-fold-search t)
765 (keywords (org-element-collect-affiliated-keywords))
766 (begin (car keywords))
767 (contents-begin (progn (forward-line) (point)))
768 (hidden (org-truely-invisible-p))
769 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_QUOTE" nil t)
770 (point-at-bol)))
771 (pos-before-blank (progn (forward-line) (point)))
772 (end (progn (org-skip-whitespace)
773 (if (eobp) (point) (point-at-bol)))))
774 `(quote-block
775 (:begin ,begin
776 :end ,end
777 :hiddenp ,hidden
778 :contents-begin ,contents-begin
779 :contents-end ,contents-end
780 :post-blank ,(count-lines pos-before-blank end)
781 ,@(cadr keywords))))))
783 (defun org-element-quote-block-interpreter (quote-block contents)
784 "Interpret QUOTE-BLOCK element as Org syntax.
785 CONTENTS is the contents of the element."
786 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
789 ;;;; Section
791 (defun org-element-section-parser ()
792 "Parse a section.
794 Return a list whose CAR is `section' and CDR is a plist
795 containing `:begin', `:end', `:contents-begin', `contents-end'
796 and `:post-blank' keywords."
797 (save-excursion
798 ;; Beginning of section is the beginning of the first non-blank
799 ;; line after previous headline.
800 (org-with-limited-levels
801 (let ((begin
802 (save-excursion
803 (outline-previous-heading)
804 (if (not (org-at-heading-p)) (point)
805 (forward-line) (org-skip-whitespace) (point-at-bol))))
806 (end (progn (outline-next-heading) (point)))
807 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
808 (forward-line)
809 (point))))
810 `(section
811 (:begin ,begin
812 :end ,end
813 :contents-begin ,begin
814 :contents-end ,pos-before-blank
815 :post-blank ,(count-lines pos-before-blank end)))))))
817 (defun org-element-section-interpreter (section contents)
818 "Interpret SECTION element as Org syntax.
819 CONTENTS is the contents of the element."
820 contents)
823 ;;;; Special Block
825 (defun org-element-special-block-parser ()
826 "Parse a special block.
828 Return a list whose CAR is `special-block' and CDR is a plist
829 containing `:type', `:begin', `:end', `:hiddenp',
830 `:contents-begin', `:contents-end' and `:post-blank' keywords.
832 Assume point is at the beginning of the block."
833 (save-excursion
834 (let* ((case-fold-search t)
835 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)")
836 (org-match-string-no-properties 1)))
837 (keywords (org-element-collect-affiliated-keywords))
838 (begin (car keywords))
839 (contents-begin (progn (forward-line) (point)))
840 (hidden (org-truely-invisible-p))
841 (contents-end
842 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
843 (point-at-bol)))
844 (pos-before-blank (progn (forward-line) (point)))
845 (end (progn (org-skip-whitespace)
846 (if (eobp) (point) (point-at-bol)))))
847 `(special-block
848 (:type ,type
849 :begin ,begin
850 :end ,end
851 :hiddenp ,hidden
852 :contents-begin ,contents-begin
853 :contents-end ,contents-end
854 :post-blank ,(count-lines pos-before-blank end)
855 ,@(cadr keywords))))))
857 (defun org-element-special-block-interpreter (special-block contents)
858 "Interpret SPECIAL-BLOCK element as Org syntax.
859 CONTENTS is the contents of the element."
860 (let ((block-type (org-element-property :type special-block)))
861 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
865 ;;; Elements
867 ;; For each element, a parser and an interpreter are also defined.
868 ;; Both follow the same naming convention used for greater elements.
870 ;; Also, as for greater elements, adding a new element type is done
871 ;; through the following steps: implement a parser and an interpreter,
872 ;; tweak `org-element-current-element' so that it recognizes the new
873 ;; type and add that new type to `org-element-all-elements'.
875 ;; As a special case, when the newly defined type is a block type,
876 ;; `org-element-block-name-alist' has to be modified accordingly.
879 ;;;; Babel Call
881 (defun org-element-babel-call-parser ()
882 "Parse a babel call.
884 Return a list whose CAR is `babel-call' and CDR is a plist
885 containing `:begin', `:end', `:info' and `:post-blank' as
886 keywords."
887 (save-excursion
888 (let ((case-fold-search t)
889 (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
890 (org-babel-lob-get-info)))
891 (begin (point-at-bol))
892 (pos-before-blank (progn (forward-line) (point)))
893 (end (progn (org-skip-whitespace)
894 (if (eobp) (point) (point-at-bol)))))
895 `(babel-call
896 (:begin ,begin
897 :end ,end
898 :info ,info
899 :post-blank ,(count-lines pos-before-blank end))))))
901 (defun org-element-babel-call-interpreter (babel-call contents)
902 "Interpret BABEL-CALL element as Org syntax.
903 CONTENTS is nil."
904 (let* ((babel-info (org-element-property :info babel-call))
905 (main (car babel-info))
906 (post-options (nth 1 babel-info)))
907 (concat "#+CALL: "
908 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
909 ;; Remove redundant square brackets.
910 (replace-match (match-string 1 main) nil nil main))
911 (and post-options (format "[%s]" post-options)))))
914 ;;;; Clock
916 (defun org-element-clock-parser ()
917 "Parse a clock.
919 Return a list whose CAR is `clock' and CDR is a plist containing
920 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
921 as keywords."
922 (save-excursion
923 (let* ((case-fold-search nil)
924 (begin (point))
925 (value (progn (search-forward org-clock-string (line-end-position) t)
926 (org-skip-whitespace)
927 (looking-at "\\[.*\\]")
928 (org-match-string-no-properties 0)))
929 (time (and (progn (goto-char (match-end 0))
930 (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
931 (org-match-string-no-properties 1)))
932 (status (if time 'closed 'running))
933 (post-blank (let ((before-blank (progn (forward-line) (point))))
934 (org-skip-whitespace)
935 (unless (eobp) (beginning-of-line))
936 (count-lines before-blank (point))))
937 (end (point)))
938 `(clock (:status ,status
939 :value ,value
940 :time ,time
941 :begin ,begin
942 :end ,end
943 :post-blank ,post-blank)))))
945 (defun org-element-clock-interpreter (clock contents)
946 "Interpret CLOCK element as Org syntax.
947 CONTENTS is nil."
948 (concat org-clock-string " "
949 (org-element-property :value clock)
950 (let ((time (org-element-property :time clock)))
951 (and time
952 (concat " => "
953 (apply 'format
954 "%2s:%02s"
955 (org-split-string time ":")))))))
958 ;;;; Comment
960 (defun org-element-comment-parser ()
961 "Parse a comment.
963 Return a list whose CAR is `comment' and CDR is a plist
964 containing `:begin', `:end', `:value' and `:post-blank'
965 keywords.
967 Assume point is at comment beginning."
968 (save-excursion
969 (let* ((keywords (org-element-collect-affiliated-keywords))
970 (begin (car keywords))
971 ;; Match first line with a loose regexp since it might as
972 ;; well be an ill-defined keyword.
973 (value (progn
974 (looking-at "#\\+? ?")
975 (buffer-substring-no-properties
976 (match-end 0) (progn (forward-line) (point)))))
977 (com-end
978 ;; Get comments ending. This may not be accurate if
979 ;; commented lines within an item are followed by
980 ;; commented lines outside of a list. Though, parser will
981 ;; always get it right as it already knows surrounding
982 ;; element and has narrowed buffer to its contents.
983 (progn
984 (while (looking-at "\\(\\(# ?\\)[^+]\\|[ \t]*#\\+\\( \\|$\\)\\)")
985 ;; Accumulate lines without leading hash and plus sign
986 ;; if any. First whitespace is also ignored.
987 (setq value
988 (concat value
989 (buffer-substring-no-properties
990 (or (match-end 2) (match-end 3))
991 (progn (forward-line) (point))))))
992 (point)))
993 (end (progn (goto-char com-end)
994 (org-skip-whitespace)
995 (if (eobp) (point) (point-at-bol)))))
996 `(comment
997 (:begin ,begin
998 :end ,end
999 :value ,value
1000 :post-blank ,(count-lines com-end end)
1001 ,@(cadr keywords))))))
1003 (defun org-element-comment-interpreter (comment contents)
1004 "Interpret COMMENT element as Org syntax.
1005 CONTENTS is nil."
1006 (replace-regexp-in-string "^" "#+ " (org-element-property :value comment)))
1009 ;;;; Comment Block
1011 (defun org-element-comment-block-parser ()
1012 "Parse an export block.
1014 Return a list whose CAR is `comment-block' and CDR is a plist
1015 containing `:begin', `:end', `:hiddenp', `:value' and
1016 `:post-blank' keywords.
1018 Assume point is at comment block beginning."
1019 (save-excursion
1020 (let* ((case-fold-search t)
1021 (keywords (org-element-collect-affiliated-keywords))
1022 (begin (car keywords))
1023 (contents-begin (progn (forward-line) (point)))
1024 (hidden (org-truely-invisible-p))
1025 (contents-end
1026 (progn (re-search-forward "^[ \t]*#\\+END_COMMENT" nil t)
1027 (point-at-bol)))
1028 (pos-before-blank (progn (forward-line) (point)))
1029 (end (progn (org-skip-whitespace)
1030 (if (eobp) (point) (point-at-bol))))
1031 (value (buffer-substring-no-properties contents-begin contents-end)))
1032 `(comment-block
1033 (:begin ,begin
1034 :end ,end
1035 :value ,value
1036 :hiddenp ,hidden
1037 :post-blank ,(count-lines pos-before-blank end)
1038 ,@(cadr keywords))))))
1040 (defun org-element-comment-block-interpreter (comment-block contents)
1041 "Interpret COMMENT-BLOCK element as Org syntax.
1042 CONTENTS is nil."
1043 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1044 (org-remove-indentation (org-element-property :value comment-block))))
1047 ;;;; Example Block
1049 (defun org-element-example-block-parser ()
1050 "Parse an example block.
1052 Return a list whose CAR is `example-block' and CDR is a plist
1053 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1054 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1055 `:switches', `:value' and `:post-blank' keywords."
1056 (save-excursion
1057 (let* ((case-fold-search t)
1058 (switches
1059 (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1060 (org-match-string-no-properties 1)))
1061 ;; Switches analysis
1062 (number-lines (cond ((not switches) nil)
1063 ((string-match "-n\\>" switches) 'new)
1064 ((string-match "+n\\>" switches) 'continued)))
1065 (preserve-indent (and switches (string-match "-i\\>" switches)))
1066 ;; Should labels be retained in (or stripped from) example
1067 ;; blocks?
1068 (retain-labels
1069 (or (not switches)
1070 (not (string-match "-r\\>" switches))
1071 (and number-lines (string-match "-k\\>" switches))))
1072 ;; What should code-references use - labels or
1073 ;; line-numbers?
1074 (use-labels
1075 (or (not switches)
1076 (and retain-labels (not (string-match "-k\\>" switches)))))
1077 (label-fmt (and switches
1078 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1079 (match-string 1 switches)))
1080 ;; Standard block parsing.
1081 (keywords (org-element-collect-affiliated-keywords))
1082 (begin (car keywords))
1083 (contents-begin (progn (forward-line) (point)))
1084 (hidden (org-truely-invisible-p))
1085 (contents-end
1086 (progn (re-search-forward "^[ \t]*#\\+END_EXAMPLE" nil t)
1087 (point-at-bol)))
1088 (value (buffer-substring-no-properties contents-begin contents-end))
1089 (pos-before-blank (progn (forward-line) (point)))
1090 (end (progn (org-skip-whitespace)
1091 (if (eobp) (point) (point-at-bol)))))
1092 `(example-block
1093 (:begin ,begin
1094 :end ,end
1095 :value ,value
1096 :switches ,switches
1097 :number-lines ,number-lines
1098 :preserve-indent ,preserve-indent
1099 :retain-labels ,retain-labels
1100 :use-labels ,use-labels
1101 :label-fmt ,label-fmt
1102 :hiddenp ,hidden
1103 :post-blank ,(count-lines pos-before-blank end)
1104 ,@(cadr keywords))))))
1106 (defun org-element-example-block-interpreter (example-block contents)
1107 "Interpret EXAMPLE-BLOCK element as Org syntax.
1108 CONTENTS is nil."
1109 (let ((switches (org-element-property :switches example-block)))
1110 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1111 (org-remove-indentation
1112 (org-element-property :value example-block))
1113 "#+END_EXAMPLE")))
1116 ;;;; Export Block
1118 (defun org-element-export-block-parser ()
1119 "Parse an export block.
1121 Return a list whose CAR is `export-block' and CDR is a plist
1122 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1123 `:post-blank' keywords.
1125 Assume point is at export-block beginning."
1126 (save-excursion
1127 (let* ((case-fold-search t)
1128 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([A-Za-z0-9]+\\)")
1129 (upcase (org-match-string-no-properties 1))))
1130 (keywords (org-element-collect-affiliated-keywords))
1131 (begin (car keywords))
1132 (contents-begin (progn (forward-line) (point)))
1133 (hidden (org-truely-invisible-p))
1134 (contents-end
1135 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
1136 (point-at-bol)))
1137 (pos-before-blank (progn (forward-line) (point)))
1138 (end (progn (org-skip-whitespace)
1139 (if (eobp) (point) (point-at-bol))))
1140 (value (buffer-substring-no-properties contents-begin contents-end)))
1141 `(export-block
1142 (:begin ,begin
1143 :end ,end
1144 :type ,type
1145 :value ,value
1146 :hiddenp ,hidden
1147 :post-blank ,(count-lines pos-before-blank end)
1148 ,@(cadr keywords))))))
1150 (defun org-element-export-block-interpreter (export-block contents)
1151 "Interpret EXPORT-BLOCK element as Org syntax.
1152 CONTENTS is nil."
1153 (let ((type (org-element-property :type export-block)))
1154 (concat (format "#+BEGIN_%s\n" type)
1155 (org-element-property :value export-block)
1156 (format "#+END_%s" type))))
1159 ;;;; Fixed-width
1161 (defun org-element-fixed-width-parser ()
1162 "Parse a fixed-width section.
1164 Return a list whose CAR is `fixed-width' and CDR is a plist
1165 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1167 Assume point is at the beginning of the fixed-width area."
1168 (save-excursion
1169 (let* ((keywords (org-element-collect-affiliated-keywords))
1170 (begin (car keywords))
1171 value
1172 (end-area
1173 ;; Ending position may not be accurate if fixed-width
1174 ;; lines within an item are followed by fixed-width lines
1175 ;; outside of a list. Though, parser will always get it
1176 ;; right as it already knows surrounding element and has
1177 ;; narrowed buffer to its contents.
1178 (progn
1179 (while (looking-at "[ \t]*:\\( \\|$\\)")
1180 ;, Accumulate text without starting colons.
1181 (setq value
1182 (concat value
1183 (buffer-substring-no-properties
1184 (match-end 0) (point-at-eol))
1185 "\n"))
1186 (forward-line))
1187 (point)))
1188 (end (progn (org-skip-whitespace)
1189 (if (eobp) (point) (point-at-bol)))))
1190 `(fixed-width
1191 (:begin ,begin
1192 :end ,end
1193 :value ,value
1194 :post-blank ,(count-lines end-area end)
1195 ,@(cadr keywords))))))
1197 (defun org-element-fixed-width-interpreter (fixed-width contents)
1198 "Interpret FIXED-WIDTH element as Org syntax.
1199 CONTENTS is nil."
1200 (replace-regexp-in-string
1201 "^" ": " (substring (org-element-property :value fixed-width) 0 -1)))
1204 ;;;; Horizontal Rule
1206 (defun org-element-horizontal-rule-parser ()
1207 "Parse an horizontal rule.
1209 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1210 containing `:begin', `:end' and `:post-blank' keywords."
1211 (save-excursion
1212 (let* ((keywords (org-element-collect-affiliated-keywords))
1213 (begin (car keywords))
1214 (post-hr (progn (forward-line) (point)))
1215 (end (progn (org-skip-whitespace)
1216 (if (eobp) (point) (point-at-bol)))))
1217 `(horizontal-rule
1218 (:begin ,begin
1219 :end ,end
1220 :post-blank ,(count-lines post-hr end)
1221 ,@(cadr keywords))))))
1223 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1224 "Interpret HORIZONTAL-RULE element as Org syntax.
1225 CONTENTS is nil."
1226 "-----")
1229 ;;;; Keyword
1231 (defun org-element-keyword-parser ()
1232 "Parse a keyword at point.
1234 Return a list whose CAR is `keyword' and CDR is a plist
1235 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1236 keywords."
1237 (save-excursion
1238 (let* ((case-fold-search t)
1239 (begin (point))
1240 (key (progn (looking-at
1241 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1242 (upcase (org-match-string-no-properties 1))))
1243 (value (org-trim (buffer-substring-no-properties
1244 (match-end 0) (point-at-eol))))
1245 (pos-before-blank (progn (forward-line) (point)))
1246 (end (progn (org-skip-whitespace)
1247 (if (eobp) (point) (point-at-bol)))))
1248 `(keyword
1249 (:key ,key
1250 :value ,value
1251 :begin ,begin
1252 :end ,end
1253 :post-blank ,(count-lines pos-before-blank end))))))
1255 (defun org-element-keyword-interpreter (keyword contents)
1256 "Interpret KEYWORD element as Org syntax.
1257 CONTENTS is nil."
1258 (format "#+%s: %s"
1259 (org-element-property :key keyword)
1260 (org-element-property :value keyword)))
1263 ;;;; Latex Environment
1265 (defun org-element-latex-environment-parser ()
1266 "Parse a LaTeX environment.
1268 Return a list whose CAR is `latex-environment' and CDR is a plist
1269 containing `:begin', `:end', `:value' and `:post-blank'
1270 keywords.
1272 Assume point is at the beginning of the latex environment."
1273 (save-excursion
1274 (let* ((case-fold-search t)
1275 (code-begin (point))
1276 (keywords (org-element-collect-affiliated-keywords))
1277 (begin (car keywords))
1278 (env (progn (looking-at "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}")
1279 (regexp-quote (match-string 1))))
1280 (code-end
1281 (progn (re-search-forward (format "^[ \t]*\\\\end{%s}" env))
1282 (forward-line)
1283 (point)))
1284 (value (buffer-substring-no-properties code-begin code-end))
1285 (end (progn (org-skip-whitespace)
1286 (if (eobp) (point) (point-at-bol)))))
1287 `(latex-environment
1288 (:begin ,begin
1289 :end ,end
1290 :value ,value
1291 :post-blank ,(count-lines code-end end)
1292 ,@(cadr keywords))))))
1294 (defun org-element-latex-environment-interpreter (latex-environment contents)
1295 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1296 CONTENTS is nil."
1297 (org-element-property :value latex-environment))
1300 ;;;; Paragraph
1302 (defun org-element-paragraph-parser ()
1303 "Parse a paragraph.
1305 Return a list whose CAR is `paragraph' and CDR is a plist
1306 containing `:begin', `:end', `:contents-begin' and
1307 `:contents-end' and `:post-blank' keywords.
1309 Assume point is at the beginning of the paragraph."
1310 (save-excursion
1311 (let* ((contents-begin (point))
1312 (keywords (org-element-collect-affiliated-keywords))
1313 (begin (car keywords))
1314 (contents-end
1315 (progn (end-of-line)
1316 (if (re-search-forward org-element-paragraph-separate nil 'm)
1317 (progn (forward-line -1) (end-of-line) (point))
1318 (point))))
1319 (pos-before-blank (progn (forward-line) (point)))
1320 (end (progn (org-skip-whitespace)
1321 (if (eobp) (point) (point-at-bol)))))
1322 `(paragraph
1323 (:begin ,begin
1324 :end ,end
1325 :contents-begin ,contents-begin
1326 :contents-end ,contents-end
1327 :post-blank ,(count-lines pos-before-blank end)
1328 ,@(cadr keywords))))))
1330 (defun org-element-paragraph-interpreter (paragraph contents)
1331 "Interpret PARAGRAPH element as Org syntax.
1332 CONTENTS is the contents of the element."
1333 contents)
1336 ;;;; Planning
1338 (defun org-element-planning-parser ()
1339 "Parse a planning.
1341 Return a list whose CAR is `planning' and CDR is a plist
1342 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
1343 and `:post-blank' keywords."
1344 (save-excursion
1345 (let* ((case-fold-search nil)
1346 (begin (point))
1347 (post-blank (let ((before-blank (progn (forward-line) (point))))
1348 (org-skip-whitespace)
1349 (unless (eobp) (beginning-of-line))
1350 (count-lines before-blank (point))))
1351 (end (point))
1352 closed deadline scheduled)
1353 (goto-char begin)
1354 (while (re-search-forward org-keyword-time-not-clock-regexp
1355 (line-end-position) t)
1356 (goto-char (match-end 1))
1357 (org-skip-whitespace)
1358 (let ((time (buffer-substring-no-properties (point) (match-end 0)))
1359 (keyword (match-string 1)))
1360 (cond ((equal keyword org-closed-string) (setq closed time))
1361 ((equal keyword org-deadline-string) (setq deadline time))
1362 (t (setq scheduled time)))))
1363 `(planning
1364 (:closed ,closed
1365 :deadline ,deadline
1366 :scheduled ,scheduled
1367 :begin ,begin
1368 :end ,end
1369 :post-blank ,post-blank)))))
1371 (defun org-element-planning-interpreter (planning contents)
1372 "Interpret PLANNING element as Org syntax.
1373 CONTENTS is nil."
1374 (mapconcat
1375 'identity
1376 (delq nil
1377 (list (let ((closed (org-element-property :closed planning)))
1378 (when closed (concat org-closed-string " " closed)))
1379 (let ((deadline (org-element-property :deadline planning)))
1380 (when deadline (concat org-deadline-string " " deadline)))
1381 (let ((scheduled (org-element-property :scheduled planning)))
1382 (when scheduled (concat org-scheduled-string " " scheduled)))))
1383 " "))
1386 ;;;; Property Drawer
1388 (defun org-element-property-drawer-parser ()
1389 "Parse a property drawer.
1391 Return a list whose CAR is `property-drawer' and CDR is a plist
1392 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1393 `:contents-end', `:properties' and `:post-blank' keywords.
1395 Assume point is at the beginning of the property drawer."
1396 (save-excursion
1397 (let ((case-fold-search t)
1398 (begin (point))
1399 (prop-begin (progn (forward-line) (point)))
1400 (hidden (org-truely-invisible-p))
1401 (properties
1402 (let (val)
1403 (while (not (looking-at "^[ \t]*:END:"))
1404 (when (looking-at "[ \t]*:\\([A-Za-z][-_A-Za-z0-9]*\\):")
1405 (push (cons (org-match-string-no-properties 1)
1406 (org-trim
1407 (buffer-substring-no-properties
1408 (match-end 0) (point-at-eol))))
1409 val))
1410 (forward-line))
1411 val))
1412 (prop-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1413 (point-at-bol)))
1414 (pos-before-blank (progn (forward-line) (point)))
1415 (end (progn (org-skip-whitespace)
1416 (if (eobp) (point) (point-at-bol)))))
1417 `(property-drawer
1418 (:begin ,begin
1419 :end ,end
1420 :hiddenp ,hidden
1421 :properties ,properties
1422 :post-blank ,(count-lines pos-before-blank end))))))
1424 (defun org-element-property-drawer-interpreter (property-drawer contents)
1425 "Interpret PROPERTY-DRAWER element as Org syntax.
1426 CONTENTS is nil."
1427 (let ((props (org-element-property :properties property-drawer)))
1428 (concat
1429 ":PROPERTIES:\n"
1430 (mapconcat (lambda (p)
1431 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1432 (nreverse props) "\n")
1433 "\n:END:")))
1436 ;;;; Quote Section
1438 (defun org-element-quote-section-parser ()
1439 "Parse a quote section.
1441 Return a list whose CAR is `quote-section' and CDR is a plist
1442 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1444 Assume point is at beginning of the section."
1445 (save-excursion
1446 (let* ((begin (point))
1447 (end (progn (org-with-limited-levels (outline-next-heading))
1448 (point)))
1449 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1450 (forward-line)
1451 (point)))
1452 (value (buffer-substring-no-properties begin pos-before-blank)))
1453 `(quote-section
1454 (:begin ,begin
1455 :end ,end
1456 :value ,value
1457 :post-blank ,(count-lines pos-before-blank end))))))
1459 (defun org-element-quote-section-interpreter (quote-section contents)
1460 "Interpret QUOTE-SECTION element as Org syntax.
1461 CONTENTS is nil."
1462 (org-element-property :value quote-section))
1465 ;;;; Src Block
1467 (defun org-element-src-block-parser ()
1468 "Parse a src block.
1470 Return a list whose CAR is `src-block' and CDR is a plist
1471 containing `:language', `:switches', `:parameters', `:begin',
1472 `:end', `:hiddenp', `:number-lines', `:retain-labels',
1473 `:use-labels', `:label-fmt', `:preserve-indent', `:value' and
1474 `:post-blank' keywords.
1476 Assume point is at the beginning of the block."
1477 (save-excursion
1478 (let* ((case-fold-search t)
1479 (contents-begin (point))
1480 ;; Get affiliated keywords.
1481 (keywords (org-element-collect-affiliated-keywords))
1482 ;; Get beginning position.
1483 (begin (car keywords))
1484 ;; Get language as a string.
1485 (language
1486 (progn
1487 (looking-at
1488 (concat "^[ \t]*#\\+BEGIN_SRC"
1489 "\\(?: +\\(\\S-+\\)\\)?"
1490 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
1491 "\\(.*\\)[ \t]*$"))
1492 (org-match-string-no-properties 1)))
1493 ;; Get switches.
1494 (switches (org-match-string-no-properties 2))
1495 ;; Get parameters.
1496 (parameters (org-match-string-no-properties 3))
1497 ;; Switches analysis
1498 (number-lines (cond ((not switches) nil)
1499 ((string-match "-n\\>" switches) 'new)
1500 ((string-match "+n\\>" switches) 'continued)))
1501 (preserve-indent (and switches (string-match "-i\\>" switches)))
1502 (label-fmt (and switches
1503 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1504 (match-string 1 switches)))
1505 ;; Should labels be retained in (or stripped from) src
1506 ;; blocks?
1507 (retain-labels
1508 (or (not switches)
1509 (not (string-match "-r\\>" switches))
1510 (and number-lines (string-match "-k\\>" switches))))
1511 ;; What should code-references use - labels or
1512 ;; line-numbers?
1513 (use-labels
1514 (or (not switches)
1515 (and retain-labels (not (string-match "-k\\>" switches)))))
1516 ;; Get position at end of block.
1517 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_SRC" nil t)
1518 (forward-line)
1519 (point)))
1520 ;; Retrieve code.
1521 (value (buffer-substring-no-properties
1522 (save-excursion (goto-char contents-begin)
1523 (forward-line)
1524 (point))
1525 (match-beginning 0)))
1526 ;; Get position after ending blank lines.
1527 (end (progn (org-skip-whitespace)
1528 (if (eobp) (point) (point-at-bol))))
1529 ;; Get visibility status.
1530 (hidden (progn (goto-char contents-begin)
1531 (forward-line)
1532 (org-truely-invisible-p))))
1533 `(src-block
1534 (:language ,language
1535 :switches ,(and (org-string-nw-p switches)
1536 (org-trim switches))
1537 :parameters ,(and (org-string-nw-p parameters)
1538 (org-trim parameters))
1539 :begin ,begin
1540 :end ,end
1541 :number-lines ,number-lines
1542 :preserve-indent ,preserve-indent
1543 :retain-labels ,retain-labels
1544 :use-labels ,use-labels
1545 :label-fmt ,label-fmt
1546 :hiddenp ,hidden
1547 :value ,value
1548 :post-blank ,(count-lines contents-end end)
1549 ,@(cadr keywords))))))
1551 (defun org-element-src-block-interpreter (src-block contents)
1552 "Interpret SRC-BLOCK element as Org syntax.
1553 CONTENTS is nil."
1554 (let ((lang (org-element-property :language src-block))
1555 (switches (org-element-property :switches src-block))
1556 (params (org-element-property :parameters src-block))
1557 (value (let ((val (org-element-property :value src-block)))
1558 (cond
1560 (org-src-preserve-indentation val)
1561 ((zerop org-edit-src-content-indentation)
1562 (org-remove-indentation val))
1564 (let ((ind (make-string
1565 org-edit-src-content-indentation 32)))
1566 (replace-regexp-in-string
1567 "\\(^\\)[ \t]*\\S-" ind
1568 (org-remove-indentation val) nil nil 1)))))))
1569 (concat (format "#+BEGIN_SRC%s\n"
1570 (concat (and lang (concat " " lang))
1571 (and switches (concat " " switches))
1572 (and params (concat " " params))))
1573 value
1574 "#+END_SRC")))
1577 ;;;; Table
1579 (defun org-element-table-parser ()
1580 "Parse a table at point.
1582 Return a list whose CAR is `table' and CDR is a plist containing
1583 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
1584 `:contents-end', `:value' and `:post-blank' keywords.
1586 Assume point is at the beginning of the table."
1587 (save-excursion
1588 (let* ((case-fold-search t)
1589 (table-begin (point))
1590 (type (if (org-at-table.el-p) 'table.el 'org))
1591 (keywords (org-element-collect-affiliated-keywords))
1592 (begin (car keywords))
1593 (table-end (goto-char (marker-position (org-table-end t))))
1594 (tblfm (let (acc)
1595 (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
1596 (push (org-match-string-no-properties 1) acc)
1597 (forward-line))
1598 acc))
1599 (pos-before-blank (point))
1600 (end (progn (org-skip-whitespace)
1601 (if (eobp) (point) (point-at-bol)))))
1602 `(table
1603 (:begin ,begin
1604 :end ,end
1605 :type ,type
1606 :tblfm ,tblfm
1607 ;; Only `org' tables have contents. `table.el' tables
1608 ;; use a `:value' property to store raw table as
1609 ;; a string.
1610 :contents-begin ,(and (eq type 'org) table-begin)
1611 :contents-end ,(and (eq type 'org) table-end)
1612 :value ,(and (eq type 'table.el)
1613 (buffer-substring-no-properties
1614 table-begin table-end))
1615 :post-blank ,(count-lines pos-before-blank end)
1616 ,@(cadr keywords))))))
1618 (defun org-element-table-interpreter (table contents)
1619 "Interpret TABLE element as Org syntax.
1620 CONTENTS is nil."
1621 (if (eq (org-element-property :type table) 'table.el)
1622 (org-remove-indentation (org-element-property :value table))
1623 (concat (with-temp-buffer (insert contents)
1624 (org-table-align)
1625 (buffer-string))
1626 (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
1627 (reverse (org-element-property :tblfm table))
1628 "\n"))))
1631 ;;;; Table Row
1633 (defun org-element-table-row-parser ()
1634 "Parse table row at point.
1636 Return a list whose CAR is `table-row' and CDR is a plist
1637 containing `:begin', `:end', `:contents-begin', `:contents-end',
1638 `:type' and `:post-blank' keywords."
1639 (save-excursion
1640 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
1641 (begin (point))
1642 ;; A table rule has no contents. In that case, ensure
1643 ;; CONTENTS-BEGIN matches CONTENTS-END.
1644 (contents-begin (if (eq type 'standard)
1645 (progn (search-forward "|") (point))
1646 (end-of-line)
1647 (skip-chars-backward " \r\t\n")
1648 (point)))
1649 (contents-end (progn (end-of-line)
1650 (skip-chars-backward " \r\t\n")
1651 (point)))
1652 (end (progn (forward-line) (point))))
1653 `(table-row
1654 (:type ,type
1655 :begin ,begin
1656 :end ,end
1657 :contents-begin ,contents-begin
1658 :contents-end ,contents-end
1659 :post-blank 0)))))
1661 (defun org-element-table-row-interpreter (table-row contents)
1662 "Interpret TABLE-ROW element as Org syntax.
1663 CONTENTS is the contents of the table row."
1664 (if (eq (org-element-property :type table-row) 'rule) "|-"
1665 (concat "| " contents)))
1668 ;;;; Verse Block
1670 (defun org-element-verse-block-parser ()
1671 "Parse a verse block.
1673 Return a list whose CAR is `verse-block' and CDR is a plist
1674 containing `:begin', `:end', `:contents-begin', `:contents-end',
1675 `:hiddenp' and `:post-blank' keywords.
1677 Assume point is at beginning of the block."
1678 (save-excursion
1679 (let* ((case-fold-search t)
1680 (keywords (org-element-collect-affiliated-keywords))
1681 (begin (car keywords))
1682 (hidden (progn (forward-line) (org-truely-invisible-p)))
1683 (contents-begin (point))
1684 (contents-end
1685 (progn
1686 (re-search-forward (concat "^[ \t]*#\\+END_VERSE") nil t)
1687 (point-at-bol)))
1688 (pos-before-blank (progn (forward-line) (point)))
1689 (end (progn (org-skip-whitespace)
1690 (if (eobp) (point) (point-at-bol)))))
1691 `(verse-block
1692 (:begin ,begin
1693 :end ,end
1694 :contents-begin ,contents-begin
1695 :contents-end ,contents-end
1696 :hiddenp ,hidden
1697 :post-blank ,(count-lines pos-before-blank end)
1698 ,@(cadr keywords))))))
1700 (defun org-element-verse-block-interpreter (verse-block contents)
1701 "Interpret VERSE-BLOCK element as Org syntax.
1702 CONTENTS is verse block contents."
1703 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
1707 ;;; Objects
1709 ;; Unlike to elements, interstices can be found between objects.
1710 ;; That's why, along with the parser, successor functions are provided
1711 ;; for each object. Some objects share the same successor (i.e. `code'
1712 ;; and `verbatim' objects).
1714 ;; A successor must accept a single argument bounding the search. It
1715 ;; will return either a cons cell whose CAR is the object's type, as
1716 ;; a symbol, and CDR the position of its next occurrence, or nil.
1718 ;; Successors follow the naming convention:
1719 ;; org-element-NAME-successor, where NAME is the name of the
1720 ;; successor, as defined in `org-element-all-successors'.
1722 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1723 ;; object types they can contain will be specified in
1724 ;; `org-element-object-restrictions'.
1726 ;; Adding a new type of object is simple. Implement a successor,
1727 ;; a parser, and an interpreter for it, all following the naming
1728 ;; convention. Register type in `org-element-all-objects' and
1729 ;; successor in `org-element-all-successors'. Maybe tweak
1730 ;; restrictions about it, and that's it.
1733 ;;;; Bold
1735 (defun org-element-bold-parser ()
1736 "Parse bold object at point.
1738 Return a list whose CAR is `bold' and CDR is a plist with
1739 `:begin', `:end', `:contents-begin' and `:contents-end' and
1740 `:post-blank' keywords.
1742 Assume point is at the first star marker."
1743 (save-excursion
1744 (unless (bolp) (backward-char 1))
1745 (looking-at org-emph-re)
1746 (let ((begin (match-beginning 2))
1747 (contents-begin (match-beginning 4))
1748 (contents-end (match-end 4))
1749 (post-blank (progn (goto-char (match-end 2))
1750 (skip-chars-forward " \t")))
1751 (end (point)))
1752 `(bold
1753 (:begin ,begin
1754 :end ,end
1755 :contents-begin ,contents-begin
1756 :contents-end ,contents-end
1757 :post-blank ,post-blank)))))
1759 (defun org-element-bold-interpreter (bold contents)
1760 "Interpret BOLD object as Org syntax.
1761 CONTENTS is the contents of the object."
1762 (format "*%s*" contents))
1764 (defun org-element-text-markup-successor (limit)
1765 "Search for the next text-markup object.
1767 LIMIT bounds the search.
1769 Return value is a cons cell whose CAR is a symbol among `bold',
1770 `italic', `underline', `strike-through', `code' and `verbatim'
1771 and CDR is beginning position."
1772 (save-excursion
1773 (unless (bolp) (backward-char))
1774 (when (re-search-forward org-emph-re limit t)
1775 (let ((marker (match-string 3)))
1776 (cons (cond
1777 ((equal marker "*") 'bold)
1778 ((equal marker "/") 'italic)
1779 ((equal marker "_") 'underline)
1780 ((equal marker "+") 'strike-through)
1781 ((equal marker "~") 'code)
1782 ((equal marker "=") 'verbatim)
1783 (t (error "Unknown marker at %d" (match-beginning 3))))
1784 (match-beginning 2))))))
1787 ;;;; Code
1789 (defun org-element-code-parser ()
1790 "Parse code object at point.
1792 Return a list whose CAR is `code' and CDR is a plist with
1793 `:value', `:begin', `:end' and `:post-blank' keywords.
1795 Assume point is at the first tilde marker."
1796 (save-excursion
1797 (unless (bolp) (backward-char 1))
1798 (looking-at org-emph-re)
1799 (let ((begin (match-beginning 2))
1800 (value (org-match-string-no-properties 4))
1801 (post-blank (progn (goto-char (match-end 2))
1802 (skip-chars-forward " \t")))
1803 (end (point)))
1804 `(code
1805 (:value ,value
1806 :begin ,begin
1807 :end ,end
1808 :post-blank ,post-blank)))))
1810 (defun org-element-code-interpreter (code contents)
1811 "Interpret CODE object as Org syntax.
1812 CONTENTS is nil."
1813 (format "~%s~" (org-element-property :value code)))
1816 ;;;; Entity
1818 (defun org-element-entity-parser ()
1819 "Parse entity at point.
1821 Return a list whose CAR is `entity' and CDR a plist with
1822 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1823 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1824 keywords.
1826 Assume point is at the beginning of the entity."
1827 (save-excursion
1828 (looking-at "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1829 (let* ((value (org-entity-get (match-string 1)))
1830 (begin (match-beginning 0))
1831 (bracketsp (string= (match-string 2) "{}"))
1832 (post-blank (progn (goto-char (match-end 1))
1833 (when bracketsp (forward-char 2))
1834 (skip-chars-forward " \t")))
1835 (end (point)))
1836 `(entity
1837 (:name ,(car value)
1838 :latex ,(nth 1 value)
1839 :latex-math-p ,(nth 2 value)
1840 :html ,(nth 3 value)
1841 :ascii ,(nth 4 value)
1842 :latin1 ,(nth 5 value)
1843 :utf-8 ,(nth 6 value)
1844 :begin ,begin
1845 :end ,end
1846 :use-brackets-p ,bracketsp
1847 :post-blank ,post-blank)))))
1849 (defun org-element-entity-interpreter (entity contents)
1850 "Interpret ENTITY object as Org syntax.
1851 CONTENTS is nil."
1852 (concat "\\"
1853 (org-element-property :name entity)
1854 (when (org-element-property :use-brackets-p entity) "{}")))
1856 (defun org-element-latex-or-entity-successor (limit)
1857 "Search for the next latex-fragment or entity object.
1859 LIMIT bounds the search.
1861 Return value is a cons cell whose CAR is `entity' or
1862 `latex-fragment' and CDR is beginning position."
1863 (save-excursion
1864 (let ((matchers (plist-get org-format-latex-options :matchers))
1865 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1866 (entity-re
1867 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))
1868 (when (re-search-forward
1869 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1870 matchers "\\|")
1871 "\\|" entity-re)
1872 limit t)
1873 (goto-char (match-beginning 0))
1874 (if (looking-at entity-re)
1875 ;; Determine if it's a real entity or a LaTeX command.
1876 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1877 (match-beginning 0))
1878 ;; No entity nor command: point is at a LaTeX fragment.
1879 ;; Determine its type to get the correct beginning position.
1880 (cons 'latex-fragment
1881 (catch 'return
1882 (mapc (lambda (e)
1883 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1884 (throw 'return
1885 (match-beginning
1886 (nth 2 (assoc e org-latex-regexps))))))
1887 matchers)
1888 (point))))))))
1891 ;;;; Export Snippet
1893 (defun org-element-export-snippet-parser ()
1894 "Parse export snippet at point.
1896 Return a list whose CAR is `export-snippet' and CDR a plist with
1897 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1898 keywords.
1900 Assume point is at the beginning of the snippet."
1901 (save-excursion
1902 (looking-at "<\\([-A-Za-z0-9]+\\)@")
1903 (let* ((begin (point))
1904 (back-end (org-match-string-no-properties 1))
1905 (inner-begin (match-end 0))
1906 (inner-end
1907 (let ((count 1))
1908 (goto-char inner-begin)
1909 (while (and (> count 0) (re-search-forward "[<>]" nil t))
1910 (if (equal (match-string 0) "<") (incf count) (decf count)))
1911 (1- (point))))
1912 (value (buffer-substring-no-properties inner-begin inner-end))
1913 (post-blank (skip-chars-forward " \t"))
1914 (end (point)))
1915 `(export-snippet
1916 (:back-end ,back-end
1917 :value ,value
1918 :begin ,begin
1919 :end ,end
1920 :post-blank ,post-blank)))))
1922 (defun org-element-export-snippet-interpreter (export-snippet contents)
1923 "Interpret EXPORT-SNIPPET object as Org syntax.
1924 CONTENTS is nil."
1925 (format "<%s@%s>"
1926 (org-element-property :back-end export-snippet)
1927 (org-element-property :value export-snippet)))
1929 (defun org-element-export-snippet-successor (limit)
1930 "Search for the next export-snippet object.
1932 LIMIT bounds the search.
1934 Return value is a cons cell whose CAR is `export-snippet' CDR is
1935 its beginning position."
1936 (save-excursion
1937 (catch 'exit
1938 (while (re-search-forward "<[-A-Za-z0-9]+@" limit t)
1939 (save-excursion
1940 (let ((beg (match-beginning 0))
1941 (count 1))
1942 (while (re-search-forward "[<>]" limit t)
1943 (if (equal (match-string 0) "<") (incf count) (decf count))
1944 (when (zerop count)
1945 (throw 'exit (cons 'export-snippet beg))))))))))
1948 ;;;; Footnote Reference
1950 (defun org-element-footnote-reference-parser ()
1951 "Parse footnote reference at point.
1953 Return a list whose CAR is `footnote-reference' and CDR a plist
1954 with `:label', `:type', `:inline-definition', `:begin', `:end'
1955 and `:post-blank' as keywords."
1956 (save-excursion
1957 (looking-at org-footnote-re)
1958 (let* ((begin (point))
1959 (label (or (org-match-string-no-properties 2)
1960 (org-match-string-no-properties 3)
1961 (and (match-string 1)
1962 (concat "fn:" (org-match-string-no-properties 1)))))
1963 (type (if (or (not label) (match-string 1)) 'inline 'standard))
1964 (inner-begin (match-end 0))
1965 (inner-end
1966 (let ((count 1))
1967 (forward-char)
1968 (while (and (> count 0) (re-search-forward "[][]" nil t))
1969 (if (equal (match-string 0) "[") (incf count) (decf count)))
1970 (1- (point))))
1971 (post-blank (progn (goto-char (1+ inner-end))
1972 (skip-chars-forward " \t")))
1973 (end (point))
1974 (inline-definition
1975 (and (eq type 'inline)
1976 (org-element-parse-secondary-string
1977 (buffer-substring inner-begin inner-end)
1978 (org-element-restriction 'footnote-reference)))))
1979 `(footnote-reference
1980 (:label ,label
1981 :type ,type
1982 :inline-definition ,inline-definition
1983 :begin ,begin
1984 :end ,end
1985 :post-blank ,post-blank)))))
1987 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1988 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1989 CONTENTS is nil."
1990 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
1991 (def
1992 (let ((inline-def
1993 (org-element-property :inline-definition footnote-reference)))
1994 (if (not inline-def) ""
1995 (concat ":" (org-element-interpret-data inline-def))))))
1996 (format "[%s]" (concat label def))))
1998 (defun org-element-footnote-reference-successor (limit)
1999 "Search for the next footnote-reference object.
2001 LIMIT bounds the search.
2003 Return value is a cons cell whose CAR is `footnote-reference' and
2004 CDR is beginning position."
2005 (save-excursion
2006 (catch 'exit
2007 (while (re-search-forward org-footnote-re limit t)
2008 (save-excursion
2009 (let ((beg (match-beginning 0))
2010 (count 1))
2011 (backward-char)
2012 (while (re-search-forward "[][]" limit t)
2013 (if (equal (match-string 0) "[") (incf count) (decf count))
2014 (when (zerop count)
2015 (throw 'exit (cons 'footnote-reference beg))))))))))
2018 ;;;; Inline Babel Call
2020 (defun org-element-inline-babel-call-parser ()
2021 "Parse inline babel call at point.
2023 Return a list whose CAR is `inline-babel-call' and CDR a plist
2024 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2026 Assume point is at the beginning of the babel call."
2027 (save-excursion
2028 (unless (bolp) (backward-char))
2029 (looking-at org-babel-inline-lob-one-liner-regexp)
2030 (let ((info (save-match-data (org-babel-lob-get-info)))
2031 (begin (match-end 1))
2032 (post-blank (progn (goto-char (match-end 0))
2033 (skip-chars-forward " \t")))
2034 (end (point)))
2035 `(inline-babel-call
2036 (:begin ,begin
2037 :end ,end
2038 :info ,info
2039 :post-blank ,post-blank)))))
2041 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2042 "Interpret INLINE-BABEL-CALL object as Org syntax.
2043 CONTENTS is nil."
2044 (let* ((babel-info (org-element-property :info inline-babel-call))
2045 (main-source (car babel-info))
2046 (post-options (nth 1 babel-info)))
2047 (concat "call_"
2048 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2049 ;; Remove redundant square brackets.
2050 (replace-match
2051 (match-string 1 main-source) nil nil main-source)
2052 main-source)
2053 (and post-options (format "[%s]" post-options)))))
2055 (defun org-element-inline-babel-call-successor (limit)
2056 "Search for the next inline-babel-call object.
2058 LIMIT bounds the search.
2060 Return value is a cons cell whose CAR is `inline-babel-call' and
2061 CDR is beginning position."
2062 (save-excursion
2063 ;; Use a simplified version of
2064 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
2065 (when (re-search-forward
2066 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
2067 limit t)
2068 (cons 'inline-babel-call (match-beginning 0)))))
2071 ;;;; Inline Src Block
2073 (defun org-element-inline-src-block-parser ()
2074 "Parse inline source block at point.
2076 Return a list whose CAR is `inline-src-block' and CDR a plist
2077 with `:begin', `:end', `:language', `:value', `:parameters' and
2078 `:post-blank' as keywords.
2080 Assume point is at the beginning of the inline src block."
2081 (save-excursion
2082 (unless (bolp) (backward-char))
2083 (looking-at org-babel-inline-src-block-regexp)
2084 (let ((begin (match-beginning 1))
2085 (language (org-match-string-no-properties 2))
2086 (parameters (org-match-string-no-properties 4))
2087 (value (org-match-string-no-properties 5))
2088 (post-blank (progn (goto-char (match-end 0))
2089 (skip-chars-forward " \t")))
2090 (end (point)))
2091 `(inline-src-block
2092 (:language ,language
2093 :value ,value
2094 :parameters ,parameters
2095 :begin ,begin
2096 :end ,end
2097 :post-blank ,post-blank)))))
2099 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2100 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2101 CONTENTS is nil."
2102 (let ((language (org-element-property :language inline-src-block))
2103 (arguments (org-element-property :parameters inline-src-block))
2104 (body (org-element-property :value inline-src-block)))
2105 (format "src_%s%s{%s}"
2106 language
2107 (if arguments (format "[%s]" arguments) "")
2108 body)))
2110 (defun org-element-inline-src-block-successor (limit)
2111 "Search for the next inline-babel-call element.
2113 LIMIT bounds the search.
2115 Return value is a cons cell whose CAR is `inline-babel-call' and
2116 CDR is beginning position."
2117 (save-excursion
2118 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
2119 (cons 'inline-src-block (match-beginning 1)))))
2121 ;;;; Italic
2123 (defun org-element-italic-parser ()
2124 "Parse italic object at point.
2126 Return a list whose CAR is `italic' and CDR is a plist with
2127 `:begin', `:end', `:contents-begin' and `:contents-end' and
2128 `:post-blank' keywords.
2130 Assume point is at the first slash marker."
2131 (save-excursion
2132 (unless (bolp) (backward-char 1))
2133 (looking-at org-emph-re)
2134 (let ((begin (match-beginning 2))
2135 (contents-begin (match-beginning 4))
2136 (contents-end (match-end 4))
2137 (post-blank (progn (goto-char (match-end 2))
2138 (skip-chars-forward " \t")))
2139 (end (point)))
2140 `(italic
2141 (:begin ,begin
2142 :end ,end
2143 :contents-begin ,contents-begin
2144 :contents-end ,contents-end
2145 :post-blank ,post-blank)))))
2147 (defun org-element-italic-interpreter (italic contents)
2148 "Interpret ITALIC object as Org syntax.
2149 CONTENTS is the contents of the object."
2150 (format "/%s/" contents))
2153 ;;;; Latex Fragment
2155 (defun org-element-latex-fragment-parser ()
2156 "Parse latex fragment at point.
2158 Return a list whose CAR is `latex-fragment' and CDR a plist with
2159 `:value', `:begin', `:end', and `:post-blank' as keywords.
2161 Assume point is at the beginning of the latex fragment."
2162 (save-excursion
2163 (let* ((begin (point))
2164 (substring-match
2165 (catch 'exit
2166 (mapc (lambda (e)
2167 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2168 (when (or (looking-at latex-regexp)
2169 (and (not (bobp))
2170 (save-excursion
2171 (backward-char)
2172 (looking-at latex-regexp))))
2173 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2174 (plist-get org-format-latex-options :matchers))
2175 ;; None found: it's a macro.
2176 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2178 (value (match-string-no-properties substring-match))
2179 (post-blank (progn (goto-char (match-end substring-match))
2180 (skip-chars-forward " \t")))
2181 (end (point)))
2182 `(latex-fragment
2183 (:value ,value
2184 :begin ,begin
2185 :end ,end
2186 :post-blank ,post-blank)))))
2188 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2189 "Interpret LATEX-FRAGMENT object as Org syntax.
2190 CONTENTS is nil."
2191 (org-element-property :value latex-fragment))
2193 ;;;; Line Break
2195 (defun org-element-line-break-parser ()
2196 "Parse line break at point.
2198 Return a list whose CAR is `line-break', and CDR a plist with
2199 `:begin', `:end' and `:post-blank' keywords.
2201 Assume point is at the beginning of the line break."
2202 (let ((begin (point))
2203 (end (save-excursion (forward-line) (point))))
2204 `(line-break (:begin ,begin :end ,end :post-blank 0))))
2206 (defun org-element-line-break-interpreter (line-break contents)
2207 "Interpret LINE-BREAK object as Org syntax.
2208 CONTENTS is nil."
2209 "\\\\\n")
2211 (defun org-element-line-break-successor (limit)
2212 "Search for the next line-break object.
2214 LIMIT bounds the search.
2216 Return value is a cons cell whose CAR is `line-break' and CDR is
2217 beginning position."
2218 (save-excursion
2219 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2220 (goto-char (match-beginning 1)))))
2221 ;; A line break can only happen on a non-empty line.
2222 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2223 (cons 'line-break beg)))))
2226 ;;;; Link
2228 (defun org-element-link-parser ()
2229 "Parse link at point.
2231 Return a list whose CAR is `link' and CDR a plist with `:type',
2232 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
2233 `:contents-end' and `:post-blank' as keywords.
2235 Assume point is at the beginning of the link."
2236 (save-excursion
2237 (let ((begin (point))
2238 end contents-begin contents-end link-end post-blank path type
2239 raw-link link)
2240 (cond
2241 ;; Type 1: Text targeted from a radio target.
2242 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2243 (setq type "radio"
2244 link-end (match-end 0)
2245 path (org-match-string-no-properties 0)))
2246 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2247 ((looking-at org-bracket-link-regexp)
2248 (setq contents-begin (match-beginning 3)
2249 contents-end (match-end 3)
2250 link-end (match-end 0)
2251 ;; RAW-LINK is the original link.
2252 raw-link (org-match-string-no-properties 1)
2253 link (org-translate-link
2254 (org-link-expand-abbrev
2255 (org-link-unescape raw-link))))
2256 ;; Determine TYPE of link and set PATH accordingly.
2257 (cond
2258 ;; File type.
2259 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2260 (setq type "file" path link))
2261 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2262 ((string-match org-link-re-with-space3 link)
2263 (setq type (match-string 1 link) path (match-string 2 link)))
2264 ;; Id type: PATH is the id.
2265 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2266 (setq type "id" path (match-string 1 link)))
2267 ;; Code-ref type: PATH is the name of the reference.
2268 ((string-match "^(\\(.*\\))$" link)
2269 (setq type "coderef" path (match-string 1 link)))
2270 ;; Custom-id type: PATH is the name of the custom id.
2271 ((= (aref link 0) ?#)
2272 (setq type "custom-id" path (substring link 1)))
2273 ;; Fuzzy type: Internal link either matches a target, an
2274 ;; headline name or nothing. PATH is the target or
2275 ;; headline's name.
2276 (t (setq type "fuzzy" path link))))
2277 ;; Type 3: Plain link, i.e. http://orgmode.org
2278 ((looking-at org-plain-link-re)
2279 (setq raw-link (org-match-string-no-properties 0)
2280 type (org-match-string-no-properties 1)
2281 path (org-match-string-no-properties 2)
2282 link-end (match-end 0)))
2283 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2284 ((looking-at org-angle-link-re)
2285 (setq raw-link (buffer-substring-no-properties
2286 (match-beginning 1) (match-end 2))
2287 type (org-match-string-no-properties 1)
2288 path (org-match-string-no-properties 2)
2289 link-end (match-end 0))))
2290 ;; In any case, deduce end point after trailing white space from
2291 ;; LINK-END variable.
2292 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2293 end (point))
2294 `(link
2295 (:type ,type
2296 :path ,path
2297 :raw-link ,(or raw-link path)
2298 :begin ,begin
2299 :end ,end
2300 :contents-begin ,contents-begin
2301 :contents-end ,contents-end
2302 :post-blank ,post-blank)))))
2304 (defun org-element-link-interpreter (link contents)
2305 "Interpret LINK object as Org syntax.
2306 CONTENTS is the contents of the object, or nil."
2307 (let ((type (org-element-property :type link))
2308 (raw-link (org-element-property :raw-link link)))
2309 (if (string= type "radio") raw-link
2310 (format "[[%s]%s]"
2311 raw-link
2312 (if contents (format "[%s]" contents) "")))))
2314 (defun org-element-link-successor (limit)
2315 "Search for the next link object.
2317 LIMIT bounds the search.
2319 Return value is a cons cell whose CAR is `link' and CDR is
2320 beginning position."
2321 (save-excursion
2322 (let ((link-regexp
2323 (if (not org-target-link-regexp) org-any-link-re
2324 (concat org-any-link-re "\\|" org-target-link-regexp))))
2325 (when (re-search-forward link-regexp limit t)
2326 (cons 'link (match-beginning 0))))))
2329 ;;;; Macro
2331 (defun org-element-macro-parser ()
2332 "Parse macro at point.
2334 Return a list whose CAR is `macro' and CDR a plist with `:key',
2335 `:args', `:begin', `:end', `:value' and `:post-blank' as
2336 keywords.
2338 Assume point is at the macro."
2339 (save-excursion
2340 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2341 (let ((begin (point))
2342 (key (downcase (org-match-string-no-properties 1)))
2343 (value (org-match-string-no-properties 0))
2344 (post-blank (progn (goto-char (match-end 0))
2345 (skip-chars-forward " \t")))
2346 (end (point))
2347 (args (let ((args (org-match-string-no-properties 3)) args2)
2348 (when args
2349 (setq args (org-split-string args ","))
2350 (while args
2351 (while (string-match "\\\\\\'" (car args))
2352 ;; Repair bad splits.
2353 (setcar (cdr args) (concat (substring (car args) 0 -1)
2354 "," (nth 1 args)))
2355 (pop args))
2356 (push (pop args) args2))
2357 (mapcar 'org-trim (nreverse args2))))))
2358 `(macro
2359 (:key ,key
2360 :value ,value
2361 :args ,args
2362 :begin ,begin
2363 :end ,end
2364 :post-blank ,post-blank)))))
2366 (defun org-element-macro-interpreter (macro contents)
2367 "Interpret MACRO object as Org syntax.
2368 CONTENTS is nil."
2369 (org-element-property :value macro))
2371 (defun org-element-macro-successor (limit)
2372 "Search for the next macro object.
2374 LIMIT bounds the search.
2376 Return value is cons cell whose CAR is `macro' and CDR is
2377 beginning position."
2378 (save-excursion
2379 (when (re-search-forward
2380 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2381 limit t)
2382 (cons 'macro (match-beginning 0)))))
2385 ;;;; Radio-target
2387 (defun org-element-radio-target-parser ()
2388 "Parse radio target at point.
2390 Return a list whose CAR is `radio-target' and CDR a plist with
2391 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2392 and `:post-blank' as keywords.
2394 Assume point is at the radio target."
2395 (save-excursion
2396 (looking-at org-radio-target-regexp)
2397 (let ((begin (point))
2398 (contents-begin (match-beginning 1))
2399 (contents-end (match-end 1))
2400 (value (org-match-string-no-properties 1))
2401 (post-blank (progn (goto-char (match-end 0))
2402 (skip-chars-forward " \t")))
2403 (end (point)))
2404 `(radio-target
2405 (:begin ,begin
2406 :end ,end
2407 :contents-begin ,contents-begin
2408 :contents-end ,contents-end
2409 :post-blank ,post-blank
2410 :value ,value)))))
2412 (defun org-element-radio-target-interpreter (target contents)
2413 "Interpret TARGET object as Org syntax.
2414 CONTENTS is the contents of the object."
2415 (concat "<<<" contents ">>>"))
2417 (defun org-element-radio-target-successor (limit)
2418 "Search for the next radio-target object.
2420 LIMIT bounds the search.
2422 Return value is a cons cell whose CAR is `radio-target' and CDR
2423 is beginning position."
2424 (save-excursion
2425 (when (re-search-forward org-radio-target-regexp limit t)
2426 (cons 'radio-target (match-beginning 0)))))
2429 ;;;; Statistics Cookie
2431 (defun org-element-statistics-cookie-parser ()
2432 "Parse statistics cookie at point.
2434 Return a list whose CAR is `statistics-cookie', and CDR a plist
2435 with `:begin', `:end', `:value' and `:post-blank' keywords.
2437 Assume point is at the beginning of the statistics-cookie."
2438 (save-excursion
2439 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2440 (let* ((begin (point))
2441 (value (buffer-substring-no-properties
2442 (match-beginning 0) (match-end 0)))
2443 (post-blank (progn (goto-char (match-end 0))
2444 (skip-chars-forward " \t")))
2445 (end (point)))
2446 `(statistics-cookie
2447 (:begin ,begin
2448 :end ,end
2449 :value ,value
2450 :post-blank ,post-blank)))))
2452 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2453 "Interpret STATISTICS-COOKIE object as Org syntax.
2454 CONTENTS is nil."
2455 (org-element-property :value statistics-cookie))
2457 (defun org-element-statistics-cookie-successor (limit)
2458 "Search for the next statistics cookie object.
2460 LIMIT bounds the search.
2462 Return value is a cons cell whose CAR is `statistics-cookie' and
2463 CDR is beginning position."
2464 (save-excursion
2465 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2466 (cons 'statistics-cookie (match-beginning 0)))))
2469 ;;;; Strike-Through
2471 (defun org-element-strike-through-parser ()
2472 "Parse strike-through object at point.
2474 Return a list whose CAR is `strike-through' and CDR is a plist
2475 with `:begin', `:end', `:contents-begin' and `:contents-end' and
2476 `:post-blank' keywords.
2478 Assume point is at the first plus sign marker."
2479 (save-excursion
2480 (unless (bolp) (backward-char 1))
2481 (looking-at org-emph-re)
2482 (let ((begin (match-beginning 2))
2483 (contents-begin (match-beginning 4))
2484 (contents-end (match-end 4))
2485 (post-blank (progn (goto-char (match-end 2))
2486 (skip-chars-forward " \t")))
2487 (end (point)))
2488 `(strike-through
2489 (:begin ,begin
2490 :end ,end
2491 :contents-begin ,contents-begin
2492 :contents-end ,contents-end
2493 :post-blank ,post-blank)))))
2495 (defun org-element-strike-through-interpreter (strike-through contents)
2496 "Interpret STRIKE-THROUGH object as Org syntax.
2497 CONTENTS is the contents of the object."
2498 (format "+%s+" contents))
2501 ;;;; Subscript
2503 (defun org-element-subscript-parser ()
2504 "Parse subscript at point.
2506 Return a list whose CAR is `subscript' and CDR a plist with
2507 `:begin', `:end', `:contents-begin', `:contents-end',
2508 `:use-brackets-p' and `:post-blank' as keywords.
2510 Assume point is at the underscore."
2511 (save-excursion
2512 (unless (bolp) (backward-char))
2513 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2515 (not (looking-at org-match-substring-regexp))))
2516 (begin (match-beginning 2))
2517 (contents-begin (or (match-beginning 5)
2518 (match-beginning 3)))
2519 (contents-end (or (match-end 5) (match-end 3)))
2520 (post-blank (progn (goto-char (match-end 0))
2521 (skip-chars-forward " \t")))
2522 (end (point)))
2523 `(subscript
2524 (:begin ,begin
2525 :end ,end
2526 :use-brackets-p ,bracketsp
2527 :contents-begin ,contents-begin
2528 :contents-end ,contents-end
2529 :post-blank ,post-blank)))))
2531 (defun org-element-subscript-interpreter (subscript contents)
2532 "Interpret SUBSCRIPT object as Org syntax.
2533 CONTENTS is the contents of the object."
2534 (format
2535 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
2536 contents))
2538 (defun org-element-sub/superscript-successor (limit)
2539 "Search for the next sub/superscript object.
2541 LIMIT bounds the search.
2543 Return value is a cons cell whose CAR is either `subscript' or
2544 `superscript' and CDR is beginning position."
2545 (save-excursion
2546 (when (re-search-forward org-match-substring-regexp limit t)
2547 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2548 (match-beginning 2)))))
2551 ;;;; Superscript
2553 (defun org-element-superscript-parser ()
2554 "Parse superscript at point.
2556 Return a list whose CAR is `superscript' and CDR a plist with
2557 `:begin', `:end', `:contents-begin', `:contents-end',
2558 `:use-brackets-p' and `:post-blank' as keywords.
2560 Assume point is at the caret."
2561 (save-excursion
2562 (unless (bolp) (backward-char))
2563 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
2564 (not (looking-at org-match-substring-regexp))))
2565 (begin (match-beginning 2))
2566 (contents-begin (or (match-beginning 5)
2567 (match-beginning 3)))
2568 (contents-end (or (match-end 5) (match-end 3)))
2569 (post-blank (progn (goto-char (match-end 0))
2570 (skip-chars-forward " \t")))
2571 (end (point)))
2572 `(superscript
2573 (:begin ,begin
2574 :end ,end
2575 :use-brackets-p ,bracketsp
2576 :contents-begin ,contents-begin
2577 :contents-end ,contents-end
2578 :post-blank ,post-blank)))))
2580 (defun org-element-superscript-interpreter (superscript contents)
2581 "Interpret SUPERSCRIPT object as Org syntax.
2582 CONTENTS is the contents of the object."
2583 (format
2584 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
2585 contents))
2588 ;;;; Table Cell
2590 (defun org-element-table-cell-parser ()
2591 "Parse table cell at point.
2593 Return a list whose CAR is `table-cell' and CDR is a plist
2594 containing `:begin', `:end', `:contents-begin', `:contents-end'
2595 and `:post-blank' keywords."
2596 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
2597 (let* ((begin (match-beginning 0))
2598 (end (match-end 0))
2599 (contents-begin (match-beginning 1))
2600 (contents-end (match-end 1)))
2601 `(table-cell
2602 (:begin ,begin
2603 :end ,end
2604 :contents-begin ,contents-begin
2605 :contents-end ,contents-end
2606 :post-blank 0))))
2608 (defun org-element-table-cell-interpreter (table-cell contents)
2609 "Interpret TABLE-CELL element as Org syntax.
2610 CONTENTS is the contents of the cell, or nil."
2611 (concat " " contents " |"))
2613 (defun org-element-table-cell-successor (limit)
2614 "Search for the next table-cell object.
2616 LIMIT bounds the search.
2618 Return value is a cons cell whose CAR is `table-cell' and CDR is
2619 beginning position."
2620 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
2623 ;;;; Target
2625 (defun org-element-target-parser ()
2626 "Parse target at point.
2628 Return a list whose CAR is `target' and CDR a plist with
2629 `:begin', `:end', `:value' and `:post-blank' as keywords.
2631 Assume point is at the target."
2632 (save-excursion
2633 (looking-at org-target-regexp)
2634 (let ((begin (point))
2635 (value (org-match-string-no-properties 1))
2636 (post-blank (progn (goto-char (match-end 0))
2637 (skip-chars-forward " \t")))
2638 (end (point)))
2639 `(target
2640 (:begin ,begin
2641 :end ,end
2642 :value ,value
2643 :post-blank ,post-blank)))))
2645 (defun org-element-target-interpreter (target contents)
2646 "Interpret TARGET object as Org syntax.
2647 CONTENTS is nil."
2648 (format "<<%s>>" (org-element-property :value target)))
2650 (defun org-element-target-successor (limit)
2651 "Search for the next target object.
2653 LIMIT bounds the search.
2655 Return value is a cons cell whose CAR is `target' and CDR is
2656 beginning position."
2657 (save-excursion
2658 (when (re-search-forward org-target-regexp limit t)
2659 (cons 'target (match-beginning 0)))))
2662 ;;;; Timestamp
2664 (defun org-element-timestamp-parser ()
2665 "Parse time stamp at point.
2667 Return a list whose CAR is `timestamp', and CDR a plist with
2668 `:type', `:begin', `:end', `:value' and `:post-blank' keywords.
2670 Assume point is at the beginning of the timestamp."
2671 (save-excursion
2672 (let* ((begin (point))
2673 (type (cond
2674 ((looking-at org-tsr-regexp)
2675 (if (match-string 2) 'active-range 'active))
2676 ((looking-at org-tsr-regexp-both)
2677 (if (match-string 2) 'inactive-range 'inactive))
2678 ((looking-at
2679 (concat
2680 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2681 "\\|"
2682 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2683 'diary)))
2684 (value (org-match-string-no-properties 0))
2685 (post-blank (progn (goto-char (match-end 0))
2686 (skip-chars-forward " \t")))
2687 (end (point)))
2688 `(timestamp
2689 (:type ,type
2690 :value ,value
2691 :begin ,begin
2692 :end ,end
2693 :post-blank ,post-blank)))))
2695 (defun org-element-timestamp-interpreter (timestamp contents)
2696 "Interpret TIMESTAMP object as Org syntax.
2697 CONTENTS is nil."
2698 (org-element-property :value timestamp))
2700 (defun org-element-timestamp-successor (limit)
2701 "Search for the next timestamp object.
2703 LIMIT bounds the search.
2705 Return value is a cons cell whose CAR is `timestamp' and CDR is
2706 beginning position."
2707 (save-excursion
2708 (when (re-search-forward
2709 (concat org-ts-regexp-both
2710 "\\|"
2711 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2712 "\\|"
2713 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2714 limit t)
2715 (cons 'timestamp (match-beginning 0)))))
2718 ;;;; Underline
2720 (defun org-element-underline-parser ()
2721 "Parse underline object at point.
2723 Return a list whose CAR is `underline' and CDR is a plist with
2724 `:begin', `:end', `:contents-begin' and `:contents-end' and
2725 `:post-blank' keywords.
2727 Assume point is at the first underscore marker."
2728 (save-excursion
2729 (unless (bolp) (backward-char 1))
2730 (looking-at org-emph-re)
2731 (let ((begin (match-beginning 2))
2732 (contents-begin (match-beginning 4))
2733 (contents-end (match-end 4))
2734 (post-blank (progn (goto-char (match-end 2))
2735 (skip-chars-forward " \t")))
2736 (end (point)))
2737 `(underline
2738 (:begin ,begin
2739 :end ,end
2740 :contents-begin ,contents-begin
2741 :contents-end ,contents-end
2742 :post-blank ,post-blank)))))
2744 (defun org-element-underline-interpreter (underline contents)
2745 "Interpret UNDERLINE object as Org syntax.
2746 CONTENTS is the contents of the object."
2747 (format "_%s_" contents))
2750 ;;;; Verbatim
2752 (defun org-element-verbatim-parser ()
2753 "Parse verbatim object at point.
2755 Return a list whose CAR is `verbatim' and CDR is a plist with
2756 `:value', `:begin', `:end' and `:post-blank' keywords.
2758 Assume point is at the first equal sign marker."
2759 (save-excursion
2760 (unless (bolp) (backward-char 1))
2761 (looking-at org-emph-re)
2762 (let ((begin (match-beginning 2))
2763 (value (org-match-string-no-properties 4))
2764 (post-blank (progn (goto-char (match-end 2))
2765 (skip-chars-forward " \t")))
2766 (end (point)))
2767 `(verbatim
2768 (:value ,value
2769 :begin ,begin
2770 :end ,end
2771 :post-blank ,post-blank)))))
2773 (defun org-element-verbatim-interpreter (verbatim contents)
2774 "Interpret VERBATIM object as Org syntax.
2775 CONTENTS is nil."
2776 (format "=%s=" (org-element-property :value verbatim)))
2780 ;;; Definitions And Rules
2782 ;; Define elements, greater elements and specify recursive objects,
2783 ;; along with the affiliated keywords recognized. Also set up
2784 ;; restrictions on recursive objects combinations.
2786 ;; These variables really act as a control center for the parsing
2787 ;; process.
2788 (defconst org-element-paragraph-separate
2789 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2790 ;; Headlines and inlinetasks.
2791 org-outline-regexp-bol "\\|"
2792 ;; Comments, blocks (any type), keywords and babel calls.
2793 "^[ \t]*#\\+" "\\|" "^#\\(?: \\|$\\)" "\\|"
2794 ;; Lists.
2795 (org-item-beginning-re) "\\|"
2796 ;; Fixed-width, drawers (any type) and tables.
2797 "^[ \t]*[:|]" "\\|"
2798 ;; Footnote definitions.
2799 org-footnote-definition-re "\\|"
2800 ;; Horizontal rules.
2801 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2802 ;; LaTeX environments.
2803 "^[ \t]*\\\\\\(begin\\|end\\)" "\\|"
2804 ;; Planning and Clock lines.
2805 "^[ \t]*\\(?:"
2806 org-clock-string "\\|"
2807 org-closed-string "\\|"
2808 org-deadline-string "\\|"
2809 org-scheduled-string "\\)")
2810 "Regexp to separate paragraphs in an Org buffer.")
2812 (defconst org-element-all-elements
2813 '(center-block clock comment comment-block drawer dynamic-block example-block
2814 export-block fixed-width footnote-definition headline
2815 horizontal-rule inlinetask item keyword latex-environment
2816 babel-call paragraph plain-list planning property-drawer
2817 quote-block quote-section section special-block src-block table
2818 table-row verse-block)
2819 "Complete list of element types.")
2821 (defconst org-element-greater-elements
2822 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2823 item plain-list quote-block section special-block table)
2824 "List of recursive element types aka Greater Elements.")
2826 (defconst org-element-all-successors
2827 '(export-snippet footnote-reference inline-babel-call inline-src-block
2828 latex-or-entity line-break link macro radio-target
2829 statistics-cookie sub/superscript table-cell target
2830 text-markup timestamp)
2831 "Complete list of successors.")
2833 (defconst org-element-object-successor-alist
2834 '((subscript . sub/superscript) (superscript . sub/superscript)
2835 (bold . text-markup) (code . text-markup) (italic . text-markup)
2836 (strike-through . text-markup) (underline . text-markup)
2837 (verbatim . text-markup) (entity . latex-or-entity)
2838 (latex-fragment . latex-or-entity))
2839 "Alist of translations between object type and successor name.
2841 Sharing the same successor comes handy when, for example, the
2842 regexp matching one object can also match the other object.")
2844 (defconst org-element-all-objects
2845 '(bold code entity export-snippet footnote-reference inline-babel-call
2846 inline-src-block italic line-break latex-fragment link macro
2847 radio-target statistics-cookie strike-through subscript superscript
2848 table-cell target timestamp underline verbatim)
2849 "Complete list of object types.")
2851 (defconst org-element-recursive-objects
2852 '(bold italic link macro subscript radio-target strike-through superscript
2853 table-cell underline)
2854 "List of recursive object types.")
2856 (defconst org-element-block-name-alist
2857 '(("ASCII" . org-element-export-block-parser)
2858 ("CENTER" . org-element-center-block-parser)
2859 ("COMMENT" . org-element-comment-block-parser)
2860 ("DOCBOOK" . org-element-export-block-parser)
2861 ("EXAMPLE" . org-element-example-block-parser)
2862 ("HTML" . org-element-export-block-parser)
2863 ("LATEX" . org-element-export-block-parser)
2864 ("ODT" . org-element-export-block-parser)
2865 ("QUOTE" . org-element-quote-block-parser)
2866 ("SRC" . org-element-src-block-parser)
2867 ("VERSE" . org-element-verse-block-parser))
2868 "Alist between block names and the associated parsing function.
2869 Names must be uppercase. Any block whose name has no association
2870 is parsed with `org-element-special-block-parser'.")
2872 (defconst org-element-affiliated-keywords
2873 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "CAPTION"
2874 "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT" "RESULTS"
2875 "SOURCE" "SRCNAME" "TBLNAME")
2876 "List of affiliated keywords as strings.")
2878 (defconst org-element-keyword-translation-alist
2879 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
2880 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
2881 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
2882 "Alist of usual translations for keywords.
2883 The key is the old name and the value the new one. The property
2884 holding their value will be named after the translated name.")
2886 (defconst org-element-multiple-keywords
2887 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "HEADER")
2888 "List of affiliated keywords that can occur more that once in an element.
2890 Their value will be consed into a list of strings, which will be
2891 returned as the value of the property.
2893 This list is checked after translations have been applied. See
2894 `org-element-keyword-translation-alist'.")
2896 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "TITLE")
2897 "List of keywords whose value can be parsed.
2899 Their value will be stored as a secondary string: a list of
2900 strings and objects.
2902 This list is checked after translations have been applied. See
2903 `org-element-keyword-translation-alist'.")
2905 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
2906 "List of keywords which can have a secondary value.
2908 In Org syntax, they can be written with optional square brackets
2909 before the colons. For example, results keyword can be
2910 associated to a hash value with the following:
2912 #+RESULTS[hash-string]: some-source
2914 This list is checked after translations have been applied. See
2915 `org-element-keyword-translation-alist'.")
2917 (defconst org-element-object-restrictions
2918 `((bold entity export-snippet inline-babel-call inline-src-block link
2919 radio-target sub/superscript target text-markup timestamp)
2920 (footnote-reference entity export-snippet footnote-reference
2921 inline-babel-call inline-src-block latex-fragment
2922 line-break link macro radio-target sub/superscript
2923 target text-markup timestamp)
2924 (headline entity inline-babel-call inline-src-block latex-fragment link
2925 macro radio-target statistics-cookie sub/superscript target
2926 text-markup timestamp)
2927 (inlinetask entity inline-babel-call inline-src-block latex-fragment link
2928 macro radio-target sub/superscript target text-markup timestamp)
2929 (italic entity export-snippet inline-babel-call inline-src-block link
2930 radio-target sub/superscript target text-markup timestamp)
2931 (item entity inline-babel-call latex-fragment macro radio-target
2932 sub/superscript target text-markup)
2933 (keyword entity latex-fragment macro sub/superscript text-markup)
2934 (link entity export-snippet inline-babel-call inline-src-block
2935 latex-fragment link sub/superscript text-markup)
2936 (macro macro)
2937 (paragraph ,@org-element-all-successors)
2938 (radio-target entity export-snippet latex-fragment sub/superscript)
2939 (strike-through entity export-snippet inline-babel-call inline-src-block
2940 link radio-target sub/superscript target text-markup
2941 timestamp)
2942 (subscript entity export-snippet inline-babel-call inline-src-block
2943 latex-fragment sub/superscript target text-markup)
2944 (superscript entity export-snippet inline-babel-call inline-src-block
2945 latex-fragment sub/superscript target text-markup)
2946 (table-cell entity export-snippet latex-fragment link macro radio-target
2947 sub/superscript target text-markup timestamp)
2948 (table-row table-cell)
2949 (underline entity export-snippet inline-babel-call inline-src-block link
2950 radio-target sub/superscript target text-markup timestamp)
2951 (verse-block entity footnote-reference inline-babel-call inline-src-block
2952 latex-fragment line-break link macro radio-target
2953 sub/superscript target text-markup timestamp))
2954 "Alist of objects restrictions.
2956 CAR is an element or object type containing objects and CDR is
2957 a list of successors that will be called within an element or
2958 object of such type.
2960 For example, in a `radio-target' object, one can only find
2961 entities, export snippets, latex-fragments, subscript and
2962 superscript.
2964 This alist also applies to secondary string. For example, an
2965 `headline' type element doesn't directly contain objects, but
2966 still has an entry since one of its properties (`:title') does.")
2968 (defconst org-element-secondary-value-alist
2969 '((headline . :title)
2970 (inlinetask . :title)
2971 (item . :tag)
2972 (footnote-reference . :inline-definition))
2973 "Alist between element types and location of secondary value.")
2977 ;;; Accessors
2979 ;; Provide four accessors: `org-element-type', `org-element-property'
2980 ;; `org-element-contents' and `org-element-restriction'.
2982 (defun org-element-type (element)
2983 "Return type of element ELEMENT.
2985 The function returns the type of the element or object provided.
2986 It can also return the following special value:
2987 `plain-text' for a string
2988 `org-data' for a complete document
2989 nil in any other case."
2990 (cond
2991 ((not (consp element)) (and (stringp element) 'plain-text))
2992 ((symbolp (car element)) (car element))))
2994 (defun org-element-property (property element)
2995 "Extract the value from the PROPERTY of an ELEMENT."
2996 (plist-get (nth 1 element) property))
2998 (defun org-element-contents (element)
2999 "Extract contents from an ELEMENT."
3000 (and (consp element) (nthcdr 2 element)))
3002 (defun org-element-restriction (element)
3003 "Return restriction associated to ELEMENT.
3004 ELEMENT can be an element, an object or a symbol representing an
3005 element or object type."
3006 (cdr (assq (if (symbolp element) element (org-element-type element))
3007 org-element-object-restrictions)))
3011 ;;; Parsing Element Starting At Point
3013 ;; `org-element-current-element' is the core function of this section.
3014 ;; It returns the Lisp representation of the element starting at
3015 ;; point.
3017 ;; `org-element-current-element' makes use of special modes. They are
3018 ;; activated for fixed element chaining (i.e. `plain-list' > `item')
3019 ;; or fixed conditional element chaining (i.e. `headline' >
3020 ;; `section'). Special modes are: `section', `quote-section', `item'
3021 ;; and `table-row'.
3023 (defun org-element-current-element (&optional granularity special structure)
3024 "Parse the element starting at point.
3026 Return value is a list like (TYPE PROPS) where TYPE is the type
3027 of the element and PROPS a plist of properties associated to the
3028 element.
3030 Possible types are defined in `org-element-all-elements'.
3032 Optional argument GRANULARITY determines the depth of the
3033 recursion. Allowed values are `headline', `greater-element',
3034 `element', `object' or nil. When it is broader than `object' (or
3035 nil), secondary values will not be parsed, since they only
3036 contain objects.
3038 Optional argument SPECIAL, when non-nil, can be either `section',
3039 `quote-section', `table-row' and `item'.
3041 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3042 be computed.
3044 This function assumes point is always at the beginning of the
3045 element it has to parse."
3046 (save-excursion
3047 ;; If point is at an affiliated keyword, try moving to the
3048 ;; beginning of the associated element. If none is found, the
3049 ;; keyword is orphaned and will be treated as plain text.
3050 (when (looking-at org-element--affiliated-re)
3051 (let ((opoint (point)))
3052 (while (looking-at org-element--affiliated-re) (forward-line))
3053 (when (looking-at "[ \t]*$") (goto-char opoint))))
3054 (let ((case-fold-search t)
3055 ;; Determine if parsing depth allows for secondary strings
3056 ;; parsing. It only applies to elements referenced in
3057 ;; `org-element-secondary-value-alist'.
3058 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3059 (cond
3060 ;; Item.
3061 ((eq special 'item)
3062 (org-element-item-parser (or structure (org-list-struct))
3063 raw-secondary-p))
3064 ;; Quote Section.
3065 ((eq special 'quote-section) (org-element-quote-section-parser))
3066 ;; Table Row.
3067 ((eq special 'table-row) (org-element-table-row-parser))
3068 ;; Headline.
3069 ((org-with-limited-levels (org-at-heading-p))
3070 (org-element-headline-parser raw-secondary-p))
3071 ;; Section (must be checked after headline).
3072 ((eq special 'section) (org-element-section-parser))
3073 ;; Planning and Clock.
3074 ((and (looking-at org-planning-or-clock-line-re))
3075 (if (equal (match-string 1) org-clock-string)
3076 (org-element-clock-parser)
3077 (org-element-planning-parser)))
3078 ;; Blocks.
3079 ((when (looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
3080 (let ((name (upcase (match-string 1))) parser)
3081 (cond
3082 ((not (save-excursion
3083 (re-search-forward
3084 (format "^[ \t]*#\\+END_%s\\(?: \\|$\\)" name) nil t)))
3085 (org-element-paragraph-parser))
3086 ((setq parser (assoc name org-element-block-name-alist))
3087 (funcall (cdr parser)))
3088 (t (org-element-special-block-parser))))))
3089 ;; Inlinetask.
3090 ((org-at-heading-p) (org-element-inlinetask-parser raw-secondary-p))
3091 ;; LaTeX Environment.
3092 ((looking-at "[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}")
3093 (if (save-excursion
3094 (re-search-forward
3095 (format "[ \t]*\\\\end{%s}[ \t]*"
3096 (regexp-quote (match-string 1)))
3097 nil t))
3098 (org-element-latex-environment-parser)
3099 (org-element-paragraph-parser)))
3100 ;; Drawer and Property Drawer.
3101 ((looking-at org-drawer-regexp)
3102 (let ((name (match-string 1)))
3103 (cond
3104 ((not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t)))
3105 (org-element-paragraph-parser))
3106 ((equal "PROPERTIES" name) (org-element-property-drawer-parser))
3107 (t (org-element-drawer-parser)))))
3108 ;; Fixed Width
3109 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
3110 ;; Babel Call, Dynamic Block and Keyword.
3111 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
3112 (let ((key (upcase (match-string 1))))
3113 (cond
3114 ((equal key "CALL") (org-element-babel-call-parser))
3115 ((and (equal key "BEGIN")
3116 (save-excursion
3117 (re-search-forward "^[ \t]*#\\+END:\\(?: \\|$\\)" nil t)))
3118 (org-element-dynamic-block-parser))
3119 ((and (not (equal key "TBLFM"))
3120 (not (member key org-element-affiliated-keywords)))
3121 (org-element-keyword-parser))
3122 (t (org-element-paragraph-parser)))))
3123 ;; Footnote Definition.
3124 ((looking-at org-footnote-definition-re)
3125 (org-element-footnote-definition-parser))
3126 ;; Comment.
3127 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
3128 (org-element-comment-parser))
3129 ;; Horizontal Rule.
3130 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3131 (org-element-horizontal-rule-parser))
3132 ;; Table.
3133 ((org-at-table-p t) (org-element-table-parser))
3134 ;; List.
3135 ((looking-at (org-item-re))
3136 (org-element-plain-list-parser (or structure (org-list-struct))))
3137 ;; Default element: Paragraph.
3138 (t (org-element-paragraph-parser))))))
3141 ;; Most elements can have affiliated keywords. When looking for an
3142 ;; element beginning, we want to move before them, as they belong to
3143 ;; that element, and, in the meantime, collect information they give
3144 ;; into appropriate properties. Hence the following function.
3146 ;; Usage of optional arguments may not be obvious at first glance:
3148 ;; - TRANS-LIST is used to polish keywords names that have evolved
3149 ;; during Org history. In example, even though =result= and
3150 ;; =results= coexist, we want to have them under the same =result=
3151 ;; property. It's also true for "srcname" and "name", where the
3152 ;; latter seems to be preferred nowadays (thus the "name" property).
3154 ;; - CONSED allows to regroup multi-lines keywords under the same
3155 ;; property, while preserving their own identity. This is mostly
3156 ;; used for "attr_latex" and al.
3158 ;; - PARSED prepares a keyword value for export. This is useful for
3159 ;; "caption". Objects restrictions for such keywords are defined in
3160 ;; `org-element-object-restrictions'.
3162 ;; - DUALS is used to take care of keywords accepting a main and an
3163 ;; optional secondary values. For example "results" has its
3164 ;; source's name as the main value, and may have an hash string in
3165 ;; optional square brackets as the secondary one.
3167 ;; A keyword may belong to more than one category.
3169 (defconst org-element--affiliated-re
3170 (format "[ \t]*#\\+\\(%s\\):"
3171 (mapconcat
3172 (lambda (keyword)
3173 (if (member keyword org-element-dual-keywords)
3174 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
3175 (regexp-quote keyword))
3176 (regexp-quote keyword)))
3177 org-element-affiliated-keywords "\\|"))
3178 "Regexp matching any affiliated keyword.
3180 Keyword name is put in match group 1. Moreover, if keyword
3181 belongs to `org-element-dual-keywords', put the dual value in
3182 match group 2.
3184 Don't modify it, set `org-element-affiliated-keywords' instead.")
3186 (defun org-element-collect-affiliated-keywords
3187 (&optional key-re trans-list consed parsed duals)
3188 "Collect affiliated keywords before point.
3190 Optional argument KEY-RE is a regexp matching keywords, which
3191 puts matched keyword in group 1. It defaults to
3192 `org-element--affiliated-re'.
3194 TRANS-LIST is an alist where key is the keyword and value the
3195 property name it should be translated to, without the colons. It
3196 defaults to `org-element-keyword-translation-alist'.
3198 CONSED is a list of strings. Any keyword belonging to that list
3199 will have its value consed. The check is done after keyword
3200 translation. It defaults to `org-element-multiple-keywords'.
3202 PARSED is a list of strings. Any keyword member of this list
3203 will have its value parsed. The check is done after keyword
3204 translation. If a keyword is a member of both CONSED and PARSED,
3205 it's value will be a list of parsed strings. It defaults to
3206 `org-element-parsed-keywords'.
3208 DUALS is a list of strings. Any keyword member of this list can
3209 have two parts: one mandatory and one optional. Its value is
3210 a cons cell whose CAR is the former, and the CDR the latter. If
3211 a keyword is a member of both PARSED and DUALS, both values will
3212 be parsed. It defaults to `org-element-dual-keywords'.
3214 Return a list whose CAR is the position at the first of them and
3215 CDR a plist of keywords and values."
3216 (save-excursion
3217 (let ((case-fold-search t)
3218 (key-re (or key-re org-element--affiliated-re))
3219 (trans-list (or trans-list org-element-keyword-translation-alist))
3220 (consed (or consed org-element-multiple-keywords))
3221 (parsed (or parsed org-element-parsed-keywords))
3222 (duals (or duals org-element-dual-keywords))
3223 ;; RESTRICT is the list of objects allowed in parsed
3224 ;; keywords value.
3225 (restrict (org-element-restriction 'keyword))
3226 output)
3227 (unless (bobp)
3228 (while (and (not (bobp))
3229 (progn (forward-line -1) (looking-at key-re)))
3230 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3231 ;; Apply translation to RAW-KWD. From there, KWD is
3232 ;; the official keyword.
3233 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3234 ;; Find main value for any keyword.
3235 (value
3236 (save-match-data
3237 (org-trim
3238 (buffer-substring-no-properties
3239 (match-end 0) (point-at-eol)))))
3240 ;; If KWD is a dual keyword, find its secondary
3241 ;; value. Maybe parse it.
3242 (dual-value
3243 (and (member kwd duals)
3244 (let ((sec (org-match-string-no-properties 3)))
3245 (if (or (not sec) (not (member kwd parsed))) sec
3246 (org-element-parse-secondary-string sec restrict)))))
3247 ;; Attribute a property name to KWD.
3248 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3249 ;; Now set final shape for VALUE.
3250 (when (member kwd parsed)
3251 (setq value (org-element-parse-secondary-string value restrict)))
3252 (when (member kwd duals)
3253 ;; VALUE is mandatory. Set it to nil if there is none.
3254 (setq value (and value (cons value dual-value))))
3255 (when (member kwd consed)
3256 (setq value (cons value (plist-get output kwd-sym))))
3257 ;; Eventually store the new value in OUTPUT.
3258 (setq output (plist-put output kwd-sym value))))
3259 (unless (looking-at key-re) (forward-line 1)))
3260 (list (point) output))))
3264 ;;; The Org Parser
3266 ;; The two major functions here are `org-element-parse-buffer', which
3267 ;; parses Org syntax inside the current buffer, taking into account
3268 ;; region, narrowing, or even visibility if specified, and
3269 ;; `org-element-parse-secondary-string', which parses objects within
3270 ;; a given string.
3272 ;; The (almost) almighty `org-element-map' allows to apply a function
3273 ;; on elements or objects matching some type, and accumulate the
3274 ;; resulting values. In an export situation, it also skips unneeded
3275 ;; parts of the parse tree.
3277 (defun org-element-parse-buffer (&optional granularity visible-only)
3278 "Recursively parse the buffer and return structure.
3279 If narrowing is in effect, only parse the visible part of the
3280 buffer.
3282 Optional argument GRANULARITY determines the depth of the
3283 recursion. It can be set to the following symbols:
3285 `headline' Only parse headlines.
3286 `greater-element' Don't recurse into greater elements excepted
3287 headlines and sections. Thus, elements
3288 parsed are the top-level ones.
3289 `element' Parse everything but objects and plain text.
3290 `object' Parse the complete buffer (default).
3292 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3293 elements.
3295 Assume buffer is in Org mode."
3296 (save-excursion
3297 (goto-char (point-min))
3298 (org-skip-whitespace)
3299 (org-element-parse-elements
3300 (point-at-bol) (point-max)
3301 ;; Start in `section' mode so text before the first
3302 ;; headline belongs to a section.
3303 'section nil granularity visible-only (list 'org-data nil))))
3305 (defun org-element-parse-secondary-string (string restriction)
3306 "Recursively parse objects in STRING and return structure.
3308 RESTRICTION, when non-nil, is a symbol limiting the object types
3309 that will be looked after."
3310 (with-temp-buffer
3311 (insert string)
3312 (org-element-parse-objects (point-min) (point-max) nil restriction)))
3314 (defun org-element-map (data types fun &optional info first-match no-recursion)
3315 "Map a function on selected elements or objects.
3317 DATA is the parsed tree, as returned by, i.e,
3318 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3319 of elements or objects types. FUN is the function called on the
3320 matching element or object. It must accept one arguments: the
3321 element or object itself.
3323 When optional argument INFO is non-nil, it should be a plist
3324 holding export options. In that case, parts of the parse tree
3325 not exportable according to that property list will be skipped.
3327 When optional argument FIRST-MATCH is non-nil, stop at the first
3328 match for which FUN doesn't return nil, and return that value.
3330 Optional argument NO-RECURSION is a symbol or a list of symbols
3331 representing elements or objects types. `org-element-map' won't
3332 enter any recursive element or object whose type belongs to that
3333 list. Though, FUN can still be applied on them.
3335 Nil values returned from FUN do not appear in the results."
3336 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3337 (unless (listp types) (setq types (list types)))
3338 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3339 ;; Recursion depth is determined by --CATEGORY.
3340 (let* ((--category
3341 (cond
3342 ((every (lambda (el) (memq el org-element-greater-elements)) types)
3343 'greater-elements)
3344 ((every (lambda (el) (memq el org-element-all-elements)) types)
3345 'elements)
3346 (t 'objects)))
3347 --acc
3348 --walk-tree
3349 (--walk-tree
3350 (function
3351 (lambda (--data)
3352 ;; Recursively walk DATA. INFO, if non-nil, is a plist
3353 ;; holding contextual information.
3354 (let ((--type (org-element-type --data)))
3355 (cond
3356 ((not --data))
3357 ;; Ignored element in an export context.
3358 ((and info (member --data (plist-get info :ignore-list))))
3359 ;; Secondary string: only objects can be found there.
3360 ((not --type)
3361 (when (eq --category 'objects) (mapc --walk-tree --data)))
3362 ;; Unconditionally enter parse trees.
3363 ((eq --type 'org-data)
3364 (mapc --walk-tree (org-element-contents --data)))
3366 ;; Check if TYPE is matching among TYPES. If so,
3367 ;; apply FUN to --DATA and accumulate return value
3368 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3369 (when (memq --type types)
3370 (let ((result (funcall fun --data)))
3371 (cond ((not result))
3372 (first-match (throw 'first-match result))
3373 (t (push result --acc)))))
3374 ;; If --DATA has a secondary string that can contain
3375 ;; objects with their type among TYPES, look into it.
3376 (when (eq --category 'objects)
3377 (let ((sec-prop
3378 (assq --type org-element-secondary-value-alist)))
3379 (when sec-prop
3380 (funcall --walk-tree
3381 (org-element-property (cdr sec-prop) --data)))))
3382 ;; Determine if a recursion into --DATA is possible.
3383 (cond
3384 ;; --TYPE is explicitly removed from recursion.
3385 ((memq --type no-recursion))
3386 ;; --DATA has no contents.
3387 ((not (org-element-contents --data)))
3388 ;; Looking for greater elements but --DATA is simply
3389 ;; an element or an object.
3390 ((and (eq --category 'greater-elements)
3391 (not (memq --type org-element-greater-elements))))
3392 ;; Looking for elements but --DATA is an object.
3393 ((and (eq --category 'elements)
3394 (memq --type org-element-all-objects)))
3395 ;; In any other case, map contents.
3396 (t (mapc --walk-tree (org-element-contents --data)))))))))))
3397 (catch 'first-match
3398 (funcall --walk-tree data)
3399 ;; Return value in a proper order.
3400 (nreverse --acc))))
3402 ;; The following functions are internal parts of the parser.
3404 ;; The first one, `org-element-parse-elements' acts at the element's
3405 ;; level.
3407 ;; The second one, `org-element-parse-objects' applies on all objects
3408 ;; of a paragraph or a secondary string. It uses
3409 ;; `org-element-get-candidates' to optimize the search of the next
3410 ;; object in the buffer.
3412 ;; More precisely, that function looks for every allowed object type
3413 ;; first. Then, it discards failed searches, keeps further matches,
3414 ;; and searches again types matched behind point, for subsequent
3415 ;; calls. Thus, searching for a given type fails only once, and every
3416 ;; object is searched only once at top level (but sometimes more for
3417 ;; nested types).
3419 (defun org-element-parse-elements
3420 (beg end special structure granularity visible-only acc)
3421 "Parse elements between BEG and END positions.
3423 SPECIAL prioritize some elements over the others. It can be set
3424 to `quote-section', `section' `item' or `table-row'.
3426 When value is `item', STRUCTURE will be used as the current list
3427 structure.
3429 GRANULARITY determines the depth of the recursion. See
3430 `org-element-parse-buffer' for more information.
3432 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3433 elements.
3435 Elements are accumulated into ACC."
3436 (save-excursion
3437 (save-restriction
3438 (narrow-to-region beg end)
3439 (goto-char beg)
3440 ;; When parsing only headlines, skip any text before first one.
3441 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3442 (org-with-limited-levels (outline-next-heading)))
3443 ;; Main loop start.
3444 (while (not (eobp))
3445 ;; Find current element's type and parse it accordingly to
3446 ;; its category.
3447 (let* ((element (org-element-current-element
3448 granularity special structure))
3449 (type (org-element-type element))
3450 (cbeg (org-element-property :contents-begin element)))
3451 ;; Set ACC as parent of current element. It will be
3452 ;; completed by side-effect. If the element contains any
3453 ;; secondary string, also set `:parent' property of every
3454 ;; object within it as current element.
3455 (plist-put (nth 1 element) :parent acc)
3456 (let ((sec-loc (assq type org-element-secondary-value-alist)))
3457 (when sec-loc
3458 (let ((sec-value (org-element-property (cdr sec-loc) element)))
3459 (unless (stringp sec-value)
3460 (mapc (lambda (obj)
3461 (unless (stringp obj)
3462 (plist-put (nth 1 obj) :parent element)))
3463 sec-value)))))
3464 (goto-char (org-element-property :end element))
3465 (nconc
3467 (list
3468 (cond
3469 ;; Case 1. Simply accumulate element if VISIBLE-ONLY is
3470 ;; true and element is hidden or if it has no contents
3471 ;; anyway.
3472 ((or (and visible-only (org-element-property :hiddenp element))
3473 (not cbeg)) element)
3474 ;; Case 2. Greater element: parse it between
3475 ;; `contents-begin' and `contents-end'. Make sure
3476 ;; GRANULARITY allows the recursion, or ELEMENT is an
3477 ;; headline, in which case going inside is mandatory, in
3478 ;; order to get sub-level headings.
3479 ((and (memq type org-element-greater-elements)
3480 (or (memq granularity '(element object nil))
3481 (and (eq granularity 'greater-element)
3482 (eq type 'section))
3483 (eq type 'headline)))
3484 (org-element-parse-elements
3485 cbeg (org-element-property :contents-end element)
3486 ;; Possibly switch to a special mode.
3487 (case type
3488 (headline
3489 (if (org-element-property :quotedp element) 'quote-section
3490 'section))
3491 (plain-list 'item)
3492 (table 'table-row))
3493 (org-element-property :structure element)
3494 granularity visible-only element))
3495 ;; Case 3. ELEMENT has contents. Parse objects inside,
3496 ;; if GRANULARITY allows it.
3497 ((and cbeg (memq granularity '(object nil)))
3498 (org-element-parse-objects
3499 cbeg (org-element-property :contents-end element)
3500 element (org-element-restriction type)))
3501 ;; Case 4. Else, just accumulate ELEMENT.
3502 (t element)))))))
3503 ;; Return result.
3504 acc))
3506 (defun org-element-parse-objects (beg end acc restriction)
3507 "Parse objects between BEG and END and return recursive structure.
3509 Objects are accumulated in ACC.
3511 RESTRICTION is a list of object types which are allowed in the
3512 current object."
3513 (let ((get-next-object
3514 (function
3515 (lambda (cand)
3516 ;; Return the parsing function associated to the nearest
3517 ;; object among list of candidates CAND.
3518 (let ((pos (apply 'min (mapcar 'cdr cand))))
3519 (save-excursion
3520 (goto-char pos)
3521 (funcall
3522 (intern
3523 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3524 next-object candidates)
3525 (save-excursion
3526 (goto-char beg)
3527 (while (setq candidates (org-element-get-next-object-candidates
3528 end restriction candidates))
3529 (setq next-object (funcall get-next-object candidates))
3530 ;; Set ACC as parent of current element. It will be completed
3531 ;; by side-effect.
3532 (plist-put (nth 1 next-object) :parent acc)
3533 ;; 1. Text before any object. Untabify it.
3534 (let ((obj-beg (org-element-property :begin next-object)))
3535 (unless (= (point) obj-beg)
3536 (let ((beg-text
3537 (list
3538 (replace-regexp-in-string
3539 "\t" (make-string tab-width ? )
3540 (buffer-substring-no-properties (point) obj-beg)))))
3541 (if acc (nconc acc beg-text) (setq acc beg-text)))))
3542 ;; 2. Object...
3543 (let* ((obj-end (org-element-property :end next-object))
3544 (cont-beg (org-element-property :contents-begin next-object))
3545 (complete-next-object
3546 (if (and (memq (car next-object) org-element-recursive-objects)
3547 cont-beg)
3548 ;; ... recursive. The CONT-BEG check is for
3549 ;; links, as some of them might not be recursive
3550 ;; (i.e. plain links).
3551 (save-restriction
3552 (narrow-to-region
3553 cont-beg
3554 (org-element-property :contents-end next-object))
3555 (org-element-parse-objects
3556 (point-min) (point-max) next-object
3557 ;; Restrict allowed objects.
3558 (org-element-restriction next-object)))
3559 next-object)))
3560 (if acc (nconc acc (list complete-next-object))
3561 (setq acc (list complete-next-object)))
3562 ;; If the object contains any secondary string, also set
3563 ;; `:parent' property of every object within it as current
3564 ;; object.
3565 (let ((sec-loc (assq (org-element-type next-object)
3566 org-element-secondary-value-alist)))
3567 (when sec-loc
3568 (let ((sec-value
3569 (org-element-property (cdr sec-loc) next-object)))
3570 (unless (stringp sec-value)
3571 (mapc (lambda (obj)
3572 (unless (stringp obj)
3573 (plist-put (nth 1 obj)
3574 :parent
3575 complete-next-object)))
3576 sec-value)))))
3577 (goto-char obj-end)))
3578 ;; 3. Text after last object. Untabify it.
3579 (unless (= (point) end)
3580 (let ((end-text
3581 (list
3582 (replace-regexp-in-string
3583 "\t" (make-string tab-width ? )
3584 (buffer-substring-no-properties (point) end)))))
3585 (if acc (nconc acc end-text) (setq acc end-text))))
3586 ;; Result.
3587 acc)))
3589 (defun org-element-get-next-object-candidates (limit restriction objects)
3590 "Return an alist of candidates for the next object.
3592 LIMIT bounds the search, and RESTRICTION narrows candidates to
3593 some object types.
3595 Return value is an alist whose CAR is position and CDR the object
3596 type, as a symbol.
3598 OBJECTS is the previous candidates alist."
3599 (let (next-candidates types-to-search)
3600 ;; If no previous result, search every object type in RESTRICTION.
3601 ;; Otherwise, keep potential candidates (old objects located after
3602 ;; point) and ask to search again those which had matched before.
3603 (if (not objects) (setq types-to-search restriction)
3604 (mapc (lambda (obj)
3605 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3606 (push obj next-candidates)))
3607 objects))
3608 ;; Call the appropriate successor function for each type to search
3609 ;; and accumulate matches.
3610 (mapc
3611 (lambda (type)
3612 (let* ((successor-fun
3613 (intern
3614 (format "org-element-%s-successor"
3615 (or (cdr (assq type org-element-object-successor-alist))
3616 type))))
3617 (obj (funcall successor-fun limit)))
3618 (and obj (push obj next-candidates))))
3619 types-to-search)
3620 ;; Return alist.
3621 next-candidates))
3625 ;;; Towards A Bijective Process
3627 ;; The parse tree obtained with `org-element-parse-buffer' is really
3628 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3629 ;; interpreted and expanded into a string with canonical Org syntax.
3630 ;; Hence `org-element-interpret-data'.
3632 ;; The function relies internally on
3633 ;; `org-element-interpret--affiliated-keywords'.
3635 (defun org-element-interpret-data (data &optional parent)
3636 "Interpret DATA as Org syntax.
3638 DATA is a parse tree, an element, an object or a secondary string
3639 to interpret.
3641 Optional argument PARENT is used for recursive calls. It contains
3642 the element or object containing data, or nil.
3644 Return Org syntax as a string."
3645 (let* ((type (org-element-type data))
3646 (results
3647 (cond
3648 ;; Secondary string.
3649 ((not type)
3650 (mapconcat
3651 (lambda (obj) (org-element-interpret-data obj parent))
3652 data ""))
3653 ;; Full Org document.
3654 ((eq type 'org-data)
3655 (mapconcat
3656 (lambda (obj) (org-element-interpret-data obj parent))
3657 (org-element-contents data) ""))
3658 ;; Plain text.
3659 ((stringp data) data)
3660 ;; Element/Object without contents.
3661 ((not (org-element-contents data))
3662 (funcall (intern (format "org-element-%s-interpreter" type))
3663 data nil))
3664 ;; Element/Object with contents.
3666 (let* ((greaterp (memq type org-element-greater-elements))
3667 (objectp (and (not greaterp)
3668 (memq type org-element-recursive-objects)))
3669 (contents
3670 (mapconcat
3671 (lambda (obj) (org-element-interpret-data obj data))
3672 (org-element-contents
3673 (if (or greaterp objectp) data
3674 ;; Elements directly containing objects must
3675 ;; have their indentation normalized first.
3676 (org-element-normalize-contents
3677 data
3678 ;; When normalizing first paragraph of an
3679 ;; item or a footnote-definition, ignore
3680 ;; first line's indentation.
3681 (and (eq type 'paragraph)
3682 (equal data (car (org-element-contents parent)))
3683 (memq (org-element-type parent)
3684 '(footnote-definiton item))))))
3685 "")))
3686 (funcall (intern (format "org-element-%s-interpreter" type))
3687 data
3688 (if greaterp (org-element-normalize-contents contents)
3689 contents)))))))
3690 (if (memq type '(org-data plain-text nil)) results
3691 ;; Build white spaces. If no `:post-blank' property is
3692 ;; specified, assume its value is 0.
3693 (let ((post-blank (or (org-element-property :post-blank data) 0)))
3694 (if (memq type org-element-all-objects)
3695 (concat results (make-string post-blank 32))
3696 (concat
3697 (org-element-interpret--affiliated-keywords data)
3698 (org-element-normalize-string results)
3699 (make-string post-blank 10)))))))
3701 (defun org-element-interpret--affiliated-keywords (element)
3702 "Return ELEMENT's affiliated keywords as Org syntax.
3703 If there is no affiliated keyword, return the empty string."
3704 (let ((keyword-to-org
3705 (function
3706 (lambda (key value)
3707 (let (dual)
3708 (when (member key org-element-dual-keywords)
3709 (setq dual (cdr value) value (car value)))
3710 (concat "#+" key
3711 (and dual
3712 (format "[%s]" (org-element-interpret-data dual)))
3713 ": "
3714 (if (member key org-element-parsed-keywords)
3715 (org-element-interpret-data value)
3716 value)
3717 "\n"))))))
3718 (mapconcat
3719 (lambda (key)
3720 (let ((value (org-element-property (intern (concat ":" (downcase key)))
3721 element)))
3722 (when value
3723 (if (member key org-element-multiple-keywords)
3724 (mapconcat (lambda (line)
3725 (funcall keyword-to-org key line))
3726 value "")
3727 (funcall keyword-to-org key value)))))
3728 ;; Remove translated keywords.
3729 (delq nil
3730 (mapcar
3731 (lambda (key)
3732 (and (not (assoc key org-element-keyword-translation-alist)) key))
3733 org-element-affiliated-keywords))
3734 "")))
3736 ;; Because interpretation of the parse tree must return the same
3737 ;; number of blank lines between elements and the same number of white
3738 ;; space after objects, some special care must be given to white
3739 ;; spaces.
3741 ;; The first function, `org-element-normalize-string', ensures any
3742 ;; string different from the empty string will end with a single
3743 ;; newline character.
3745 ;; The second function, `org-element-normalize-contents', removes
3746 ;; global indentation from the contents of the current element.
3748 (defun org-element-normalize-string (s)
3749 "Ensure string S ends with a single newline character.
3751 If S isn't a string return it unchanged. If S is the empty
3752 string, return it. Otherwise, return a new string with a single
3753 newline character at its end."
3754 (cond
3755 ((not (stringp s)) s)
3756 ((string= "" s) "")
3757 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3758 (replace-match "\n" nil nil s)))))
3760 (defun org-element-normalize-contents (element &optional ignore-first)
3761 "Normalize plain text in ELEMENT's contents.
3763 ELEMENT must only contain plain text and objects.
3765 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3766 indentation to compute maximal common indentation.
3768 Return the normalized element that is element with global
3769 indentation removed from its contents. The function assumes that
3770 indentation is not done with TAB characters."
3771 (let* (ind-list ; for byte-compiler
3772 collect-inds ; for byte-compiler
3773 (collect-inds
3774 (function
3775 ;; Return list of indentations within BLOB. This is done by
3776 ;; walking recursively BLOB and updating IND-LIST along the
3777 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3778 ;; been seen yet. It is required as this string is the only
3779 ;; one whose indentation doesn't happen after a newline
3780 ;; character.
3781 (lambda (blob first-flag)
3782 (mapc
3783 (lambda (object)
3784 (when (and first-flag (stringp object))
3785 (setq first-flag nil)
3786 (string-match "\\`\\( *\\)" object)
3787 (let ((len (length (match-string 1 object))))
3788 ;; An indentation of zero means no string will be
3789 ;; modified. Quit the process.
3790 (if (zerop len) (throw 'zero (setq ind-list nil))
3791 (push len ind-list))))
3792 (cond
3793 ((stringp object)
3794 (let ((start 0))
3795 ;; Avoid matching blank or empty lines.
3796 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
3797 (not (equal (match-string 2 object) " ")))
3798 (setq start (match-end 0))
3799 (push (length (match-string 1 object)) ind-list))))
3800 ((memq (org-element-type object) org-element-recursive-objects)
3801 (funcall collect-inds object first-flag))))
3802 (org-element-contents blob))))))
3803 ;; Collect indentation list in ELEMENT. Possibly remove first
3804 ;; value if IGNORE-FIRST is non-nil.
3805 (catch 'zero (funcall collect-inds element (not ignore-first)))
3806 (if (not ind-list) element
3807 ;; Build ELEMENT back, replacing each string with the same
3808 ;; string minus common indentation.
3809 (let* (build ; for byte compiler
3810 (build
3811 (function
3812 (lambda (blob mci first-flag)
3813 ;; Return BLOB with all its strings indentation
3814 ;; shortened from MCI white spaces. FIRST-FLAG is
3815 ;; non-nil when the first string hasn't been seen
3816 ;; yet.
3817 (nconc
3818 (list (org-element-type blob) (nth 1 blob))
3819 (mapcar
3820 (lambda (object)
3821 (when (and first-flag (stringp object))
3822 (setq first-flag nil)
3823 (setq object
3824 (replace-regexp-in-string
3825 (format "\\` \\{%d\\}" mci) "" object)))
3826 (cond
3827 ((stringp object)
3828 (replace-regexp-in-string
3829 (format "\n \\{%d\\}" mci) "\n" object))
3830 ((memq (org-element-type object)
3831 org-element-recursive-objects)
3832 (funcall build object mci first-flag))
3833 (t object)))
3834 (org-element-contents blob)))))))
3835 (funcall build element (apply 'min ind-list) (not ignore-first))))))
3839 ;;; The Toolbox
3841 ;; The first move is to implement a way to obtain the smallest element
3842 ;; containing point. This is the job of `org-element-at-point'. It
3843 ;; basically jumps back to the beginning of section containing point
3844 ;; and moves, element after element, with
3845 ;; `org-element-current-element' until the container is found.
3847 ;; Note: When using `org-element-at-point', secondary values are never
3848 ;; parsed since the function focuses on elements, not on objects.
3850 (defun org-element-at-point (&optional keep-trail)
3851 "Determine closest element around point.
3853 Return value is a list like (TYPE PROPS) where TYPE is the type
3854 of the element and PROPS a plist of properties associated to the
3855 element. Possible types are defined in
3856 `org-element-all-elements'.
3858 As a special case, if point is at the very beginning of a list or
3859 sub-list, returned element will be that list instead of the first
3860 item. In the same way, if point is at the beginning of the first
3861 row of a table, returned element will be the table instead of the
3862 first row.
3864 If optional argument KEEP-TRAIL is non-nil, the function returns
3865 a list of of elements leading to element at point. The list's
3866 CAR is always the element at point. Following positions contain
3867 element's siblings, then parents, siblings of parents, until the
3868 first element of current section."
3869 (org-with-wide-buffer
3870 ;; If at an headline, parse it. It is the sole element that
3871 ;; doesn't require to know about context. Be sure to disallow
3872 ;; secondary string parsing, though.
3873 (if (org-with-limited-levels (org-at-heading-p))
3874 (progn
3875 (beginning-of-line)
3876 (if (not keep-trail) (org-element-headline-parser t)
3877 (list (org-element-headline-parser t))))
3878 ;; Otherwise move at the beginning of the section containing
3879 ;; point.
3880 (let ((origin (point)) element type special-flag trail struct prevs)
3881 (org-with-limited-levels
3882 (if (org-before-first-heading-p) (goto-char (point-min))
3883 (org-back-to-heading)
3884 (forward-line)))
3885 (org-skip-whitespace)
3886 (beginning-of-line)
3887 ;; Parse successively each element, skipping those ending
3888 ;; before original position.
3889 (catch 'exit
3890 (while t
3891 (setq element (org-element-current-element
3892 'element special-flag struct)
3893 type (car element))
3894 (push element trail)
3895 (cond
3896 ;; 1. Skip any element ending before point or at point.
3897 ((let ((end (org-element-property :end element)))
3898 (when (<= end origin)
3899 (if (> (point-max) end) (goto-char end)
3900 (throw 'exit (if keep-trail trail element))))))
3901 ;; 2. An element containing point is always the element at
3902 ;; point.
3903 ((not (memq type org-element-greater-elements))
3904 (throw 'exit (if keep-trail trail element)))
3905 ;; 3. At any other greater element type, if point is
3906 ;; within contents, move into it. Otherwise, return
3907 ;; that element.
3909 (let ((beg (org-element-property :contents-begin element))
3910 (end (org-element-property :contents-end element)))
3911 (if (or (not beg) (not end) (> beg origin) (<= end origin)
3912 (and (= beg origin) (memq type '(plain-list table))))
3913 (throw 'exit (if keep-trail trail element))
3914 (case type
3915 (plain-list
3916 (setq special-flag 'item
3917 struct (org-element-property :structure element)))
3918 (table (setq special-flag 'table-row))
3919 (otherwise (setq special-flag nil)))
3920 (narrow-to-region beg end)
3921 (goto-char beg)))))))))))
3924 ;; Once the local structure around point is well understood, it's easy
3925 ;; to implement some replacements for `forward-paragraph'
3926 ;; `backward-paragraph', namely `org-element-forward' and
3927 ;; `org-element-backward'.
3929 ;; Also, `org-transpose-elements' mimics the behaviour of
3930 ;; `transpose-words', at the element's level, whereas
3931 ;; `org-element-drag-forward', `org-element-drag-backward', and
3932 ;; `org-element-up' generalize, respectively, functions
3933 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3935 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3936 ;; smartly remove global indentation from buffer, making it possible
3937 ;; to use Org indent mode on a file created with hard indentation.
3939 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3940 ;; internally by some of the previously cited tools.
3942 (defsubst org-element-nested-p (elem-A elem-B)
3943 "Non-nil when elements ELEM-A and ELEM-B are nested."
3944 (let ((beg-A (org-element-property :begin elem-A))
3945 (beg-B (org-element-property :begin elem-B))
3946 (end-A (org-element-property :end elem-A))
3947 (end-B (org-element-property :end elem-B)))
3948 (or (and (>= beg-A beg-B) (<= end-A end-B))
3949 (and (>= beg-B beg-A) (<= end-B end-A)))))
3951 (defun org-element-swap-A-B (elem-A elem-B)
3952 "Swap elements ELEM-A and ELEM-B.
3953 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
3954 end of ELEM-A."
3955 (goto-char (org-element-property :begin elem-A))
3956 ;; There are two special cases when an element doesn't start at bol:
3957 ;; the first paragraph in an item or in a footnote definition.
3958 (let ((specialp (not (bolp))))
3959 ;; Only a paragraph without any affiliated keyword can be moved at
3960 ;; ELEM-A position in such a situation. Note that the case of
3961 ;; a footnote definition is impossible: it cannot contain two
3962 ;; paragraphs in a row because it cannot contain a blank line.
3963 (if (and specialp
3964 (or (not (eq (org-element-type elem-B) 'paragraph))
3965 (/= (org-element-property :begin elem-B)
3966 (org-element-property :contents-begin elem-B))))
3967 (error "Cannot swap elements"))
3968 ;; In a special situation, ELEM-A will have no indentation. We'll
3969 ;; give it ELEM-B's (which will in, in turn, have no indentation).
3970 (let* ((ind-B (when specialp
3971 (goto-char (org-element-property :begin elem-B))
3972 (org-get-indentation)))
3973 (beg-A (org-element-property :begin elem-A))
3974 (end-A (save-excursion
3975 (goto-char (org-element-property :end elem-A))
3976 (skip-chars-backward " \r\t\n")
3977 (point-at-eol)))
3978 (beg-B (org-element-property :begin elem-B))
3979 (end-B (save-excursion
3980 (goto-char (org-element-property :end elem-B))
3981 (skip-chars-backward " \r\t\n")
3982 (point-at-eol)))
3983 ;; Store overlays responsible for visibility status. We
3984 ;; also need to store their boundaries as they will be
3985 ;; removed from buffer.
3986 (overlays
3987 (cons
3988 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
3989 (overlays-in beg-A end-A))
3990 (mapcar (lambda (ov) (list ov (overlay-start ov) (overlay-end ov)))
3991 (overlays-in beg-B end-B))))
3992 ;; Get contents.
3993 (body-A (buffer-substring beg-A end-A))
3994 (body-B (delete-and-extract-region beg-B end-B)))
3995 (goto-char beg-B)
3996 (when specialp
3997 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
3998 (org-indent-to-column ind-B))
3999 (insert body-A)
4000 ;; Restore ex ELEM-A overlays.
4001 (mapc (lambda (ov)
4002 (move-overlay
4003 (car ov)
4004 (+ (nth 1 ov) (- beg-B beg-A))
4005 (+ (nth 2 ov) (- beg-B beg-A))))
4006 (car overlays))
4007 (goto-char beg-A)
4008 (delete-region beg-A end-A)
4009 (insert body-B)
4010 ;; Restore ex ELEM-B overlays.
4011 (mapc (lambda (ov)
4012 (move-overlay (car ov)
4013 (+ (nth 1 ov) (- beg-A beg-B))
4014 (+ (nth 2 ov) (- beg-A beg-B))))
4015 (cdr overlays))
4016 (goto-char (org-element-property :end elem-B)))))
4018 (defun org-element-forward ()
4019 "Move forward by one element.
4020 Move to the next element at the same level, when possible."
4021 (interactive)
4022 (if (org-with-limited-levels (org-at-heading-p))
4023 (let ((origin (point)))
4024 (org-forward-same-level 1)
4025 (unless (org-with-limited-levels (org-at-heading-p))
4026 (goto-char origin)
4027 (error "Cannot move further down")))
4028 (let* ((trail (org-element-at-point 'keep-trail))
4029 (elem (pop trail))
4030 (end (org-element-property :end elem))
4031 (parent (loop for prev in trail
4032 when (>= (org-element-property :end prev) end)
4033 return prev)))
4034 (cond
4035 ((eobp) (error "Cannot move further down"))
4036 ((and parent (= (org-element-property :contents-end parent) end))
4037 (goto-char (org-element-property :end parent)))
4038 (t (goto-char end))))))
4040 (defun org-element-backward ()
4041 "Move backward by one element.
4042 Move to the previous element at the same level, when possible."
4043 (interactive)
4044 (if (org-with-limited-levels (org-at-heading-p))
4045 ;; At an headline, move to the previous one, if any, or stay
4046 ;; here.
4047 (let ((origin (point)))
4048 (org-backward-same-level 1)
4049 (unless (org-with-limited-levels (org-at-heading-p))
4050 (goto-char origin)
4051 (error "Cannot move further up")))
4052 (let* ((trail (org-element-at-point 'keep-trail))
4053 (elem (car trail))
4054 (prev-elem (nth 1 trail))
4055 (beg (org-element-property :begin elem)))
4056 (cond
4057 ;; Move to beginning of current element if point isn't there
4058 ;; already.
4059 ((/= (point) beg) (goto-char beg))
4060 ((not prev-elem) (error "Cannot move further up"))
4061 (t (goto-char (org-element-property :begin prev-elem)))))))
4063 (defun org-element-up ()
4064 "Move to upper element."
4065 (interactive)
4066 (if (org-with-limited-levels (org-at-heading-p))
4067 (unless (org-up-heading-safe)
4068 (error "No surrounding element"))
4069 (let* ((trail (org-element-at-point 'keep-trail))
4070 (elem (pop trail))
4071 (end (org-element-property :end elem))
4072 (parent (loop for prev in trail
4073 when (>= (org-element-property :end prev) end)
4074 return prev)))
4075 (cond
4076 (parent (goto-char (org-element-property :begin parent)))
4077 ((org-before-first-heading-p) (error "No surrounding element"))
4078 (t (org-back-to-heading))))))
4080 (defun org-element-down ()
4081 "Move to inner element."
4082 (interactive)
4083 (let ((element (org-element-at-point)))
4084 (cond
4085 ((memq (org-element-type element) '(plain-list table))
4086 (goto-char (org-element-property :contents-begin element))
4087 (forward-char))
4088 ((memq (org-element-type element) org-element-greater-elements)
4089 ;; If contents are hidden, first disclose them.
4090 (when (org-element-property :hiddenp element) (org-cycle))
4091 (goto-char (org-element-property :contents-begin element)))
4092 (t (error "No inner element")))))
4094 (defun org-element-drag-backward ()
4095 "Move backward element at point."
4096 (interactive)
4097 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
4098 (let* ((trail (org-element-at-point 'keep-trail))
4099 (elem (car trail))
4100 (prev-elem (nth 1 trail)))
4101 ;; Error out if no previous element or previous element is
4102 ;; a parent of the current one.
4103 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
4104 (error "Cannot drag element backward")
4105 (let ((pos (point)))
4106 (org-element-swap-A-B prev-elem elem)
4107 (goto-char (+ (org-element-property :begin prev-elem)
4108 (- pos (org-element-property :begin elem)))))))))
4110 (defun org-element-drag-forward ()
4111 "Move forward element at point."
4112 (interactive)
4113 (let* ((pos (point))
4114 (elem (org-element-at-point)))
4115 (when (= (point-max) (org-element-property :end elem))
4116 (error "Cannot drag element forward"))
4117 (goto-char (org-element-property :end elem))
4118 (let ((next-elem (org-element-at-point)))
4119 (when (or (org-element-nested-p elem next-elem)
4120 (and (eq (org-element-type next-elem) 'headline)
4121 (not (eq (org-element-type elem) 'headline))))
4122 (goto-char pos)
4123 (error "Cannot drag element forward"))
4124 ;; Compute new position of point: it's shifted by NEXT-ELEM
4125 ;; body's length (without final blanks) and by the length of
4126 ;; blanks between ELEM and NEXT-ELEM.
4127 (let ((size-next (- (save-excursion
4128 (goto-char (org-element-property :end next-elem))
4129 (skip-chars-backward " \r\t\n")
4130 (forward-line)
4131 ;; Small correction if buffer doesn't end
4132 ;; with a newline character.
4133 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
4134 (org-element-property :begin next-elem)))
4135 (size-blank (- (org-element-property :end elem)
4136 (save-excursion
4137 (goto-char (org-element-property :end elem))
4138 (skip-chars-backward " \r\t\n")
4139 (forward-line)
4140 (point)))))
4141 (org-element-swap-A-B elem next-elem)
4142 (goto-char (+ pos size-next size-blank))))))
4144 (defun org-element-mark-element ()
4145 "Put point at beginning of this element, mark at end.
4147 Interactively, if this command is repeated or (in Transient Mark
4148 mode) if the mark is active, it marks the next element after the
4149 ones already marked."
4150 (interactive)
4151 (let (deactivate-mark)
4152 (if (or (and (eq last-command this-command) (mark t))
4153 (and transient-mark-mode mark-active))
4154 (set-mark
4155 (save-excursion
4156 (goto-char (mark))
4157 (goto-char (org-element-property :end (org-element-at-point)))))
4158 (let ((element (org-element-at-point)))
4159 (end-of-line)
4160 (push-mark (org-element-property :end element) t t)
4161 (goto-char (org-element-property :begin element))))))
4163 (defun org-narrow-to-element ()
4164 "Narrow buffer to current element."
4165 (interactive)
4166 (let ((elem (org-element-at-point)))
4167 (cond
4168 ((eq (car elem) 'headline)
4169 (narrow-to-region
4170 (org-element-property :begin elem)
4171 (org-element-property :end elem)))
4172 ((memq (car elem) org-element-greater-elements)
4173 (narrow-to-region
4174 (org-element-property :contents-begin elem)
4175 (org-element-property :contents-end elem)))
4177 (narrow-to-region
4178 (org-element-property :begin elem)
4179 (org-element-property :end elem))))))
4181 (defun org-element-transpose ()
4182 "Transpose current and previous elements, keeping blank lines between.
4183 Point is moved after both elements."
4184 (interactive)
4185 (org-skip-whitespace)
4186 (let ((end (org-element-property :end (org-element-at-point))))
4187 (org-element-drag-backward)
4188 (goto-char end)))
4190 (defun org-element-unindent-buffer ()
4191 "Un-indent the visible part of the buffer.
4192 Relative indentation (between items, inside blocks, etc.) isn't
4193 modified."
4194 (interactive)
4195 (unless (eq major-mode 'org-mode)
4196 (error "Cannot un-indent a buffer not in Org mode"))
4197 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
4198 unindent-tree ; For byte-compiler.
4199 (unindent-tree
4200 (function
4201 (lambda (contents)
4202 (mapc
4203 (lambda (element)
4204 (if (memq (org-element-type element) '(headline section))
4205 (funcall unindent-tree (org-element-contents element))
4206 (save-excursion
4207 (save-restriction
4208 (narrow-to-region
4209 (org-element-property :begin element)
4210 (org-element-property :end element))
4211 (org-do-remove-indentation)))))
4212 (reverse contents))))))
4213 (funcall unindent-tree (org-element-contents parse-tree))))
4215 (defun org-element-fill-paragraph (&optional justify)
4216 "Fill element at point, when applicable.
4218 This function only applies to paragraph, comment blocks, example
4219 blocks and fixed-width areas. Also, as a special case, re-align
4220 table when point is at one.
4222 If JUSTIFY is non-nil (interactively, with prefix argument),
4223 justify as well. If `sentence-end-double-space' is non-nil, then
4224 period followed by one space does not end a sentence, so don't
4225 break a line there. The variable `fill-column' controls the
4226 width for filling."
4227 (let ((element (org-element-at-point)))
4228 (case (org-element-type element)
4229 ;; Align Org tables, leave table.el tables as-is.
4230 (table-row (org-table-align) t)
4231 (table
4232 (when (eq (org-element-property :type element) 'org) (org-table-align))
4234 ;; Elements that may contain `line-break' type objects.
4235 ((paragraph verse-block)
4236 (let ((beg (org-element-property :contents-begin element))
4237 (end (org-element-property :contents-end element)))
4238 ;; Do nothing if point is at an affiliated keyword or at
4239 ;; verse block markers.
4240 (if (or (< (point) beg) (>= (point) end)) t
4241 ;; At a verse block, first narrow to current "paragraph"
4242 ;; and set current element to that paragraph.
4243 (save-restriction
4244 (when (eq (org-element-type element) 'verse-block)
4245 (narrow-to-region beg end)
4246 (save-excursion
4247 (end-of-line)
4248 (let ((bol-pos (point-at-bol)))
4249 (re-search-backward org-element-paragraph-separate nil 'move)
4250 (unless (or (bobp) (= (point-at-bol) bol-pos))
4251 (forward-line))
4252 (setq element (org-element-paragraph-parser)
4253 beg (org-element-property :contents-begin element)
4254 end (org-element-property :contents-end element)))))
4255 ;; Fill paragraph, taking line breaks into consideration.
4256 ;; For that, slice the paragraph using line breaks as
4257 ;; separators, and fill the parts in reverse order to
4258 ;; avoid messing with markers.
4259 (save-excursion
4260 (goto-char end)
4261 (mapc
4262 (lambda (pos)
4263 (fill-region-as-paragraph pos (point) justify)
4264 (goto-char pos))
4265 ;; Find the list of ending positions for line breaks
4266 ;; in the current paragraph. Add paragraph beginning
4267 ;; to include first slice.
4268 (nreverse
4269 (cons beg
4270 (org-element-map
4271 (org-element-parse-objects
4272 beg end nil org-element-all-objects)
4273 'line-break
4274 (lambda (lb) (org-element-property :end lb)))))))) t)))
4275 ;; Elements whose contents should be filled as plain text.
4276 ((comment-block example-block)
4277 (save-restriction
4278 (narrow-to-region
4279 (save-excursion
4280 (goto-char (org-element-property :begin element))
4281 (while (looking-at org-element--affiliated-re) (forward-line))
4282 (forward-line)
4283 (point))
4284 (save-excursion
4285 (goto-char (org-element-property :end element))
4286 (if (bolp) (forward-line -1) (beginning-of-line))
4287 (point)))
4288 (fill-paragraph justify) t))
4289 ;; Ignore every other element.
4290 (otherwise t))))
4293 (provide 'org-element)
4294 ;;; org-element.el ends here