org-element: Remove an obsolete defconst
[org-mode.git] / contrib / lisp / org-element.el
blob8835391287db4538a98113b212276f8c2af67d1d
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, three 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, and `:post-blank', which holds the
70 ;; number of blank lines, or white spaces, at its end. Greater
71 ;; elements and elements containing objects will also have
72 ;; `:contents-begin' and `:contents-end' properties to delimit
73 ;; 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 ;; Indent contents.
689 (concat
690 bullet
691 (and counter (format "[@%d] " counter))
692 (cond
693 ((eq checkbox 'on) "[X] ")
694 ((eq checkbox 'off) "[ ] ")
695 ((eq checkbox 'trans) "[-] "))
696 (and tag (format "%s :: " tag))
697 (org-trim
698 (replace-regexp-in-string "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))))
701 ;;;; Plain List
703 (defun org-element-plain-list-parser (&optional structure)
704 "Parse a plain list.
706 Optional argument STRUCTURE, when non-nil, is the structure of
707 the plain list being parsed.
709 Return a list whose CAR is `plain-list' and CDR is a plist
710 containing `:type', `:begin', `:end', `:contents-begin' and
711 `:contents-end', `:structure' and `:post-blank' keywords.
713 Assume point is at the beginning of the list."
714 (save-excursion
715 (let* ((struct (or structure (org-list-struct)))
716 (prevs (org-list-prevs-alist struct))
717 (parents (org-list-parents-alist struct))
718 (type (org-list-get-list-type (point) struct prevs))
719 (contents-begin (point))
720 (keywords (org-element-collect-affiliated-keywords))
721 (begin (car keywords))
722 (contents-end
723 (goto-char (org-list-get-list-end (point) struct prevs)))
724 (end (save-excursion (org-skip-whitespace)
725 (if (eobp) (point) (point-at-bol)))))
726 ;; Blank lines below list belong to the top-level list only.
727 (unless (= (org-list-get-top-point struct) contents-begin)
728 (setq end (min (org-list-get-bottom-point struct)
729 (progn (org-skip-whitespace)
730 (if (eobp) (point) (point-at-bol))))))
731 ;; Return value.
732 `(plain-list
733 (:type ,type
734 :begin ,begin
735 :end ,end
736 :contents-begin ,contents-begin
737 :contents-end ,contents-end
738 :structure ,struct
739 :post-blank ,(count-lines contents-end end)
740 ,@(cadr keywords))))))
742 (defun org-element-plain-list-interpreter (plain-list contents)
743 "Interpret PLAIN-LIST element as Org syntax.
744 CONTENTS is the contents of the element."
745 contents)
748 ;;;; Quote Block
750 (defun org-element-quote-block-parser ()
751 "Parse a quote block.
753 Return a list whose CAR is `quote-block' and CDR is a plist
754 containing `:begin', `:end', `:hiddenp', `:contents-begin',
755 `:contents-end' and `:post-blank' keywords.
757 Assume point is at the beginning of the block."
758 (save-excursion
759 (let* ((case-fold-search t)
760 (keywords (org-element-collect-affiliated-keywords))
761 (begin (car keywords))
762 (contents-begin (progn (forward-line) (point)))
763 (hidden (org-truely-invisible-p))
764 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_QUOTE" nil t)
765 (point-at-bol)))
766 (pos-before-blank (progn (forward-line) (point)))
767 (end (progn (org-skip-whitespace)
768 (if (eobp) (point) (point-at-bol)))))
769 `(quote-block
770 (:begin ,begin
771 :end ,end
772 :hiddenp ,hidden
773 :contents-begin ,contents-begin
774 :contents-end ,contents-end
775 :post-blank ,(count-lines pos-before-blank end)
776 ,@(cadr keywords))))))
778 (defun org-element-quote-block-interpreter (quote-block contents)
779 "Interpret QUOTE-BLOCK element as Org syntax.
780 CONTENTS is the contents of the element."
781 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
784 ;;;; Section
786 (defun org-element-section-parser ()
787 "Parse a section.
789 Return a list whose CAR is `section' and CDR is a plist
790 containing `:begin', `:end', `:contents-begin', `contents-end'
791 and `:post-blank' keywords."
792 (save-excursion
793 ;; Beginning of section is the beginning of the first non-blank
794 ;; line after previous headline.
795 (org-with-limited-levels
796 (let ((begin
797 (save-excursion
798 (outline-previous-heading)
799 (if (not (org-at-heading-p)) (point)
800 (forward-line) (org-skip-whitespace) (point-at-bol))))
801 (end (progn (outline-next-heading) (point)))
802 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
803 (forward-line)
804 (point))))
805 `(section
806 (:begin ,begin
807 :end ,end
808 :contents-begin ,begin
809 :contents-end ,pos-before-blank
810 :post-blank ,(count-lines pos-before-blank end)))))))
812 (defun org-element-section-interpreter (section contents)
813 "Interpret SECTION element as Org syntax.
814 CONTENTS is the contents of the element."
815 contents)
818 ;;;; Special Block
820 (defun org-element-special-block-parser ()
821 "Parse a special block.
823 Return a list whose CAR is `special-block' and CDR is a plist
824 containing `:type', `:begin', `:end', `:hiddenp',
825 `:contents-begin', `:contents-end' and `:post-blank' keywords.
827 Assume point is at the beginning of the block."
828 (save-excursion
829 (let* ((case-fold-search t)
830 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)")
831 (org-match-string-no-properties 1)))
832 (keywords (org-element-collect-affiliated-keywords))
833 (begin (car keywords))
834 (contents-begin (progn (forward-line) (point)))
835 (hidden (org-truely-invisible-p))
836 (contents-end
837 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
838 (point-at-bol)))
839 (pos-before-blank (progn (forward-line) (point)))
840 (end (progn (org-skip-whitespace)
841 (if (eobp) (point) (point-at-bol)))))
842 `(special-block
843 (:type ,type
844 :begin ,begin
845 :end ,end
846 :hiddenp ,hidden
847 :contents-begin ,contents-begin
848 :contents-end ,contents-end
849 :post-blank ,(count-lines pos-before-blank end)
850 ,@(cadr keywords))))))
852 (defun org-element-special-block-interpreter (special-block contents)
853 "Interpret SPECIAL-BLOCK element as Org syntax.
854 CONTENTS is the contents of the element."
855 (let ((block-type (org-element-property :type special-block)))
856 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
860 ;;; Elements
862 ;; For each element, a parser and an interpreter are also defined.
863 ;; Both follow the same naming convention used for greater elements.
865 ;; Also, as for greater elements, adding a new element type is done
866 ;; through the following steps: implement a parser and an interpreter,
867 ;; tweak `org-element-current-element' so that it recognizes the new
868 ;; type and add that new type to `org-element-all-elements'.
870 ;; As a special case, when the newly defined type is a block type,
871 ;; `org-element-block-name-alist' has to be modified accordingly.
874 ;;;; Babel Call
876 (defun org-element-babel-call-parser ()
877 "Parse a babel call.
879 Return a list whose CAR is `babel-call' and CDR is a plist
880 containing `:begin', `:end', `:info' and `:post-blank' as
881 keywords."
882 (save-excursion
883 (let ((case-fold-search t)
884 (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
885 (org-babel-lob-get-info)))
886 (begin (point-at-bol))
887 (pos-before-blank (progn (forward-line) (point)))
888 (end (progn (org-skip-whitespace)
889 (if (eobp) (point) (point-at-bol)))))
890 `(babel-call
891 (:begin ,begin
892 :end ,end
893 :info ,info
894 :post-blank ,(count-lines pos-before-blank end))))))
896 (defun org-element-babel-call-interpreter (babel-call contents)
897 "Interpret BABEL-CALL element as Org syntax.
898 CONTENTS is nil."
899 (let* ((babel-info (org-element-property :info babel-call))
900 (main (car babel-info))
901 (post-options (nth 1 babel-info)))
902 (concat "#+CALL: "
903 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
904 ;; Remove redundant square brackets.
905 (replace-match (match-string 1 main) nil nil main))
906 (and post-options (format "[%s]" post-options)))))
909 ;;;; Clock
911 (defun org-element-clock-parser ()
912 "Parse a clock.
914 Return a list whose CAR is `clock' and CDR is a plist containing
915 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
916 as keywords."
917 (save-excursion
918 (let* ((case-fold-search nil)
919 (begin (point))
920 (value (progn (search-forward org-clock-string (line-end-position) t)
921 (org-skip-whitespace)
922 (looking-at "\\[.*\\]")
923 (org-match-string-no-properties 0)))
924 (time (and (progn (goto-char (match-end 0))
925 (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
926 (org-match-string-no-properties 1)))
927 (status (if time 'closed 'running))
928 (post-blank (let ((before-blank (progn (forward-line) (point))))
929 (org-skip-whitespace)
930 (unless (eobp) (beginning-of-line))
931 (count-lines before-blank (point))))
932 (end (point)))
933 `(clock (:status ,status
934 :value ,value
935 :time ,time
936 :begin ,begin
937 :end ,end
938 :post-blank ,post-blank)))))
940 (defun org-element-clock-interpreter (clock contents)
941 "Interpret CLOCK element as Org syntax.
942 CONTENTS is nil."
943 (concat org-clock-string " "
944 (org-element-property :value clock)
945 (let ((time (org-element-property :time clock)))
946 (and time
947 (concat " => "
948 (apply 'format
949 "%2s:%02s"
950 (org-split-string time ":")))))))
953 ;;;; Comment
955 (defun org-element-comment-parser ()
956 "Parse a comment.
958 Return a list whose CAR is `comment' and CDR is a plist
959 containing `:begin', `:end', `:value' and `:post-blank'
960 keywords.
962 Assume point is at comment beginning."
963 (save-excursion
964 (let* ((keywords (org-element-collect-affiliated-keywords))
965 (begin (car keywords))
966 value
967 (com-end
968 ;; Get comments ending. This may not be accurate if
969 ;; commented lines within an item are followed by
970 ;; commented lines outside of a list. Though, parser will
971 ;; always get it right as it already knows surrounding
972 ;; element and has narrowed buffer to its contents.
973 (progn
974 (while (looking-at "\\(\\(# ?\\)[^+]\\|[ \t]*#\\+\\( \\|$\\)\\)")
975 ;; Accumulate lines without leading hash and plus sign
976 ;; if any. First whitespace is also ignored.
977 (setq value
978 (concat value
979 (buffer-substring-no-properties
980 (or (match-end 2) (match-end 3)) (point-at-eol))
981 "\n"))
982 (forward-line))
983 (point)))
984 (end (progn (goto-char com-end)
985 (org-skip-whitespace)
986 (if (eobp) (point) (point-at-bol)))))
987 `(comment
988 (:begin ,begin
989 :end ,end
990 :value ,value
991 :post-blank ,(count-lines com-end end)
992 ,@(cadr keywords))))))
994 (defun org-element-comment-interpreter (comment contents)
995 "Interpret COMMENT element as Org syntax.
996 CONTENTS is nil."
997 (replace-regexp-in-string
998 "^" "#+ "
999 (substring (org-element-property :value comment) 0 -1)))
1002 ;;;; Comment Block
1004 (defun org-element-comment-block-parser ()
1005 "Parse an export block.
1007 Return a list whose CAR is `comment-block' and CDR is a plist
1008 containing `:begin', `:end', `:hiddenp', `:value' and
1009 `:post-blank' keywords.
1011 Assume point is at comment block beginning."
1012 (save-excursion
1013 (let* ((case-fold-search t)
1014 (keywords (org-element-collect-affiliated-keywords))
1015 (begin (car keywords))
1016 (contents-begin (progn (forward-line) (point)))
1017 (hidden (org-truely-invisible-p))
1018 (contents-end
1019 (progn (re-search-forward "^[ \t]*#\\+END_COMMENT" nil t)
1020 (point-at-bol)))
1021 (pos-before-blank (progn (forward-line) (point)))
1022 (end (progn (org-skip-whitespace)
1023 (if (eobp) (point) (point-at-bol))))
1024 (value (buffer-substring-no-properties contents-begin contents-end)))
1025 `(comment-block
1026 (:begin ,begin
1027 :end ,end
1028 :value ,value
1029 :hiddenp ,hidden
1030 :post-blank ,(count-lines pos-before-blank end)
1031 ,@(cadr keywords))))))
1033 (defun org-element-comment-block-interpreter (comment-block contents)
1034 "Interpret COMMENT-BLOCK element as Org syntax.
1035 CONTENTS is nil."
1036 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1037 (org-remove-indentation (org-element-property :value comment-block))))
1040 ;;;; Example Block
1042 (defun org-element-example-block-parser ()
1043 "Parse an example block.
1045 Return a list whose CAR is `example-block' and CDR is a plist
1046 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1047 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1048 `:switches', `:value' and `:post-blank' keywords."
1049 (save-excursion
1050 (let* ((case-fold-search t)
1051 (switches
1052 (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1053 (org-match-string-no-properties 1)))
1054 ;; Switches analysis
1055 (number-lines (cond ((not switches) nil)
1056 ((string-match "-n\\>" switches) 'new)
1057 ((string-match "+n\\>" switches) 'continued)))
1058 (preserve-indent (and switches (string-match "-i\\>" switches)))
1059 ;; Should labels be retained in (or stripped from) example
1060 ;; blocks?
1061 (retain-labels
1062 (or (not switches)
1063 (not (string-match "-r\\>" switches))
1064 (and number-lines (string-match "-k\\>" switches))))
1065 ;; What should code-references use - labels or
1066 ;; line-numbers?
1067 (use-labels
1068 (or (not switches)
1069 (and retain-labels (not (string-match "-k\\>" switches)))))
1070 (label-fmt (and switches
1071 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1072 (match-string 1 switches)))
1073 ;; Standard block parsing.
1074 (keywords (org-element-collect-affiliated-keywords))
1075 (begin (car keywords))
1076 (contents-begin (progn (forward-line) (point)))
1077 (hidden (org-truely-invisible-p))
1078 (contents-end
1079 (progn (re-search-forward "^[ \t]*#\\+END_EXAMPLE" nil t)
1080 (point-at-bol)))
1081 (value (buffer-substring-no-properties contents-begin contents-end))
1082 (pos-before-blank (progn (forward-line) (point)))
1083 (end (progn (org-skip-whitespace)
1084 (if (eobp) (point) (point-at-bol)))))
1085 `(example-block
1086 (:begin ,begin
1087 :end ,end
1088 :value ,value
1089 :switches ,switches
1090 :number-lines ,number-lines
1091 :preserve-indent ,preserve-indent
1092 :retain-labels ,retain-labels
1093 :use-labels ,use-labels
1094 :label-fmt ,label-fmt
1095 :hiddenp ,hidden
1096 :post-blank ,(count-lines pos-before-blank end)
1097 ,@(cadr keywords))))))
1099 (defun org-element-example-block-interpreter (example-block contents)
1100 "Interpret EXAMPLE-BLOCK element as Org syntax.
1101 CONTENTS is nil."
1102 (let ((switches (org-element-property :switches example-block)))
1103 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1104 (org-remove-indentation
1105 (org-element-property :value example-block))
1106 "#+END_EXAMPLE")))
1109 ;;;; Export Block
1111 (defun org-element-export-block-parser ()
1112 "Parse an export block.
1114 Return a list whose CAR is `export-block' and CDR is a plist
1115 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1116 `:post-blank' keywords.
1118 Assume point is at export-block beginning."
1119 (save-excursion
1120 (let* ((case-fold-search t)
1121 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([A-Za-z0-9]+\\)")
1122 (upcase (org-match-string-no-properties 1))))
1123 (keywords (org-element-collect-affiliated-keywords))
1124 (begin (car keywords))
1125 (contents-begin (progn (forward-line) (point)))
1126 (hidden (org-truely-invisible-p))
1127 (contents-end
1128 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
1129 (point-at-bol)))
1130 (pos-before-blank (progn (forward-line) (point)))
1131 (end (progn (org-skip-whitespace)
1132 (if (eobp) (point) (point-at-bol))))
1133 (value (buffer-substring-no-properties contents-begin contents-end)))
1134 `(export-block
1135 (:begin ,begin
1136 :end ,end
1137 :type ,type
1138 :value ,value
1139 :hiddenp ,hidden
1140 :post-blank ,(count-lines pos-before-blank end)
1141 ,@(cadr keywords))))))
1143 (defun org-element-export-block-interpreter (export-block contents)
1144 "Interpret EXPORT-BLOCK element as Org syntax.
1145 CONTENTS is nil."
1146 (let ((type (org-element-property :type export-block)))
1147 (concat (format "#+BEGIN_%s\n" type)
1148 (org-element-property :value export-block)
1149 (format "#+END_%s" type))))
1152 ;;;; Fixed-width
1154 (defun org-element-fixed-width-parser ()
1155 "Parse a fixed-width section.
1157 Return a list whose CAR is `fixed-width' and CDR is a plist
1158 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1160 Assume point is at the beginning of the fixed-width area."
1161 (save-excursion
1162 (let* ((keywords (org-element-collect-affiliated-keywords))
1163 (begin (car keywords))
1164 value
1165 (end-area
1166 ;; Ending position may not be accurate if fixed-width
1167 ;; lines within an item are followed by fixed-width lines
1168 ;; outside of a list. Though, parser will always get it
1169 ;; right as it already knows surrounding element and has
1170 ;; narrowed buffer to its contents.
1171 (progn
1172 (while (looking-at "[ \t]*:\\( \\|$\\)")
1173 ;, Accumulate text without starting colons.
1174 (setq value
1175 (concat value
1176 (buffer-substring-no-properties
1177 (match-end 0) (point-at-eol))
1178 "\n"))
1179 (forward-line))
1180 (point)))
1181 (end (progn (org-skip-whitespace)
1182 (if (eobp) (point) (point-at-bol)))))
1183 `(fixed-width
1184 (:begin ,begin
1185 :end ,end
1186 :value ,value
1187 :post-blank ,(count-lines end-area end)
1188 ,@(cadr keywords))))))
1190 (defun org-element-fixed-width-interpreter (fixed-width contents)
1191 "Interpret FIXED-WIDTH element as Org syntax.
1192 CONTENTS is nil."
1193 (replace-regexp-in-string
1194 "^" ": " (substring (org-element-property :value fixed-width) 0 -1)))
1197 ;;;; Horizontal Rule
1199 (defun org-element-horizontal-rule-parser ()
1200 "Parse an horizontal rule.
1202 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1203 containing `:begin', `:end' and `:post-blank' keywords."
1204 (save-excursion
1205 (let* ((keywords (org-element-collect-affiliated-keywords))
1206 (begin (car keywords))
1207 (post-hr (progn (forward-line) (point)))
1208 (end (progn (org-skip-whitespace)
1209 (if (eobp) (point) (point-at-bol)))))
1210 `(horizontal-rule
1211 (:begin ,begin
1212 :end ,end
1213 :post-blank ,(count-lines post-hr end)
1214 ,@(cadr keywords))))))
1216 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1217 "Interpret HORIZONTAL-RULE element as Org syntax.
1218 CONTENTS is nil."
1219 "-----")
1222 ;;;; Keyword
1224 (defun org-element-keyword-parser ()
1225 "Parse a keyword at point.
1227 Return a list whose CAR is `keyword' and CDR is a plist
1228 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1229 keywords."
1230 (save-excursion
1231 (let* ((case-fold-search t)
1232 (begin (point))
1233 (key (progn (looking-at
1234 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1235 (upcase (org-match-string-no-properties 1))))
1236 (value (org-trim (buffer-substring-no-properties
1237 (match-end 0) (point-at-eol))))
1238 (pos-before-blank (progn (forward-line) (point)))
1239 (end (progn (org-skip-whitespace)
1240 (if (eobp) (point) (point-at-bol)))))
1241 `(keyword
1242 (:key ,key
1243 :value ,value
1244 :begin ,begin
1245 :end ,end
1246 :post-blank ,(count-lines pos-before-blank end))))))
1248 (defun org-element-keyword-interpreter (keyword contents)
1249 "Interpret KEYWORD element as Org syntax.
1250 CONTENTS is nil."
1251 (format "#+%s: %s"
1252 (org-element-property :key keyword)
1253 (org-element-property :value keyword)))
1256 ;;;; Latex Environment
1258 (defun org-element-latex-environment-parser ()
1259 "Parse a LaTeX environment.
1261 Return a list whose CAR is `latex-environment' and CDR is a plist
1262 containing `:begin', `:end', `:value' and `:post-blank'
1263 keywords.
1265 Assume point is at the beginning of the latex environment."
1266 (save-excursion
1267 (let* ((case-fold-search t)
1268 (contents-begin (point))
1269 (keywords (org-element-collect-affiliated-keywords))
1270 (begin (car keywords))
1271 (contents-end (progn (re-search-forward "^[ \t]*\\\\end")
1272 (forward-line)
1273 (point)))
1274 (value (buffer-substring-no-properties contents-begin contents-end))
1275 (end (progn (org-skip-whitespace)
1276 (if (eobp) (point) (point-at-bol)))))
1277 `(latex-environment
1278 (:begin ,begin
1279 :end ,end
1280 :value ,value
1281 :post-blank ,(count-lines contents-end end)
1282 ,@(cadr keywords))))))
1284 (defun org-element-latex-environment-interpreter (latex-environment contents)
1285 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1286 CONTENTS is nil."
1287 (org-element-property :value latex-environment))
1290 ;;;; Paragraph
1292 (defun org-element-paragraph-parser ()
1293 "Parse a paragraph.
1295 Return a list whose CAR is `paragraph' and CDR is a plist
1296 containing `:begin', `:end', `:contents-begin' and
1297 `:contents-end' and `:post-blank' keywords.
1299 Assume point is at the beginning of the paragraph."
1300 (save-excursion
1301 (let* ((contents-begin (point))
1302 (keywords (org-element-collect-affiliated-keywords))
1303 (begin (car keywords))
1304 (contents-end
1305 (progn (end-of-line)
1306 (if (re-search-forward org-element-paragraph-separate nil 'm)
1307 (progn (forward-line -1) (end-of-line) (point))
1308 (point))))
1309 (pos-before-blank (progn (forward-line) (point)))
1310 (end (progn (org-skip-whitespace)
1311 (if (eobp) (point) (point-at-bol)))))
1312 `(paragraph
1313 (:begin ,begin
1314 :end ,end
1315 :contents-begin ,contents-begin
1316 :contents-end ,contents-end
1317 :post-blank ,(count-lines pos-before-blank end)
1318 ,@(cadr keywords))))))
1320 (defun org-element-paragraph-interpreter (paragraph contents)
1321 "Interpret PARAGRAPH element as Org syntax.
1322 CONTENTS is the contents of the element."
1323 contents)
1326 ;;;; Planning
1328 (defun org-element-planning-parser ()
1329 "Parse a planning.
1331 Return a list whose CAR is `planning' and CDR is a plist
1332 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
1333 and `:post-blank' keywords."
1334 (save-excursion
1335 (let* ((case-fold-search nil)
1336 (begin (point))
1337 (post-blank (let ((before-blank (progn (forward-line) (point))))
1338 (org-skip-whitespace)
1339 (unless (eobp) (beginning-of-line))
1340 (count-lines before-blank (point))))
1341 (end (point))
1342 closed deadline scheduled)
1343 (goto-char begin)
1344 (while (re-search-forward org-keyword-time-not-clock-regexp
1345 (line-end-position) t)
1346 (goto-char (match-end 1))
1347 (org-skip-whitespace)
1348 (let ((time (buffer-substring-no-properties (point) (match-end 0)))
1349 (keyword (match-string 1)))
1350 (cond ((equal keyword org-closed-string) (setq closed time))
1351 ((equal keyword org-deadline-string) (setq deadline time))
1352 (t (setq scheduled time)))))
1353 `(planning
1354 (:closed ,closed
1355 :deadline ,deadline
1356 :scheduled ,scheduled
1357 :begin ,begin
1358 :end ,end
1359 :post-blank ,post-blank)))))
1361 (defun org-element-planning-interpreter (planning contents)
1362 "Interpret PLANNING element as Org syntax.
1363 CONTENTS is nil."
1364 (mapconcat
1365 'identity
1366 (delq nil
1367 (list (let ((closed (org-element-property :closed planning)))
1368 (when closed (concat org-closed-string " " closed)))
1369 (let ((deadline (org-element-property :deadline planning)))
1370 (when deadline (concat org-deadline-string " " deadline)))
1371 (let ((scheduled (org-element-property :scheduled planning)))
1372 (when scheduled (concat org-scheduled-string " " scheduled)))))
1373 " "))
1376 ;;;; Property Drawer
1378 (defun org-element-property-drawer-parser ()
1379 "Parse a property drawer.
1381 Return a list whose CAR is `property-drawer' and CDR is a plist
1382 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1383 `:contents-end', `:properties' and `:post-blank' keywords.
1385 Assume point is at the beginning of the property drawer."
1386 (save-excursion
1387 (let ((case-fold-search t)
1388 (begin (point))
1389 (prop-begin (progn (forward-line) (point)))
1390 (hidden (org-truely-invisible-p))
1391 (properties
1392 (let (val)
1393 (while (not (looking-at "^[ \t]*:END:"))
1394 (when (looking-at "[ \t]*:\\([A-Za-z][-_A-Za-z0-9]*\\):")
1395 (push (cons (org-match-string-no-properties 1)
1396 (org-trim
1397 (buffer-substring-no-properties
1398 (match-end 0) (point-at-eol))))
1399 val))
1400 (forward-line))
1401 val))
1402 (prop-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1403 (point-at-bol)))
1404 (pos-before-blank (progn (forward-line) (point)))
1405 (end (progn (org-skip-whitespace)
1406 (if (eobp) (point) (point-at-bol)))))
1407 `(property-drawer
1408 (:begin ,begin
1409 :end ,end
1410 :hiddenp ,hidden
1411 :properties ,properties
1412 :post-blank ,(count-lines pos-before-blank end))))))
1414 (defun org-element-property-drawer-interpreter (property-drawer contents)
1415 "Interpret PROPERTY-DRAWER element as Org syntax.
1416 CONTENTS is nil."
1417 (let ((props (org-element-property :properties property-drawer)))
1418 (concat
1419 ":PROPERTIES:\n"
1420 (mapconcat (lambda (p)
1421 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1422 (nreverse props) "\n")
1423 "\n:END:")))
1426 ;;;; Quote Section
1428 (defun org-element-quote-section-parser ()
1429 "Parse a quote section.
1431 Return a list whose CAR is `quote-section' and CDR is a plist
1432 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1434 Assume point is at beginning of the section."
1435 (save-excursion
1436 (let* ((begin (point))
1437 (end (progn (org-with-limited-levels (outline-next-heading))
1438 (point)))
1439 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1440 (forward-line)
1441 (point)))
1442 (value (buffer-substring-no-properties begin pos-before-blank)))
1443 `(quote-section
1444 (:begin ,begin
1445 :end ,end
1446 :value ,value
1447 :post-blank ,(count-lines pos-before-blank end))))))
1449 (defun org-element-quote-section-interpreter (quote-section contents)
1450 "Interpret QUOTE-SECTION element as Org syntax.
1451 CONTENTS is nil."
1452 (org-element-property :value quote-section))
1455 ;;;; Src Block
1457 (defun org-element-src-block-parser ()
1458 "Parse a src block.
1460 Return a list whose CAR is `src-block' and CDR is a plist
1461 containing `:language', `:switches', `:parameters', `:begin',
1462 `:end', `:hiddenp', `:contents-begin', `:contents-end',
1463 `:number-lines', `:retain-labels', `:use-labels', `:label-fmt',
1464 `:preserve-indent', `:value' and `:post-blank' keywords.
1466 Assume point is at the beginning of the block."
1467 (save-excursion
1468 (let* ((case-fold-search t)
1469 (contents-begin (point))
1470 ;; Get affiliated keywords.
1471 (keywords (org-element-collect-affiliated-keywords))
1472 ;; Get beginning position.
1473 (begin (car keywords))
1474 ;; Get language as a string.
1475 (language
1476 (progn
1477 (looking-at
1478 (concat "^[ \t]*#\\+BEGIN_SRC"
1479 "\\(?: +\\(\\S-+\\)\\)?"
1480 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
1481 "\\(.*\\)[ \t]*$"))
1482 (org-match-string-no-properties 1)))
1483 ;; Get switches.
1484 (switches (org-match-string-no-properties 2))
1485 ;; Get parameters.
1486 (parameters (org-match-string-no-properties 3))
1487 ;; Switches analysis
1488 (number-lines (cond ((not switches) nil)
1489 ((string-match "-n\\>" switches) 'new)
1490 ((string-match "+n\\>" switches) 'continued)))
1491 (preserve-indent (and switches (string-match "-i\\>" switches)))
1492 (label-fmt (and switches
1493 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1494 (match-string 1 switches)))
1495 ;; Should labels be retained in (or stripped from) src
1496 ;; blocks?
1497 (retain-labels
1498 (or (not switches)
1499 (not (string-match "-r\\>" switches))
1500 (and number-lines (string-match "-k\\>" switches))))
1501 ;; What should code-references use - labels or
1502 ;; line-numbers?
1503 (use-labels
1504 (or (not switches)
1505 (and retain-labels (not (string-match "-k\\>" switches)))))
1506 ;; Get position at end of block.
1507 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_SRC" nil t)
1508 (forward-line)
1509 (point)))
1510 ;; Retrieve code.
1511 (value (buffer-substring-no-properties
1512 (save-excursion (goto-char contents-begin)
1513 (forward-line)
1514 (point))
1515 (match-beginning 0)))
1516 ;; Get position after ending blank lines.
1517 (end (progn (org-skip-whitespace)
1518 (if (eobp) (point) (point-at-bol))))
1519 ;; Get visibility status.
1520 (hidden (progn (goto-char contents-begin)
1521 (forward-line)
1522 (org-truely-invisible-p))))
1523 `(src-block
1524 (:language ,language
1525 :switches ,(and (org-string-nw-p switches)
1526 (org-trim switches))
1527 :parameters ,(and (org-string-nw-p parameters)
1528 (org-trim parameters))
1529 :begin ,begin
1530 :end ,end
1531 :number-lines ,number-lines
1532 :preserve-indent ,preserve-indent
1533 :retain-labels ,retain-labels
1534 :use-labels ,use-labels
1535 :label-fmt ,label-fmt
1536 :hiddenp ,hidden
1537 :value ,value
1538 :post-blank ,(count-lines contents-end end)
1539 ,@(cadr keywords))))))
1541 (defun org-element-src-block-interpreter (src-block contents)
1542 "Interpret SRC-BLOCK element as Org syntax.
1543 CONTENTS is nil."
1544 (let ((lang (org-element-property :language src-block))
1545 (switches (org-element-property :switches src-block))
1546 (params (org-element-property :parameters src-block))
1547 (value (let ((val (org-element-property :value src-block)))
1548 (cond
1550 (org-src-preserve-indentation val)
1551 ((zerop org-edit-src-content-indentation)
1552 (org-remove-indentation val))
1554 (let ((ind (make-string
1555 org-edit-src-content-indentation 32)))
1556 (replace-regexp-in-string
1557 "\\(^\\)[ \t]*\\S-" ind
1558 (org-remove-indentation val) nil nil 1)))))))
1559 (concat (format "#+BEGIN_SRC%s\n"
1560 (concat (and lang (concat " " lang))
1561 (and switches (concat " " switches))
1562 (and params (concat " " params))))
1563 value
1564 "#+END_SRC")))
1567 ;;;; Table
1569 (defun org-element-table-parser ()
1570 "Parse a table at point.
1572 Return a list whose CAR is `table' and CDR is a plist containing
1573 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
1574 `:contents-end', `:value' and `:post-blank' keywords.
1576 Assume point is at the beginning of the table."
1577 (save-excursion
1578 (let* ((case-fold-search t)
1579 (table-begin (point))
1580 (type (if (org-at-table.el-p) 'table.el 'org))
1581 (keywords (org-element-collect-affiliated-keywords))
1582 (begin (car keywords))
1583 (table-end (goto-char (marker-position (org-table-end t))))
1584 (tblfm (when (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
1585 (prog1 (org-match-string-no-properties 1)
1586 (forward-line))))
1587 (pos-before-blank (point))
1588 (end (progn (org-skip-whitespace)
1589 (if (eobp) (point) (point-at-bol)))))
1590 `(table
1591 (:begin ,begin
1592 :end ,end
1593 :type ,type
1594 :tblfm ,tblfm
1595 ;; Only `org' tables have contents. `table.el' tables
1596 ;; use a `:value' property to store raw table as
1597 ;; a string.
1598 :contents-begin ,(and (eq type 'org) table-begin)
1599 :contents-end ,(and (eq type 'org) table-end)
1600 :value ,(and (eq type 'table.el)
1601 (buffer-substring-no-properties
1602 table-begin table-end))
1603 :post-blank ,(count-lines pos-before-blank end)
1604 ,@(cadr keywords))))))
1606 (defun org-element-table-interpreter (table contents)
1607 "Interpret TABLE element as Org syntax.
1608 CONTENTS is nil."
1609 (if (eq (org-element-property :type table) 'table.el)
1610 (org-remove-indentation (org-element-property :value table))
1611 (concat (with-temp-buffer (insert contents)
1612 (org-table-align)
1613 (buffer-string))
1614 (when (org-element-property :tblfm table)
1615 (format "#+TBLFM: " (org-element-property :tblfm table))))))
1618 ;;;; Table Row
1620 (defun org-element-table-row-parser ()
1621 "Parse table row at point.
1623 Return a list whose CAR is `table-row' and CDR is a plist
1624 containing `:begin', `:end', `:contents-begin', `:contents-end',
1625 `:type' and `:post-blank' keywords."
1626 (save-excursion
1627 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
1628 (begin (point))
1629 ;; A table rule has no contents. In that case, ensure
1630 ;; CONTENTS-BEGIN matches CONTENTS-END.
1631 (contents-begin (if (eq type 'standard)
1632 (progn (search-forward "|") (point))
1633 (end-of-line)
1634 (skip-chars-backward " \r\t\n")
1635 (point)))
1636 (contents-end (progn (end-of-line)
1637 (skip-chars-backward " \r\t\n")
1638 (point)))
1639 (end (progn (forward-line) (point))))
1640 `(table-row
1641 (:type ,type
1642 :begin ,begin
1643 :end ,end
1644 :contents-begin ,contents-begin
1645 :contents-end ,contents-end
1646 :post-blank 0)))))
1648 (defun org-element-table-row-interpreter (table-row contents)
1649 "Interpret TABLE-ROW element as Org syntax.
1650 CONTENTS is the contents of the table row."
1651 (if (eq (org-element-property :type table-row) 'rule) "|-"
1652 (concat "| " contents)))
1655 ;;;; Verse Block
1657 (defun org-element-verse-block-parser ()
1658 "Parse a verse block.
1660 Return a list whose CAR is `verse-block' and CDR is a plist
1661 containing `:begin', `:end', `:contents-begin', `:contents-end',
1662 `:hiddenp' and `:post-blank' keywords.
1664 Assume point is at beginning of the block."
1665 (save-excursion
1666 (let* ((case-fold-search t)
1667 (keywords (org-element-collect-affiliated-keywords))
1668 (begin (car keywords))
1669 (hidden (progn (forward-line) (org-truely-invisible-p)))
1670 (contents-begin (point))
1671 (contents-end
1672 (progn
1673 (re-search-forward (concat "^[ \t]*#\\+END_VERSE") nil t)
1674 (point-at-bol)))
1675 (pos-before-blank (progn (forward-line) (point)))
1676 (end (progn (org-skip-whitespace)
1677 (if (eobp) (point) (point-at-bol)))))
1678 `(verse-block
1679 (:begin ,begin
1680 :end ,end
1681 :contents-begin ,contents-begin
1682 :contents-end ,contents-end
1683 :hiddenp ,hidden
1684 :post-blank ,(count-lines pos-before-blank end)
1685 ,@(cadr keywords))))))
1687 (defun org-element-verse-block-interpreter (verse-block contents)
1688 "Interpret VERSE-BLOCK element as Org syntax.
1689 CONTENTS is verse block contents."
1690 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
1694 ;;; Objects
1696 ;; Unlike to elements, interstices can be found between objects.
1697 ;; That's why, along with the parser, successor functions are provided
1698 ;; for each object. Some objects share the same successor (i.e. `code'
1699 ;; and `verbatim' objects).
1701 ;; A successor must accept a single argument bounding the search. It
1702 ;; will return either a cons cell whose CAR is the object's type, as
1703 ;; a symbol, and CDR the position of its next occurrence, or nil.
1705 ;; Successors follow the naming convention:
1706 ;; org-element-NAME-successor, where NAME is the name of the
1707 ;; successor, as defined in `org-element-all-successors'.
1709 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1710 ;; object types they can contain will be specified in
1711 ;; `org-element-object-restrictions'.
1713 ;; Adding a new type of object is simple. Implement a successor,
1714 ;; a parser, and an interpreter for it, all following the naming
1715 ;; convention. Register type in `org-element-all-objects' and
1716 ;; successor in `org-element-all-successors'. Maybe tweak
1717 ;; restrictions about it, and that's it.
1720 ;;;; Bold
1722 (defun org-element-bold-parser ()
1723 "Parse bold object at point.
1725 Return a list whose CAR is `bold' and CDR is a plist with
1726 `:begin', `:end', `:contents-begin' and `:contents-end' and
1727 `:post-blank' keywords.
1729 Assume point is at the first star marker."
1730 (save-excursion
1731 (unless (bolp) (backward-char 1))
1732 (looking-at org-emph-re)
1733 (let ((begin (match-beginning 2))
1734 (contents-begin (match-beginning 4))
1735 (contents-end (match-end 4))
1736 (post-blank (progn (goto-char (match-end 2))
1737 (skip-chars-forward " \t")))
1738 (end (point)))
1739 `(bold
1740 (:begin ,begin
1741 :end ,end
1742 :contents-begin ,contents-begin
1743 :contents-end ,contents-end
1744 :post-blank ,post-blank)))))
1746 (defun org-element-bold-interpreter (bold contents)
1747 "Interpret BOLD object as Org syntax.
1748 CONTENTS is the contents of the object."
1749 (format "*%s*" contents))
1751 (defun org-element-text-markup-successor (limit)
1752 "Search for the next text-markup object.
1754 LIMIT bounds the search.
1756 Return value is a cons cell whose CAR is a symbol among `bold',
1757 `italic', `underline', `strike-through', `code' and `verbatim'
1758 and CDR is beginning position."
1759 (save-excursion
1760 (unless (bolp) (backward-char))
1761 (when (re-search-forward org-emph-re limit t)
1762 (let ((marker (match-string 3)))
1763 (cons (cond
1764 ((equal marker "*") 'bold)
1765 ((equal marker "/") 'italic)
1766 ((equal marker "_") 'underline)
1767 ((equal marker "+") 'strike-through)
1768 ((equal marker "~") 'code)
1769 ((equal marker "=") 'verbatim)
1770 (t (error "Unknown marker at %d" (match-beginning 3))))
1771 (match-beginning 2))))))
1774 ;;;; Code
1776 (defun org-element-code-parser ()
1777 "Parse code object at point.
1779 Return a list whose CAR is `code' and CDR is a plist with
1780 `:value', `:begin', `:end' and `:post-blank' keywords.
1782 Assume point is at the first tilde marker."
1783 (save-excursion
1784 (unless (bolp) (backward-char 1))
1785 (looking-at org-emph-re)
1786 (let ((begin (match-beginning 2))
1787 (value (org-match-string-no-properties 4))
1788 (post-blank (progn (goto-char (match-end 2))
1789 (skip-chars-forward " \t")))
1790 (end (point)))
1791 `(code
1792 (:value ,value
1793 :begin ,begin
1794 :end ,end
1795 :post-blank ,post-blank)))))
1797 (defun org-element-code-interpreter (code contents)
1798 "Interpret CODE object as Org syntax.
1799 CONTENTS is nil."
1800 (format "~%s~" (org-element-property :value code)))
1803 ;;;; Entity
1805 (defun org-element-entity-parser ()
1806 "Parse entity at point.
1808 Return a list whose CAR is `entity' and CDR a plist with
1809 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1810 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1811 keywords.
1813 Assume point is at the beginning of the entity."
1814 (save-excursion
1815 (looking-at "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1816 (let* ((value (org-entity-get (match-string 1)))
1817 (begin (match-beginning 0))
1818 (bracketsp (string= (match-string 2) "{}"))
1819 (post-blank (progn (goto-char (match-end 1))
1820 (when bracketsp (forward-char 2))
1821 (skip-chars-forward " \t")))
1822 (end (point)))
1823 `(entity
1824 (:name ,(car value)
1825 :latex ,(nth 1 value)
1826 :latex-math-p ,(nth 2 value)
1827 :html ,(nth 3 value)
1828 :ascii ,(nth 4 value)
1829 :latin1 ,(nth 5 value)
1830 :utf-8 ,(nth 6 value)
1831 :begin ,begin
1832 :end ,end
1833 :use-brackets-p ,bracketsp
1834 :post-blank ,post-blank)))))
1836 (defun org-element-entity-interpreter (entity contents)
1837 "Interpret ENTITY object as Org syntax.
1838 CONTENTS is nil."
1839 (concat "\\"
1840 (org-element-property :name entity)
1841 (when (org-element-property :use-brackets-p entity) "{}")))
1843 (defun org-element-latex-or-entity-successor (limit)
1844 "Search for the next latex-fragment or entity object.
1846 LIMIT bounds the search.
1848 Return value is a cons cell whose CAR is `entity' or
1849 `latex-fragment' and CDR is beginning position."
1850 (save-excursion
1851 (let ((matchers (plist-get org-format-latex-options :matchers))
1852 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1853 (entity-re
1854 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"))
1855 (when (re-search-forward
1856 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1857 matchers "\\|")
1858 "\\|" entity-re)
1859 limit t)
1860 (goto-char (match-beginning 0))
1861 (if (looking-at entity-re)
1862 ;; Determine if it's a real entity or a LaTeX command.
1863 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1864 (match-beginning 0))
1865 ;; No entity nor command: point is at a LaTeX fragment.
1866 ;; Determine its type to get the correct beginning position.
1867 (cons 'latex-fragment
1868 (catch 'return
1869 (mapc (lambda (e)
1870 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1871 (throw 'return
1872 (match-beginning
1873 (nth 2 (assoc e org-latex-regexps))))))
1874 matchers)
1875 (point))))))))
1878 ;;;; Export Snippet
1880 (defun org-element-export-snippet-parser ()
1881 "Parse export snippet at point.
1883 Return a list whose CAR is `export-snippet' and CDR a plist with
1884 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1885 keywords.
1887 Assume point is at the beginning of the snippet."
1888 (save-excursion
1889 (looking-at "<\\([-A-Za-z0-9]+\\)@")
1890 (let* ((begin (point))
1891 (back-end (org-match-string-no-properties 1))
1892 (inner-begin (match-end 0))
1893 (inner-end
1894 (let ((count 1))
1895 (goto-char inner-begin)
1896 (while (and (> count 0) (re-search-forward "[<>]" nil t))
1897 (if (equal (match-string 0) "<") (incf count) (decf count)))
1898 (1- (point))))
1899 (value (buffer-substring-no-properties inner-begin inner-end))
1900 (post-blank (skip-chars-forward " \t"))
1901 (end (point)))
1902 `(export-snippet
1903 (:back-end ,back-end
1904 :value ,value
1905 :begin ,begin
1906 :end ,end
1907 :post-blank ,post-blank)))))
1909 (defun org-element-export-snippet-interpreter (export-snippet contents)
1910 "Interpret EXPORT-SNIPPET object as Org syntax.
1911 CONTENTS is nil."
1912 (format "<%s@%s>"
1913 (org-element-property :back-end export-snippet)
1914 (org-element-property :value export-snippet)))
1916 (defun org-element-export-snippet-successor (limit)
1917 "Search for the next export-snippet object.
1919 LIMIT bounds the search.
1921 Return value is a cons cell whose CAR is `export-snippet' CDR is
1922 its beginning position."
1923 (save-excursion
1924 (catch 'exit
1925 (while (re-search-forward "<[-A-Za-z0-9]+@" limit t)
1926 (save-excursion
1927 (let ((beg (match-beginning 0))
1928 (count 1))
1929 (while (re-search-forward "[<>]" limit t)
1930 (if (equal (match-string 0) "<") (incf count) (decf count))
1931 (when (zerop count)
1932 (throw 'exit (cons 'export-snippet beg))))))))))
1935 ;;;; Footnote Reference
1937 (defun org-element-footnote-reference-parser ()
1938 "Parse footnote reference at point.
1940 Return a list whose CAR is `footnote-reference' and CDR a plist
1941 with `:label', `:type', `:inline-definition', `:begin', `:end'
1942 and `:post-blank' as keywords."
1943 (save-excursion
1944 (looking-at org-footnote-re)
1945 (let* ((begin (point))
1946 (label (or (org-match-string-no-properties 2)
1947 (org-match-string-no-properties 3)
1948 (and (match-string 1)
1949 (concat "fn:" (org-match-string-no-properties 1)))))
1950 (type (if (or (not label) (match-string 1)) 'inline 'standard))
1951 (inner-begin (match-end 0))
1952 (inner-end
1953 (let ((count 1))
1954 (forward-char)
1955 (while (and (> count 0) (re-search-forward "[][]" nil t))
1956 (if (equal (match-string 0) "[") (incf count) (decf count)))
1957 (1- (point))))
1958 (post-blank (progn (goto-char (1+ inner-end))
1959 (skip-chars-forward " \t")))
1960 (end (point))
1961 (inline-definition
1962 (and (eq type 'inline)
1963 (org-element-parse-secondary-string
1964 (buffer-substring inner-begin inner-end)
1965 (org-element-restriction 'footnote-reference)))))
1966 `(footnote-reference
1967 (:label ,label
1968 :type ,type
1969 :inline-definition ,inline-definition
1970 :begin ,begin
1971 :end ,end
1972 :post-blank ,post-blank)))))
1974 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1975 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1976 CONTENTS is nil."
1977 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
1978 (def
1979 (let ((inline-def
1980 (org-element-property :inline-definition footnote-reference)))
1981 (if (not inline-def) ""
1982 (concat ":" (org-element-interpret-data inline-def))))))
1983 (format "[%s]" (concat label def))))
1985 (defun org-element-footnote-reference-successor (limit)
1986 "Search for the next footnote-reference object.
1988 LIMIT bounds the search.
1990 Return value is a cons cell whose CAR is `footnote-reference' and
1991 CDR is beginning position."
1992 (save-excursion
1993 (catch 'exit
1994 (while (re-search-forward org-footnote-re limit t)
1995 (save-excursion
1996 (let ((beg (match-beginning 0))
1997 (count 1))
1998 (backward-char)
1999 (while (re-search-forward "[][]" limit t)
2000 (if (equal (match-string 0) "[") (incf count) (decf count))
2001 (when (zerop count)
2002 (throw 'exit (cons 'footnote-reference beg))))))))))
2005 ;;;; Inline Babel Call
2007 (defun org-element-inline-babel-call-parser ()
2008 "Parse inline babel call at point.
2010 Return a list whose CAR is `inline-babel-call' and CDR a plist
2011 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2013 Assume point is at the beginning of the babel call."
2014 (save-excursion
2015 (unless (bolp) (backward-char))
2016 (looking-at org-babel-inline-lob-one-liner-regexp)
2017 (let ((info (save-match-data (org-babel-lob-get-info)))
2018 (begin (match-end 1))
2019 (post-blank (progn (goto-char (match-end 0))
2020 (skip-chars-forward " \t")))
2021 (end (point)))
2022 `(inline-babel-call
2023 (:begin ,begin
2024 :end ,end
2025 :info ,info
2026 :post-blank ,post-blank)))))
2028 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2029 "Interpret INLINE-BABEL-CALL object as Org syntax.
2030 CONTENTS is nil."
2031 (let* ((babel-info (org-element-property :info inline-babel-call))
2032 (main-source (car babel-info))
2033 (post-options (nth 1 babel-info)))
2034 (concat "call_"
2035 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2036 ;; Remove redundant square brackets.
2037 (replace-match
2038 (match-string 1 main-source) nil nil main-source)
2039 main-source)
2040 (and post-options (format "[%s]" post-options)))))
2042 (defun org-element-inline-babel-call-successor (limit)
2043 "Search for the next inline-babel-call object.
2045 LIMIT bounds the search.
2047 Return value is a cons cell whose CAR is `inline-babel-call' and
2048 CDR is beginning position."
2049 (save-excursion
2050 ;; Use a simplified version of
2051 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
2052 (when (re-search-forward
2053 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
2054 limit t)
2055 (cons 'inline-babel-call (match-beginning 0)))))
2058 ;;;; Inline Src Block
2060 (defun org-element-inline-src-block-parser ()
2061 "Parse inline source block at point.
2063 Return a list whose CAR is `inline-src-block' and CDR a plist
2064 with `:begin', `:end', `:language', `:value', `:parameters' and
2065 `:post-blank' as keywords.
2067 Assume point is at the beginning of the inline src block."
2068 (save-excursion
2069 (unless (bolp) (backward-char))
2070 (looking-at org-babel-inline-src-block-regexp)
2071 (let ((begin (match-beginning 1))
2072 (language (org-match-string-no-properties 2))
2073 (parameters (org-match-string-no-properties 4))
2074 (value (org-match-string-no-properties 5))
2075 (post-blank (progn (goto-char (match-end 0))
2076 (skip-chars-forward " \t")))
2077 (end (point)))
2078 `(inline-src-block
2079 (:language ,language
2080 :value ,value
2081 :parameters ,parameters
2082 :begin ,begin
2083 :end ,end
2084 :post-blank ,post-blank)))))
2086 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2087 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2088 CONTENTS is nil."
2089 (let ((language (org-element-property :language inline-src-block))
2090 (arguments (org-element-property :parameters inline-src-block))
2091 (body (org-element-property :value inline-src-block)))
2092 (format "src_%s%s{%s}"
2093 language
2094 (if arguments (format "[%s]" arguments) "")
2095 body)))
2097 (defun org-element-inline-src-block-successor (limit)
2098 "Search for the next inline-babel-call element.
2100 LIMIT bounds the search.
2102 Return value is a cons cell whose CAR is `inline-babel-call' and
2103 CDR is beginning position."
2104 (save-excursion
2105 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
2106 (cons 'inline-src-block (match-beginning 1)))))
2108 ;;;; Italic
2110 (defun org-element-italic-parser ()
2111 "Parse italic object at point.
2113 Return a list whose CAR is `italic' and CDR is a plist with
2114 `:begin', `:end', `:contents-begin' and `:contents-end' and
2115 `:post-blank' keywords.
2117 Assume point is at the first slash marker."
2118 (save-excursion
2119 (unless (bolp) (backward-char 1))
2120 (looking-at org-emph-re)
2121 (let ((begin (match-beginning 2))
2122 (contents-begin (match-beginning 4))
2123 (contents-end (match-end 4))
2124 (post-blank (progn (goto-char (match-end 2))
2125 (skip-chars-forward " \t")))
2126 (end (point)))
2127 `(italic
2128 (:begin ,begin
2129 :end ,end
2130 :contents-begin ,contents-begin
2131 :contents-end ,contents-end
2132 :post-blank ,post-blank)))))
2134 (defun org-element-italic-interpreter (italic contents)
2135 "Interpret ITALIC object as Org syntax.
2136 CONTENTS is the contents of the object."
2137 (format "/%s/" contents))
2140 ;;;; Latex Fragment
2142 (defun org-element-latex-fragment-parser ()
2143 "Parse latex fragment at point.
2145 Return a list whose CAR is `latex-fragment' and CDR a plist with
2146 `:value', `:begin', `:end', and `:post-blank' as keywords.
2148 Assume point is at the beginning of the latex fragment."
2149 (save-excursion
2150 (let* ((begin (point))
2151 (substring-match
2152 (catch 'exit
2153 (mapc (lambda (e)
2154 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2155 (when (or (looking-at latex-regexp)
2156 (and (not (bobp))
2157 (save-excursion
2158 (backward-char)
2159 (looking-at latex-regexp))))
2160 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2161 (plist-get org-format-latex-options :matchers))
2162 ;; None found: it's a macro.
2163 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2165 (value (match-string-no-properties substring-match))
2166 (post-blank (progn (goto-char (match-end substring-match))
2167 (skip-chars-forward " \t")))
2168 (end (point)))
2169 `(latex-fragment
2170 (:value ,value
2171 :begin ,begin
2172 :end ,end
2173 :post-blank ,post-blank)))))
2175 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2176 "Interpret LATEX-FRAGMENT object as Org syntax.
2177 CONTENTS is nil."
2178 (org-element-property :value latex-fragment))
2180 ;;;; Line Break
2182 (defun org-element-line-break-parser ()
2183 "Parse line break at point.
2185 Return a list whose CAR is `line-break', and CDR a plist with
2186 `:begin', `:end' and `:post-blank' keywords.
2188 Assume point is at the beginning of the line break."
2189 (let ((begin (point))
2190 (end (save-excursion (forward-line) (point))))
2191 `(line-break (:begin ,begin :end ,end :post-blank 0))))
2193 (defun org-element-line-break-interpreter (line-break contents)
2194 "Interpret LINE-BREAK object as Org syntax.
2195 CONTENTS is nil."
2196 "\\\\\n")
2198 (defun org-element-line-break-successor (limit)
2199 "Search for the next line-break object.
2201 LIMIT bounds the search.
2203 Return value is a cons cell whose CAR is `line-break' and CDR is
2204 beginning position."
2205 (save-excursion
2206 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2207 (goto-char (match-beginning 1)))))
2208 ;; A line break can only happen on a non-empty line.
2209 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2210 (cons 'line-break beg)))))
2213 ;;;; Link
2215 (defun org-element-link-parser ()
2216 "Parse link at point.
2218 Return a list whose CAR is `link' and CDR a plist with `:type',
2219 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
2220 `:contents-end' and `:post-blank' as keywords.
2222 Assume point is at the beginning of the link."
2223 (save-excursion
2224 (let ((begin (point))
2225 end contents-begin contents-end link-end post-blank path type
2226 raw-link link)
2227 (cond
2228 ;; Type 1: Text targeted from a radio target.
2229 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2230 (setq type "radio"
2231 link-end (match-end 0)
2232 path (org-match-string-no-properties 0)))
2233 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2234 ((looking-at org-bracket-link-regexp)
2235 (setq contents-begin (match-beginning 3)
2236 contents-end (match-end 3)
2237 link-end (match-end 0)
2238 ;; RAW-LINK is the original link.
2239 raw-link (org-match-string-no-properties 1)
2240 link (org-translate-link
2241 (org-link-expand-abbrev
2242 (org-link-unescape raw-link))))
2243 ;; Determine TYPE of link and set PATH accordingly.
2244 (cond
2245 ;; File type.
2246 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2247 (setq type "file" path link))
2248 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2249 ((string-match org-link-re-with-space3 link)
2250 (setq type (match-string 1 link) path (match-string 2 link)))
2251 ;; Id type: PATH is the id.
2252 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2253 (setq type "id" path (match-string 1 link)))
2254 ;; Code-ref type: PATH is the name of the reference.
2255 ((string-match "^(\\(.*\\))$" link)
2256 (setq type "coderef" path (match-string 1 link)))
2257 ;; Custom-id type: PATH is the name of the custom id.
2258 ((= (aref link 0) ?#)
2259 (setq type "custom-id" path (substring link 1)))
2260 ;; Fuzzy type: Internal link either matches a target, an
2261 ;; headline name or nothing. PATH is the target or
2262 ;; headline's name.
2263 (t (setq type "fuzzy" path link))))
2264 ;; Type 3: Plain link, i.e. http://orgmode.org
2265 ((looking-at org-plain-link-re)
2266 (setq raw-link (org-match-string-no-properties 0)
2267 type (org-match-string-no-properties 1)
2268 path (org-match-string-no-properties 2)
2269 link-end (match-end 0)))
2270 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2271 ((looking-at org-angle-link-re)
2272 (setq raw-link (buffer-substring-no-properties
2273 (match-beginning 1) (match-end 2))
2274 type (org-match-string-no-properties 1)
2275 path (org-match-string-no-properties 2)
2276 link-end (match-end 0))))
2277 ;; In any case, deduce end point after trailing white space from
2278 ;; LINK-END variable.
2279 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2280 end (point))
2281 `(link
2282 (:type ,type
2283 :path ,path
2284 :raw-link ,(or raw-link path)
2285 :begin ,begin
2286 :end ,end
2287 :contents-begin ,contents-begin
2288 :contents-end ,contents-end
2289 :post-blank ,post-blank)))))
2291 (defun org-element-link-interpreter (link contents)
2292 "Interpret LINK object as Org syntax.
2293 CONTENTS is the contents of the object, or nil."
2294 (let ((type (org-element-property :type link))
2295 (raw-link (org-element-property :raw-link link)))
2296 (if (string= type "radio") raw-link
2297 (format "[[%s]%s]"
2298 raw-link
2299 (if contents (format "[%s]" contents) "")))))
2301 (defun org-element-link-successor (limit)
2302 "Search for the next link object.
2304 LIMIT bounds the search.
2306 Return value is a cons cell whose CAR is `link' and CDR is
2307 beginning position."
2308 (save-excursion
2309 (let ((link-regexp
2310 (if (not org-target-link-regexp) org-any-link-re
2311 (concat org-any-link-re "\\|" org-target-link-regexp))))
2312 (when (re-search-forward link-regexp limit t)
2313 (cons 'link (match-beginning 0))))))
2316 ;;;; Macro
2318 (defun org-element-macro-parser ()
2319 "Parse macro at point.
2321 Return a list whose CAR is `macro' and CDR a plist with `:key',
2322 `:args', `:begin', `:end', `:value' and `:post-blank' as
2323 keywords.
2325 Assume point is at the macro."
2326 (save-excursion
2327 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2328 (let ((begin (point))
2329 (key (downcase (org-match-string-no-properties 1)))
2330 (value (org-match-string-no-properties 0))
2331 (post-blank (progn (goto-char (match-end 0))
2332 (skip-chars-forward " \t")))
2333 (end (point))
2334 (args (let ((args (org-match-string-no-properties 3)) args2)
2335 (when args
2336 (setq args (org-split-string args ","))
2337 (while args
2338 (while (string-match "\\\\\\'" (car args))
2339 ;; Repair bad splits.
2340 (setcar (cdr args) (concat (substring (car args) 0 -1)
2341 "," (nth 1 args)))
2342 (pop args))
2343 (push (pop args) args2))
2344 (mapcar 'org-trim (nreverse args2))))))
2345 `(macro
2346 (:key ,key
2347 :value ,value
2348 :args ,args
2349 :begin ,begin
2350 :end ,end
2351 :post-blank ,post-blank)))))
2353 (defun org-element-macro-interpreter (macro contents)
2354 "Interpret MACRO object as Org syntax.
2355 CONTENTS is nil."
2356 (org-element-property :value macro))
2358 (defun org-element-macro-successor (limit)
2359 "Search for the next macro object.
2361 LIMIT bounds the search.
2363 Return value is cons cell whose CAR is `macro' and CDR is
2364 beginning position."
2365 (save-excursion
2366 (when (re-search-forward
2367 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2368 limit t)
2369 (cons 'macro (match-beginning 0)))))
2372 ;;;; Radio-target
2374 (defun org-element-radio-target-parser ()
2375 "Parse radio target at point.
2377 Return a list whose CAR is `radio-target' and CDR a plist with
2378 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2379 and `:post-blank' as keywords.
2381 Assume point is at the radio target."
2382 (save-excursion
2383 (looking-at org-radio-target-regexp)
2384 (let ((begin (point))
2385 (contents-begin (match-beginning 1))
2386 (contents-end (match-end 1))
2387 (value (org-match-string-no-properties 1))
2388 (post-blank (progn (goto-char (match-end 0))
2389 (skip-chars-forward " \t")))
2390 (end (point)))
2391 `(radio-target
2392 (:begin ,begin
2393 :end ,end
2394 :contents-begin ,contents-begin
2395 :contents-end ,contents-end
2396 :post-blank ,post-blank
2397 :value ,value)))))
2399 (defun org-element-radio-target-interpreter (target contents)
2400 "Interpret TARGET object as Org syntax.
2401 CONTENTS is the contents of the object."
2402 (concat "<<<" contents ">>>"))
2404 (defun org-element-radio-target-successor (limit)
2405 "Search for the next radio-target object.
2407 LIMIT bounds the search.
2409 Return value is a cons cell whose CAR is `radio-target' and CDR
2410 is beginning position."
2411 (save-excursion
2412 (when (re-search-forward org-radio-target-regexp limit t)
2413 (cons 'radio-target (match-beginning 0)))))
2416 ;;;; Statistics Cookie
2418 (defun org-element-statistics-cookie-parser ()
2419 "Parse statistics cookie at point.
2421 Return a list whose CAR is `statistics-cookie', and CDR a plist
2422 with `:begin', `:end', `:value' and `:post-blank' keywords.
2424 Assume point is at the beginning of the statistics-cookie."
2425 (save-excursion
2426 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2427 (let* ((begin (point))
2428 (value (buffer-substring-no-properties
2429 (match-beginning 0) (match-end 0)))
2430 (post-blank (progn (goto-char (match-end 0))
2431 (skip-chars-forward " \t")))
2432 (end (point)))
2433 `(statistics-cookie
2434 (:begin ,begin
2435 :end ,end
2436 :value ,value
2437 :post-blank ,post-blank)))))
2439 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2440 "Interpret STATISTICS-COOKIE object as Org syntax.
2441 CONTENTS is nil."
2442 (org-element-property :value statistics-cookie))
2444 (defun org-element-statistics-cookie-successor (limit)
2445 "Search for the next statistics cookie object.
2447 LIMIT bounds the search.
2449 Return value is a cons cell whose CAR is `statistics-cookie' and
2450 CDR is beginning position."
2451 (save-excursion
2452 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2453 (cons 'statistics-cookie (match-beginning 0)))))
2456 ;;;; Strike-Through
2458 (defun org-element-strike-through-parser ()
2459 "Parse strike-through object at point.
2461 Return a list whose CAR is `strike-through' and CDR is a plist
2462 with `:begin', `:end', `:contents-begin' and `:contents-end' and
2463 `:post-blank' keywords.
2465 Assume point is at the first plus sign marker."
2466 (save-excursion
2467 (unless (bolp) (backward-char 1))
2468 (looking-at org-emph-re)
2469 (let ((begin (match-beginning 2))
2470 (contents-begin (match-beginning 4))
2471 (contents-end (match-end 4))
2472 (post-blank (progn (goto-char (match-end 2))
2473 (skip-chars-forward " \t")))
2474 (end (point)))
2475 `(strike-through
2476 (:begin ,begin
2477 :end ,end
2478 :contents-begin ,contents-begin
2479 :contents-end ,contents-end
2480 :post-blank ,post-blank)))))
2482 (defun org-element-strike-through-interpreter (strike-through contents)
2483 "Interpret STRIKE-THROUGH object as Org syntax.
2484 CONTENTS is the contents of the object."
2485 (format "+%s+" contents))
2488 ;;;; Subscript
2490 (defun org-element-subscript-parser ()
2491 "Parse subscript at point.
2493 Return a list whose CAR is `subscript' and CDR a plist with
2494 `:begin', `:end', `:contents-begin', `:contents-end',
2495 `:use-brackets-p' and `:post-blank' as keywords.
2497 Assume point is at the underscore."
2498 (save-excursion
2499 (unless (bolp) (backward-char))
2500 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2502 (not (looking-at org-match-substring-regexp))))
2503 (begin (match-beginning 2))
2504 (contents-begin (or (match-beginning 5)
2505 (match-beginning 3)))
2506 (contents-end (or (match-end 5) (match-end 3)))
2507 (post-blank (progn (goto-char (match-end 0))
2508 (skip-chars-forward " \t")))
2509 (end (point)))
2510 `(subscript
2511 (:begin ,begin
2512 :end ,end
2513 :use-brackets-p ,bracketsp
2514 :contents-begin ,contents-begin
2515 :contents-end ,contents-end
2516 :post-blank ,post-blank)))))
2518 (defun org-element-subscript-interpreter (subscript contents)
2519 "Interpret SUBSCRIPT object as Org syntax.
2520 CONTENTS is the contents of the object."
2521 (format
2522 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
2523 contents))
2525 (defun org-element-sub/superscript-successor (limit)
2526 "Search for the next sub/superscript object.
2528 LIMIT bounds the search.
2530 Return value is a cons cell whose CAR is either `subscript' or
2531 `superscript' and CDR is beginning position."
2532 (save-excursion
2533 (when (re-search-forward org-match-substring-regexp limit t)
2534 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2535 (match-beginning 2)))))
2538 ;;;; Superscript
2540 (defun org-element-superscript-parser ()
2541 "Parse superscript at point.
2543 Return a list whose CAR is `superscript' and CDR a plist with
2544 `:begin', `:end', `:contents-begin', `:contents-end',
2545 `:use-brackets-p' and `:post-blank' as keywords.
2547 Assume point is at the caret."
2548 (save-excursion
2549 (unless (bolp) (backward-char))
2550 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
2551 (not (looking-at org-match-substring-regexp))))
2552 (begin (match-beginning 2))
2553 (contents-begin (or (match-beginning 5)
2554 (match-beginning 3)))
2555 (contents-end (or (match-end 5) (match-end 3)))
2556 (post-blank (progn (goto-char (match-end 0))
2557 (skip-chars-forward " \t")))
2558 (end (point)))
2559 `(superscript
2560 (:begin ,begin
2561 :end ,end
2562 :use-brackets-p ,bracketsp
2563 :contents-begin ,contents-begin
2564 :contents-end ,contents-end
2565 :post-blank ,post-blank)))))
2567 (defun org-element-superscript-interpreter (superscript contents)
2568 "Interpret SUPERSCRIPT object as Org syntax.
2569 CONTENTS is the contents of the object."
2570 (format
2571 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
2572 contents))
2575 ;;;; Table Cell
2577 (defun org-element-table-cell-parser ()
2578 "Parse table cell at point.
2580 Return a list whose CAR is `table-cell' and CDR is a plist
2581 containing `:begin', `:end', `:contents-begin', `:contents-end'
2582 and `:post-blank' keywords."
2583 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
2584 (let* ((begin (match-beginning 0))
2585 (end (match-end 0))
2586 (contents-begin (match-beginning 1))
2587 (contents-end (match-end 1)))
2588 `(table-cell
2589 (:begin ,begin
2590 :end ,end
2591 :contents-begin ,contents-begin
2592 :contents-end ,contents-end
2593 :post-blank 0))))
2595 (defun org-element-table-cell-interpreter (table-cell contents)
2596 "Interpret TABLE-CELL element as Org syntax.
2597 CONTENTS is the contents of the cell, or nil."
2598 (concat " " contents " |"))
2600 (defun org-element-table-cell-successor (limit)
2601 "Search for the next table-cell object.
2603 LIMIT bounds the search.
2605 Return value is a cons cell whose CAR is `table-cell' and CDR is
2606 beginning position."
2607 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
2610 ;;;; Target
2612 (defun org-element-target-parser ()
2613 "Parse target at point.
2615 Return a list whose CAR is `target' and CDR a plist with
2616 `:begin', `:end', `:value' and `:post-blank' as keywords.
2618 Assume point is at the target."
2619 (save-excursion
2620 (looking-at org-target-regexp)
2621 (let ((begin (point))
2622 (value (org-match-string-no-properties 1))
2623 (post-blank (progn (goto-char (match-end 0))
2624 (skip-chars-forward " \t")))
2625 (end (point)))
2626 `(target
2627 (:begin ,begin
2628 :end ,end
2629 :value ,value
2630 :post-blank ,post-blank)))))
2632 (defun org-element-target-interpreter (target contents)
2633 "Interpret TARGET object as Org syntax.
2634 CONTENTS is nil."
2635 (format "<<%s>>" (org-element-property :value target)))
2637 (defun org-element-target-successor (limit)
2638 "Search for the next target object.
2640 LIMIT bounds the search.
2642 Return value is a cons cell whose CAR is `target' and CDR is
2643 beginning position."
2644 (save-excursion
2645 (when (re-search-forward org-target-regexp limit t)
2646 (cons 'target (match-beginning 0)))))
2649 ;;;; Timestamp
2651 (defun org-element-timestamp-parser ()
2652 "Parse time stamp at point.
2654 Return a list whose CAR is `timestamp', and CDR a plist with
2655 `:type', `:begin', `:end', `:value' and `:post-blank' keywords.
2657 Assume point is at the beginning of the timestamp."
2658 (save-excursion
2659 (let* ((begin (point))
2660 (type (cond
2661 ((looking-at org-tsr-regexp)
2662 (if (match-string 2) 'active-range 'active))
2663 ((looking-at org-tsr-regexp-both)
2664 (if (match-string 2) 'inactive-range 'inactive))
2665 ((looking-at
2666 (concat
2667 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2668 "\\|"
2669 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2670 'diary)))
2671 (value (org-match-string-no-properties 0))
2672 (post-blank (progn (goto-char (match-end 0))
2673 (skip-chars-forward " \t")))
2674 (end (point)))
2675 `(timestamp
2676 (:type ,type
2677 :value ,value
2678 :begin ,begin
2679 :end ,end
2680 :post-blank ,post-blank)))))
2682 (defun org-element-timestamp-interpreter (timestamp contents)
2683 "Interpret TIMESTAMP object as Org syntax.
2684 CONTENTS is nil."
2685 (org-element-property :value timestamp))
2687 (defun org-element-timestamp-successor (limit)
2688 "Search for the next timestamp object.
2690 LIMIT bounds the search.
2692 Return value is a cons cell whose CAR is `timestamp' and CDR is
2693 beginning position."
2694 (save-excursion
2695 (when (re-search-forward
2696 (concat org-ts-regexp-both
2697 "\\|"
2698 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2699 "\\|"
2700 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2701 limit t)
2702 (cons 'timestamp (match-beginning 0)))))
2705 ;;;; Underline
2707 (defun org-element-underline-parser ()
2708 "Parse underline object at point.
2710 Return a list whose CAR is `underline' and CDR is a plist with
2711 `:begin', `:end', `:contents-begin' and `:contents-end' and
2712 `:post-blank' keywords.
2714 Assume point is at the first underscore marker."
2715 (save-excursion
2716 (unless (bolp) (backward-char 1))
2717 (looking-at org-emph-re)
2718 (let ((begin (match-beginning 2))
2719 (contents-begin (match-beginning 4))
2720 (contents-end (match-end 4))
2721 (post-blank (progn (goto-char (match-end 2))
2722 (skip-chars-forward " \t")))
2723 (end (point)))
2724 `(underline
2725 (:begin ,begin
2726 :end ,end
2727 :contents-begin ,contents-begin
2728 :contents-end ,contents-end
2729 :post-blank ,post-blank)))))
2731 (defun org-element-underline-interpreter (underline contents)
2732 "Interpret UNDERLINE object as Org syntax.
2733 CONTENTS is the contents of the object."
2734 (format "_%s_" contents))
2737 ;;;; Verbatim
2739 (defun org-element-verbatim-parser ()
2740 "Parse verbatim object at point.
2742 Return a list whose CAR is `verbatim' and CDR is a plist with
2743 `:value', `:begin', `:end' and `:post-blank' keywords.
2745 Assume point is at the first equal sign marker."
2746 (save-excursion
2747 (unless (bolp) (backward-char 1))
2748 (looking-at org-emph-re)
2749 (let ((begin (match-beginning 2))
2750 (value (org-match-string-no-properties 4))
2751 (post-blank (progn (goto-char (match-end 2))
2752 (skip-chars-forward " \t")))
2753 (end (point)))
2754 `(verbatim
2755 (:value ,value
2756 :begin ,begin
2757 :end ,end
2758 :post-blank ,post-blank)))))
2760 (defun org-element-verbatim-interpreter (verbatim contents)
2761 "Interpret VERBATIM object as Org syntax.
2762 CONTENTS is nil."
2763 (format "=%s=" (org-element-property :value verbatim)))
2767 ;;; Definitions And Rules
2769 ;; Define elements, greater elements and specify recursive objects,
2770 ;; along with the affiliated keywords recognized. Also set up
2771 ;; restrictions on recursive objects combinations.
2773 ;; These variables really act as a control center for the parsing
2774 ;; process.
2775 (defconst org-element-paragraph-separate
2776 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2777 ;; Headlines and inlinetasks.
2778 org-outline-regexp-bol "\\|"
2779 ;; Comments, blocks (any type), keywords and babel calls.
2780 "^[ \t]*#\\+" "\\|" "^#\\(?: \\|$\\)" "\\|"
2781 ;; Lists.
2782 (org-item-beginning-re) "\\|"
2783 ;; Fixed-width, drawers (any type) and tables.
2784 "^[ \t]*[:|]" "\\|"
2785 ;; Footnote definitions.
2786 org-footnote-definition-re "\\|"
2787 ;; Horizontal rules.
2788 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2789 ;; LaTeX environments.
2790 "^[ \t]*\\\\\\(begin\\|end\\)"
2791 ;; Planning and Clock lines.
2792 "^[ \t]*\\(?:"
2793 org-clock-string "\\|"
2794 org-closed-string "\\|"
2795 org-deadline-string "\\|"
2796 org-scheduled-string "\\)")
2797 "Regexp to separate paragraphs in an Org buffer.")
2799 (defconst org-element-all-elements
2800 '(center-block clock comment comment-block drawer dynamic-block example-block
2801 export-block fixed-width footnote-definition headline
2802 horizontal-rule inlinetask item keyword latex-environment
2803 babel-call paragraph plain-list planning property-drawer
2804 quote-block quote-section section special-block src-block table
2805 table-row verse-block)
2806 "Complete list of element types.")
2808 (defconst org-element-greater-elements
2809 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2810 item plain-list quote-block section special-block table)
2811 "List of recursive element types aka Greater Elements.")
2813 (defconst org-element-all-successors
2814 '(export-snippet footnote-reference inline-babel-call inline-src-block
2815 latex-or-entity line-break link macro radio-target
2816 statistics-cookie sub/superscript table-cell target
2817 text-markup timestamp)
2818 "Complete list of successors.")
2820 (defconst org-element-object-successor-alist
2821 '((subscript . sub/superscript) (superscript . sub/superscript)
2822 (bold . text-markup) (code . text-markup) (italic . text-markup)
2823 (strike-through . text-markup) (underline . text-markup)
2824 (verbatim . text-markup) (entity . latex-or-entity)
2825 (latex-fragment . latex-or-entity))
2826 "Alist of translations between object type and successor name.
2828 Sharing the same successor comes handy when, for example, the
2829 regexp matching one object can also match the other object.")
2831 (defconst org-element-all-objects
2832 '(bold code entity export-snippet footnote-reference inline-babel-call
2833 inline-src-block italic line-break latex-fragment link macro
2834 radio-target statistics-cookie strike-through subscript superscript
2835 table-cell target timestamp underline verbatim)
2836 "Complete list of object types.")
2838 (defconst org-element-recursive-objects
2839 '(bold italic link macro subscript radio-target strike-through superscript
2840 table-cell underline)
2841 "List of recursive object types.")
2843 (defconst org-element-block-name-alist
2844 '(("ASCII" . export-block)
2845 ("CENTER" . center-block)
2846 ("COMMENT" . comment-block)
2847 ("DOCBOOK" . export-block)
2848 ("EXAMPLE" . example-block)
2849 ("HTML" . export-block)
2850 ("LATEX" . export-block)
2851 ("ODT" . export-block)
2852 ("QUOTE" . quote-block)
2853 ("SRC" . src-block)
2854 ("VERSE" . verse-block))
2855 "Alist between block names and their element type.
2856 Any block whose name has no association in the current list has
2857 a `special-block' type.")
2859 (defconst org-element-affiliated-keywords
2860 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "CAPTION"
2861 "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT" "RESULTS"
2862 "SOURCE" "SRCNAME" "TBLNAME")
2863 "List of affiliated keywords as strings.")
2865 (defconst org-element-keyword-translation-alist
2866 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
2867 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
2868 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
2869 "Alist of usual translations for keywords.
2870 The key is the old name and the value the new one. The property
2871 holding their value will be named after the translated name.")
2873 (defconst org-element-multiple-keywords
2874 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "HEADER")
2875 "List of affiliated keywords that can occur more that once in an element.
2877 Their value will be consed into a list of strings, which will be
2878 returned as the value of the property.
2880 This list is checked after translations have been applied. See
2881 `org-element-keyword-translation-alist'.")
2883 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "TITLE")
2884 "List of keywords whose value can be parsed.
2886 Their value will be stored as a secondary string: a list of
2887 strings and objects.
2889 This list is checked after translations have been applied. See
2890 `org-element-keyword-translation-alist'.")
2892 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
2893 "List of keywords which can have a secondary value.
2895 In Org syntax, they can be written with optional square brackets
2896 before the colons. For example, results keyword can be
2897 associated to a hash value with the following:
2899 #+RESULTS[hash-string]: some-source
2901 This list is checked after translations have been applied. See
2902 `org-element-keyword-translation-alist'.")
2904 (defconst org-element-object-restrictions
2905 `((bold entity export-snippet inline-babel-call inline-src-block link
2906 radio-target sub/superscript target text-markup timestamp)
2907 (footnote-reference entity export-snippet footnote-reference
2908 inline-babel-call inline-src-block latex-fragment
2909 line-break link macro radio-target sub/superscript
2910 target text-markup timestamp)
2911 (headline entity inline-babel-call inline-src-block latex-fragment link
2912 macro radio-target statistics-cookie sub/superscript text-markup
2913 timestamp)
2914 (inlinetask entity inline-babel-call inline-src-block latex-fragment link
2915 macro radio-target sub/superscript text-markup timestamp)
2916 (italic entity export-snippet inline-babel-call inline-src-block link
2917 radio-target sub/superscript target text-markup timestamp)
2918 (item entity inline-babel-call latex-fragment macro radio-target
2919 sub/superscript target text-markup)
2920 (keyword entity latex-fragment macro sub/superscript text-markup)
2921 (link entity export-snippet inline-babel-call inline-src-block
2922 latex-fragment link sub/superscript text-markup)
2923 (macro macro)
2924 (paragraph ,@org-element-all-successors)
2925 (radio-target entity export-snippet latex-fragment sub/superscript)
2926 (strike-through entity export-snippet inline-babel-call inline-src-block
2927 link radio-target sub/superscript target text-markup
2928 timestamp)
2929 (subscript entity export-snippet inline-babel-call inline-src-block
2930 latex-fragment sub/superscript text-markup)
2931 (superscript entity export-snippet inline-babel-call inline-src-block
2932 latex-fragment sub/superscript text-markup)
2933 (table-cell entity export-snippet latex-fragment link macro radio-target
2934 sub/superscript target text-markup timestamp)
2935 (table-row table-cell)
2936 (underline entity export-snippet inline-babel-call inline-src-block link
2937 radio-target sub/superscript target text-markup timestamp)
2938 (verse-block entity footnote-reference inline-babel-call inline-src-block
2939 latex-fragment line-break link macro radio-target
2940 sub/superscript target text-markup timestamp))
2941 "Alist of objects restrictions.
2943 CAR is an element or object type containing objects and CDR is
2944 a list of successors that will be called within an element or
2945 object of such type.
2947 For example, in a `radio-target' object, one can only find
2948 entities, export snippets, latex-fragments, subscript and
2949 superscript.
2951 This alist also applies to secondary string. For example, an
2952 `headline' type element doesn't directly contain objects, but
2953 still has an entry since one of its properties (`:title') does.")
2955 (defconst org-element-secondary-value-alist
2956 '((headline . :title)
2957 (inlinetask . :title)
2958 (item . :tag)
2959 (footnote-reference . :inline-definition))
2960 "Alist between element types and location of secondary value.")
2964 ;;; Accessors
2966 ;; Provide four accessors: `org-element-type', `org-element-property'
2967 ;; `org-element-contents' and `org-element-restriction'.
2969 (defun org-element-type (element)
2970 "Return type of element ELEMENT.
2972 The function returns the type of the element or object provided.
2973 It can also return the following special value:
2974 `plain-text' for a string
2975 `org-data' for a complete document
2976 nil in any other case."
2977 (cond
2978 ((not (consp element)) (and (stringp element) 'plain-text))
2979 ((symbolp (car element)) (car element))))
2981 (defun org-element-property (property element)
2982 "Extract the value from the PROPERTY of an ELEMENT."
2983 (plist-get (nth 1 element) property))
2985 (defun org-element-contents (element)
2986 "Extract contents from an ELEMENT."
2987 (and (consp element) (nthcdr 2 element)))
2989 (defun org-element-restriction (element)
2990 "Return restriction associated to ELEMENT.
2991 ELEMENT can be an element, an object or a symbol representing an
2992 element or object type."
2993 (cdr (assq (if (symbolp element) element (org-element-type element))
2994 org-element-object-restrictions)))
2998 ;;; Parsing Element Starting At Point
3000 ;; `org-element-current-element' is the core function of this section.
3001 ;; It returns the Lisp representation of the element starting at
3002 ;; point.
3004 ;; `org-element-current-element' makes use of special modes. They are
3005 ;; activated for fixed element chaining (i.e. `plain-list' > `item')
3006 ;; or fixed conditional element chaining (i.e. `headline' >
3007 ;; `section'). Special modes are: `section', `quote-section', `item'
3008 ;; and `table-row'.
3010 (defun org-element-current-element (&optional granularity special structure)
3011 "Parse the element starting at point.
3013 Return value is a list like (TYPE PROPS) where TYPE is the type
3014 of the element and PROPS a plist of properties associated to the
3015 element.
3017 Possible types are defined in `org-element-all-elements'.
3019 Optional argument GRANULARITY determines the depth of the
3020 recursion. Allowed values are `headline', `greater-element',
3021 `element', `object' or nil. When it is broader than `object' (or
3022 nil), secondary values will not be parsed, since they only
3023 contain objects.
3025 Optional argument SPECIAL, when non-nil, can be either `section',
3026 `quote-section', `table-row' and `item'.
3028 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3029 be computed.
3031 This function assumes point is always at the beginning of the
3032 element it has to parse."
3033 (save-excursion
3034 ;; If point is at an affiliated keyword, try moving to the
3035 ;; beginning of the associated element. If none is found, the
3036 ;; keyword is orphaned and will be treated as plain text.
3037 (when (looking-at org-element--affiliated-re)
3038 (let ((opoint (point)))
3039 (while (looking-at org-element--affiliated-re) (forward-line))
3040 (when (looking-at "[ \t]*$") (goto-char opoint))))
3041 (let ((case-fold-search t)
3042 ;; Determine if parsing depth allows for secondary strings
3043 ;; parsing. It only applies to elements referenced in
3044 ;; `org-element-secondary-value-alist'.
3045 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3046 (cond
3047 ;; Item.
3048 ((eq special 'item)
3049 (org-element-item-parser (or structure (org-list-struct))
3050 raw-secondary-p))
3051 ;; Quote Section.
3052 ((eq special 'quote-section) (org-element-quote-section-parser))
3053 ;; Table Row.
3054 ((eq special 'table-row) (org-element-table-row-parser))
3055 ;; Headline.
3056 ((org-with-limited-levels (org-at-heading-p))
3057 (org-element-headline-parser raw-secondary-p))
3058 ;; Section (must be checked after headline).
3059 ((eq special 'section) (org-element-section-parser))
3060 ;; Planning and Clock.
3061 ((and (looking-at org-planning-or-clock-line-re))
3062 (if (equal (match-string 1) org-clock-string)
3063 (org-element-clock-parser)
3064 (org-element-planning-parser)))
3065 ;; Blocks.
3066 ((when (looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
3067 (let ((name (upcase (match-string 1))) type)
3068 (cond
3069 ((not (save-excursion
3070 (re-search-forward
3071 (format "^[ \t]*#\\+END_%s\\(?: \\|$\\)" name) nil t)))
3072 (org-element-paragraph-parser))
3073 ((setq type (assoc name org-element-block-name-alist))
3074 (funcall (intern (format "org-element-%s-parser" (cdr type)))))
3075 (t (org-element-special-block-parser))))))
3076 ;; Inlinetask.
3077 ((org-at-heading-p) (org-element-inlinetask-parser raw-secondary-p))
3078 ;; LaTeX Environment.
3079 ((looking-at "[ \t]*\\\\begin{")
3080 (if (save-excursion
3081 (re-search-forward "[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
3082 (org-element-latex-environment-parser)
3083 (org-element-paragraph-parser)))
3084 ;; Drawer and Property Drawer.
3085 ((looking-at org-drawer-regexp)
3086 (let ((name (match-string 1)))
3087 (cond
3088 ((not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t)))
3089 (org-element-paragraph-parser))
3090 ((equal "PROPERTIES" name) (org-element-property-drawer-parser))
3091 (t (org-element-drawer-parser)))))
3092 ;; Fixed Width
3093 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
3094 ;; Babel Call, Dynamic Block and Keyword.
3095 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
3096 (let ((key (upcase (match-string 1))))
3097 (cond
3098 ((equal key "CALL") (org-element-babel-call-parser))
3099 ((and (equal key "BEGIN")
3100 (save-excursion
3101 (re-search-forward "^[ \t]*#\\+END:\\(?: \\|$\\)" nil t)))
3102 (org-element-dynamic-block-parser))
3103 ((and (not (equal key "TBLFM"))
3104 (not (member key org-element-affiliated-keywords)))
3105 (org-element-keyword-parser))
3106 (t (org-element-paragraph-parser)))))
3107 ;; Footnote Definition.
3108 ((looking-at org-footnote-definition-re)
3109 (org-element-footnote-definition-parser))
3110 ;; Comment.
3111 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
3112 (org-element-comment-parser))
3113 ;; Horizontal Rule.
3114 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3115 (org-element-horizontal-rule-parser))
3116 ;; Table.
3117 ((org-at-table-p t) (org-element-table-parser))
3118 ;; List.
3119 ((looking-at (org-item-re))
3120 (org-element-plain-list-parser (or structure (org-list-struct))))
3121 ;; Default element: Paragraph.
3122 (t (org-element-paragraph-parser))))))
3125 ;; Most elements can have affiliated keywords. When looking for an
3126 ;; element beginning, we want to move before them, as they belong to
3127 ;; that element, and, in the meantime, collect information they give
3128 ;; into appropriate properties. Hence the following function.
3130 ;; Usage of optional arguments may not be obvious at first glance:
3132 ;; - TRANS-LIST is used to polish keywords names that have evolved
3133 ;; during Org history. In example, even though =result= and
3134 ;; =results= coexist, we want to have them under the same =result=
3135 ;; property. It's also true for "srcname" and "name", where the
3136 ;; latter seems to be preferred nowadays (thus the "name" property).
3138 ;; - CONSED allows to regroup multi-lines keywords under the same
3139 ;; property, while preserving their own identity. This is mostly
3140 ;; used for "attr_latex" and al.
3142 ;; - PARSED prepares a keyword value for export. This is useful for
3143 ;; "caption". Objects restrictions for such keywords are defined in
3144 ;; `org-element-object-restrictions'.
3146 ;; - DUALS is used to take care of keywords accepting a main and an
3147 ;; optional secondary values. For example "results" has its
3148 ;; source's name as the main value, and may have an hash string in
3149 ;; optional square brackets as the secondary one.
3151 ;; A keyword may belong to more than one category.
3153 (defconst org-element--affiliated-re
3154 (format "[ \t]*#\\+\\(%s\\):"
3155 (mapconcat
3156 (lambda (keyword)
3157 (if (member keyword org-element-dual-keywords)
3158 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
3159 (regexp-quote keyword))
3160 (regexp-quote keyword)))
3161 org-element-affiliated-keywords "\\|"))
3162 "Regexp matching any affiliated keyword.
3164 Keyword name is put in match group 1. Moreover, if keyword
3165 belongs to `org-element-dual-keywords', put the dual value in
3166 match group 2.
3168 Don't modify it, set `org-element-affiliated-keywords' instead.")
3170 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
3171 consed parsed duals)
3172 "Collect affiliated keywords before point.
3174 Optional argument KEY-RE is a regexp matching keywords, which
3175 puts matched keyword in group 1. It defaults to
3176 `org-element--affiliated-re'.
3178 TRANS-LIST is an alist where key is the keyword and value the
3179 property name it should be translated to, without the colons. It
3180 defaults to `org-element-keyword-translation-alist'.
3182 CONSED is a list of strings. Any keyword belonging to that list
3183 will have its value consed. The check is done after keyword
3184 translation. It defaults to `org-element-multiple-keywords'.
3186 PARSED is a list of strings. Any keyword member of this list
3187 will have its value parsed. The check is done after keyword
3188 translation. If a keyword is a member of both CONSED and PARSED,
3189 it's value will be a list of parsed strings. It defaults to
3190 `org-element-parsed-keywords'.
3192 DUALS is a list of strings. Any keyword member of this list can
3193 have two parts: one mandatory and one optional. Its value is
3194 a cons cell whose car is the former, and the cdr the latter. If
3195 a keyword is a member of both PARSED and DUALS, both values will
3196 be parsed. It defaults to `org-element-dual-keywords'.
3198 Return a list whose car is the position at the first of them and
3199 cdr a plist of keywords and values."
3200 (save-excursion
3201 (let ((case-fold-search t)
3202 (key-re (or key-re org-element--affiliated-re))
3203 (trans-list (or trans-list org-element-keyword-translation-alist))
3204 (consed (or consed org-element-multiple-keywords))
3205 (parsed (or parsed org-element-parsed-keywords))
3206 (duals (or duals org-element-dual-keywords))
3207 ;; RESTRICT is the list of objects allowed in parsed
3208 ;; keywords value.
3209 (restrict (org-element-restriction 'keyword))
3210 output)
3211 (unless (bobp)
3212 (while (and (not (bobp))
3213 (progn (forward-line -1) (looking-at key-re)))
3214 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3215 ;; Apply translation to RAW-KWD. From there, KWD is
3216 ;; the official keyword.
3217 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3218 ;; Find main value for any keyword.
3219 (value
3220 (save-match-data
3221 (org-trim
3222 (buffer-substring-no-properties
3223 (match-end 0) (point-at-eol)))))
3224 ;; If KWD is a dual keyword, find its secondary
3225 ;; value. Maybe parse it.
3226 (dual-value
3227 (and (member kwd duals)
3228 (let ((sec (org-match-string-no-properties 3)))
3229 (if (or (not sec) (not (member kwd parsed))) sec
3230 (org-element-parse-secondary-string sec restrict)))))
3231 ;; Attribute a property name to KWD.
3232 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3233 ;; Now set final shape for VALUE.
3234 (when (member kwd parsed)
3235 (setq value (org-element-parse-secondary-string value restrict)))
3236 (when (member kwd duals)
3237 ;; VALUE is mandatory. Set it to nil if there is none.
3238 (setq value (and value (cons value dual-value))))
3239 (when (member kwd consed)
3240 (setq value (cons value (plist-get output kwd-sym))))
3241 ;; Eventually store the new value in OUTPUT.
3242 (setq output (plist-put output kwd-sym value))))
3243 (unless (looking-at key-re) (forward-line 1)))
3244 (list (point) output))))
3248 ;;; The Org Parser
3250 ;; The two major functions here are `org-element-parse-buffer', which
3251 ;; parses Org syntax inside the current buffer, taking into account
3252 ;; region, narrowing, or even visibility if specified, and
3253 ;; `org-element-parse-secondary-string', which parses objects within
3254 ;; a given string.
3256 ;; The (almost) almighty `org-element-map' allows to apply a function
3257 ;; on elements or objects matching some type, and accumulate the
3258 ;; resulting values. In an export situation, it also skips unneeded
3259 ;; parts of the parse tree.
3261 (defun org-element-parse-buffer (&optional granularity visible-only)
3262 "Recursively parse the buffer and return structure.
3263 If narrowing is in effect, only parse the visible part of the
3264 buffer.
3266 Optional argument GRANULARITY determines the depth of the
3267 recursion. It can be set to the following symbols:
3269 `headline' Only parse headlines.
3270 `greater-element' Don't recurse into greater elements excepted
3271 headlines and sections. Thus, elements
3272 parsed are the top-level ones.
3273 `element' Parse everything but objects and plain text.
3274 `object' Parse the complete buffer (default).
3276 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3277 elements.
3279 Assume buffer is in Org mode."
3280 (save-excursion
3281 (goto-char (point-min))
3282 (org-skip-whitespace)
3283 (nconc (list 'org-data nil)
3284 (org-element-parse-elements
3285 (point-at-bol) (point-max)
3286 ;; Start in `section' mode so text before the first
3287 ;; headline belongs to a section.
3288 'section nil granularity visible-only nil))))
3290 (defun org-element-parse-secondary-string (string restriction)
3291 "Recursively parse objects in STRING and return structure.
3293 RESTRICTION, when non-nil, is a symbol limiting the object types
3294 that will be looked after."
3295 (with-temp-buffer
3296 (insert string)
3297 (org-element-parse-objects (point-min) (point-max) nil restriction)))
3299 (defun org-element-map (data types fun &optional info first-match no-recursion)
3300 "Map a function on selected elements or objects.
3302 DATA is the parsed tree, as returned by, i.e,
3303 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3304 of elements or objects types. FUN is the function called on the
3305 matching element or object. It must accept one arguments: the
3306 element or object itself.
3308 When optional argument INFO is non-nil, it should be a plist
3309 holding export options. In that case, parts of the parse tree
3310 not exportable according to that property list will be skipped.
3312 When optional argument FIRST-MATCH is non-nil, stop at the first
3313 match for which FUN doesn't return nil, and return that value.
3315 Optional argument NO-RECURSION is a symbol or a list of symbols
3316 representing elements or objects types. `org-element-map' won't
3317 enter any recursive element or object whose type belongs to that
3318 list. Though, FUN can still be applied on them.
3320 Nil values returned from FUN do not appear in the results."
3321 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3322 (unless (listp types) (setq types (list types)))
3323 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3324 ;; Recursion depth is determined by --CATEGORY.
3325 (let* ((--category
3326 (cond
3327 ((loop for type in types
3328 always (memq type org-element-greater-elements))
3329 'greater-elements)
3330 ((loop for type in types
3331 always (memq type org-element-all-elements))
3332 'elements)
3333 (t 'objects)))
3334 ;; --RESTRICTS is a list of element types whose secondary
3335 ;; string could possibly contain an object with a type among
3336 ;; TYPES.
3337 (--restricts
3338 (and (eq --category 'objects)
3339 (loop for el in org-element-secondary-value-alist
3340 when
3341 (loop for o in types
3342 thereis (memq o (org-element-restriction (car el))))
3343 collect (car el))))
3344 --acc
3345 (--walk-tree
3346 (function
3347 (lambda (--data)
3348 ;; Recursively walk DATA. INFO, if non-nil, is
3349 ;; a plist holding contextual information.
3350 (mapc
3351 (lambda (--blob)
3352 (unless (and info (member --blob (plist-get info :ignore-list)))
3353 (let ((--type (org-element-type --blob)))
3354 ;; Check if TYPE is matching among TYPES. If so,
3355 ;; apply FUN to --BLOB and accumulate return value
3356 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3357 (when (memq --type types)
3358 (let ((result (funcall fun --blob)))
3359 (cond ((not result))
3360 (first-match (throw 'first-match result))
3361 (t (push result --acc)))))
3362 ;; If --BLOB has a secondary string that can
3363 ;; contain objects with their type among TYPES,
3364 ;; look into that string.
3365 (when (memq --type --restricts)
3366 (funcall
3367 --walk-tree
3368 `(org-data
3370 ,@(org-element-property
3371 (cdr (assq --type org-element-secondary-value-alist))
3372 --blob))))
3373 ;; Now determine if a recursion into --BLOB is
3374 ;; possible. If so, do it.
3375 (unless (memq --type no-recursion)
3376 (when (or (and (memq --type org-element-greater-elements)
3377 (not (eq --category 'greater-elements)))
3378 (and (memq --type org-element-all-elements)
3379 (not (eq --category 'elements)))
3380 (org-element-contents --blob))
3381 (funcall --walk-tree --blob))))))
3382 (org-element-contents --data))))))
3383 (catch 'first-match
3384 (funcall --walk-tree data)
3385 ;; Return value in a proper order.
3386 (nreverse --acc))))
3388 ;; The following functions are internal parts of the parser.
3390 ;; The first one, `org-element-parse-elements' acts at the element's
3391 ;; level.
3393 ;; The second one, `org-element-parse-objects' applies on all objects
3394 ;; of a paragraph or a secondary string. It uses
3395 ;; `org-element-get-candidates' to optimize the search of the next
3396 ;; object in the buffer.
3398 ;; More precisely, that function looks for every allowed object type
3399 ;; first. Then, it discards failed searches, keeps further matches,
3400 ;; and searches again types matched behind point, for subsequent
3401 ;; calls. Thus, searching for a given type fails only once, and every
3402 ;; object is searched only once at top level (but sometimes more for
3403 ;; nested types).
3405 (defun org-element-parse-elements
3406 (beg end special structure granularity visible-only acc)
3407 "Parse elements between BEG and END positions.
3409 SPECIAL prioritize some elements over the others. It can be set
3410 to `quote-section', `section' `item' or `table-row'.
3412 When value is `item', STRUCTURE will be used as the current list
3413 structure.
3415 GRANULARITY determines the depth of the recursion. See
3416 `org-element-parse-buffer' for more information.
3418 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3419 elements.
3421 Elements are accumulated into ACC."
3422 (save-excursion
3423 (save-restriction
3424 (narrow-to-region beg end)
3425 (goto-char beg)
3426 ;; When parsing only headlines, skip any text before first one.
3427 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3428 (org-with-limited-levels (outline-next-heading)))
3429 ;; Main loop start.
3430 (while (not (eobp))
3431 (push
3432 ;; Find current element's type and parse it accordingly to
3433 ;; its category.
3434 (let* ((element (org-element-current-element
3435 granularity special structure))
3436 (type (org-element-type element))
3437 (cbeg (org-element-property :contents-begin element)))
3438 (goto-char (org-element-property :end element))
3439 (cond
3440 ;; Case 1. Simply accumulate element if VISIBLE-ONLY is
3441 ;; true and element is hidden or if it has no contents
3442 ;; anyway.
3443 ((or (and visible-only (org-element-property :hiddenp element))
3444 (not cbeg)) element)
3445 ;; Case 2. Greater element: parse it between
3446 ;; `contents-begin' and `contents-end'. Make sure
3447 ;; GRANULARITY allows the recursion, or ELEMENT is an
3448 ;; headline, in which case going inside is mandatory, in
3449 ;; order to get sub-level headings.
3450 ((and (memq type org-element-greater-elements)
3451 (or (memq granularity '(element object nil))
3452 (and (eq granularity 'greater-element)
3453 (eq type 'section))
3454 (eq type 'headline)))
3455 (org-element-parse-elements
3456 cbeg (org-element-property :contents-end element)
3457 ;; Possibly switch to a special mode.
3458 (case type
3459 (headline
3460 (if (org-element-property :quotedp element) 'quote-section
3461 'section))
3462 (plain-list 'item)
3463 (table 'table-row))
3464 (org-element-property :structure element)
3465 granularity visible-only (nreverse element)))
3466 ;; Case 3. ELEMENT has contents. Parse objects inside,
3467 ;; if GRANULARITY allows it.
3468 ((and cbeg (memq granularity '(object nil)))
3469 (org-element-parse-objects
3470 cbeg (org-element-property :contents-end element)
3471 (nreverse element) (org-element-restriction type)))
3472 ;; Case 4. Else, just accumulate ELEMENT.
3473 (t element)))
3474 acc)))
3475 ;; Return result.
3476 (nreverse acc)))
3478 (defun org-element-parse-objects (beg end acc restriction)
3479 "Parse objects between BEG and END and return recursive structure.
3481 Objects are accumulated in ACC.
3483 RESTRICTION is a list of object types which are allowed in the
3484 current object."
3485 (let ((get-next-object
3486 (function
3487 (lambda (cand)
3488 ;; Return the parsing function associated to the nearest
3489 ;; object among list of candidates CAND.
3490 (let ((pos (apply 'min (mapcar 'cdr cand))))
3491 (save-excursion
3492 (goto-char pos)
3493 (funcall
3494 (intern
3495 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3496 next-object candidates)
3497 (save-excursion
3498 (goto-char beg)
3499 (while (setq candidates (org-element-get-next-object-candidates
3500 end restriction candidates))
3501 (setq next-object (funcall get-next-object candidates))
3502 ;; 1. Text before any object. Untabify it.
3503 (let ((obj-beg (org-element-property :begin next-object)))
3504 (unless (= (point) obj-beg)
3505 (push (replace-regexp-in-string
3506 "\t" (make-string tab-width ? )
3507 (buffer-substring-no-properties (point) obj-beg))
3508 acc)))
3509 ;; 2. Object...
3510 (let ((obj-end (org-element-property :end next-object))
3511 (cont-beg (org-element-property :contents-begin next-object)))
3512 (push (if (and (memq (car next-object) org-element-recursive-objects)
3513 cont-beg)
3514 ;; ... recursive. The CONT-BEG check is for
3515 ;; links, as some of them might not be recursive
3516 ;; (i.e. plain links).
3517 (save-restriction
3518 (narrow-to-region
3519 cont-beg
3520 (org-element-property :contents-end next-object))
3521 (org-element-parse-objects
3522 (point-min) (point-max)
3523 (nreverse next-object)
3524 ;; Restrict allowed objects.
3525 (org-element-restriction next-object)))
3526 ;; ... not recursive. Accumulate the object.
3527 next-object)
3528 acc)
3529 (goto-char obj-end)))
3530 ;; 3. Text after last object. Untabify it.
3531 (unless (= (point) end)
3532 (push (replace-regexp-in-string
3533 "\t" (make-string tab-width ? )
3534 (buffer-substring-no-properties (point) end))
3535 acc))
3536 ;; Result.
3537 (nreverse acc))))
3539 (defun org-element-get-next-object-candidates (limit restriction objects)
3540 "Return an alist of candidates for the next object.
3542 LIMIT bounds the search, and RESTRICTION narrows candidates to
3543 some object types.
3545 Return value is an alist whose CAR is position and CDR the object
3546 type, as a symbol.
3548 OBJECTS is the previous candidates alist."
3549 (let (next-candidates types-to-search)
3550 ;; If no previous result, search every object type in RESTRICTION.
3551 ;; Otherwise, keep potential candidates (old objects located after
3552 ;; point) and ask to search again those which had matched before.
3553 (if (not objects) (setq types-to-search restriction)
3554 (mapc (lambda (obj)
3555 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3556 (push obj next-candidates)))
3557 objects))
3558 ;; Call the appropriate successor function for each type to search
3559 ;; and accumulate matches.
3560 (mapc
3561 (lambda (type)
3562 (let* ((successor-fun
3563 (intern
3564 (format "org-element-%s-successor"
3565 (or (cdr (assq type org-element-object-successor-alist))
3566 type))))
3567 (obj (funcall successor-fun limit)))
3568 (and obj (push obj next-candidates))))
3569 types-to-search)
3570 ;; Return alist.
3571 next-candidates))
3575 ;;; Towards A Bijective Process
3577 ;; The parse tree obtained with `org-element-parse-buffer' is really
3578 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3579 ;; interpreted and expanded into a string with canonical Org syntax.
3580 ;; Hence `org-element-interpret-data'.
3582 ;; The function relies internally on
3583 ;; `org-element-interpret--affiliated-keywords'.
3585 (defun org-element-interpret-data (data &optional parent)
3586 "Interpret DATA as Org syntax.
3588 DATA is a parse tree, an element, an object or a secondary string
3589 to interpret.
3591 Optional argument PARENT is used for recursive calls. It contains
3592 the element or object containing data, or nil.
3594 Return Org syntax as a string."
3595 (let* ((type (org-element-type data))
3596 (results
3597 (cond
3598 ;; Secondary string.
3599 ((not type)
3600 (mapconcat
3601 (lambda (obj) (org-element-interpret-data obj parent))
3602 data ""))
3603 ;; Full Org document.
3604 ((eq type 'org-data)
3605 (mapconcat
3606 (lambda (obj) (org-element-interpret-data obj parent))
3607 (org-element-contents data) ""))
3608 ;; Plain text.
3609 ((stringp data) data)
3610 ;; Element/Object without contents.
3611 ((not (org-element-contents data))
3612 (funcall (intern (format "org-element-%s-interpreter" type))
3613 data nil))
3614 ;; Element/Object with contents.
3616 (let* ((greaterp (memq type org-element-greater-elements))
3617 (objectp (and (not greaterp)
3618 (memq type org-element-recursive-objects)))
3619 (contents
3620 (mapconcat
3621 (lambda (obj) (org-element-interpret-data obj data))
3622 (org-element-contents
3623 (if (or greaterp objectp) data
3624 ;; Elements directly containing objects must
3625 ;; have their indentation normalized first.
3626 (org-element-normalize-contents
3627 data
3628 ;; When normalizing first paragraph of an
3629 ;; item or a footnote-definition, ignore
3630 ;; first line's indentation.
3631 (and (eq type 'paragraph)
3632 (equal data (car (org-element-contents parent)))
3633 (memq (org-element-type parent)
3634 '(footnote-definiton item))))))
3635 "")))
3636 (funcall (intern (format "org-element-%s-interpreter" type))
3637 data
3638 (if greaterp (org-element-normalize-contents contents)
3639 contents)))))))
3640 (if (memq type '(org-data plain-text nil)) results
3641 ;; Build white spaces. If no `:post-blank' property is
3642 ;; specified, assume its value is 0.
3643 (let ((post-blank (or (org-element-property :post-blank data) 0)))
3644 (if (memq type org-element-all-objects)
3645 (concat results (make-string post-blank 32))
3646 (concat
3647 (org-element-interpret--affiliated-keywords data)
3648 (org-element-normalize-string results)
3649 (make-string post-blank 10)))))))
3651 (defun org-element-interpret--affiliated-keywords (element)
3652 "Return ELEMENT's affiliated keywords as Org syntax.
3653 If there is no affiliated keyword, return the empty string."
3654 (let ((keyword-to-org
3655 (function
3656 (lambda (key value)
3657 (let (dual)
3658 (when (member key org-element-dual-keywords)
3659 (setq dual (cdr value) value (car value)))
3660 (concat "#+" key
3661 (and dual
3662 (format "[%s]" (org-element-interpret-data dual)))
3663 ": "
3664 (if (member key org-element-parsed-keywords)
3665 (org-element-interpret-data value)
3666 value)
3667 "\n"))))))
3668 (mapconcat
3669 (lambda (key)
3670 (let ((value (org-element-property (intern (concat ":" (downcase key)))
3671 element)))
3672 (when value
3673 (if (member key org-element-multiple-keywords)
3674 (mapconcat (lambda (line)
3675 (funcall keyword-to-org key line))
3676 value "")
3677 (funcall keyword-to-org key value)))))
3678 ;; Remove translated keywords.
3679 (delq nil
3680 (mapcar
3681 (lambda (key)
3682 (and (not (assoc key org-element-keyword-translation-alist)) key))
3683 org-element-affiliated-keywords))
3684 "")))
3686 ;; Because interpretation of the parse tree must return the same
3687 ;; number of blank lines between elements and the same number of white
3688 ;; space after objects, some special care must be given to white
3689 ;; spaces.
3691 ;; The first function, `org-element-normalize-string', ensures any
3692 ;; string different from the empty string will end with a single
3693 ;; newline character.
3695 ;; The second function, `org-element-normalize-contents', removes
3696 ;; global indentation from the contents of the current element.
3698 (defun org-element-normalize-string (s)
3699 "Ensure string S ends with a single newline character.
3701 If S isn't a string return it unchanged. If S is the empty
3702 string, return it. Otherwise, return a new string with a single
3703 newline character at its end."
3704 (cond
3705 ((not (stringp s)) s)
3706 ((string= "" s) "")
3707 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3708 (replace-match "\n" nil nil s)))))
3710 (defun org-element-normalize-contents (element &optional ignore-first)
3711 "Normalize plain text in ELEMENT's contents.
3713 ELEMENT must only contain plain text and objects.
3715 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3716 indentation to compute maximal common indentation.
3718 Return the normalized element that is element with global
3719 indentation removed from its contents. The function assumes that
3720 indentation is not done with TAB characters."
3721 (let (ind-list
3722 (collect-inds
3723 (function
3724 ;; Return list of indentations within BLOB. This is done by
3725 ;; walking recursively BLOB and updating IND-LIST along the
3726 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3727 ;; been seen yet. It is required as this string is the only
3728 ;; one whose indentation doesn't happen after a newline
3729 ;; character.
3730 (lambda (blob first-flag)
3731 (mapc
3732 (lambda (object)
3733 (when (and first-flag (stringp object))
3734 (setq first-flag nil)
3735 (string-match "\\`\\( *\\)" object)
3736 (let ((len (length (match-string 1 object))))
3737 ;; An indentation of zero means no string will be
3738 ;; modified. Quit the process.
3739 (if (zerop len) (throw 'zero (setq ind-list nil))
3740 (push len ind-list))))
3741 (cond
3742 ((stringp object)
3743 (let ((start 0))
3744 ;; Avoid matching blank or empty lines.
3745 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
3746 (not (equal (match-string 2 object) " ")))
3747 (setq start (match-end 0))
3748 (push (length (match-string 1 object)) ind-list))))
3749 ((memq (org-element-type object) org-element-recursive-objects)
3750 (funcall collect-inds object first-flag))))
3751 (org-element-contents blob))))))
3752 ;; Collect indentation list in ELEMENT. Possibly remove first
3753 ;; value if IGNORE-FIRST is non-nil.
3754 (catch 'zero (funcall collect-inds element (not ignore-first)))
3755 (if (not ind-list) element
3756 ;; Build ELEMENT back, replacing each string with the same
3757 ;; string minus common indentation.
3758 (let ((build
3759 (function
3760 (lambda (blob mci first-flag)
3761 ;; Return BLOB with all its strings indentation
3762 ;; shortened from MCI white spaces. FIRST-FLAG is
3763 ;; non-nil when the first string hasn't been seen
3764 ;; yet.
3765 (nconc
3766 (list (org-element-type blob) (nth 1 blob))
3767 (mapcar
3768 (lambda (object)
3769 (when (and first-flag (stringp object))
3770 (setq first-flag nil)
3771 (setq object
3772 (replace-regexp-in-string
3773 (format "\\` \\{%d\\}" mci) "" object)))
3774 (cond
3775 ((stringp object)
3776 (replace-regexp-in-string
3777 (format "\n \\{%d\\}" mci) "\n" object))
3778 ((memq (org-element-type object)
3779 org-element-recursive-objects)
3780 (funcall build object mci first-flag))
3781 (t object)))
3782 (org-element-contents blob)))))))
3783 (funcall build element (apply 'min ind-list) (not ignore-first))))))
3787 ;;; The Toolbox
3789 ;; The first move is to implement a way to obtain the smallest element
3790 ;; containing point. This is the job of `org-element-at-point'. It
3791 ;; basically jumps back to the beginning of section containing point
3792 ;; and moves, element after element, with
3793 ;; `org-element-current-element' until the container is found.
3795 ;; Note: When using `org-element-at-point', secondary values are never
3796 ;; parsed since the function focuses on elements, not on objects.
3798 (defun org-element-at-point (&optional keep-trail)
3799 "Determine closest element around point.
3801 Return value is a list like (TYPE PROPS) where TYPE is the type
3802 of the element and PROPS a plist of properties associated to the
3803 element. Possible types are defined in
3804 `org-element-all-elements'.
3806 As a special case, if point is at the very beginning of a list or
3807 sub-list, returned element will be that list instead of the first
3808 item. In the same way, if point is at the beginning of the first
3809 row of a table, returned element will be the table instead of the
3810 first row.
3812 If optional argument KEEP-TRAIL is non-nil, the function returns
3813 a list of of elements leading to element at point. The list's
3814 CAR is always the element at point. Following positions contain
3815 element's siblings, then parents, siblings of parents, until the
3816 first element of current section."
3817 (org-with-wide-buffer
3818 ;; If at an headline, parse it. It is the sole element that
3819 ;; doesn't require to know about context. Be sure to disallow
3820 ;; secondary string parsing, though.
3821 (if (org-with-limited-levels (org-at-heading-p))
3822 (progn
3823 (beginning-of-line)
3824 (if (not keep-trail) (org-element-headline-parser t)
3825 (list (org-element-headline-parser t))))
3826 ;; Otherwise move at the beginning of the section containing
3827 ;; point.
3828 (let ((origin (point)) element type special-flag trail struct prevs)
3829 (org-with-limited-levels
3830 (if (org-before-first-heading-p) (goto-char (point-min))
3831 (org-back-to-heading)
3832 (forward-line)))
3833 (org-skip-whitespace)
3834 (beginning-of-line)
3835 ;; Parse successively each element, skipping those ending
3836 ;; before original position.
3837 (catch 'exit
3838 (while t
3839 (setq element (org-element-current-element
3840 'element special-flag struct)
3841 type (car element))
3842 (push element trail)
3843 (cond
3844 ;; 1. Skip any element ending before point or at point.
3845 ((let ((end (org-element-property :end element)))
3846 (when (<= end origin)
3847 (if (> (point-max) end) (goto-char end)
3848 (throw 'exit (if keep-trail trail element))))))
3849 ;; 2. An element containing point is always the element at
3850 ;; point.
3851 ((not (memq type org-element-greater-elements))
3852 (throw 'exit (if keep-trail trail element)))
3853 ;; 3. At any other greater element type, if point is
3854 ;; within contents, move into it. Otherwise, return
3855 ;; that element.
3857 (let ((beg (org-element-property :contents-begin element))
3858 (end (org-element-property :contents-end element)))
3859 (if (or (not beg) (not end) (> beg origin) (<= end origin)
3860 (and (= beg origin) (memq type '(plain-list table))))
3861 (throw 'exit (if keep-trail trail element))
3862 (case type
3863 (plain-list
3864 (setq special-flag 'item
3865 struct (org-element-property :structure element)))
3866 (table (setq special-flag 'table-row))
3867 (otherwise (setq special-flag nil)))
3868 (narrow-to-region beg end)
3869 (goto-char beg)))))))))))
3872 ;; Once the local structure around point is well understood, it's easy
3873 ;; to implement some replacements for `forward-paragraph'
3874 ;; `backward-paragraph', namely `org-element-forward' and
3875 ;; `org-element-backward'.
3877 ;; Also, `org-transpose-elements' mimics the behaviour of
3878 ;; `transpose-words', at the element's level, whereas
3879 ;; `org-element-drag-forward', `org-element-drag-backward', and
3880 ;; `org-element-up' generalize, respectively, functions
3881 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3883 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3884 ;; smartly remove global indentation from buffer, making it possible
3885 ;; to use Org indent mode on a file created with hard indentation.
3887 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3888 ;; internally by some of the previously cited tools.
3890 (defsubst org-element-nested-p (elem-A elem-B)
3891 "Non-nil when elements ELEM-A and ELEM-B are nested."
3892 (let ((beg-A (org-element-property :begin elem-A))
3893 (beg-B (org-element-property :begin elem-B))
3894 (end-A (org-element-property :end elem-A))
3895 (end-B (org-element-property :end elem-B)))
3896 (or (and (>= beg-A beg-B) (<= end-A end-B))
3897 (and (>= beg-B beg-A) (<= end-B end-A)))))
3899 (defun org-element-swap-A-B (elem-A elem-B)
3900 "Swap elements ELEM-A and ELEM-B.
3901 Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
3902 end of ELEM-A."
3903 (goto-char (org-element-property :begin elem-A))
3904 ;; There are two special cases when an element doesn't start at bol:
3905 ;; the first paragraph in an item or in a footnote definition.
3906 (let ((specialp (not (bolp))))
3907 ;; Only a paragraph without any affiliated keyword can be moved at
3908 ;; ELEM-A position in such a situation. Note that the case of
3909 ;; a footnote definition is impossible: it cannot contain two
3910 ;; paragraphs in a row because it cannot contain a blank line.
3911 (if (and specialp
3912 (or (not (eq (org-element-type elem-B) 'paragraph))
3913 (/= (org-element-property :begin elem-B)
3914 (org-element-property :contents-begin elem-B))))
3915 (error "Cannot swap elements"))
3916 ;; In a special situation, ELEM-A will have no indentation. We'll
3917 ;; give it ELEM-B's (which will in, in turn, have no indentation).
3918 (let* ((ind-B (when specialp
3919 (goto-char (org-element-property :begin elem-B))
3920 (org-get-indentation)))
3921 (beg-A (org-element-property :begin elem-A))
3922 (end-A (save-excursion
3923 (goto-char (org-element-property :end elem-A))
3924 (skip-chars-backward " \r\t\n")
3925 (point-at-eol)))
3926 (beg-B (org-element-property :begin elem-B))
3927 (end-B (save-excursion
3928 (goto-char (org-element-property :end elem-B))
3929 (skip-chars-backward " \r\t\n")
3930 (point-at-eol)))
3931 (body-A (buffer-substring beg-A end-A))
3932 (body-B (delete-and-extract-region beg-B end-B)))
3933 (goto-char beg-B)
3934 (when specialp
3935 (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
3936 (org-indent-to-column ind-B))
3937 (insert body-A)
3938 (goto-char beg-A)
3939 (delete-region beg-A end-A)
3940 (insert body-B)
3941 (goto-char (org-element-property :end elem-B)))))
3943 (defun org-element-forward ()
3944 "Move forward by one element.
3945 Move to the next element at the same level, when possible."
3946 (interactive)
3947 (if (org-with-limited-levels (org-at-heading-p))
3948 (let ((origin (point)))
3949 (org-forward-same-level 1)
3950 (unless (org-with-limited-levels (org-at-heading-p))
3951 (goto-char origin)
3952 (error "Cannot move further down")))
3953 (let* ((trail (org-element-at-point 'keep-trail))
3954 (elem (pop trail))
3955 (end (org-element-property :end elem))
3956 (parent (loop for prev in trail
3957 when (>= (org-element-property :end prev) end)
3958 return prev)))
3959 (cond
3960 ((eobp) (error "Cannot move further down"))
3961 ((and parent (= (org-element-property :contents-end parent) end))
3962 (goto-char (org-element-property :end parent)))
3963 (t (goto-char end))))))
3965 (defun org-element-backward ()
3966 "Move backward by one element.
3967 Move to the previous element at the same level, when possible."
3968 (interactive)
3969 (if (org-with-limited-levels (org-at-heading-p))
3970 ;; At an headline, move to the previous one, if any, or stay
3971 ;; here.
3972 (let ((origin (point)))
3973 (org-backward-same-level 1)
3974 (unless (org-with-limited-levels (org-at-heading-p))
3975 (goto-char origin)
3976 (error "Cannot move further up")))
3977 (let* ((trail (org-element-at-point 'keep-trail))
3978 (elem (car trail))
3979 (prev-elem (nth 1 trail))
3980 (beg (org-element-property :begin elem)))
3981 (cond
3982 ;; Move to beginning of current element if point isn't there
3983 ;; already.
3984 ((/= (point) beg) (goto-char beg))
3985 ((not prev-elem) (error "Cannot move further up"))
3986 (t (goto-char (org-element-property :begin prev-elem)))))))
3988 (defun org-element-up ()
3989 "Move to upper element."
3990 (interactive)
3991 (if (org-with-limited-levels (org-at-heading-p))
3992 (unless (org-up-heading-safe)
3993 (error "No surrounding element"))
3994 (let* ((trail (org-element-at-point 'keep-trail))
3995 (elem (pop trail))
3996 (end (org-element-property :end elem))
3997 (parent (loop for prev in trail
3998 when (>= (org-element-property :end prev) end)
3999 return prev)))
4000 (cond
4001 (parent (goto-char (org-element-property :begin parent)))
4002 ((org-before-first-heading-p) (error "No surrounding element"))
4003 (t (org-back-to-heading))))))
4005 (defun org-element-down ()
4006 "Move to inner element."
4007 (interactive)
4008 (let ((element (org-element-at-point)))
4009 (cond
4010 ((memq (org-element-type element) '(plain-list table))
4011 (goto-char (org-element-property :contents-begin element))
4012 (forward-char))
4013 ((memq (org-element-type element) org-element-greater-elements)
4014 ;; If contents are hidden, first disclose them.
4015 (when (org-element-property :hiddenp element) (org-cycle))
4016 (goto-char (org-element-property :contents-begin element)))
4017 (t (error "No inner element")))))
4019 (defun org-element-drag-backward ()
4020 "Move backward element at point."
4021 (interactive)
4022 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
4023 (let* ((trail (org-element-at-point 'keep-trail))
4024 (elem (car trail))
4025 (prev-elem (nth 1 trail)))
4026 ;; Error out if no previous element or previous element is
4027 ;; a parent of the current one.
4028 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
4029 (error "Cannot drag element backward")
4030 (let ((pos (point)))
4031 (org-element-swap-A-B prev-elem elem)
4032 (goto-char (+ (org-element-property :begin prev-elem)
4033 (- pos (org-element-property :begin elem)))))))))
4035 (defun org-element-drag-forward ()
4036 "Move forward element at point."
4037 (interactive)
4038 (let* ((pos (point))
4039 (elem (org-element-at-point)))
4040 (when (= (point-max) (org-element-property :end elem))
4041 (error "Cannot drag element forward"))
4042 (goto-char (org-element-property :end elem))
4043 (let ((next-elem (org-element-at-point)))
4044 (when (or (org-element-nested-p elem next-elem)
4045 (and (eq (org-element-type next-elem) 'headline)
4046 (not (eq (org-element-type elem) 'headline))))
4047 (goto-char pos)
4048 (error "Cannot drag element forward"))
4049 ;; Compute new position of point: it's shifted by NEXT-ELEM
4050 ;; body's length (without final blanks) and by the length of
4051 ;; blanks between ELEM and NEXT-ELEM.
4052 (let ((size-next (- (save-excursion
4053 (goto-char (org-element-property :end next-elem))
4054 (skip-chars-backward " \r\t\n")
4055 (forward-line)
4056 ;; Small correction if buffer doesn't end
4057 ;; with a newline character.
4058 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
4059 (org-element-property :begin next-elem)))
4060 (size-blank (- (org-element-property :end elem)
4061 (save-excursion
4062 (goto-char (org-element-property :end elem))
4063 (skip-chars-backward " \r\t\n")
4064 (forward-line)
4065 (point)))))
4066 (org-element-swap-A-B elem next-elem)
4067 (goto-char (+ pos size-next size-blank))))))
4069 (defun org-element-mark-element ()
4070 "Put point at beginning of this element, mark at end.
4072 Interactively, if this command is repeated or (in Transient Mark
4073 mode) if the mark is active, it marks the next element after the
4074 ones already marked."
4075 (interactive)
4076 (let (deactivate-mark)
4077 (if (or (and (eq last-command this-command) (mark t))
4078 (and transient-mark-mode mark-active))
4079 (set-mark
4080 (save-excursion
4081 (goto-char (mark))
4082 (goto-char (org-element-property :end (org-element-at-point)))))
4083 (let ((element (org-element-at-point)))
4084 (end-of-line)
4085 (push-mark (org-element-property :end element) t t)
4086 (goto-char (org-element-property :begin element))))))
4088 (defun org-narrow-to-element ()
4089 "Narrow buffer to current element."
4090 (interactive)
4091 (let ((elem (org-element-at-point)))
4092 (cond
4093 ((eq (car elem) 'headline)
4094 (narrow-to-region
4095 (org-element-property :begin elem)
4096 (org-element-property :end elem)))
4097 ((memq (car elem) org-element-greater-elements)
4098 (narrow-to-region
4099 (org-element-property :contents-begin elem)
4100 (org-element-property :contents-end elem)))
4102 (narrow-to-region
4103 (org-element-property :begin elem)
4104 (org-element-property :end elem))))))
4106 (defun org-element-transpose ()
4107 "Transpose current and previous elements, keeping blank lines between.
4108 Point is moved after both elements."
4109 (interactive)
4110 (org-skip-whitespace)
4111 (let ((end (org-element-property :end (org-element-at-point))))
4112 (org-element-drag-backward)
4113 (goto-char end)))
4115 (defun org-element-unindent-buffer ()
4116 "Un-indent the visible part of the buffer.
4117 Relative indentation (between items, inside blocks, etc.) isn't
4118 modified."
4119 (interactive)
4120 (unless (eq major-mode 'org-mode)
4121 (error "Cannot un-indent a buffer not in Org mode"))
4122 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
4123 unindent-tree ; For byte-compiler.
4124 (unindent-tree
4125 (function
4126 (lambda (contents)
4127 (mapc
4128 (lambda (element)
4129 (if (memq (org-element-type element) '(headline section))
4130 (funcall unindent-tree (org-element-contents element))
4131 (save-excursion
4132 (save-restriction
4133 (narrow-to-region
4134 (org-element-property :begin element)
4135 (org-element-property :end element))
4136 (org-do-remove-indentation)))))
4137 (reverse contents))))))
4138 (funcall unindent-tree (org-element-contents parse-tree))))
4141 (provide 'org-element)
4142 ;;; org-element.el ends here