org-element: code clean-up and some optimizations
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-element.el
blob0da8515bc5d23a7c37f87ed4affc35e5725b6f7d
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-cell', `table-row' and `verse-block'. Among them,
50 ;; `paragraph', `table-cell' and `verse-block' types can contain Org
51 ;; objects and plain text.
53 ;; Objects are related to document's contents. Some of them are
54 ;; recursive. Associated types are of the following: `bold', `code',
55 ;; `entity', `export-snippet', `footnote-reference',
56 ;; `inline-babel-call', `inline-src-block', `italic',
57 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
58 ;; `statistics-cookie', `strike-through', `subscript', `superscript',
59 ;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
61 ;; Some elements also have special properties whose value can hold
62 ;; objects themselves (i.e. an item tag or an headline name). Such
63 ;; values are called "secondary strings". Any object belongs to
64 ;; either an element or a secondary string.
66 ;; Notwithstanding affiliated keywords, each greater element, element
67 ;; and object has a fixed set of properties attached to it. Among
68 ;; them, three are shared by all types: `:begin' and `:end', which
69 ;; refer to the beginning and ending buffer positions of the
70 ;; considered element or object, and `:post-blank', which holds the
71 ;; number of blank lines, or white spaces, at its end. Greater
72 ;; elements and elements containing objects will also have
73 ;; `:contents-begin' and `:contents-end' properties to delimit
74 ;; contents.
76 ;; Lisp-wise, an element or an object can be represented as a list.
77 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
78 ;; TYPE is a symbol describing the Org element or object.
79 ;; PROPERTIES is the property list attached to it. See docstring of
80 ;; appropriate parsing function to get an exhaustive
81 ;; list.
82 ;; CONTENTS is a list of elements, objects or raw strings contained
83 ;; in the current element or object, when applicable.
85 ;; An Org buffer is a nested list of such elements and objects, whose
86 ;; type is `org-data' and properties is nil.
88 ;; The first part of this file implements a parser and an interpreter
89 ;; for each type of Org syntax.
91 ;; The next two parts introduce four accessors and a function
92 ;; retrieving the element starting at point (respectively
93 ;; `org-element-type', `org-element-property', `org-element-contents',
94 ;; `org-element-restriction' and `org-element-current-element').
96 ;; The following part creates a fully recursive buffer parser. It
97 ;; also provides a tool to map a function to elements or objects
98 ;; matching some criteria in the parse tree. Functions of interest
99 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
100 ;; extent, `org-element-parse-secondary-string'.
102 ;; The penultimate part is the cradle of an interpreter for the
103 ;; obtained parse tree: `org-element-interpret-data'.
105 ;; The library ends by furnishing a set of interactive tools for
106 ;; element's navigation and manipulation, mostly based on
107 ;; `org-element-at-point' function.
110 ;;; Code:
112 (eval-when-compile (require 'cl))
113 (require 'org)
114 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
117 ;;; Greater elements
119 ;; For each greater element type, we define a parser and an
120 ;; interpreter.
122 ;; A parser returns the element or object as the list described above.
123 ;; Most of them accepts no argument. Though, exceptions exist. Hence
124 ;; every element containing a secondary string (see
125 ;; `org-element-secondary-value-alist') will accept an optional
126 ;; argument to toggle parsing of that secondary string. Moreover,
127 ;; `item' parser requires current list's structure as its first
128 ;; element.
130 ;; An interpreter accepts two arguments: the list representation of
131 ;; the element or object, and its contents. The latter may be nil,
132 ;; depending on the element or object considered. It returns the
133 ;; appropriate Org syntax, as a string.
135 ;; Parsing functions must follow the naming convention:
136 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
137 ;; defined in `org-element-greater-elements'.
139 ;; Similarly, interpreting functions must follow the naming
140 ;; convention: org-element-TYPE-interpreter.
142 ;; With the exception of `headline' and `item' types, greater elements
143 ;; cannot contain other greater elements of their own type.
145 ;; Beside implementing a parser and an interpreter, adding a new
146 ;; greater element requires to tweak `org-element-current-element'.
147 ;; Moreover, the newly defined type must be added to both
148 ;; `org-element-all-elements' and `org-element-greater-elements'.
151 ;;;; Center Block
153 (defun org-element-center-block-parser ()
154 "Parse a center block.
156 Return a list whose CAR is `center-block' and CDR is a plist
157 containing `:begin', `:end', `:hiddenp', `:contents-begin',
158 `:contents-end' and `:post-blank' keywords.
160 Assume point is at the beginning of the block."
161 (save-excursion
162 (let* ((case-fold-search t)
163 (keywords (org-element-collect-affiliated-keywords))
164 (begin (car keywords))
165 (contents-begin (progn (forward-line) (point)))
166 (hidden (org-truely-invisible-p))
167 (contents-end
168 (progn (re-search-forward "^[ \t]*#\\+END_CENTER" nil t)
169 (point-at-bol)))
170 (pos-before-blank (progn (forward-line) (point)))
171 (end (progn (org-skip-whitespace)
172 (if (eobp) (point) (point-at-bol)))))
173 `(center-block
174 (:begin ,begin
175 :end ,end
176 :hiddenp ,hidden
177 :contents-begin ,contents-begin
178 :contents-end ,contents-end
179 :post-blank ,(count-lines pos-before-blank end)
180 ,@(cadr keywords))))))
182 (defun org-element-center-block-interpreter (center-block contents)
183 "Interpret CENTER-BLOCK element as Org syntax.
184 CONTENTS is the contents of the element."
185 (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
188 ;;;; Drawer
190 (defun org-element-drawer-parser ()
191 "Parse a drawer.
193 Return a list whose CAR is `drawer' and CDR is a plist containing
194 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
195 `:contents-end' and `:post-blank' keywords.
197 Assume point is at beginning of drawer."
198 (save-excursion
199 (let* ((case-fold-search t)
200 (name (progn (looking-at org-drawer-regexp)
201 (org-match-string-no-properties 1)))
202 (keywords (org-element-collect-affiliated-keywords))
203 (begin (car keywords))
204 (contents-begin (progn (forward-line) (point)))
205 (hidden (org-truely-invisible-p))
206 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
207 (point-at-bol)))
208 (pos-before-blank (progn (forward-line) (point)))
209 (end (progn (org-skip-whitespace)
210 (if (eobp) (point) (point-at-bol)))))
211 `(drawer
212 (:begin ,begin
213 :end ,end
214 :drawer-name ,name
215 :hiddenp ,hidden
216 :contents-begin ,contents-begin
217 :contents-end ,contents-end
218 :post-blank ,(count-lines pos-before-blank end)
219 ,@(cadr keywords))))))
221 (defun org-element-drawer-interpreter (drawer contents)
222 "Interpret DRAWER element as Org syntax.
223 CONTENTS is the contents of the element."
224 (format ":%s:\n%s:END:"
225 (org-element-property :drawer-name drawer)
226 contents))
229 ;;;; Dynamic Block
231 (defun org-element-dynamic-block-parser ()
232 "Parse a dynamic block.
234 Return a list whose CAR is `dynamic-block' and CDR is a plist
235 containing `:block-name', `:begin', `:end', `:hiddenp',
236 `:contents-begin', `:contents-end', `:arguments' and
237 `:post-blank' keywords.
239 Assume point is at beginning of dynamic block."
240 (save-excursion
241 (let* ((case-fold-search t)
242 (name (progn (looking-at org-dblock-start-re)
243 (org-match-string-no-properties 1)))
244 (arguments (org-match-string-no-properties 3))
245 (keywords (org-element-collect-affiliated-keywords))
246 (begin (car keywords))
247 (contents-begin (progn (forward-line) (point)))
248 (hidden (org-truely-invisible-p))
249 (contents-end (progn (re-search-forward org-dblock-end-re nil t)
250 (point-at-bol)))
251 (pos-before-blank (progn (forward-line) (point)))
252 (end (progn (org-skip-whitespace)
253 (if (eobp) (point) (point-at-bol)))))
254 (list 'dynamic-block
255 `(:begin ,begin
256 :end ,end
257 :block-name ,name
258 :arguments ,arguments
259 :hiddenp ,hidden
260 :contents-begin ,contents-begin
261 :contents-end ,contents-end
262 :post-blank ,(count-lines pos-before-blank end)
263 ,@(cadr keywords))))))
265 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
266 "Interpret DYNAMIC-BLOCK element as Org syntax.
267 CONTENTS is the contents of the element."
268 (format "#+BEGIN: %s%s\n%s#+END:"
269 (org-element-property :block-name dynamic-block)
270 (let ((args (org-element-property :arguments dynamic-block)))
271 (and args (concat " " args)))
272 contents))
275 ;;;; Footnote Definition
277 (defun org-element-footnote-definition-parser ()
278 "Parse a footnote definition.
280 Return a list whose CAR is `footnote-definition' and CDR is
281 a plist containing `:label', `:begin' `:end', `:contents-begin',
282 `:contents-end' and `:post-blank' keywords.
284 Assume point is at the beginning of the footnote definition."
285 (save-excursion
286 (looking-at org-footnote-definition-re)
287 (let* ((label (org-match-string-no-properties 1))
288 (keywords (org-element-collect-affiliated-keywords))
289 (begin (car keywords))
290 (contents-begin (progn (search-forward "]")
291 (org-skip-whitespace)
292 (point)))
293 (contents-end (if (progn
294 (end-of-line)
295 (re-search-forward
296 (concat org-outline-regexp-bol "\\|"
297 org-footnote-definition-re "\\|"
298 "^[ \t]*$") nil t))
299 (match-beginning 0)
300 (point-max)))
301 (end (progn (org-skip-whitespace)
302 (if (eobp) (point) (point-at-bol)))))
303 `(footnote-definition
304 (:label ,label
305 :begin ,begin
306 :end ,end
307 :contents-begin ,contents-begin
308 :contents-end ,contents-end
309 :post-blank ,(count-lines contents-end end)
310 ,@(cadr keywords))))))
312 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
313 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
314 CONTENTS is the contents of the footnote-definition."
315 (concat (format "[%s]" (org-element-property :label footnote-definition))
317 contents))
320 ;;;; Headline
322 (defun org-element-headline-parser (&optional raw-secondary-p)
323 "Parse an headline.
325 Return a list whose CAR is `headline' and CDR is a plist
326 containing `:raw-value', `:title', `:begin', `:end',
327 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
328 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
329 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
330 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
331 keywords.
333 The plist also contains any property set in the property drawer,
334 with its name in lowercase, the underscores replaced with hyphens
335 and colons at the beginning (i.e. `:custom-id').
337 When RAW-SECONDARY-P is non-nil, headline's title will not be
338 parsed as a secondary string, but as a plain string instead.
340 Assume point is at beginning of the headline."
341 (save-excursion
342 (let* ((components (org-heading-components))
343 (level (nth 1 components))
344 (todo (nth 2 components))
345 (todo-type
346 (and todo (if (member todo org-done-keywords) 'done 'todo)))
347 (tags (nth 5 components))
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
356 (and tags
357 (let ((case-fold-search nil))
358 (string-match (format ":%s:" org-archive-tag) tags))))
359 (footnote-section-p (and org-footnote-section
360 (string= org-footnote-section raw-value)))
361 (standard-props (let (plist)
362 (mapc
363 (lambda (p)
364 (let ((p-name (downcase (car p))))
365 (while (string-match "_" p-name)
366 (setq p-name
367 (replace-match "-" nil nil p-name)))
368 (setq p-name (intern (concat ":" p-name)))
369 (setq plist
370 (plist-put plist p-name (cdr p)))))
371 (org-entry-properties nil 'standard))
372 plist))
373 (time-props (org-entry-properties nil 'special "CLOCK"))
374 (scheduled (cdr (assoc "SCHEDULED" time-props)))
375 (deadline (cdr (assoc "DEADLINE" time-props)))
376 (clock (cdr (assoc "CLOCK" time-props)))
377 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
378 (begin (point))
379 (pos-after-head (save-excursion (forward-line) (point)))
380 (contents-begin (save-excursion (forward-line)
381 (org-skip-whitespace)
382 (if (eobp) (point) (point-at-bol))))
383 (hidden (save-excursion (forward-line) (org-truely-invisible-p)))
384 (end (progn (goto-char (org-end-of-subtree t t))))
385 (contents-end (progn (skip-chars-backward " \r\t\n")
386 (forward-line)
387 (point)))
388 title)
389 ;; Clean RAW-VALUE from any quote or comment string.
390 (when (or quotedp commentedp)
391 (setq raw-value
392 (replace-regexp-in-string
393 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
395 raw-value)))
396 ;; Clean TAGS from archive tag, if any.
397 (when archivedp
398 (setq tags
399 (and (not (string= tags (format ":%s:" org-archive-tag)))
400 (replace-regexp-in-string
401 (concat org-archive-tag ":") "" tags)))
402 (when (string= tags ":") (setq tags nil)))
403 ;; Then get TITLE.
404 (setq title
405 (if raw-secondary-p raw-value
406 (org-element-parse-secondary-string
407 raw-value (org-element-restriction 'headline))))
408 `(headline
409 (:raw-value ,raw-value
410 :title ,title
411 :begin ,begin
412 :end ,end
413 :pre-blank ,(count-lines pos-after-head contents-begin)
414 :hiddenp ,hidden
415 :contents-begin ,contents-begin
416 :contents-end ,contents-end
417 :level ,level
418 :priority ,(nth 3 components)
419 :tags ,tags
420 :todo-keyword ,todo
421 :todo-type ,todo-type
422 :scheduled ,scheduled
423 :deadline ,deadline
424 :timestamp ,timestamp
425 :clock ,clock
426 :post-blank ,(count-lines contents-end end)
427 :footnote-section-p ,footnote-section-p
428 :archivedp ,archivedp
429 :commentedp ,commentedp
430 :quotedp ,quotedp
431 ,@standard-props)))))
433 (defun org-element-headline-interpreter (headline contents)
434 "Interpret HEADLINE element as Org syntax.
435 CONTENTS is the contents of the element."
436 (let* ((level (org-element-property :level headline))
437 (todo (org-element-property :todo-keyword headline))
438 (priority (org-element-property :priority headline))
439 (title (org-element-interpret-data (org-element-property :title headline)))
440 (tags (let ((tag-string (org-element-property :tags headline))
441 (archivedp (org-element-property :archivedp headline)))
442 (cond
443 ((and (not tag-string) archivedp)
444 (format ":%s:" org-archive-tag))
445 (archivedp (concat ":" org-archive-tag tag-string))
446 (t tag-string))))
447 (commentedp (org-element-property :commentedp headline))
448 (quotedp (org-element-property :quotedp headline))
449 (pre-blank (org-element-property :pre-blank headline))
450 (heading (concat (make-string level ?*)
451 (and todo (concat " " todo))
452 (and quotedp (concat " " org-quote-string))
453 (and commentedp (concat " " org-comment-string))
454 (and priority
455 (format " [#%s]" (char-to-string priority)))
456 (cond ((and org-footnote-section
457 (org-element-property
458 :footnote-section-p headline))
459 (concat " " org-footnote-section))
460 (title (concat " " title))))))
461 (concat heading
462 ;; Align tags.
463 (when tags
464 (cond
465 ((zerop org-tags-column) (format " %s" tags))
466 ((< org-tags-column 0)
467 (concat
468 (make-string
469 (max (- (+ org-tags-column (length heading) (length tags))) 1)
471 tags))
473 (concat
474 (make-string (max (- org-tags-column (length heading)) 1) ? )
475 tags))))
476 (make-string (1+ pre-blank) 10)
477 contents)))
480 ;;;; Inlinetask
482 (defun org-element-inlinetask-parser (&optional raw-secondary-p)
483 "Parse an inline task.
485 Return a list whose CAR is `inlinetask' and CDR is a plist
486 containing `:title', `:begin', `:end', `:hiddenp',
487 `:contents-begin' and `:contents-end', `:level', `:priority',
488 `:tags', `:todo-keyword', `:todo-type', `:scheduled',
489 `:deadline', `:timestamp', `:clock' and `:post-blank' keywords.
491 The plist also contains any property set in the property drawer,
492 with its name in lowercase, the underscores replaced with hyphens
493 and colons at the beginning (i.e. `:custom-id').
495 When optional argument RAW-SECONDARY-P is non-nil, inline-task's
496 title will not be parsed as a secondary string, but as a plain
497 string instead.
499 Assume point is at beginning of the inline task."
500 (save-excursion
501 (let* ((keywords (org-element-collect-affiliated-keywords))
502 (begin (car keywords))
503 (components (org-heading-components))
504 (todo (nth 2 components))
505 (todo-type (and todo
506 (if (member todo org-done-keywords) 'done 'todo)))
507 (title (if raw-secondary-p (nth 4 components)
508 (org-element-parse-secondary-string
509 (nth 4 components)
510 (org-element-restriction 'inlinetask))))
511 (standard-props (let (plist)
512 (mapc
513 (lambda (p)
514 (let ((p-name (downcase (car p))))
515 (while (string-match "_" p-name)
516 (setq p-name
517 (replace-match "-" nil nil p-name)))
518 (setq p-name (intern (concat ":" p-name)))
519 (setq plist
520 (plist-put plist p-name (cdr p)))))
521 (org-entry-properties nil 'standard))
522 plist))
523 (time-props (org-entry-properties nil 'special "CLOCK"))
524 (scheduled (cdr (assoc "SCHEDULED" time-props)))
525 (deadline (cdr (assoc "DEADLINE" time-props)))
526 (clock (cdr (assoc "CLOCK" time-props)))
527 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
528 (contents-begin (save-excursion (forward-line) (point)))
529 (hidden (org-truely-invisible-p))
530 (pos-before-blank (org-inlinetask-goto-end))
531 ;; In the case of a single line task, CONTENTS-BEGIN and
532 ;; CONTENTS-END might overlap.
533 (contents-end (max contents-begin
534 (if (not (bolp)) (point-at-bol)
535 (save-excursion (forward-line -1) (point)))))
536 (end (progn (org-skip-whitespace)
537 (if (eobp) (point) (point-at-bol)))))
538 `(inlinetask
539 (:title ,title
540 :begin ,begin
541 :end ,end
542 :hiddenp ,(and (> contents-end contents-begin) hidden)
543 :contents-begin ,contents-begin
544 :contents-end ,contents-end
545 :level ,(nth 1 components)
546 :priority ,(nth 3 components)
547 :tags ,(nth 5 components)
548 :todo-keyword ,todo
549 :todo-type ,todo-type
550 :scheduled ,scheduled
551 :deadline ,deadline
552 :timestamp ,timestamp
553 :clock ,clock
554 :post-blank ,(count-lines pos-before-blank end)
555 ,@standard-props
556 ,@(cadr keywords))))))
558 (defun org-element-inlinetask-interpreter (inlinetask contents)
559 "Interpret INLINETASK element as Org syntax.
560 CONTENTS is the contents of inlinetask."
561 (let* ((level (org-element-property :level inlinetask))
562 (todo (org-element-property :todo-keyword inlinetask))
563 (priority (org-element-property :priority inlinetask))
564 (title (org-element-interpret-data
565 (org-element-property :title inlinetask)))
566 (tags (org-element-property :tags inlinetask))
567 (task (concat (make-string level ?*)
568 (and todo (concat " " todo))
569 (and priority
570 (format " [#%s]" (char-to-string priority)))
571 (and title (concat " " title)))))
572 (concat task
573 ;; Align tags.
574 (when tags
575 (cond
576 ((zerop org-tags-column) (format " %s" tags))
577 ((< org-tags-column 0)
578 (concat
579 (make-string
580 (max (- (+ org-tags-column (length task) (length tags))) 1)
582 tags))
584 (concat
585 (make-string (max (- org-tags-column (length task)) 1) ? )
586 tags))))
587 ;; Prefer degenerate inlinetasks when there are no
588 ;; contents.
589 (when contents
590 (concat "\n"
591 contents
592 (make-string level ?*) " END")))))
595 ;;;; Item
597 (defun org-element-item-parser (struct &optional raw-secondary-p)
598 "Parse an item.
600 STRUCT is the structure of the plain list.
602 Return a list whose CAR is `item' and CDR is a plist containing
603 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
604 `:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
605 `:post-blank' keywords.
607 When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
608 any, will not be parsed as a secondary string, but as a plain
609 string instead.
611 Assume point is at the beginning of the item."
612 (save-excursion
613 (beginning-of-line)
614 (let* ((begin (point))
615 (bullet (org-list-get-bullet (point) struct))
616 (checkbox (let ((box (org-list-get-checkbox begin struct)))
617 (cond ((equal "[ ]" box) 'off)
618 ((equal "[X]" box) 'on)
619 ((equal "[-]" box) 'trans))))
620 (counter (let ((c (org-list-get-counter begin struct)))
621 (cond
622 ((not c) nil)
623 ((string-match "[A-Za-z]" c)
624 (- (string-to-char (upcase (match-string 0 c)))
625 64))
626 ((string-match "[0-9]+" c)
627 (string-to-number (match-string 0 c))))))
628 (tag
629 (let ((raw-tag (org-list-get-tag begin struct)))
630 (and raw-tag
631 (if raw-secondary-p raw-tag
632 (org-element-parse-secondary-string
633 raw-tag (org-element-restriction 'item))))))
634 (end (org-list-get-item-end begin struct))
635 (contents-begin (progn (looking-at org-list-full-item-re)
636 (goto-char (match-end 0))
637 (org-skip-whitespace)
638 ;; If first line isn't empty,
639 ;; contents really start at the text
640 ;; after item's meta-data.
641 (if (= (point-at-bol) begin) (point)
642 (point-at-bol))))
643 (hidden (progn (forward-line)
644 (and (not (= (point) end))
645 (org-truely-invisible-p))))
646 (contents-end (progn (goto-char end)
647 (skip-chars-backward " \r\t\n")
648 (forward-line)
649 (point))))
650 `(item
651 (:bullet ,bullet
652 :begin ,begin
653 :end ,end
654 ;; CONTENTS-BEGIN and CONTENTS-END may be mixed
655 ;; up in the case of an empty item separated
656 ;; from the next by a blank line. Thus, ensure
657 ;; the former is always the smallest of two.
658 :contents-begin ,(min contents-begin contents-end)
659 :contents-end ,(max contents-begin contents-end)
660 :checkbox ,checkbox
661 :counter ,counter
662 :tag ,tag
663 :hiddenp ,hidden
664 :structure ,struct
665 :post-blank ,(count-lines contents-end end))))))
667 (defun org-element-item-interpreter (item contents)
668 "Interpret ITEM element as Org syntax.
669 CONTENTS is the contents of the element."
670 (let* ((bullet
671 (let* ((beg (org-element-property :begin item))
672 (struct (org-element-property :structure item))
673 (pre (org-list-prevs-alist struct))
674 (bul (org-element-property :bullet item)))
675 (org-list-bullet-string
676 (if (not (eq (org-list-get-list-type beg struct pre) 'ordered)) "-"
677 (let ((num
678 (car
679 (last
680 (org-list-get-item-number
681 beg struct pre (org-list-parents-alist struct))))))
682 (format "%d%s"
684 (if (eq org-plain-list-ordered-item-terminator ?\)) ")"
685 ".")))))))
686 (checkbox (org-element-property :checkbox item))
687 (counter (org-element-property :counter item))
688 (tag (let ((tag (org-element-property :tag item)))
689 (and tag (org-element-interpret-data tag))))
690 ;; Compute indentation.
691 (ind (make-string (length bullet) 32)))
692 ;; Indent contents.
693 (concat
694 bullet
695 (and counter (format "[@%d] " counter))
696 (cond
697 ((eq checkbox 'on) "[X] ")
698 ((eq checkbox 'off) "[ ] ")
699 ((eq checkbox 'trans) "[-] "))
700 (and tag (format "%s :: " tag))
701 (org-trim
702 (replace-regexp-in-string "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))))
705 ;;;; Plain List
707 (defun org-element-plain-list-parser (&optional structure)
708 "Parse a plain list.
710 Optional argument STRUCTURE, when non-nil, is the structure of
711 the plain list being parsed.
713 Return a list whose CAR is `plain-list' and CDR is a plist
714 containing `:type', `:begin', `:end', `:contents-begin' and
715 `:contents-end', `:level', `:structure' and `:post-blank'
716 keywords.
718 Assume point is at the beginning of the list."
719 (save-excursion
720 (let* ((struct (or structure (org-list-struct)))
721 (prevs (org-list-prevs-alist struct))
722 (parents (org-list-parents-alist struct))
723 (type (org-list-get-list-type (point) struct prevs))
724 (contents-begin (point))
725 (keywords (org-element-collect-affiliated-keywords))
726 (begin (car keywords))
727 (contents-end
728 (goto-char (org-list-get-list-end (point) struct prevs)))
729 (end (save-excursion (org-skip-whitespace)
730 (if (eobp) (point) (point-at-bol))))
731 (level 0))
732 ;; Get list level.
733 (let ((item contents-begin))
734 (while (setq item
735 (org-list-get-parent
736 (org-list-get-list-begin item struct prevs)
737 struct parents))
738 (incf level)))
739 ;; Blank lines below list belong to the top-level list only.
740 (when (> level 0)
741 (setq end (min (org-list-get-bottom-point struct)
742 (progn (org-skip-whitespace)
743 (if (eobp) (point) (point-at-bol))))))
744 ;; Return value.
745 `(plain-list
746 (:type ,type
747 :begin ,begin
748 :end ,end
749 :contents-begin ,contents-begin
750 :contents-end ,contents-end
751 :level ,level
752 :structure ,struct
753 :post-blank ,(count-lines contents-end end)
754 ,@(cadr keywords))))))
756 (defun org-element-plain-list-interpreter (plain-list contents)
757 "Interpret PLAIN-LIST element as Org syntax.
758 CONTENTS is the contents of the element."
759 contents)
762 ;;;; Quote Block
764 (defun org-element-quote-block-parser ()
765 "Parse a quote block.
767 Return a list whose CAR is `quote-block' and CDR is a plist
768 containing `:begin', `:end', `:hiddenp', `:contents-begin',
769 `:contents-end' and `:post-blank' keywords.
771 Assume point is at the beginning of the block."
772 (save-excursion
773 (let* ((case-fold-search t)
774 (keywords (org-element-collect-affiliated-keywords))
775 (begin (car keywords))
776 (contents-begin (progn (forward-line) (point)))
777 (hidden (org-truely-invisible-p))
778 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_QUOTE" nil t)
779 (point-at-bol)))
780 (pos-before-blank (progn (forward-line) (point)))
781 (end (progn (org-skip-whitespace)
782 (if (eobp) (point) (point-at-bol)))))
783 `(quote-block
784 (:begin ,begin
785 :end ,end
786 :hiddenp ,hidden
787 :contents-begin ,contents-begin
788 :contents-end ,contents-end
789 :post-blank ,(count-lines pos-before-blank end)
790 ,@(cadr keywords))))))
792 (defun org-element-quote-block-interpreter (quote-block contents)
793 "Interpret QUOTE-BLOCK element as Org syntax.
794 CONTENTS is the contents of the element."
795 (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
798 ;;;; Section
800 (defun org-element-section-parser ()
801 "Parse a section.
803 Return a list whose CAR is `section' and CDR is a plist
804 containing `:begin', `:end', `:contents-begin', `contents-end'
805 and `:post-blank' keywords."
806 (save-excursion
807 ;; Beginning of section is the beginning of the first non-blank
808 ;; line after previous headline.
809 (org-with-limited-levels
810 (let ((begin
811 (save-excursion
812 (outline-previous-heading)
813 (if (not (org-at-heading-p)) (point)
814 (forward-line) (org-skip-whitespace) (point-at-bol))))
815 (end (progn (outline-next-heading) (point)))
816 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
817 (forward-line)
818 (point))))
819 `(section
820 (:begin ,begin
821 :end ,end
822 :contents-begin ,begin
823 :contents-end ,pos-before-blank
824 :post-blank ,(count-lines pos-before-blank end)))))))
826 (defun org-element-section-interpreter (section contents)
827 "Interpret SECTION element as Org syntax.
828 CONTENTS is the contents of the element."
829 contents)
832 ;;;; Special Block
834 (defun org-element-special-block-parser ()
835 "Parse a special block.
837 Return a list whose CAR is `special-block' and CDR is a plist
838 containing `:type', `:begin', `:end', `:hiddenp',
839 `:contents-begin', `:contents-end' and `:post-blank' keywords.
841 Assume point is at the beginning of the block."
842 (save-excursion
843 (let* ((case-fold-search t)
844 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)")
845 (org-match-string-no-properties 1)))
846 (keywords (org-element-collect-affiliated-keywords))
847 (begin (car keywords))
848 (contents-begin (progn (forward-line) (point)))
849 (hidden (org-truely-invisible-p))
850 (contents-end
851 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
852 (point-at-bol)))
853 (pos-before-blank (progn (forward-line) (point)))
854 (end (progn (org-skip-whitespace)
855 (if (eobp) (point) (point-at-bol)))))
856 `(special-block
857 (:type ,type
858 :begin ,begin
859 :end ,end
860 :hiddenp ,hidden
861 :contents-begin ,contents-begin
862 :contents-end ,contents-end
863 :post-blank ,(count-lines pos-before-blank end)
864 ,@(cadr keywords))))))
866 (defun org-element-special-block-interpreter (special-block contents)
867 "Interpret SPECIAL-BLOCK element as Org syntax.
868 CONTENTS is the contents of the element."
869 (let ((block-type (org-element-property :type special-block)))
870 (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
874 ;;; Elements
876 ;; For each element, a parser and an interpreter are also defined.
877 ;; Both follow the same naming convention used for greater elements.
879 ;; Also, as for greater elements, adding a new element type is done
880 ;; through the following steps: implement a parser and an interpreter,
881 ;; tweak `org-element-current-element' so that it recognizes the new
882 ;; type and add that new type to `org-element-all-elements'.
884 ;; As a special case, when the newly defined type is a block type,
885 ;; `org-element-non-recursive-block-alist' has to be modified
886 ;; accordingly.
889 ;;;; Babel Call
891 (defun org-element-babel-call-parser ()
892 "Parse a babel call.
894 Return a list whose CAR is `babel-call' and CDR is a plist
895 containing `:begin', `:end', `:info' and `:post-blank' as
896 keywords."
897 (save-excursion
898 (let ((info (progn (looking-at org-babel-block-lob-one-liner-regexp)
899 (org-babel-lob-get-info)))
900 (begin (point-at-bol))
901 (pos-before-blank (progn (forward-line) (point)))
902 (end (progn (org-skip-whitespace)
903 (if (eobp) (point) (point-at-bol)))))
904 `(babel-call
905 (:begin ,begin
906 :end ,end
907 :info ,info
908 :post-blank ,(count-lines pos-before-blank end))))))
910 (defun org-element-babel-call-interpreter (babel-call contents)
911 "Interpret BABEL-CALL element as Org syntax.
912 CONTENTS is nil."
913 (let* ((babel-info (org-element-property :info babel-call))
914 (main (car babel-info))
915 (post-options (nth 1 babel-info)))
916 (concat "#+CALL: "
917 (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
918 ;; Remove redundant square brackets.
919 (replace-match (match-string 1 main) nil nil main))
920 (and post-options (format "[%s]" post-options)))))
923 ;;;; Clock
925 (defun org-element-clock-parser ()
926 "Parse a clock.
928 Return a list whose CAR is `clock' and CDR is a plist containing
929 `:status', `:value', `:time', `:begin', `:end' and `:post-blank'
930 as keywords."
931 (save-excursion
932 (let* ((case-fold-search nil)
933 (begin (point))
934 (value (progn (search-forward org-clock-string (line-end-position) t)
935 (org-skip-whitespace)
936 (looking-at "\\[.*\\]")
937 (org-match-string-no-properties 0)))
938 (time (and (progn (goto-char (match-end 0))
939 (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
940 (org-match-string-no-properties 1)))
941 (status (if time 'closed 'running))
942 (post-blank (let ((before-blank (progn (forward-line) (point))))
943 (org-skip-whitespace)
944 (unless (eobp) (beginning-of-line))
945 (count-lines before-blank (point))))
946 (end (point)))
947 `(clock (:status ,status
948 :value ,value
949 :time ,time
950 :begin ,begin
951 :end ,end
952 :post-blank ,post-blank)))))
954 (defun org-element-clock-interpreter (clock contents)
955 "Interpret CLOCK element as Org syntax.
956 CONTENTS is nil."
957 (concat org-clock-string " "
958 (org-element-property :value clock)
959 (let ((time (org-element-property :time clock)))
960 (and time
961 (concat " => "
962 (apply 'format
963 "%2s:%02s"
964 (org-split-string time ":")))))))
967 ;;;; Comment
969 (defun org-element-comment-parser ()
970 "Parse a comment.
972 Return a list whose CAR is `comment' and CDR is a plist
973 containing `:begin', `:end', `:value' and `:post-blank'
974 keywords.
976 Assume point is at comment beginning."
977 (save-excursion
978 (let* ((com-beg (point))
979 (keywords (org-element-collect-affiliated-keywords))
980 (begin (car keywords))
981 (com-end
982 ;; Get comments ending. This may not be accurate if
983 ;; commented lines within an item are followed by
984 ;; commented lines outside of a list. Though, parser will
985 ;; always get it right as it already knows surrounding
986 ;; element and has narrowed buffer to its contents.
987 (if (looking-at "#")
988 (if (re-search-forward "^\\([^#]\\|#\\+[a-z]\\)" nil 'move)
989 (progn (goto-char (match-beginning 0)) (point))
990 (point))
991 (while (looking-at "[ \t]*#\\+\\(?: \\|$\\)")
992 (forward-line))
993 (point)))
994 (end (progn (goto-char com-end)
995 (org-skip-whitespace)
996 (if (eobp) (point) (point-at-bol)))))
997 `(comment
998 (:begin ,(or (car keywords) com-beg)
999 :end ,end
1000 :value ,(buffer-substring-no-properties com-beg com-end)
1001 :post-blank ,(count-lines com-end end)
1002 ,@(cadr keywords))))))
1004 (defun org-element-comment-interpreter (comment contents)
1005 "Interpret COMMENT element as Org syntax.
1006 CONTENTS is nil."
1007 (org-element-property :value comment))
1010 ;;;; Comment Block
1012 (defun org-element-comment-block-parser ()
1013 "Parse an export block.
1015 Return a list whose CAR is `comment-block' and CDR is a plist
1016 containing `:begin', `:end', `:hiddenp', `:value' and
1017 `:post-blank' keywords.
1019 Assume point is at comment block beginning."
1020 (save-excursion
1021 (let* ((case-fold-search t)
1022 (keywords (org-element-collect-affiliated-keywords))
1023 (begin (car keywords))
1024 (contents-begin (progn (forward-line) (point)))
1025 (hidden (org-truely-invisible-p))
1026 (contents-end
1027 (progn (re-search-forward "^[ \t]*#\\+END_COMMENT" nil t)
1028 (point-at-bol)))
1029 (pos-before-blank (progn (forward-line) (point)))
1030 (end (progn (org-skip-whitespace)
1031 (if (eobp) (point) (point-at-bol))))
1032 (value (buffer-substring-no-properties contents-begin contents-end)))
1033 `(comment-block
1034 (:begin ,begin
1035 :end ,end
1036 :value ,value
1037 :hiddenp ,hidden
1038 :post-blank ,(count-lines pos-before-blank end)
1039 ,@(cadr keywords))))))
1041 (defun org-element-comment-block-interpreter (comment-block contents)
1042 "Interpret COMMENT-BLOCK element as Org syntax.
1043 CONTENTS is nil."
1044 (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
1045 (org-remove-indentation (org-element-property :value comment-block))))
1048 ;;;; Example Block
1050 (defun org-element-example-block-parser ()
1051 "Parse an example block.
1053 Return a list whose CAR is `example-block' and CDR is a plist
1054 containing `:begin', `:end', `:number-lines', `:preserve-indent',
1055 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
1056 `:switches', `:value' and `:post-blank' keywords."
1057 (save-excursion
1058 (let* ((case-fold-search t)
1059 (switches
1060 (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
1061 (org-match-string-no-properties 1)))
1062 ;; Switches analysis
1063 (number-lines (cond ((not switches) nil)
1064 ((string-match "-n\\>" switches) 'new)
1065 ((string-match "+n\\>" switches) 'continued)))
1066 (preserve-indent (and switches (string-match "-i\\>" switches)))
1067 ;; Should labels be retained in (or stripped from) example
1068 ;; blocks?
1069 (retain-labels
1070 (or (not switches)
1071 (not (string-match "-r\\>" switches))
1072 (and number-lines (string-match "-k\\>" switches))))
1073 ;; What should code-references use - labels or
1074 ;; line-numbers?
1075 (use-labels
1076 (or (not switches)
1077 (and retain-labels (not (string-match "-k\\>" switches)))))
1078 (label-fmt (and switches
1079 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1080 (match-string 1 switches)))
1081 ;; Standard block parsing.
1082 (keywords (org-element-collect-affiliated-keywords))
1083 (begin (car keywords))
1084 (contents-begin (progn (forward-line) (point)))
1085 (hidden (org-truely-invisible-p))
1086 (contents-end
1087 (progn (re-search-forward "^[ \t]*#\\+END_EXAMPLE" nil t)
1088 (point-at-bol)))
1089 (value (buffer-substring-no-properties contents-begin contents-end))
1090 (pos-before-blank (progn (forward-line) (point)))
1091 (end (progn (org-skip-whitespace)
1092 (if (eobp) (point) (point-at-bol)))))
1093 `(example-block
1094 (:begin ,begin
1095 :end ,end
1096 :value ,value
1097 :switches ,switches
1098 :number-lines ,number-lines
1099 :preserve-indent ,preserve-indent
1100 :retain-labels ,retain-labels
1101 :use-labels ,use-labels
1102 :label-fmt ,label-fmt
1103 :hiddenp ,hidden
1104 :post-blank ,(count-lines pos-before-blank end)
1105 ,@(cadr keywords))))))
1107 (defun org-element-example-block-interpreter (example-block contents)
1108 "Interpret EXAMPLE-BLOCK element as Org syntax.
1109 CONTENTS is nil."
1110 (let ((switches (org-element-property :switches example-block)))
1111 (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
1112 (org-remove-indentation
1113 (org-element-property :value example-block))
1114 "#+END_EXAMPLE")))
1117 ;;;; Export Block
1119 (defun org-element-export-block-parser ()
1120 "Parse an export block.
1122 Return a list whose CAR is `export-block' and CDR is a plist
1123 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1124 `:post-blank' keywords.
1126 Assume point is at export-block beginning."
1127 (save-excursion
1128 (let* ((case-fold-search t)
1129 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\([A-Za-z0-9]+\\)")
1130 (upcase (org-match-string-no-properties 1))))
1131 (keywords (org-element-collect-affiliated-keywords))
1132 (begin (car keywords))
1133 (contents-begin (progn (forward-line) (point)))
1134 (hidden (org-truely-invisible-p))
1135 (contents-end
1136 (progn (re-search-forward (concat "^[ \t]*#\\+END_" type) nil t)
1137 (point-at-bol)))
1138 (pos-before-blank (progn (forward-line) (point)))
1139 (end (progn (org-skip-whitespace)
1140 (if (eobp) (point) (point-at-bol))))
1141 (value (buffer-substring-no-properties contents-begin contents-end)))
1142 `(export-block
1143 (:begin ,begin
1144 :end ,end
1145 :type ,type
1146 :value ,value
1147 :hiddenp ,hidden
1148 :post-blank ,(count-lines pos-before-blank end)
1149 ,@(cadr keywords))))))
1151 (defun org-element-export-block-interpreter (export-block contents)
1152 "Interpret EXPORT-BLOCK element as Org syntax.
1153 CONTENTS is nil."
1154 (let ((type (org-element-property :type export-block)))
1155 (concat (format "#+BEGIN_%s\n" type)
1156 (org-element-property :value export-block)
1157 (format "#+END_%s" type))))
1160 ;;;; Fixed-width
1162 (defun org-element-fixed-width-parser ()
1163 "Parse a fixed-width section.
1165 Return a list whose CAR is `fixed-width' and CDR is a plist
1166 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1168 Assume point is at the beginning of the fixed-width area."
1169 (save-excursion
1170 (let* ((beg-area (point))
1171 (keywords (org-element-collect-affiliated-keywords))
1172 (begin (car keywords))
1173 (end-area
1174 (progn (while (looking-at "[ \t]*:\\( \\|$\\)")
1175 (forward-line))
1176 (point)))
1177 (end (progn (org-skip-whitespace)
1178 (if (eobp) (point) (point-at-bol))))
1179 (value (buffer-substring-no-properties beg-area end-area)))
1180 `(fixed-width
1181 (:begin ,begin
1182 :end ,end
1183 :value ,value
1184 :post-blank ,(count-lines end-area end)
1185 ,@(cadr keywords))))))
1187 (defun org-element-fixed-width-interpreter (fixed-width contents)
1188 "Interpret FIXED-WIDTH element as Org syntax.
1189 CONTENTS is nil."
1190 (org-remove-indentation (org-element-property :value fixed-width)))
1193 ;;;; Horizontal Rule
1195 (defun org-element-horizontal-rule-parser ()
1196 "Parse an horizontal rule.
1198 Return a list whose CAR is `horizontal-rule' and CDR is a plist
1199 containing `:begin', `:end' and `:post-blank' keywords."
1200 (save-excursion
1201 (let* ((keywords (org-element-collect-affiliated-keywords))
1202 (begin (car keywords))
1203 (post-hr (progn (forward-line) (point)))
1204 (end (progn (org-skip-whitespace)
1205 (if (eobp) (point) (point-at-bol)))))
1206 `(horizontal-rule
1207 (:begin ,begin
1208 :end ,end
1209 :post-blank ,(count-lines post-hr end)
1210 ,@(cadr keywords))))))
1212 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1213 "Interpret HORIZONTAL-RULE element as Org syntax.
1214 CONTENTS is nil."
1215 "-----")
1218 ;;;; Keyword
1220 (defun org-element-keyword-parser ()
1221 "Parse a keyword at point.
1223 Return a list whose CAR is `keyword' and CDR is a plist
1224 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1225 keywords."
1226 (save-excursion
1227 (let* ((case-fold-search t)
1228 (begin (point))
1229 (key (progn (looking-at
1230 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1231 (upcase (org-match-string-no-properties 1))))
1232 (value (org-trim (buffer-substring-no-properties
1233 (match-end 0) (point-at-eol))))
1234 (pos-before-blank (progn (forward-line) (point)))
1235 (end (progn (org-skip-whitespace)
1236 (if (eobp) (point) (point-at-bol)))))
1237 `(keyword
1238 (:key ,key
1239 :value ,value
1240 :begin ,begin
1241 :end ,end
1242 :post-blank ,(count-lines pos-before-blank end))))))
1244 (defun org-element-keyword-interpreter (keyword contents)
1245 "Interpret KEYWORD element as Org syntax.
1246 CONTENTS is nil."
1247 (format "#+%s: %s"
1248 (org-element-property :key keyword)
1249 (org-element-property :value keyword)))
1252 ;;;; Latex Environment
1254 (defun org-element-latex-environment-parser ()
1255 "Parse a LaTeX environment.
1257 Return a list whose CAR is `latex-environment' and CDR is a plist
1258 containing `:begin', `:end', `:value' and `:post-blank'
1259 keywords.
1261 Assume point is at the beginning of the latex environment."
1262 (save-excursion
1263 (let* ((case-fold-search t)
1264 (contents-begin (point))
1265 (keywords (org-element-collect-affiliated-keywords))
1266 (begin (car keywords))
1267 (contents-end (progn (re-search-forward "^[ \t]*\\\\end")
1268 (forward-line)
1269 (point)))
1270 (value (buffer-substring-no-properties contents-begin contents-end))
1271 (end (progn (org-skip-whitespace)
1272 (if (eobp) (point) (point-at-bol)))))
1273 `(latex-environment
1274 (:begin ,begin
1275 :end ,end
1276 :value ,value
1277 :post-blank ,(count-lines contents-end end)
1278 ,@(cadr keywords))))))
1280 (defun org-element-latex-environment-interpreter (latex-environment contents)
1281 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1282 CONTENTS is nil."
1283 (org-element-property :value latex-environment))
1286 ;;;; Paragraph
1288 (defun org-element-paragraph-parser ()
1289 "Parse a paragraph.
1291 Return a list whose CAR is `paragraph' and CDR is a plist
1292 containing `:begin', `:end', `:contents-begin' and
1293 `:contents-end' and `:post-blank' keywords.
1295 Assume point is at the beginning of the paragraph."
1296 (save-excursion
1297 (let* ((contents-begin (point))
1298 (keywords (org-element-collect-affiliated-keywords))
1299 (begin (car keywords))
1300 (contents-end
1301 (progn (end-of-line)
1302 (if (re-search-forward org-element-paragraph-separate nil 'm)
1303 (progn (forward-line -1) (end-of-line) (point))
1304 (point))))
1305 (pos-before-blank (progn (forward-line) (point)))
1306 (end (progn (org-skip-whitespace)
1307 (if (eobp) (point) (point-at-bol)))))
1308 `(paragraph
1309 (:begin ,begin
1310 :end ,end
1311 :contents-begin ,contents-begin
1312 :contents-end ,contents-end
1313 :post-blank ,(count-lines pos-before-blank end)
1314 ,@(cadr keywords))))))
1316 (defun org-element-paragraph-interpreter (paragraph contents)
1317 "Interpret PARAGRAPH element as Org syntax.
1318 CONTENTS is the contents of the element."
1319 contents)
1322 ;;;; Planning
1324 (defun org-element-planning-parser ()
1325 "Parse a planning.
1327 Return a list whose CAR is `planning' and CDR is a plist
1328 containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
1329 and `:post-blank' keywords."
1330 (save-excursion
1331 (let* ((case-fold-search nil)
1332 (begin (point))
1333 (post-blank (let ((before-blank (progn (forward-line) (point))))
1334 (org-skip-whitespace)
1335 (unless (eobp) (beginning-of-line))
1336 (count-lines before-blank (point))))
1337 (end (point))
1338 closed deadline scheduled)
1339 (goto-char begin)
1340 (while (re-search-forward org-keyword-time-not-clock-regexp
1341 (line-end-position) t)
1342 (goto-char (match-end 1))
1343 (org-skip-whitespace)
1344 (let ((time (buffer-substring-no-properties (point) (match-end 0)))
1345 (keyword (match-string 1)))
1346 (cond ((equal keyword org-closed-string) (setq closed time))
1347 ((equal keyword org-deadline-string) (setq deadline time))
1348 (t (setq scheduled time)))))
1349 `(planning
1350 (:closed ,closed
1351 :deadline ,deadline
1352 :scheduled ,scheduled
1353 :begin ,begin
1354 :end ,end
1355 :post-blank ,post-blank)))))
1357 (defun org-element-planning-interpreter (planning contents)
1358 "Interpret PLANNING element as Org syntax.
1359 CONTENTS is nil."
1360 (mapconcat
1361 'identity
1362 (delq nil
1363 (list (let ((closed (org-element-property :closed planning)))
1364 (when closed (concat org-closed-string " " closed)))
1365 (let ((deadline (org-element-property :deadline planning)))
1366 (when deadline (concat org-deadline-string " " deadline)))
1367 (let ((scheduled (org-element-property :scheduled planning)))
1368 (when scheduled (concat org-scheduled-string " " scheduled)))))
1369 " "))
1372 ;;;; Property Drawer
1374 (defun org-element-property-drawer-parser ()
1375 "Parse a property drawer.
1377 Return a list whose CAR is `property-drawer' and CDR is a plist
1378 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1379 `:contents-end', `:properties' and `:post-blank' keywords.
1381 Assume point is at the beginning of the property drawer."
1382 (save-excursion
1383 (let ((case-fold-search t)
1384 (begin (point))
1385 (prop-begin (progn (forward-line) (point)))
1386 (hidden (org-truely-invisible-p))
1387 (properties
1388 (let (val)
1389 (while (not (looking-at "^[ \t]*:END:"))
1390 (when (looking-at "[ \t]*:\\([A-Za-z][-_A-Za-z0-9]*\\):")
1391 (push (cons (org-match-string-no-properties 1)
1392 (org-trim
1393 (buffer-substring-no-properties
1394 (match-end 0) (point-at-eol))))
1395 val))
1396 (forward-line))
1397 val))
1398 (prop-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1399 (point-at-bol)))
1400 (pos-before-blank (progn (forward-line) (point)))
1401 (end (progn (org-skip-whitespace)
1402 (if (eobp) (point) (point-at-bol)))))
1403 `(property-drawer
1404 (:begin ,begin
1405 :end ,end
1406 :hiddenp ,hidden
1407 :properties ,properties
1408 :post-blank ,(count-lines pos-before-blank end))))))
1410 (defun org-element-property-drawer-interpreter (property-drawer contents)
1411 "Interpret PROPERTY-DRAWER element as Org syntax.
1412 CONTENTS is nil."
1413 (let ((props (org-element-property :properties property-drawer)))
1414 (concat
1415 ":PROPERTIES:\n"
1416 (mapconcat (lambda (p)
1417 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1418 (nreverse props) "\n")
1419 "\n:END:")))
1422 ;;;; Quote Section
1424 (defun org-element-quote-section-parser ()
1425 "Parse a quote section.
1427 Return a list whose CAR is `quote-section' and CDR is a plist
1428 containing `:begin', `:end', `:value' and `:post-blank' keywords.
1430 Assume point is at beginning of the section."
1431 (save-excursion
1432 (let* ((begin (point))
1433 (end (progn (org-with-limited-levels (outline-next-heading))
1434 (point)))
1435 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1436 (forward-line)
1437 (point)))
1438 (value (buffer-substring-no-properties begin pos-before-blank)))
1439 `(quote-section
1440 (:begin ,begin
1441 :end ,end
1442 :value ,value
1443 :post-blank ,(count-lines pos-before-blank end))))))
1445 (defun org-element-quote-section-interpreter (quote-section contents)
1446 "Interpret QUOTE-SECTION element as Org syntax.
1447 CONTENTS is nil."
1448 (org-element-property :value quote-section))
1451 ;;;; Src Block
1453 (defun org-element-src-block-parser ()
1454 "Parse a src block.
1456 Return a list whose CAR is `src-block' and CDR is a plist
1457 containing `:language', `:switches', `:parameters', `:begin',
1458 `:end', `:hiddenp', `:contents-begin', `:contents-end',
1459 `:number-lines', `:retain-labels', `:use-labels', `:label-fmt',
1460 `:preserve-indent', `:value' and `:post-blank' keywords.
1462 Assume point is at the beginning of the block."
1463 (save-excursion
1464 (let* ((case-fold-search t)
1465 (contents-begin (point))
1466 ;; Get affiliated keywords.
1467 (keywords (org-element-collect-affiliated-keywords))
1468 ;; Get beginning position.
1469 (begin (car keywords))
1470 ;; Get language as a string.
1471 (language
1472 (progn
1473 (looking-at
1474 (concat "^[ \t]*#\\+BEGIN_SRC"
1475 "\\(?: +\\(\\S-+\\)\\)?"
1476 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)+\\)?"
1477 "\\(.*\\)[ \t]*$"))
1478 (org-match-string-no-properties 1)))
1479 ;; Get switches.
1480 (switches (org-match-string-no-properties 2))
1481 ;; Get parameters.
1482 (parameters (org-match-string-no-properties 3))
1483 ;; Switches analysis
1484 (number-lines (cond ((not switches) nil)
1485 ((string-match "-n\\>" switches) 'new)
1486 ((string-match "+n\\>" switches) 'continued)))
1487 (preserve-indent (and switches (string-match "-i\\>" switches)))
1488 (label-fmt (and switches
1489 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1490 (match-string 1 switches)))
1491 ;; Should labels be retained in (or stripped from) src
1492 ;; blocks?
1493 (retain-labels
1494 (or (not switches)
1495 (not (string-match "-r\\>" switches))
1496 (and number-lines (string-match "-k\\>" switches))))
1497 ;; What should code-references use - labels or
1498 ;; line-numbers?
1499 (use-labels
1500 (or (not switches)
1501 (and retain-labels (not (string-match "-k\\>" switches)))))
1502 ;; Get position at end of block.
1503 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_SRC" nil t)
1504 (forward-line)
1505 (point)))
1506 ;; Retrieve code.
1507 (value (buffer-substring-no-properties
1508 (save-excursion (goto-char contents-begin)
1509 (forward-line)
1510 (point))
1511 (match-beginning 0)))
1512 ;; Get position after ending blank lines.
1513 (end (progn (org-skip-whitespace)
1514 (if (eobp) (point) (point-at-bol))))
1515 ;; Get visibility status.
1516 (hidden (progn (goto-char contents-begin)
1517 (forward-line)
1518 (org-truely-invisible-p))))
1519 `(src-block
1520 (:language ,language
1521 :switches ,(and (org-string-nw-p switches)
1522 (org-trim switches))
1523 :parameters ,(and (org-string-nw-p parameters)
1524 (org-trim parameters))
1525 :begin ,begin
1526 :end ,end
1527 :number-lines ,number-lines
1528 :preserve-indent ,preserve-indent
1529 :retain-labels ,retain-labels
1530 :use-labels ,use-labels
1531 :label-fmt ,label-fmt
1532 :hiddenp ,hidden
1533 :value ,value
1534 :post-blank ,(count-lines contents-end end)
1535 ,@(cadr keywords))))))
1537 (defun org-element-src-block-interpreter (src-block contents)
1538 "Interpret SRC-BLOCK element as Org syntax.
1539 CONTENTS is nil."
1540 (let ((lang (org-element-property :language src-block))
1541 (switches (org-element-property :switches src-block))
1542 (params (org-element-property :parameters src-block))
1543 (value (let ((val (org-element-property :value src-block)))
1544 (cond
1546 (org-src-preserve-indentation val)
1547 ((zerop org-edit-src-content-indentation)
1548 (org-remove-indentation val))
1550 (let ((ind (make-string
1551 org-edit-src-content-indentation 32)))
1552 (replace-regexp-in-string
1553 "\\(^\\)[ \t]*\\S-" ind
1554 (org-remove-indentation val) nil nil 1)))))))
1555 (concat (format "#+BEGIN_SRC%s\n"
1556 (concat (and lang (concat " " lang))
1557 (and switches (concat " " switches))
1558 (and params (concat " " params))))
1559 value
1560 "#+END_SRC")))
1563 ;;;; Table
1565 (defun org-element-table-parser ()
1566 "Parse a table at point.
1568 Return a list whose CAR is `table' and CDR is a plist containing
1569 `:begin', `:end', `:tblfm', `:type', `:contents-begin',
1570 `:contents-end', `:value' and `:post-blank' keywords.
1572 Assume point is at the beginning of the table."
1573 (save-excursion
1574 (let* ((case-fold-search t)
1575 (table-begin (point))
1576 (type (if (org-at-table.el-p) 'table.el 'org))
1577 (keywords (org-element-collect-affiliated-keywords))
1578 (begin (car keywords))
1579 (table-end (goto-char (marker-position (org-table-end t))))
1580 (tblfm (when (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
1581 (prog1 (org-match-string-no-properties 1)
1582 (forward-line))))
1583 (pos-before-blank (point))
1584 (end (progn (org-skip-whitespace)
1585 (if (eobp) (point) (point-at-bol)))))
1586 `(table
1587 (:begin ,begin
1588 :end ,end
1589 :type ,type
1590 :tblfm ,tblfm
1591 ;; Only `org' tables have contents. `table.el' tables
1592 ;; use a `:value' property to store raw table as
1593 ;; a string.
1594 :contents-begin ,(and (eq type 'org) table-begin)
1595 :contents-end ,(and (eq type 'org) table-end)
1596 :value ,(and (eq type 'table.el)
1597 (buffer-substring-no-properties
1598 table-begin table-end))
1599 :post-blank ,(count-lines pos-before-blank end)
1600 ,@(cadr keywords))))))
1602 (defun org-element-table-interpreter (table contents)
1603 "Interpret TABLE element as Org syntax.
1604 CONTENTS is nil."
1605 (if (eq (org-element-property :type table) 'table.el)
1606 (org-remove-indentation (org-element-property :value table))
1607 (concat (with-temp-buffer (insert contents)
1608 (org-table-align)
1609 (buffer-string))
1610 (when (org-element-property :tblfm table)
1611 (format "#+TBLFM: " (org-element-property :tblfm table))))))
1614 ;;;; Table Row
1616 (defun org-element-table-row-parser ()
1617 "Parse table row at point.
1619 Return a list whose CAR is `table-row' and CDR is a plist
1620 containing `:begin', `:end', `:contents-begin', `:contents-end',
1621 `:type' and `:post-blank' keywords."
1622 (save-excursion
1623 (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
1624 (begin (point))
1625 ;; A table rule has no contents. In that case, ensure
1626 ;; CONTENTS-BEGIN matches CONTENTS-END.
1627 (contents-begin (if (eq type 'standard)
1628 (progn (search-forward "|") (point))
1629 (end-of-line)
1630 (skip-chars-backward " \r\t\n")
1631 (point)))
1632 (contents-end (progn (end-of-line)
1633 (skip-chars-backward " \r\t\n")
1634 (point)))
1635 (end (progn (forward-line) (point))))
1636 `(table-row
1637 (:type ,type
1638 :begin ,begin
1639 :end ,end
1640 :contents-begin ,contents-begin
1641 :contents-end ,contents-end
1642 :post-blank 0)))))
1644 (defun org-element-table-row-interpreter (table-row contents)
1645 "Interpret TABLE-ROW element as Org syntax.
1646 CONTENTS is the contents of the table row."
1647 (if (eq (org-element-property :type table-row) 'rule) "|-"
1648 (concat "| " contents)))
1651 ;;;; Verse Block
1653 (defun org-element-verse-block-parser ()
1654 "Parse a verse block.
1656 Return a list whose CAR is `verse-block' and CDR is a plist
1657 containing `:begin', `:end', `:contents-begin', `:contents-end',
1658 `:hiddenp' and `:post-blank' keywords.
1660 Assume point is at beginning of the block."
1661 (save-excursion
1662 (let* ((case-fold-search t)
1663 (keywords (org-element-collect-affiliated-keywords))
1664 (begin (car keywords))
1665 (hidden (progn (forward-line) (org-truely-invisible-p)))
1666 (contents-begin (point))
1667 (contents-end
1668 (progn
1669 (re-search-forward (concat "^[ \t]*#\\+END_VERSE") nil t)
1670 (point-at-bol)))
1671 (pos-before-blank (progn (forward-line) (point)))
1672 (end (progn (org-skip-whitespace)
1673 (if (eobp) (point) (point-at-bol)))))
1674 `(verse-block
1675 (:begin ,begin
1676 :end ,end
1677 :contents-begin ,contents-begin
1678 :contents-end ,contents-end
1679 :hiddenp ,hidden
1680 :post-blank ,(count-lines pos-before-blank end)
1681 ,@(cadr keywords))))))
1683 (defun org-element-verse-block-interpreter (verse-block contents)
1684 "Interpret VERSE-BLOCK element as Org syntax.
1685 CONTENTS is verse block contents."
1686 (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
1690 ;;; Objects
1692 ;; Unlike to elements, interstices can be found between objects.
1693 ;; That's why, along with the parser, successor functions are provided
1694 ;; for each object. Some objects share the same successor (i.e. `code'
1695 ;; and `verbatim' objects).
1697 ;; A successor must accept a single argument bounding the search. It
1698 ;; will return either a cons cell whose CAR is the object's type, as
1699 ;; a symbol, and CDR the position of its next occurrence, or nil.
1701 ;; Successors follow the naming convention:
1702 ;; org-element-NAME-successor, where NAME is the name of the
1703 ;; successor, as defined in `org-element-all-successors'.
1705 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1706 ;; object types they can contain will be specified in
1707 ;; `org-element-object-restrictions'.
1709 ;; Adding a new type of object is simple. Implement a successor,
1710 ;; a parser, and an interpreter for it, all following the naming
1711 ;; convention. Register type in `org-element-all-objects' and
1712 ;; successor in `org-element-all-successors'. Maybe tweak
1713 ;; restrictions about it, and that's it.
1716 ;;;; Bold
1718 (defun org-element-bold-parser ()
1719 "Parse bold object at point.
1721 Return a list whose CAR is `bold' and CDR is a plist with
1722 `:begin', `:end', `:contents-begin' and `:contents-end' and
1723 `:post-blank' keywords.
1725 Assume point is at the first star marker."
1726 (save-excursion
1727 (unless (bolp) (backward-char 1))
1728 (looking-at org-emph-re)
1729 (let ((begin (match-beginning 2))
1730 (contents-begin (match-beginning 4))
1731 (contents-end (match-end 4))
1732 (post-blank (progn (goto-char (match-end 2))
1733 (skip-chars-forward " \t")))
1734 (end (point)))
1735 `(bold
1736 (:begin ,begin
1737 :end ,end
1738 :contents-begin ,contents-begin
1739 :contents-end ,contents-end
1740 :post-blank ,post-blank)))))
1742 (defun org-element-bold-interpreter (bold contents)
1743 "Interpret BOLD object as Org syntax.
1744 CONTENTS is the contents of the object."
1745 (format "*%s*" contents))
1747 (defun org-element-text-markup-successor (limit)
1748 "Search for the next text-markup object.
1750 LIMIT bounds the search.
1752 Return value is a cons cell whose CAR is a symbol among `bold',
1753 `italic', `underline', `strike-through', `code' and `verbatim'
1754 and CDR is beginning position."
1755 (save-excursion
1756 (unless (bolp) (backward-char))
1757 (when (re-search-forward org-emph-re limit t)
1758 (let ((marker (match-string 3)))
1759 (cons (cond
1760 ((equal marker "*") 'bold)
1761 ((equal marker "/") 'italic)
1762 ((equal marker "_") 'underline)
1763 ((equal marker "+") 'strike-through)
1764 ((equal marker "~") 'code)
1765 ((equal marker "=") 'verbatim)
1766 (t (error "Unknown marker at %d" (match-beginning 3))))
1767 (match-beginning 2))))))
1770 ;;;; Code
1772 (defun org-element-code-parser ()
1773 "Parse code object at point.
1775 Return a list whose CAR is `code' and CDR is a plist with
1776 `:value', `:begin', `:end' and `:post-blank' keywords.
1778 Assume point is at the first tilde marker."
1779 (save-excursion
1780 (unless (bolp) (backward-char 1))
1781 (looking-at org-emph-re)
1782 (let ((begin (match-beginning 2))
1783 (value (org-match-string-no-properties 4))
1784 (post-blank (progn (goto-char (match-end 2))
1785 (skip-chars-forward " \t")))
1786 (end (point)))
1787 `(code
1788 (:value ,value
1789 :begin ,begin
1790 :end ,end
1791 :post-blank ,post-blank)))))
1793 (defun org-element-code-interpreter (code contents)
1794 "Interpret CODE object as Org syntax.
1795 CONTENTS is nil."
1796 (format "~%s~" (org-element-property :value code)))
1799 ;;;; Entity
1801 (defun org-element-entity-parser ()
1802 "Parse entity at point.
1804 Return a list whose CAR is `entity' and CDR a plist with
1805 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1806 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1807 keywords.
1809 Assume point is at the beginning of the entity."
1810 (save-excursion
1811 (looking-at "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1812 (let* ((value (org-entity-get (match-string 1)))
1813 (begin (match-beginning 0))
1814 (bracketsp (string= (match-string 2) "{}"))
1815 (post-blank (progn (goto-char (match-end 1))
1816 (when bracketsp (forward-char 2))
1817 (skip-chars-forward " \t")))
1818 (end (point)))
1819 `(entity
1820 (:name ,(car value)
1821 :latex ,(nth 1 value)
1822 :latex-math-p ,(nth 2 value)
1823 :html ,(nth 3 value)
1824 :ascii ,(nth 4 value)
1825 :latin1 ,(nth 5 value)
1826 :utf-8 ,(nth 6 value)
1827 :begin ,begin
1828 :end ,end
1829 :use-brackets-p ,bracketsp
1830 :post-blank ,post-blank)))))
1832 (defun org-element-entity-interpreter (entity contents)
1833 "Interpret ENTITY object as Org syntax.
1834 CONTENTS is nil."
1835 (concat "\\"
1836 (org-element-property :name entity)
1837 (when (org-element-property :use-brackets-p entity) "{}")))
1839 (defun org-element-latex-or-entity-successor (limit)
1840 "Search for the next latex-fragment or entity object.
1842 LIMIT bounds the search.
1844 Return value is a cons cell whose CAR is `entity' or
1845 `latex-fragment' and CDR is beginning position."
1846 (save-excursion
1847 (let ((matchers (plist-get org-format-latex-options :matchers))
1848 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1849 (entity-re
1850 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"))
1851 (when (re-search-forward
1852 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1853 matchers "\\|")
1854 "\\|" entity-re)
1855 limit t)
1856 (goto-char (match-beginning 0))
1857 (if (looking-at entity-re)
1858 ;; Determine if it's a real entity or a LaTeX command.
1859 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1860 (match-beginning 0))
1861 ;; No entity nor command: point is at a LaTeX fragment.
1862 ;; Determine its type to get the correct beginning position.
1863 (cons 'latex-fragment
1864 (catch 'return
1865 (mapc (lambda (e)
1866 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1867 (throw 'return
1868 (match-beginning
1869 (nth 2 (assoc e org-latex-regexps))))))
1870 matchers)
1871 (point))))))))
1874 ;;;; Export Snippet
1876 (defun org-element-export-snippet-parser ()
1877 "Parse export snippet at point.
1879 Return a list whose CAR is `export-snippet' and CDR a plist with
1880 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1881 keywords.
1883 Assume point is at the beginning of the snippet."
1884 (save-excursion
1885 (looking-at "<\\([-A-Za-z0-9]+\\)@")
1886 (let* ((begin (point))
1887 (back-end (org-match-string-no-properties 1))
1888 (inner-begin (match-end 0))
1889 (inner-end
1890 (let ((count 1))
1891 (goto-char inner-begin)
1892 (while (and (> count 0) (re-search-forward "[<>]" nil t))
1893 (if (equal (match-string 0) "<") (incf count) (decf count)))
1894 (1- (point))))
1895 (value (buffer-substring-no-properties inner-begin inner-end))
1896 (post-blank (skip-chars-forward " \t"))
1897 (end (point)))
1898 `(export-snippet
1899 (:back-end ,back-end
1900 :value ,value
1901 :begin ,begin
1902 :end ,end
1903 :post-blank ,post-blank)))))
1905 (defun org-element-export-snippet-interpreter (export-snippet contents)
1906 "Interpret EXPORT-SNIPPET object as Org syntax.
1907 CONTENTS is nil."
1908 (format "<%s@%s>"
1909 (org-element-property :back-end export-snippet)
1910 (org-element-property :value export-snippet)))
1912 (defun org-element-export-snippet-successor (limit)
1913 "Search for the next export-snippet object.
1915 LIMIT bounds the search.
1917 Return value is a cons cell whose CAR is `export-snippet' CDR is
1918 its beginning position."
1919 (save-excursion
1920 (catch 'exit
1921 (while (re-search-forward "<[-A-Za-z0-9]+@" limit t)
1922 (save-excursion
1923 (let ((beg (match-beginning 0))
1924 (count 1))
1925 (while (re-search-forward "[<>]" limit t)
1926 (if (equal (match-string 0) "<") (incf count) (decf count))
1927 (when (zerop count)
1928 (throw 'exit (cons 'export-snippet beg))))))))))
1931 ;;;; Footnote Reference
1933 (defun org-element-footnote-reference-parser ()
1934 "Parse footnote reference at point.
1936 Return a list whose CAR is `footnote-reference' and CDR a plist
1937 with `:label', `:type', `:inline-definition', `:begin', `:end'
1938 and `:post-blank' as keywords."
1939 (save-excursion
1940 (looking-at org-footnote-re)
1941 (let* ((begin (point))
1942 (label (or (org-match-string-no-properties 2)
1943 (org-match-string-no-properties 3)
1944 (and (match-string 1)
1945 (concat "fn:" (org-match-string-no-properties 1)))))
1946 (type (if (or (not label) (match-string 1)) 'inline 'standard))
1947 (inner-begin (match-end 0))
1948 (inner-end
1949 (let ((count 1))
1950 (forward-char)
1951 (while (and (> count 0) (re-search-forward "[][]" nil t))
1952 (if (equal (match-string 0) "[") (incf count) (decf count)))
1953 (1- (point))))
1954 (post-blank (progn (goto-char (1+ inner-end))
1955 (skip-chars-forward " \t")))
1956 (end (point))
1957 (inline-definition
1958 (and (eq type 'inline)
1959 (org-element-parse-secondary-string
1960 (buffer-substring inner-begin inner-end)
1961 (org-element-restriction 'footnote-reference)))))
1962 `(footnote-reference
1963 (:label ,label
1964 :type ,type
1965 :inline-definition ,inline-definition
1966 :begin ,begin
1967 :end ,end
1968 :post-blank ,post-blank)))))
1970 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1971 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1972 CONTENTS is nil."
1973 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
1974 (def
1975 (let ((inline-def
1976 (org-element-property :inline-definition footnote-reference)))
1977 (if (not inline-def) ""
1978 (concat ":" (org-element-interpret-data inline-def))))))
1979 (format "[%s]" (concat label def))))
1981 (defun org-element-footnote-reference-successor (limit)
1982 "Search for the next footnote-reference object.
1984 LIMIT bounds the search.
1986 Return value is a cons cell whose CAR is `footnote-reference' and
1987 CDR is beginning position."
1988 (save-excursion
1989 (catch 'exit
1990 (while (re-search-forward org-footnote-re limit t)
1991 (save-excursion
1992 (let ((beg (match-beginning 0))
1993 (count 1))
1994 (backward-char)
1995 (while (re-search-forward "[][]" limit t)
1996 (if (equal (match-string 0) "[") (incf count) (decf count))
1997 (when (zerop count)
1998 (throw 'exit (cons 'footnote-reference beg))))))))))
2001 ;;;; Inline Babel Call
2003 (defun org-element-inline-babel-call-parser ()
2004 "Parse inline babel call at point.
2006 Return a list whose CAR is `inline-babel-call' and CDR a plist
2007 with `:begin', `:end', `:info' and `:post-blank' as keywords.
2009 Assume point is at the beginning of the babel call."
2010 (save-excursion
2011 (unless (bolp) (backward-char))
2012 (looking-at org-babel-inline-lob-one-liner-regexp)
2013 (let ((info (save-match-data (org-babel-lob-get-info)))
2014 (begin (match-end 1))
2015 (post-blank (progn (goto-char (match-end 0))
2016 (skip-chars-forward " \t")))
2017 (end (point)))
2018 `(inline-babel-call
2019 (:begin ,begin
2020 :end ,end
2021 :info ,info
2022 :post-blank ,post-blank)))))
2024 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
2025 "Interpret INLINE-BABEL-CALL object as Org syntax.
2026 CONTENTS is nil."
2027 (let* ((babel-info (org-element-property :info inline-babel-call))
2028 (main-source (car babel-info))
2029 (post-options (nth 1 babel-info)))
2030 (concat "call_"
2031 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
2032 ;; Remove redundant square brackets.
2033 (replace-match
2034 (match-string 1 main-source) nil nil main-source)
2035 main-source)
2036 (and post-options (format "[%s]" post-options)))))
2038 (defun org-element-inline-babel-call-successor (limit)
2039 "Search for the next inline-babel-call object.
2041 LIMIT bounds the search.
2043 Return value is a cons cell whose CAR is `inline-babel-call' and
2044 CDR is beginning position."
2045 (save-excursion
2046 ;; Use a simplified version of
2047 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
2048 (when (re-search-forward
2049 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
2050 limit t)
2051 (cons 'inline-babel-call (match-beginning 0)))))
2054 ;;;; Inline Src Block
2056 (defun org-element-inline-src-block-parser ()
2057 "Parse inline source block at point.
2059 Return a list whose CAR is `inline-src-block' and CDR a plist
2060 with `:begin', `:end', `:language', `:value', `:parameters' and
2061 `:post-blank' as keywords.
2063 Assume point is at the beginning of the inline src block."
2064 (save-excursion
2065 (unless (bolp) (backward-char))
2066 (looking-at org-babel-inline-src-block-regexp)
2067 (let ((begin (match-beginning 1))
2068 (language (org-match-string-no-properties 2))
2069 (parameters (org-match-string-no-properties 4))
2070 (value (org-match-string-no-properties 5))
2071 (post-blank (progn (goto-char (match-end 0))
2072 (skip-chars-forward " \t")))
2073 (end (point)))
2074 `(inline-src-block
2075 (:language ,language
2076 :value ,value
2077 :parameters ,parameters
2078 :begin ,begin
2079 :end ,end
2080 :post-blank ,post-blank)))))
2082 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
2083 "Interpret INLINE-SRC-BLOCK object as Org syntax.
2084 CONTENTS is nil."
2085 (let ((language (org-element-property :language inline-src-block))
2086 (arguments (org-element-property :parameters inline-src-block))
2087 (body (org-element-property :value inline-src-block)))
2088 (format "src_%s%s{%s}"
2089 language
2090 (if arguments (format "[%s]" arguments) "")
2091 body)))
2093 (defun org-element-inline-src-block-successor (limit)
2094 "Search for the next inline-babel-call element.
2096 LIMIT bounds the search.
2098 Return value is a cons cell whose CAR is `inline-babel-call' and
2099 CDR is beginning position."
2100 (save-excursion
2101 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
2102 (cons 'inline-src-block (match-beginning 1)))))
2104 ;;;; Italic
2106 (defun org-element-italic-parser ()
2107 "Parse italic object at point.
2109 Return a list whose CAR is `italic' and CDR is a plist with
2110 `:begin', `:end', `:contents-begin' and `:contents-end' and
2111 `:post-blank' keywords.
2113 Assume point is at the first slash marker."
2114 (save-excursion
2115 (unless (bolp) (backward-char 1))
2116 (looking-at org-emph-re)
2117 (let ((begin (match-beginning 2))
2118 (contents-begin (match-beginning 4))
2119 (contents-end (match-end 4))
2120 (post-blank (progn (goto-char (match-end 2))
2121 (skip-chars-forward " \t")))
2122 (end (point)))
2123 `(italic
2124 (:begin ,begin
2125 :end ,end
2126 :contents-begin ,contents-begin
2127 :contents-end ,contents-end
2128 :post-blank ,post-blank)))))
2130 (defun org-element-italic-interpreter (italic contents)
2131 "Interpret ITALIC object as Org syntax.
2132 CONTENTS is the contents of the object."
2133 (format "/%s/" contents))
2136 ;;;; Latex Fragment
2138 (defun org-element-latex-fragment-parser ()
2139 "Parse latex fragment at point.
2141 Return a list whose CAR is `latex-fragment' and CDR a plist with
2142 `:value', `:begin', `:end', and `:post-blank' as keywords.
2144 Assume point is at the beginning of the latex fragment."
2145 (save-excursion
2146 (let* ((begin (point))
2147 (substring-match
2148 (catch 'exit
2149 (mapc (lambda (e)
2150 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
2151 (when (or (looking-at latex-regexp)
2152 (and (not (bobp))
2153 (save-excursion
2154 (backward-char)
2155 (looking-at latex-regexp))))
2156 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
2157 (plist-get org-format-latex-options :matchers))
2158 ;; None found: it's a macro.
2159 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
2161 (value (match-string-no-properties substring-match))
2162 (post-blank (progn (goto-char (match-end substring-match))
2163 (skip-chars-forward " \t")))
2164 (end (point)))
2165 `(latex-fragment
2166 (:value ,value
2167 :begin ,begin
2168 :end ,end
2169 :post-blank ,post-blank)))))
2171 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
2172 "Interpret LATEX-FRAGMENT object as Org syntax.
2173 CONTENTS is nil."
2174 (org-element-property :value latex-fragment))
2176 ;;;; Line Break
2178 (defun org-element-line-break-parser ()
2179 "Parse line break at point.
2181 Return a list whose CAR is `line-break', and CDR a plist with
2182 `:begin', `:end' and `:post-blank' keywords.
2184 Assume point is at the beginning of the line break."
2185 (let ((begin (point))
2186 (end (save-excursion (forward-line) (point))))
2187 `(line-break (:begin ,begin :end ,end :post-blank 0))))
2189 (defun org-element-line-break-interpreter (line-break contents)
2190 "Interpret LINE-BREAK object as Org syntax.
2191 CONTENTS is nil."
2192 "\\\\\n")
2194 (defun org-element-line-break-successor (limit)
2195 "Search for the next line-break object.
2197 LIMIT bounds the search.
2199 Return value is a cons cell whose CAR is `line-break' and CDR is
2200 beginning position."
2201 (save-excursion
2202 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
2203 (goto-char (match-beginning 1)))))
2204 ;; A line break can only happen on a non-empty line.
2205 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
2206 (cons 'line-break beg)))))
2209 ;;;; Link
2211 (defun org-element-link-parser ()
2212 "Parse link at point.
2214 Return a list whose CAR is `link' and CDR a plist with `:type',
2215 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
2216 `:contents-end' and `:post-blank' as keywords.
2218 Assume point is at the beginning of the link."
2219 (save-excursion
2220 (let ((begin (point))
2221 end contents-begin contents-end link-end post-blank path type
2222 raw-link link)
2223 (cond
2224 ;; Type 1: Text targeted from a radio target.
2225 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2226 (setq type "radio"
2227 link-end (match-end 0)
2228 path (org-match-string-no-properties 0)))
2229 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2230 ((looking-at org-bracket-link-regexp)
2231 (setq contents-begin (match-beginning 3)
2232 contents-end (match-end 3)
2233 link-end (match-end 0)
2234 ;; RAW-LINK is the original link.
2235 raw-link (org-match-string-no-properties 1)
2236 link (org-link-expand-abbrev
2237 (replace-regexp-in-string
2238 " *\n *" " " (org-link-unescape raw-link) t t)))
2239 ;; Determine TYPE of link and set PATH accordingly.
2240 (cond
2241 ;; File type.
2242 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2243 (setq type "file" path link))
2244 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2245 ((string-match org-link-re-with-space3 link)
2246 (setq type (match-string 1 link) path (match-string 2 link)))
2247 ;; Id type: PATH is the id.
2248 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2249 (setq type "id" path (match-string 1 link)))
2250 ;; Code-ref type: PATH is the name of the reference.
2251 ((string-match "^(\\(.*\\))$" link)
2252 (setq type "coderef" path (match-string 1 link)))
2253 ;; Custom-id type: PATH is the name of the custom id.
2254 ((= (aref link 0) ?#)
2255 (setq type "custom-id" path (substring link 1)))
2256 ;; Fuzzy type: Internal link either matches a target, an
2257 ;; headline name or nothing. PATH is the target or headline's
2258 ;; name.
2259 (t (setq type "fuzzy" path link))))
2260 ;; Type 3: Plain link, i.e. http://orgmode.org
2261 ((looking-at org-plain-link-re)
2262 (setq raw-link (org-match-string-no-properties 0)
2263 type (org-match-string-no-properties 1)
2264 path (org-match-string-no-properties 2)
2265 link-end (match-end 0)))
2266 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2267 ((looking-at org-angle-link-re)
2268 (setq raw-link (buffer-substring-no-properties
2269 (match-beginning 1) (match-end 2))
2270 type (org-match-string-no-properties 1)
2271 path (org-match-string-no-properties 2)
2272 link-end (match-end 0))))
2273 ;; In any case, deduce end point after trailing white space from
2274 ;; LINK-END variable.
2275 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2276 end (point))
2277 `(link
2278 (:type ,type
2279 :path ,path
2280 :raw-link ,(or raw-link path)
2281 :begin ,begin
2282 :end ,end
2283 :contents-begin ,contents-begin
2284 :contents-end ,contents-end
2285 :post-blank ,post-blank)))))
2287 (defun org-element-link-interpreter (link contents)
2288 "Interpret LINK object as Org syntax.
2289 CONTENTS is the contents of the object, or nil."
2290 (let ((type (org-element-property :type link))
2291 (raw-link (org-element-property :raw-link link)))
2292 (if (string= type "radio") raw-link
2293 (format "[[%s]%s]"
2294 raw-link
2295 (if contents (format "[%s]" contents) "")))))
2297 (defun org-element-link-successor (limit)
2298 "Search for the next link object.
2300 LIMIT bounds the search.
2302 Return value is a cons cell whose CAR is `link' and CDR is
2303 beginning position."
2304 (save-excursion
2305 (let ((link-regexp
2306 (if (not org-target-link-regexp) org-any-link-re
2307 (concat org-any-link-re "\\|" org-target-link-regexp))))
2308 (when (re-search-forward link-regexp limit t)
2309 (cons 'link (match-beginning 0))))))
2312 ;;;; Macro
2314 (defun org-element-macro-parser ()
2315 "Parse macro at point.
2317 Return a list whose CAR is `macro' and CDR a plist with `:key',
2318 `:args', `:begin', `:end', `:value' and `:post-blank' as
2319 keywords.
2321 Assume point is at the macro."
2322 (save-excursion
2323 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2324 (let ((begin (point))
2325 (key (downcase (org-match-string-no-properties 1)))
2326 (value (org-match-string-no-properties 0))
2327 (post-blank (progn (goto-char (match-end 0))
2328 (skip-chars-forward " \t")))
2329 (end (point))
2330 (args (let ((args (org-match-string-no-properties 3)) args2)
2331 (when args
2332 (setq args (org-split-string args ","))
2333 (while args
2334 (while (string-match "\\\\\\'" (car args))
2335 ;; Repair bad splits.
2336 (setcar (cdr args) (concat (substring (car args) 0 -1)
2337 "," (nth 1 args)))
2338 (pop args))
2339 (push (pop args) args2))
2340 (mapcar 'org-trim (nreverse args2))))))
2341 `(macro
2342 (:key ,key
2343 :value ,value
2344 :args ,args
2345 :begin ,begin
2346 :end ,end
2347 :post-blank ,post-blank)))))
2349 (defun org-element-macro-interpreter (macro contents)
2350 "Interpret MACRO object as Org syntax.
2351 CONTENTS is nil."
2352 (org-element-property :value macro))
2354 (defun org-element-macro-successor (limit)
2355 "Search for the next macro object.
2357 LIMIT bounds the search.
2359 Return value is cons cell whose CAR is `macro' and CDR is
2360 beginning position."
2361 (save-excursion
2362 (when (re-search-forward
2363 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2364 limit t)
2365 (cons 'macro (match-beginning 0)))))
2368 ;;;; Radio-target
2370 (defun org-element-radio-target-parser ()
2371 "Parse radio target at point.
2373 Return a list whose CAR is `radio-target' and CDR a plist with
2374 `:begin', `:end', `:contents-begin', `:contents-end', `:value'
2375 and `:post-blank' as keywords.
2377 Assume point is at the radio target."
2378 (save-excursion
2379 (looking-at org-radio-target-regexp)
2380 (let ((begin (point))
2381 (contents-begin (match-beginning 1))
2382 (contents-end (match-end 1))
2383 (value (org-match-string-no-properties 1))
2384 (post-blank (progn (goto-char (match-end 0))
2385 (skip-chars-forward " \t")))
2386 (end (point)))
2387 `(radio-target
2388 (:begin ,begin
2389 :end ,end
2390 :contents-begin ,contents-begin
2391 :contents-end ,contents-end
2392 :post-blank ,post-blank
2393 :value ,value)))))
2395 (defun org-element-radio-target-interpreter (target contents)
2396 "Interpret TARGET object as Org syntax.
2397 CONTENTS is the contents of the object."
2398 (concat "<<<" contents ">>>"))
2400 (defun org-element-radio-target-successor (limit)
2401 "Search for the next radio-target object.
2403 LIMIT bounds the search.
2405 Return value is a cons cell whose CAR is `radio-target' and CDR
2406 is beginning position."
2407 (save-excursion
2408 (when (re-search-forward org-radio-target-regexp limit t)
2409 (cons 'radio-target (match-beginning 0)))))
2412 ;;;; Statistics Cookie
2414 (defun org-element-statistics-cookie-parser ()
2415 "Parse statistics cookie at point.
2417 Return a list whose CAR is `statistics-cookie', and CDR a plist
2418 with `:begin', `:end', `:value' and `:post-blank' keywords.
2420 Assume point is at the beginning of the statistics-cookie."
2421 (save-excursion
2422 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2423 (let* ((begin (point))
2424 (value (buffer-substring-no-properties
2425 (match-beginning 0) (match-end 0)))
2426 (post-blank (progn (goto-char (match-end 0))
2427 (skip-chars-forward " \t")))
2428 (end (point)))
2429 `(statistics-cookie
2430 (:begin ,begin
2431 :end ,end
2432 :value ,value
2433 :post-blank ,post-blank)))))
2435 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2436 "Interpret STATISTICS-COOKIE object as Org syntax.
2437 CONTENTS is nil."
2438 (org-element-property :value statistics-cookie))
2440 (defun org-element-statistics-cookie-successor (limit)
2441 "Search for the next statistics cookie object.
2443 LIMIT bounds the search.
2445 Return value is a cons cell whose CAR is `statistics-cookie' and
2446 CDR is beginning position."
2447 (save-excursion
2448 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2449 (cons 'statistics-cookie (match-beginning 0)))))
2452 ;;;; Strike-Through
2454 (defun org-element-strike-through-parser ()
2455 "Parse strike-through object at point.
2457 Return a list whose CAR is `strike-through' and CDR is a plist
2458 with `:begin', `:end', `:contents-begin' and `:contents-end' and
2459 `:post-blank' keywords.
2461 Assume point is at the first plus sign marker."
2462 (save-excursion
2463 (unless (bolp) (backward-char 1))
2464 (looking-at org-emph-re)
2465 (let ((begin (match-beginning 2))
2466 (contents-begin (match-beginning 4))
2467 (contents-end (match-end 4))
2468 (post-blank (progn (goto-char (match-end 2))
2469 (skip-chars-forward " \t")))
2470 (end (point)))
2471 `(strike-through
2472 (:begin ,begin
2473 :end ,end
2474 :contents-begin ,contents-begin
2475 :contents-end ,contents-end
2476 :post-blank ,post-blank)))))
2478 (defun org-element-strike-through-interpreter (strike-through contents)
2479 "Interpret STRIKE-THROUGH object as Org syntax.
2480 CONTENTS is the contents of the object."
2481 (format "+%s+" contents))
2484 ;;;; Subscript
2486 (defun org-element-subscript-parser ()
2487 "Parse subscript at point.
2489 Return a list whose CAR is `subscript' and CDR a plist with
2490 `:begin', `:end', `:contents-begin', `:contents-end',
2491 `:use-brackets-p' and `:post-blank' as keywords.
2493 Assume point is at the underscore."
2494 (save-excursion
2495 (unless (bolp) (backward-char))
2496 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2498 (not (looking-at org-match-substring-regexp))))
2499 (begin (match-beginning 2))
2500 (contents-begin (or (match-beginning 5)
2501 (match-beginning 3)))
2502 (contents-end (or (match-end 5) (match-end 3)))
2503 (post-blank (progn (goto-char (match-end 0))
2504 (skip-chars-forward " \t")))
2505 (end (point)))
2506 `(subscript
2507 (:begin ,begin
2508 :end ,end
2509 :use-brackets-p ,bracketsp
2510 :contents-begin ,contents-begin
2511 :contents-end ,contents-end
2512 :post-blank ,post-blank)))))
2514 (defun org-element-subscript-interpreter (subscript contents)
2515 "Interpret SUBSCRIPT object as Org syntax.
2516 CONTENTS is the contents of the object."
2517 (format
2518 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
2519 contents))
2521 (defun org-element-sub/superscript-successor (limit)
2522 "Search for the next sub/superscript object.
2524 LIMIT bounds the search.
2526 Return value is a cons cell whose CAR is either `subscript' or
2527 `superscript' and CDR is beginning position."
2528 (save-excursion
2529 (when (re-search-forward org-match-substring-regexp limit t)
2530 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2531 (match-beginning 2)))))
2534 ;;;; Superscript
2536 (defun org-element-superscript-parser ()
2537 "Parse superscript at point.
2539 Return a list whose CAR is `superscript' and CDR a plist with
2540 `:begin', `:end', `:contents-begin', `:contents-end',
2541 `:use-brackets-p' and `:post-blank' as keywords.
2543 Assume point is at the caret."
2544 (save-excursion
2545 (unless (bolp) (backward-char))
2546 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp) t
2547 (not (looking-at org-match-substring-regexp))))
2548 (begin (match-beginning 2))
2549 (contents-begin (or (match-beginning 5)
2550 (match-beginning 3)))
2551 (contents-end (or (match-end 5) (match-end 3)))
2552 (post-blank (progn (goto-char (match-end 0))
2553 (skip-chars-forward " \t")))
2554 (end (point)))
2555 `(superscript
2556 (:begin ,begin
2557 :end ,end
2558 :use-brackets-p ,bracketsp
2559 :contents-begin ,contents-begin
2560 :contents-end ,contents-end
2561 :post-blank ,post-blank)))))
2563 (defun org-element-superscript-interpreter (superscript contents)
2564 "Interpret SUPERSCRIPT object as Org syntax.
2565 CONTENTS is the contents of the object."
2566 (format
2567 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
2568 contents))
2571 ;;;; Table Cell
2573 (defun org-element-table-cell-parser ()
2574 "Parse table cell at point.
2576 Return a list whose CAR is `table-cell' and CDR is a plist
2577 containing `:begin', `:end', `:contents-begin', `:contents-end'
2578 and `:post-blank' keywords."
2579 (looking-at "[ \t]*\\(.*?\\)[ \t]*|")
2580 (let* ((begin (match-beginning 0))
2581 (end (match-end 0))
2582 (contents-begin (match-beginning 1))
2583 (contents-end (match-end 1)))
2584 `(table-cell
2585 (:begin ,begin
2586 :end ,end
2587 :contents-begin ,contents-begin
2588 :contents-end ,contents-end
2589 :post-blank 0))))
2591 (defun org-element-table-cell-interpreter (table-cell contents)
2592 "Interpret TABLE-CELL element as Org syntax.
2593 CONTENTS is the contents of the cell, or nil."
2594 (concat " " contents " |"))
2596 (defun org-element-table-cell-successor (limit)
2597 "Search for the next table-cell object.
2599 LIMIT bounds the search.
2601 Return value is a cons cell whose CAR is `table-cell' and CDR is
2602 beginning position."
2603 (when (looking-at "[ \t]*.*?[ \t]+|") (cons 'table-cell (point))))
2606 ;;;; Target
2608 (defun org-element-target-parser ()
2609 "Parse target at point.
2611 Return a list whose CAR is `target' and CDR a plist with
2612 `:begin', `:end', `:value' and `:post-blank' as keywords.
2614 Assume point is at the target."
2615 (save-excursion
2616 (looking-at org-target-regexp)
2617 (let ((begin (point))
2618 (value (org-match-string-no-properties 1))
2619 (post-blank (progn (goto-char (match-end 0))
2620 (skip-chars-forward " \t")))
2621 (end (point)))
2622 `(target
2623 (:begin ,begin
2624 :end ,end
2625 :value ,value
2626 :post-blank ,post-blank)))))
2628 (defun org-element-target-interpreter (target contents)
2629 "Interpret TARGET object as Org syntax.
2630 CONTENTS is nil."
2631 (format "<<%s>>" (org-element-property :value target)))
2633 (defun org-element-target-successor (limit)
2634 "Search for the next target object.
2636 LIMIT bounds the search.
2638 Return value is a cons cell whose CAR is `target' and CDR is
2639 beginning position."
2640 (save-excursion
2641 (when (re-search-forward org-target-regexp limit t)
2642 (cons 'target (match-beginning 0)))))
2645 ;;;; Timestamp
2647 (defun org-element-timestamp-parser ()
2648 "Parse time stamp at point.
2650 Return a list whose CAR is `timestamp', and CDR a plist with
2651 `:type', `:begin', `:end', `:value' and `:post-blank' keywords.
2653 Assume point is at the beginning of the timestamp."
2654 (save-excursion
2655 (let* ((begin (point))
2656 (type (cond
2657 ((looking-at org-tsr-regexp)
2658 (if (match-string 2) 'active-range 'active))
2659 ((looking-at org-tsr-regexp-both)
2660 (if (match-string 2) 'inactive-range 'inactive))
2661 ((looking-at
2662 (concat
2663 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2664 "\\|"
2665 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2666 'diary)))
2667 (value (org-match-string-no-properties 0))
2668 (post-blank (progn (goto-char (match-end 0))
2669 (skip-chars-forward " \t")))
2670 (end (point)))
2671 `(timestamp
2672 (:type ,type
2673 :value ,value
2674 :begin ,begin
2675 :end ,end
2676 :post-blank ,post-blank)))))
2678 (defun org-element-timestamp-interpreter (timestamp contents)
2679 "Interpret TIMESTAMP object as Org syntax.
2680 CONTENTS is nil."
2681 (org-element-property :value timestamp))
2683 (defun org-element-timestamp-successor (limit)
2684 "Search for the next timestamp object.
2686 LIMIT bounds the search.
2688 Return value is a cons cell whose CAR is `timestamp' and CDR is
2689 beginning position."
2690 (save-excursion
2691 (when (re-search-forward
2692 (concat org-ts-regexp-both
2693 "\\|"
2694 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2695 "\\|"
2696 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2697 limit t)
2698 (cons 'timestamp (match-beginning 0)))))
2701 ;;;; Underline
2703 (defun org-element-underline-parser ()
2704 "Parse underline object at point.
2706 Return a list whose CAR is `underline' and CDR is a plist with
2707 `:begin', `:end', `:contents-begin' and `:contents-end' and
2708 `:post-blank' keywords.
2710 Assume point is at the first underscore marker."
2711 (save-excursion
2712 (unless (bolp) (backward-char 1))
2713 (looking-at org-emph-re)
2714 (let ((begin (match-beginning 2))
2715 (contents-begin (match-beginning 4))
2716 (contents-end (match-end 4))
2717 (post-blank (progn (goto-char (match-end 2))
2718 (skip-chars-forward " \t")))
2719 (end (point)))
2720 `(underline
2721 (:begin ,begin
2722 :end ,end
2723 :contents-begin ,contents-begin
2724 :contents-end ,contents-end
2725 :post-blank ,post-blank)))))
2727 (defun org-element-underline-interpreter (underline contents)
2728 "Interpret UNDERLINE object as Org syntax.
2729 CONTENTS is the contents of the object."
2730 (format "_%s_" contents))
2733 ;;;; Verbatim
2735 (defun org-element-verbatim-parser ()
2736 "Parse verbatim object at point.
2738 Return a list whose CAR is `verbatim' and CDR is a plist with
2739 `:value', `:begin', `:end' and `:post-blank' keywords.
2741 Assume point is at the first equal sign marker."
2742 (save-excursion
2743 (unless (bolp) (backward-char 1))
2744 (looking-at org-emph-re)
2745 (let ((begin (match-beginning 2))
2746 (value (org-match-string-no-properties 4))
2747 (post-blank (progn (goto-char (match-end 2))
2748 (skip-chars-forward " \t")))
2749 (end (point)))
2750 `(verbatim
2751 (:value ,value
2752 :begin ,begin
2753 :end ,end
2754 :post-blank ,post-blank)))))
2756 (defun org-element-verbatim-interpreter (verbatim contents)
2757 "Interpret VERBATIM object as Org syntax.
2758 CONTENTS is nil."
2759 (format "=%s=" (org-element-property :value verbatim)))
2763 ;;; Definitions And Rules
2765 ;; Define elements, greater elements and specify recursive objects,
2766 ;; along with the affiliated keywords recognized. Also set up
2767 ;; restrictions on recursive objects combinations.
2769 ;; These variables really act as a control center for the parsing
2770 ;; process.
2771 (defconst org-element-paragraph-separate
2772 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2773 ;; Headlines and inlinetasks.
2774 org-outline-regexp-bol "\\|"
2775 ;; Comments, blocks (any type), keywords and babel calls.
2776 "^[ \t]*#\\+" "\\|" "^#\\(?: \\|$\\)" "\\|"
2777 ;; Lists.
2778 (org-item-beginning-re) "\\|"
2779 ;; Fixed-width, drawers (any type) and tables.
2780 "^[ \t]*[:|]" "\\|"
2781 ;; Footnote definitions.
2782 org-footnote-definition-re "\\|"
2783 ;; Horizontal rules.
2784 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2785 ;; LaTeX environments.
2786 "^[ \t]*\\\\\\(begin\\|end\\)"
2787 ;; Planning and Clock lines.
2788 "^[ \t]*\\(?:"
2789 org-clock-string "\\|"
2790 org-closed-string "\\|"
2791 org-deadline-string "\\|"
2792 org-scheduled-string "\\)")
2793 "Regexp to separate paragraphs in an Org buffer.")
2795 (defconst org-element-all-elements
2796 '(center-block clock comment comment-block drawer dynamic-block example-block
2797 export-block fixed-width footnote-definition headline
2798 horizontal-rule inlinetask item keyword latex-environment
2799 babel-call paragraph plain-list planning property-drawer
2800 quote-block quote-section section special-block src-block table
2801 table-row verse-block)
2802 "Complete list of element types.")
2804 (defconst org-element-greater-elements
2805 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2806 item plain-list quote-block section special-block table)
2807 "List of recursive element types aka Greater Elements.")
2809 (defconst org-element-all-successors
2810 '(export-snippet footnote-reference inline-babel-call inline-src-block
2811 latex-or-entity line-break link macro radio-target
2812 statistics-cookie sub/superscript table-cell target
2813 text-markup timestamp)
2814 "Complete list of successors.")
2816 (defconst org-element-object-successor-alist
2817 '((subscript . sub/superscript) (superscript . sub/superscript)
2818 (bold . text-markup) (code . text-markup) (italic . text-markup)
2819 (strike-through . text-markup) (underline . text-markup)
2820 (verbatim . text-markup) (entity . latex-or-entity)
2821 (latex-fragment . latex-or-entity))
2822 "Alist of translations between object type and successor name.
2824 Sharing the same successor comes handy when, for example, the
2825 regexp matching one object can also match the other object.")
2827 (defconst org-element-all-objects
2828 '(bold code entity export-snippet footnote-reference inline-babel-call
2829 inline-src-block italic line-break latex-fragment link macro
2830 radio-target statistics-cookie strike-through subscript superscript
2831 table-cell target timestamp underline verbatim)
2832 "Complete list of object types.")
2834 (defconst org-element-recursive-objects
2835 '(bold italic link macro subscript radio-target strike-through superscript
2836 table-cell underline)
2837 "List of recursive object types.")
2839 (defconst org-element-non-recursive-block-alist
2840 '(("ASCII" . export-block)
2841 ("COMMENT" . comment-block)
2842 ("DOCBOOK" . export-block)
2843 ("EXAMPLE" . example-block)
2844 ("HTML" . export-block)
2845 ("LATEX" . export-block)
2846 ("ODT" . export-block)
2847 ("SRC" . src-block)
2848 ("VERSE" . verse-block))
2849 "Alist between non-recursive block name and their element type.")
2851 (defconst org-element-affiliated-keywords
2852 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "CAPTION"
2853 "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT" "RESULTS"
2854 "SOURCE" "SRCNAME" "TBLNAME")
2855 "List of affiliated keywords as strings.")
2857 (defconst org-element-keyword-translation-alist
2858 '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
2859 ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
2860 ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
2861 "Alist of usual translations for keywords.
2862 The key is the old name and the value the new one. The property
2863 holding their value will be named after the translated name.")
2865 (defconst org-element-multiple-keywords
2866 '("ATTR_ASCII" "ATTR_DOCBOOK" "ATTR_HTML" "ATTR_LATEX" "ATTR_ODT" "HEADER")
2867 "List of affiliated keywords that can occur more that once in an element.
2869 Their value will be consed into a list of strings, which will be
2870 returned as the value of the property.
2872 This list is checked after translations have been applied. See
2873 `org-element-keyword-translation-alist'.")
2875 (defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "TITLE")
2876 "List of keywords whose value can be parsed.
2878 Their value will be stored as a secondary string: a list of
2879 strings and objects.
2881 This list is checked after translations have been applied. See
2882 `org-element-keyword-translation-alist'.")
2884 (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
2885 "List of keywords which can have a secondary value.
2887 In Org syntax, they can be written with optional square brackets
2888 before the colons. For example, results keyword can be
2889 associated to a hash value with the following:
2891 #+RESULTS[hash-string]: some-source
2893 This list is checked after translations have been applied. See
2894 `org-element-keyword-translation-alist'.")
2896 (defconst org-element-object-restrictions
2897 `((bold entity export-snippet inline-babel-call inline-src-block link
2898 radio-target sub/superscript target text-markup timestamp)
2899 (footnote-reference entity export-snippet footnote-reference
2900 inline-babel-call inline-src-block latex-fragment
2901 line-break link macro radio-target sub/superscript
2902 target text-markup timestamp)
2903 (headline entity inline-babel-call inline-src-block latex-fragment link
2904 macro radio-target statistics-cookie sub/superscript text-markup
2905 timestamp)
2906 (inlinetask entity inline-babel-call inline-src-block latex-fragment link
2907 macro radio-target sub/superscript text-markup timestamp)
2908 (italic entity export-snippet inline-babel-call inline-src-block link
2909 radio-target sub/superscript target text-markup timestamp)
2910 (item entity inline-babel-call latex-fragment macro radio-target
2911 sub/superscript target text-markup)
2912 (keyword entity latex-fragment macro sub/superscript text-markup)
2913 (link entity export-snippet inline-babel-call inline-src-block
2914 latex-fragment link sub/superscript text-markup)
2915 (macro macro)
2916 (paragraph ,@org-element-all-successors)
2917 (radio-target entity export-snippet latex-fragment sub/superscript)
2918 (strike-through entity export-snippet inline-babel-call inline-src-block
2919 link radio-target sub/superscript target text-markup
2920 timestamp)
2921 (subscript entity export-snippet inline-babel-call inline-src-block
2922 latex-fragment sub/superscript text-markup)
2923 (superscript entity export-snippet inline-babel-call inline-src-block
2924 latex-fragment sub/superscript text-markup)
2925 (table-cell entity export-snippet latex-fragment link macro radio-target
2926 sub/superscript target text-markup timestamp)
2927 (table-row table-cell)
2928 (underline entity export-snippet inline-babel-call inline-src-block link
2929 radio-target sub/superscript target text-markup timestamp)
2930 (verse-block entity footnote-reference inline-babel-call inline-src-block
2931 latex-fragment line-break link macro radio-target
2932 sub/superscript target text-markup timestamp))
2933 "Alist of objects restrictions.
2935 CAR is an element or object type containing objects and CDR is
2936 a list of successors that will be called within an element or
2937 object of such type.
2939 For example, in a `radio-target' object, one can only find
2940 entities, export snippets, latex-fragments, subscript and
2941 superscript.
2943 This alist also applies to secondary string. For example, an
2944 `headline' type element doesn't directly contain objects, but
2945 still has an entry since one of its properties (`:title') does.")
2947 (defconst org-element-secondary-value-alist
2948 '((headline . :title)
2949 (inlinetask . :title)
2950 (item . :tag)
2951 (footnote-reference . :inline-definition))
2952 "Alist between element types and location of secondary value.")
2956 ;;; Accessors
2958 ;; Provide four accessors: `org-element-type', `org-element-property'
2959 ;; `org-element-contents' and `org-element-restriction'.
2961 (defun org-element-type (element)
2962 "Return type of element ELEMENT.
2964 The function returns the type of the element or object provided.
2965 It can also return the following special value:
2966 `plain-text' for a string
2967 `org-data' for a complete document
2968 nil in any other case."
2969 (cond
2970 ((not (consp element)) (and (stringp element) 'plain-text))
2971 ((symbolp (car element)) (car element))))
2973 (defun org-element-property (property element)
2974 "Extract the value from the PROPERTY of an ELEMENT."
2975 (plist-get (nth 1 element) property))
2977 (defun org-element-contents (element)
2978 "Extract contents from an ELEMENT."
2979 (and (consp element) (nthcdr 2 element)))
2981 (defun org-element-restriction (element)
2982 "Return restriction associated to ELEMENT.
2983 ELEMENT can be an element, an object or a symbol representing an
2984 element or object type."
2985 (cdr (assq (if (symbolp element) element (org-element-type element))
2986 org-element-object-restrictions)))
2990 ;;; Parsing Element Starting At Point
2992 ;; `org-element-current-element' is the core function of this section.
2993 ;; It returns the Lisp representation of the element starting at
2994 ;; point. It uses `org-element--element-block-re' for quick access to
2995 ;; a common regexp.
2997 ;; `org-element-current-element' makes use of special modes. They are
2998 ;; activated for fixed element chaining (i.e. `plain-list' > `item')
2999 ;; or fixed conditional element chaining (i.e. `headline' >
3000 ;; `section'). Special modes are: `section', `quote-section', `item'
3001 ;; and `table-row'.
3003 (defconst org-element--element-block-re
3004 (format "[ \t]*#\\+BEGIN_\\(%s\\)\\(?: \\|$\\)"
3005 (mapconcat
3006 'regexp-quote
3007 (mapcar 'car org-element-non-recursive-block-alist) "\\|"))
3008 "Regexp matching the beginning of a non-recursive block type.
3009 Used internally by `org-element-current-element'.")
3011 (defun org-element-current-element (&optional granularity special structure)
3012 "Parse the element starting at point.
3014 Return value is a list like (TYPE PROPS) where TYPE is the type
3015 of the element and PROPS a plist of properties associated to the
3016 element.
3018 Possible types are defined in `org-element-all-elements'.
3020 Optional argument GRANULARITY determines the depth of the
3021 recursion. Allowed values are `headline', `greater-element',
3022 `element', `object' or nil. When it is broader than `object' (or
3023 nil), secondary values will not be parsed, since they only
3024 contain objects.
3026 Optional argument SPECIAL, when non-nil, can be either `section',
3027 `quote-section', `table-row' and `item'.
3029 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3030 be computed.
3032 Unlike to `org-element-at-point', this function assumes point is
3033 always at the beginning of the element it has to parse. As such,
3034 it is quicker than its counterpart, albeit more restrictive."
3035 (save-excursion
3036 ;; If point is at an affiliated keyword, try moving to the
3037 ;; beginning of the associated element. If none is found, the
3038 ;; keyword is orphaned and will be treated as plain text.
3039 (when (looking-at org-element--affiliated-re)
3040 (let ((opoint (point)))
3041 (while (looking-at org-element--affiliated-re) (forward-line))
3042 (when (looking-at "[ \t]*$") (goto-char opoint))))
3043 (let ((case-fold-search t)
3044 ;; Determine if parsing depth allows for secondary strings
3045 ;; parsing. It only applies to elements referenced in
3046 ;; `org-element-secondary-value-alist'.
3047 (raw-secondary-p (and granularity (not (eq granularity 'object)))))
3048 (cond
3049 ;; Item
3050 ((eq special 'item)
3051 (org-element-item-parser (or structure (org-list-struct))
3052 raw-secondary-p))
3053 ;; Quote Section.
3054 ((eq special 'quote-section) (org-element-quote-section-parser))
3055 ;; Table Row.
3056 ((eq special 'table-row) (org-element-table-row-parser))
3057 ;; Headline.
3058 ((org-with-limited-levels (org-at-heading-p))
3059 (org-element-headline-parser raw-secondary-p))
3060 ;; Section (must be checked after headline).
3061 ((eq special 'section) (org-element-section-parser))
3062 ;; Planning and Clock.
3063 ((and (looking-at org-planning-or-clock-line-re))
3064 (if (equal (match-string 1) org-clock-string)
3065 (org-element-clock-parser)
3066 (org-element-planning-parser)))
3067 ;; Non-recursive block.
3068 ((when (looking-at org-element--element-block-re)
3069 (let ((type (upcase (match-string 1))))
3070 (if (save-excursion
3071 (re-search-forward
3072 (format "^[ \t]*#\\+END_%s\\(?: \\|$\\)" type) nil t))
3073 (funcall
3074 (intern
3075 (format
3076 "org-element-%s-parser"
3077 (cdr (assoc type org-element-non-recursive-block-alist)))))
3078 (org-element-paragraph-parser)))))
3079 ;; Inlinetask.
3080 ((org-at-heading-p) (org-element-inlinetask-parser raw-secondary-p))
3081 ;; LaTeX Environment or Paragraph if incomplete.
3082 ((looking-at "[ \t]*\\\\begin{")
3083 (if (save-excursion
3084 (re-search-forward "[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
3085 (org-element-latex-environment-parser)
3086 (org-element-paragraph-parser)))
3087 ;; Property Drawer.
3088 ((looking-at org-property-start-re)
3089 (if (save-excursion (re-search-forward org-property-end-re nil t))
3090 (org-element-property-drawer-parser)
3091 (org-element-paragraph-parser)))
3092 ;; Recursive Block, or Paragraph if incomplete.
3093 ((looking-at "[ \t]*#\\+BEGIN_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
3094 (let ((type (upcase (match-string 1))))
3095 (cond
3096 ((not (save-excursion
3097 (re-search-forward
3098 (format "^[ \t]*#\\+END_%s\\(?: \\|$\\)" type) nil t)))
3099 (org-element-paragraph-parser))
3100 ((string= type "CENTER") (org-element-center-block-parser))
3101 ((string= type "QUOTE") (org-element-quote-block-parser))
3102 (t (org-element-special-block-parser)))))
3103 ;; Drawer.
3104 ((looking-at org-drawer-regexp)
3105 (if (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t))
3106 (org-element-drawer-parser)
3107 (org-element-paragraph-parser)))
3108 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
3109 ;; Babel Call.
3110 ((looking-at org-babel-block-lob-one-liner-regexp)
3111 (org-element-babel-call-parser))
3112 ;; Dynamic Block or Paragraph if incomplete. This must be
3113 ;; checked before regular keywords since their regexp matches
3114 ;; dynamic blocks too.
3115 ((looking-at "[ \t]*#\\+BEGIN:\\(?: \\|$\\)")
3116 (if (save-excursion
3117 (re-search-forward "^[ \t]*#\\+END:\\(?: \\|$\\)" nil t))
3118 (org-element-dynamic-block-parser)
3119 (org-element-paragraph-parser)))
3120 ;; Keyword, or Paragraph if at an orphaned affiliated keyword.
3121 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
3122 (let ((key (upcase (match-string 1))))
3123 (if (or (string= key "TBLFM")
3124 (member key org-element-affiliated-keywords))
3125 (org-element-paragraph-parser)
3126 (org-element-keyword-parser))))
3127 ;; Footnote definition.
3128 ((looking-at org-footnote-definition-re)
3129 (org-element-footnote-definition-parser))
3130 ;; Comment.
3131 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
3132 (org-element-comment-parser))
3133 ;; Horizontal Rule.
3134 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3135 (org-element-horizontal-rule-parser))
3136 ;; Table.
3137 ((org-at-table-p t) (org-element-table-parser))
3138 ;; List or Item.
3139 ((looking-at (org-item-re))
3140 (org-element-plain-list-parser (or structure (org-list-struct))))
3141 ;; Default element: Paragraph.
3142 (t (org-element-paragraph-parser))))))
3145 ;; Most elements can have affiliated keywords. When looking for an
3146 ;; element beginning, we want to move before them, as they belong to
3147 ;; that element, and, in the meantime, collect information they give
3148 ;; into appropriate properties. Hence the following function.
3150 ;; Usage of optional arguments may not be obvious at first glance:
3152 ;; - TRANS-LIST is used to polish keywords names that have evolved
3153 ;; during Org history. In example, even though =result= and
3154 ;; =results= coexist, we want to have them under the same =result=
3155 ;; property. It's also true for "srcname" and "name", where the
3156 ;; latter seems to be preferred nowadays (thus the "name" property).
3158 ;; - CONSED allows to regroup multi-lines keywords under the same
3159 ;; property, while preserving their own identity. This is mostly
3160 ;; used for "attr_latex" and al.
3162 ;; - PARSED prepares a keyword value for export. This is useful for
3163 ;; "caption". Objects restrictions for such keywords are defined in
3164 ;; `org-element-object-restrictions'.
3166 ;; - DUALS is used to take care of keywords accepting a main and an
3167 ;; optional secondary values. For example "results" has its
3168 ;; source's name as the main value, and may have an hash string in
3169 ;; optional square brackets as the secondary one.
3171 ;; A keyword may belong to more than one category.
3173 (defconst org-element--affiliated-re
3174 (format "[ \t]*#\\+\\(%s\\):"
3175 (mapconcat
3176 (lambda (keyword)
3177 (if (member keyword org-element-dual-keywords)
3178 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
3179 (regexp-quote keyword))
3180 (regexp-quote keyword)))
3181 org-element-affiliated-keywords "\\|"))
3182 "Regexp matching any affiliated keyword.
3184 Keyword name is put in match group 1. Moreover, if keyword
3185 belongs to `org-element-dual-keywords', put the dual value in
3186 match group 2.
3188 Don't modify it, set `org-element-affiliated-keywords' instead.")
3190 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
3191 consed parsed duals)
3192 "Collect affiliated keywords before point.
3194 Optional argument KEY-RE is a regexp matching keywords, which
3195 puts matched keyword in group 1. It defaults to
3196 `org-element--affiliated-re'.
3198 TRANS-LIST is an alist where key is the keyword and value the
3199 property name it should be translated to, without the colons. It
3200 defaults to `org-element-keyword-translation-alist'.
3202 CONSED is a list of strings. Any keyword belonging to that list
3203 will have its value consed. The check is done after keyword
3204 translation. It defaults to `org-element-multiple-keywords'.
3206 PARSED is a list of strings. Any keyword member of this list
3207 will have its value parsed. The check is done after keyword
3208 translation. If a keyword is a member of both CONSED and PARSED,
3209 it's value will be a list of parsed strings. It defaults to
3210 `org-element-parsed-keywords'.
3212 DUALS is a list of strings. Any keyword member of this list can
3213 have two parts: one mandatory and one optional. Its value is
3214 a cons cell whose car is the former, and the cdr the latter. If
3215 a keyword is a member of both PARSED and DUALS, both values will
3216 be parsed. It defaults to `org-element-dual-keywords'.
3218 Return a list whose car is the position at the first of them and
3219 cdr a plist of keywords and values."
3220 (save-excursion
3221 (let ((case-fold-search t)
3222 (key-re (or key-re org-element--affiliated-re))
3223 (trans-list (or trans-list org-element-keyword-translation-alist))
3224 (consed (or consed org-element-multiple-keywords))
3225 (parsed (or parsed org-element-parsed-keywords))
3226 (duals (or duals org-element-dual-keywords))
3227 ;; RESTRICT is the list of objects allowed in parsed
3228 ;; keywords value.
3229 (restrict (org-element-restriction 'keyword))
3230 output)
3231 (unless (bobp)
3232 (while (and (not (bobp))
3233 (progn (forward-line -1) (looking-at key-re)))
3234 (let* ((raw-kwd (upcase (or (match-string 2) (match-string 1))))
3235 ;; Apply translation to RAW-KWD. From there, KWD is
3236 ;; the official keyword.
3237 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
3238 ;; Find main value for any keyword.
3239 (value
3240 (save-match-data
3241 (org-trim
3242 (buffer-substring-no-properties
3243 (match-end 0) (point-at-eol)))))
3244 ;; If KWD is a dual keyword, find its secondary
3245 ;; value. Maybe parse it.
3246 (dual-value
3247 (and (member kwd duals)
3248 (let ((sec (org-match-string-no-properties 3)))
3249 (if (or (not sec) (not (member kwd parsed))) sec
3250 (org-element-parse-secondary-string sec restrict)))))
3251 ;; Attribute a property name to KWD.
3252 (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
3253 ;; Now set final shape for VALUE.
3254 (when (member kwd parsed)
3255 (setq value (org-element-parse-secondary-string value restrict)))
3256 (when (member kwd duals)
3257 ;; VALUE is mandatory. Set it to nil if there is none.
3258 (setq value (and value (cons value dual-value))))
3259 (when (member kwd consed)
3260 (setq value (cons value (plist-get output kwd-sym))))
3261 ;; Eventually store the new value in OUTPUT.
3262 (setq output (plist-put output kwd-sym value))))
3263 (unless (looking-at key-re) (forward-line 1)))
3264 (list (point) output))))
3268 ;;; The Org Parser
3270 ;; The two major functions here are `org-element-parse-buffer', which
3271 ;; parses Org syntax inside the current buffer, taking into account
3272 ;; region, narrowing, or even visibility if specified, and
3273 ;; `org-element-parse-secondary-string', which parses objects within
3274 ;; a given string.
3276 ;; The (almost) almighty `org-element-map' allows to apply a function
3277 ;; on elements or objects matching some type, and accumulate the
3278 ;; resulting values. In an export situation, it also skips unneeded
3279 ;; parts of the parse tree.
3281 (defun org-element-parse-buffer (&optional granularity visible-only)
3282 "Recursively parse the buffer and return structure.
3283 If narrowing is in effect, only parse the visible part of the
3284 buffer.
3286 Optional argument GRANULARITY determines the depth of the
3287 recursion. It can be set to the following symbols:
3289 `headline' Only parse headlines.
3290 `greater-element' Don't recurse into greater elements excepted
3291 headlines and sections. Thus, elements
3292 parsed are the top-level ones.
3293 `element' Parse everything but objects and plain text.
3294 `object' Parse the complete buffer (default).
3296 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3297 elements.
3299 Assume buffer is in Org mode."
3300 (save-excursion
3301 (goto-char (point-min))
3302 (org-skip-whitespace)
3303 (nconc (list 'org-data nil)
3304 (org-element-parse-elements
3305 (point-at-bol) (point-max)
3306 ;; Start in `section' mode so text before the first
3307 ;; headline belongs to a section.
3308 'section nil granularity visible-only nil))))
3310 (defun org-element-parse-secondary-string (string restriction)
3311 "Recursively parse objects in STRING and return structure.
3313 RESTRICTION, when non-nil, is a symbol limiting the object types
3314 that will be looked after."
3315 (with-temp-buffer
3316 (insert string)
3317 (org-element-parse-objects (point-min) (point-max) nil restriction)))
3319 (defun org-element-map (data types fun &optional info first-match no-recursion)
3320 "Map a function on selected elements or objects.
3322 DATA is the parsed tree, as returned by, i.e,
3323 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
3324 of elements or objects types. FUN is the function called on the
3325 matching element or object. It must accept one arguments: the
3326 element or object itself.
3328 When optional argument INFO is non-nil, it should be a plist
3329 holding export options. In that case, parts of the parse tree
3330 not exportable according to that property list will be skipped.
3332 When optional argument FIRST-MATCH is non-nil, stop at the first
3333 match for which FUN doesn't return nil, and return that value.
3335 Optional argument NO-RECURSION is a symbol or a list of symbols
3336 representing elements or objects types. `org-element-map' won't
3337 enter any recursive element or object whose type belongs to that
3338 list. Though, FUN can still be applied on them.
3340 Nil values returned from FUN do not appear in the results."
3341 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3342 (unless (listp types) (setq types (list types)))
3343 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3344 ;; Recursion depth is determined by --CATEGORY.
3345 (let* ((--category
3346 (cond
3347 ((loop for type in types
3348 always (memq type org-element-greater-elements))
3349 'greater-elements)
3350 ((loop for type in types
3351 always (memq type org-element-all-elements))
3352 'elements)
3353 (t 'objects)))
3354 ;; --RESTRICTS is a list of element types whose secondary
3355 ;; string could possibly contain an object with a type among
3356 ;; TYPES.
3357 (--restricts
3358 (and (eq --category 'objects)
3359 (loop for el in org-element-secondary-value-alist
3360 when
3361 (loop for o in types
3362 thereis (memq o (org-element-restriction (car el))))
3363 collect (car el))))
3364 --acc
3365 (--walk-tree
3366 (function
3367 (lambda (--data)
3368 ;; Recursively walk DATA. INFO, if non-nil, is
3369 ;; a plist holding contextual information.
3370 (mapc
3371 (lambda (--blob)
3372 (unless (and info (member --blob (plist-get info :ignore-list)))
3373 (let ((--type (org-element-type --blob)))
3374 ;; Check if TYPE is matching among TYPES. If so,
3375 ;; apply FUN to --BLOB and accumulate return value
3376 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3377 (when (memq --type types)
3378 (let ((result (funcall fun --blob)))
3379 (cond ((not result))
3380 (first-match (throw 'first-match result))
3381 (t (push result --acc)))))
3382 ;; If --BLOB has a secondary string that can
3383 ;; contain objects with their type among TYPES,
3384 ;; look into that string.
3385 (when (memq --type --restricts)
3386 (funcall
3387 --walk-tree
3388 `(org-data
3390 ,@(org-element-property
3391 (cdr (assq --type org-element-secondary-value-alist))
3392 --blob))))
3393 ;; Now determine if a recursion into --BLOB is
3394 ;; possible. If so, do it.
3395 (unless (memq --type no-recursion)
3396 (when (or (and (memq --type org-element-greater-elements)
3397 (not (eq --category 'greater-elements)))
3398 (and (memq --type org-element-all-elements)
3399 (not (eq --category 'elements)))
3400 (org-element-contents --blob))
3401 (funcall --walk-tree --blob))))))
3402 (org-element-contents --data))))))
3403 (catch 'first-match
3404 (funcall --walk-tree data)
3405 ;; Return value in a proper order.
3406 (nreverse --acc))))
3408 ;; The following functions are internal parts of the parser.
3410 ;; The first one, `org-element-parse-elements' acts at the element's
3411 ;; level.
3413 ;; The second one, `org-element-parse-objects' applies on all objects
3414 ;; of a paragraph or a secondary string. It uses
3415 ;; `org-element-get-candidates' to optimize the search of the next
3416 ;; object in the buffer.
3418 ;; More precisely, that function looks for every allowed object type
3419 ;; first. Then, it discards failed searches, keeps further matches,
3420 ;; and searches again types matched behind point, for subsequent
3421 ;; calls. Thus, searching for a given type fails only once, and every
3422 ;; object is searched only once at top level (but sometimes more for
3423 ;; nested types).
3425 (defun org-element-parse-elements
3426 (beg end special structure granularity visible-only acc)
3427 "Parse elements between BEG and END positions.
3429 SPECIAL prioritize some elements over the others. It can be set
3430 to `quote-section', `section' `item' or `table-row'.
3432 When value is `item', STRUCTURE will be used as the current list
3433 structure.
3435 GRANULARITY determines the depth of the recursion. See
3436 `org-element-parse-buffer' for more information.
3438 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3439 elements.
3441 Elements are accumulated into ACC."
3442 (save-excursion
3443 (save-restriction
3444 (narrow-to-region beg end)
3445 (goto-char beg)
3446 ;; When parsing only headlines, skip any text before first one.
3447 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3448 (org-with-limited-levels (outline-next-heading)))
3449 ;; Main loop start.
3450 (while (not (eobp))
3451 (push
3452 ;; Find current element's type and parse it accordingly to
3453 ;; its category.
3454 (let* ((element (org-element-current-element
3455 granularity special structure))
3456 (type (org-element-type element))
3457 (cbeg (org-element-property :contents-begin element)))
3458 (goto-char (org-element-property :end element))
3459 (cond
3460 ;; Case 1. Simply accumulate element if VISIBLE-ONLY is
3461 ;; true and element is hidden or if it has no contents
3462 ;; anyway.
3463 ((or (and visible-only (org-element-property :hiddenp element))
3464 (not cbeg)) element)
3465 ;; Case 2. Greater element: parse it between
3466 ;; `contents-begin' and `contents-end'. Make sure
3467 ;; GRANULARITY allows the recursion, or ELEMENT is an
3468 ;; headline, in which case going inside is mandatory, in
3469 ;; order to get sub-level headings.
3470 ((and (memq type org-element-greater-elements)
3471 (or (memq granularity '(element object nil))
3472 (and (eq granularity 'greater-element)
3473 (eq type 'section))
3474 (eq type 'headline)))
3475 (org-element-parse-elements
3476 cbeg (org-element-property :contents-end element)
3477 ;; Possibly switch to a special mode.
3478 (case type
3479 (headline
3480 (if (org-element-property :quotedp element) 'quote-section
3481 'section))
3482 (plain-list 'item)
3483 (table 'table-row))
3484 (org-element-property :structure element)
3485 granularity visible-only (nreverse element)))
3486 ;; Case 3. ELEMENT has contents. Parse objects inside,
3487 ;; if GRANULARITY allows it.
3488 ((and cbeg (memq granularity '(object nil)))
3489 (org-element-parse-objects
3490 cbeg (org-element-property :contents-end element)
3491 (nreverse element) (org-element-restriction type)))
3492 ;; Case 4. Else, just accumulate ELEMENT.
3493 (t element)))
3494 acc)))
3495 ;; Return result.
3496 (nreverse acc)))
3498 (defun org-element-parse-objects (beg end acc restriction)
3499 "Parse objects between BEG and END and return recursive structure.
3501 Objects are accumulated in ACC.
3503 RESTRICTION is a list of object types which are allowed in the
3504 current object."
3505 (let ((get-next-object
3506 (function
3507 (lambda (cand)
3508 ;; Return the parsing function associated to the nearest
3509 ;; object among list of candidates CAND.
3510 (let ((pos (apply 'min (mapcar 'cdr cand))))
3511 (save-excursion
3512 (goto-char pos)
3513 (funcall
3514 (intern
3515 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3516 next-object candidates)
3517 (save-excursion
3518 (goto-char beg)
3519 (while (setq candidates (org-element-get-next-object-candidates
3520 end restriction candidates))
3521 (setq next-object (funcall get-next-object candidates))
3522 ;; 1. Text before any object. Untabify it.
3523 (let ((obj-beg (org-element-property :begin next-object)))
3524 (unless (= (point) obj-beg)
3525 (push (replace-regexp-in-string
3526 "\t" (make-string tab-width ? )
3527 (buffer-substring-no-properties (point) obj-beg))
3528 acc)))
3529 ;; 2. Object...
3530 (let ((obj-end (org-element-property :end next-object))
3531 (cont-beg (org-element-property :contents-begin next-object)))
3532 (push (if (and (memq (car next-object) org-element-recursive-objects)
3533 cont-beg)
3534 ;; ... recursive. The CONT-BEG check is for
3535 ;; links, as some of them might not be recursive
3536 ;; (i.e. plain links).
3537 (save-restriction
3538 (narrow-to-region
3539 cont-beg
3540 (org-element-property :contents-end next-object))
3541 (org-element-parse-objects
3542 (point-min) (point-max)
3543 (nreverse next-object)
3544 ;; Restrict allowed objects.
3545 (org-element-restriction next-object)))
3546 ;; ... not recursive. Accumulate the object.
3547 next-object)
3548 acc)
3549 (goto-char obj-end)))
3550 ;; 3. Text after last object. Untabify it.
3551 (unless (= (point) end)
3552 (push (replace-regexp-in-string
3553 "\t" (make-string tab-width ? )
3554 (buffer-substring-no-properties (point) end))
3555 acc))
3556 ;; Result.
3557 (nreverse acc))))
3559 (defun org-element-get-next-object-candidates (limit restriction objects)
3560 "Return an alist of candidates for the next object.
3562 LIMIT bounds the search, and RESTRICTION narrows candidates to
3563 some object types.
3565 Return value is an alist whose CAR is position and CDR the object
3566 type, as a symbol.
3568 OBJECTS is the previous candidates alist."
3569 (let (next-candidates types-to-search)
3570 ;; If no previous result, search every object type in RESTRICTION.
3571 ;; Otherwise, keep potential candidates (old objects located after
3572 ;; point) and ask to search again those which had matched before.
3573 (if (not objects) (setq types-to-search restriction)
3574 (mapc (lambda (obj)
3575 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3576 (push obj next-candidates)))
3577 objects))
3578 ;; Call the appropriate successor function for each type to search
3579 ;; and accumulate matches.
3580 (mapc
3581 (lambda (type)
3582 (let* ((successor-fun
3583 (intern
3584 (format "org-element-%s-successor"
3585 (or (cdr (assq type org-element-object-successor-alist))
3586 type))))
3587 (obj (funcall successor-fun limit)))
3588 (and obj (push obj next-candidates))))
3589 types-to-search)
3590 ;; Return alist.
3591 next-candidates))
3595 ;;; Towards A Bijective Process
3597 ;; The parse tree obtained with `org-element-parse-buffer' is really
3598 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3599 ;; interpreted and expanded into a string with canonical Org syntax.
3600 ;; Hence `org-element-interpret-data'.
3602 ;; The function relies internally on
3603 ;; `org-element-interpret--affiliated-keywords'.
3605 (defun org-element-interpret-data (data &optional parent)
3606 "Interpret DATA as Org syntax.
3608 DATA is a parse tree, an element, an object or a secondary string
3609 to interpret.
3611 Optional argument PARENT is used for recursive calls. It contains
3612 the element or object containing data, or nil.
3614 Return Org syntax as a string."
3615 (let* ((type (org-element-type data))
3616 (results
3617 (cond
3618 ;; Secondary string.
3619 ((not type)
3620 (mapconcat
3621 (lambda (obj) (org-element-interpret-data obj parent))
3622 data ""))
3623 ;; Full Org document.
3624 ((eq type 'org-data)
3625 (mapconcat
3626 (lambda (obj) (org-element-interpret-data obj parent))
3627 (org-element-contents data) ""))
3628 ;; Plain text.
3629 ((stringp data) data)
3630 ;; Element/Object without contents.
3631 ((not (org-element-contents data))
3632 (funcall (intern (format "org-element-%s-interpreter" type))
3633 data nil))
3634 ;; Element/Object with contents.
3636 (let* ((greaterp (memq type org-element-greater-elements))
3637 (objectp (and (not greaterp)
3638 (memq type org-element-recursive-objects)))
3639 (contents
3640 (mapconcat
3641 (lambda (obj) (org-element-interpret-data obj data))
3642 (org-element-contents
3643 (if (or greaterp objectp) data
3644 ;; Elements directly containing objects must
3645 ;; have their indentation normalized first.
3646 (org-element-normalize-contents
3647 data
3648 ;; When normalizing first paragraph of an
3649 ;; item or a footnote-definition, ignore
3650 ;; first line's indentation.
3651 (and (eq type 'paragraph)
3652 (equal data (car (org-element-contents parent)))
3653 (memq (org-element-type parent)
3654 '(footnote-definiton item))))))
3655 "")))
3656 (funcall (intern (format "org-element-%s-interpreter" type))
3657 data
3658 (if greaterp (org-element-normalize-contents contents)
3659 contents)))))))
3660 (if (memq type '(org-data plain-text nil)) results
3661 ;; Build white spaces. If no `:post-blank' property is
3662 ;; specified, assume its value is 0.
3663 (let ((post-blank (or (org-element-property :post-blank data) 0)))
3664 (if (memq type org-element-all-objects)
3665 (concat results (make-string post-blank 32))
3666 (concat
3667 (org-element-interpret--affiliated-keywords data)
3668 (org-element-normalize-string results)
3669 (make-string post-blank 10)))))))
3671 (defun org-element-interpret--affiliated-keywords (element)
3672 "Return ELEMENT's affiliated keywords as Org syntax.
3673 If there is no affiliated keyword, return the empty string."
3674 (let ((keyword-to-org
3675 (function
3676 (lambda (key value)
3677 (let (dual)
3678 (when (member key org-element-dual-keywords)
3679 (setq dual (cdr value) value (car value)))
3680 (concat "#+" key
3681 (and dual
3682 (format "[%s]" (org-element-interpret-data dual)))
3683 ": "
3684 (if (member key org-element-parsed-keywords)
3685 (org-element-interpret-data value)
3686 value)
3687 "\n"))))))
3688 (mapconcat
3689 (lambda (key)
3690 (let ((value (org-element-property (intern (concat ":" (downcase key)))
3691 element)))
3692 (when value
3693 (if (member key org-element-multiple-keywords)
3694 (mapconcat (lambda (line)
3695 (funcall keyword-to-org key line))
3696 value "")
3697 (funcall keyword-to-org key value)))))
3698 ;; Remove translated keywords.
3699 (delq nil
3700 (mapcar
3701 (lambda (key)
3702 (and (not (assoc key org-element-keyword-translation-alist)) key))
3703 org-element-affiliated-keywords))
3704 "")))
3706 ;; Because interpretation of the parse tree must return the same
3707 ;; number of blank lines between elements and the same number of white
3708 ;; space after objects, some special care must be given to white
3709 ;; spaces.
3711 ;; The first function, `org-element-normalize-string', ensures any
3712 ;; string different from the empty string will end with a single
3713 ;; newline character.
3715 ;; The second function, `org-element-normalize-contents', removes
3716 ;; global indentation from the contents of the current element.
3718 (defun org-element-normalize-string (s)
3719 "Ensure string S ends with a single newline character.
3721 If S isn't a string return it unchanged. If S is the empty
3722 string, return it. Otherwise, return a new string with a single
3723 newline character at its end."
3724 (cond
3725 ((not (stringp s)) s)
3726 ((string= "" s) "")
3727 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3728 (replace-match "\n" nil nil s)))))
3730 (defun org-element-normalize-contents (element &optional ignore-first)
3731 "Normalize plain text in ELEMENT's contents.
3733 ELEMENT must only contain plain text and objects.
3735 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3736 indentation to compute maximal common indentation.
3738 Return the normalized element that is element with global
3739 indentation removed from its contents. The function assumes that
3740 indentation is not done with TAB characters."
3741 (let (ind-list
3742 (collect-inds
3743 (function
3744 ;; Return list of indentations within BLOB. This is done by
3745 ;; walking recursively BLOB and updating IND-LIST along the
3746 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3747 ;; been seen yet. It is required as this string is the only
3748 ;; one whose indentation doesn't happen after a newline
3749 ;; character.
3750 (lambda (blob first-flag)
3751 (mapc
3752 (lambda (object)
3753 (when (and first-flag (stringp object))
3754 (setq first-flag nil)
3755 (string-match "\\`\\( *\\)" object)
3756 (let ((len (length (match-string 1 object))))
3757 ;; An indentation of zero means no string will be
3758 ;; modified. Quit the process.
3759 (if (zerop len) (throw 'zero (setq ind-list nil))
3760 (push len ind-list))))
3761 (cond
3762 ((stringp object)
3763 (let ((start 0))
3764 ;; Avoid matching blank or empty lines.
3765 (while (and (string-match "\n\\( *\\)\\(.\\)" object start)
3766 (not (equal (match-string 2 object) " ")))
3767 (setq start (match-end 0))
3768 (push (length (match-string 1 object)) ind-list))))
3769 ((memq (org-element-type object) org-element-recursive-objects)
3770 (funcall collect-inds object first-flag))))
3771 (org-element-contents blob))))))
3772 ;; Collect indentation list in ELEMENT. Possibly remove first
3773 ;; value if IGNORE-FIRST is non-nil.
3774 (catch 'zero (funcall collect-inds element (not ignore-first)))
3775 (if (not ind-list) element
3776 ;; Build ELEMENT back, replacing each string with the same
3777 ;; string minus common indentation.
3778 (let ((build
3779 (function
3780 (lambda (blob mci first-flag)
3781 ;; Return BLOB with all its strings indentation
3782 ;; shortened from MCI white spaces. FIRST-FLAG is
3783 ;; non-nil when the first string hasn't been seen
3784 ;; yet.
3785 (nconc
3786 (list (org-element-type blob) (nth 1 blob))
3787 (mapcar
3788 (lambda (object)
3789 (when (and first-flag (stringp object))
3790 (setq first-flag nil)
3791 (setq object
3792 (replace-regexp-in-string
3793 (format "\\` \\{%d\\}" mci) "" object)))
3794 (cond
3795 ((stringp object)
3796 (replace-regexp-in-string
3797 (format "\n \\{%d\\}" mci) "\n" object))
3798 ((memq (org-element-type object)
3799 org-element-recursive-objects)
3800 (funcall build object mci first-flag))
3801 (t object)))
3802 (org-element-contents blob)))))))
3803 (funcall build element (apply 'min ind-list) (not ignore-first))))))
3807 ;;; The Toolbox
3809 ;; The first move is to implement a way to obtain the smallest element
3810 ;; containing point. This is the job of `org-element-at-point'. It
3811 ;; basically jumps back to the beginning of section containing point
3812 ;; and moves, element after element, with
3813 ;; `org-element-current-element' until the container is found.
3815 ;; Note: When using `org-element-at-point', secondary values are never
3816 ;; parsed since the function focuses on elements, not on objects.
3818 (defun org-element-at-point (&optional keep-trail)
3819 "Determine closest element around point.
3821 Return value is a list like (TYPE PROPS) where TYPE is the type
3822 of the element and PROPS a plist of properties associated to the
3823 element. Possible types are defined in
3824 `org-element-all-elements'.
3826 As a special case, if point is at the very beginning of a list or
3827 sub-list, returned element will be that list instead of the first
3828 item. In the same way, if point is at the beginning of the first
3829 row of a table, returned element will be the table instead of the
3830 first row.
3832 If optional argument KEEP-TRAIL is non-nil, the function returns
3833 a list of of elements leading to element at point. The list's
3834 CAR is always the element at point. Its last item will be the
3835 element's parent, unless element was either the first in its
3836 section (in which case the last item in the list is the first
3837 element of section) or an headline (in which case the list
3838 contains that headline as its single element). Elements
3839 in-between, if any, are siblings of the element at point."
3840 (org-with-wide-buffer
3841 ;; If at an headline, parse it. It is the sole element that
3842 ;; doesn't require to know about context. Be sure to disallow
3843 ;; secondary string parsing, though.
3844 (if (org-with-limited-levels (org-at-heading-p))
3845 (if (not keep-trail) (org-element-headline-parser t)
3846 (list (org-element-headline-parser t)))
3847 ;; Otherwise move at the beginning of the section containing
3848 ;; point.
3849 (let ((origin (point)) element type special-flag trail struct prevs)
3850 (org-with-limited-levels
3851 (if (org-before-first-heading-p) (goto-char (point-min))
3852 (org-back-to-heading)
3853 (forward-line)))
3854 (org-skip-whitespace)
3855 (beginning-of-line)
3856 ;; Starting parsing successively each element with
3857 ;; `org-element-current-element'. Skip those ending before
3858 ;; original position.
3859 (catch 'exit
3860 (while t
3861 (setq element (org-element-current-element
3862 'element special-flag struct)
3863 type (car element))
3864 (when keep-trail (push element trail))
3865 (cond
3866 ;; 1. Skip any element ending before point or at point.
3867 ((let ((end (org-element-property :end element)))
3868 (when (<= end origin)
3869 (if (> (point-max) end) (goto-char end)
3870 (throw 'exit (or trail element))))))
3871 ;; 2. An element containing point is always the element at
3872 ;; point.
3873 ((not (memq type org-element-greater-elements))
3874 (throw 'exit (if keep-trail trail element)))
3875 ;; 3. At a plain list.
3876 ((eq type 'plain-list)
3877 (setq struct (org-element-property :structure element)
3878 prevs (or prevs (org-list-prevs-alist struct)))
3879 (let ((beg (org-element-property :contents-begin element)))
3880 (if (<= origin beg) (throw 'exit (or trail element))
3881 ;; Find the item at this level containing ORIGIN.
3882 (let ((items (org-list-get-all-items beg struct prevs))
3883 parent)
3884 (catch 'local
3885 (mapc
3886 (lambda (pos)
3887 (cond
3888 ;; Item ends before point: skip it.
3889 ((<= (org-list-get-item-end pos struct) origin))
3890 ;; Item contains point: store is in PARENT.
3891 ((<= pos origin) (setq parent pos))
3892 ;; We went too far: return PARENT.
3893 (t (throw 'local nil)))) items))
3894 ;; No parent: no item contained point, though the
3895 ;; plain list does. Point is in the blank lines
3896 ;; after the list: return plain list.
3897 (if (not parent) (throw 'exit (or trail element))
3898 (setq special-flag 'item)
3899 (goto-char parent))))))
3900 ;; 4. At a table.
3901 ((eq type 'table)
3902 (if (eq (org-element-property :type element) 'table.el)
3903 (throw 'exit (or trail element))
3904 (let ((beg (org-element-property :contents-begin element))
3905 (end (org-element-property :contents-end element)))
3906 (if (or (<= origin beg) (>= origin end))
3907 (throw 'exit (or trail element))
3908 (when keep-trail (setq trail (list element)))
3909 (setq special-flag 'table-row)
3910 (narrow-to-region beg end)))))
3911 ;; 4. At any other greater element type, if point is
3912 ;; within contents, move into it. Otherwise, return
3913 ;; that element.
3915 (when (eq type 'item) (setq special-flag nil))
3916 (let ((beg (org-element-property :contents-begin element))
3917 (end (org-element-property :contents-end element)))
3918 (if (or (not beg) (not end) (> beg origin) (< end origin))
3919 (throw 'exit (or trail element))
3920 ;; Reset trail, since we found a parent.
3921 (when keep-trail (setq trail (list element)))
3922 (narrow-to-region beg end)
3923 (goto-char beg)))))))))))
3926 ;; Once the local structure around point is well understood, it's easy
3927 ;; to implement some replacements for `forward-paragraph'
3928 ;; `backward-paragraph', namely `org-element-forward' and
3929 ;; `org-element-backward'.
3931 ;; Also, `org-transpose-elements' mimics the behaviour of
3932 ;; `transpose-words', at the element's level, whereas
3933 ;; `org-element-drag-forward', `org-element-drag-backward', and
3934 ;; `org-element-up' generalize, respectively, functions
3935 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3937 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3938 ;; smartly remove global indentation from buffer, making it possible
3939 ;; to use Org indent mode on a file created with hard indentation.
3941 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3942 ;; internally by some of the previously cited tools.
3944 (defsubst org-element-nested-p (elem-A elem-B)
3945 "Non-nil when elements ELEM-A and ELEM-B are nested."
3946 (let ((beg-A (org-element-property :begin elem-A))
3947 (beg-B (org-element-property :begin elem-B))
3948 (end-A (org-element-property :end elem-A))
3949 (end-B (org-element-property :end elem-B)))
3950 (or (and (>= beg-A beg-B) (<= end-A end-B))
3951 (and (>= beg-B beg-A) (<= end-B end-A)))))
3953 (defun org-element-swap-A-B (elem-A elem-B)
3954 "Swap elements ELEM-A and ELEM-B.
3956 Leave point at the end of ELEM-A."
3957 (goto-char (org-element-property :begin elem-A))
3958 (let* ((beg-A (org-element-property :begin elem-A))
3959 (end-A (save-excursion
3960 (goto-char (org-element-property :end elem-A))
3961 (skip-chars-backward " \r\t\n")
3962 (point-at-eol)))
3963 (beg-B (org-element-property :begin elem-B))
3964 (end-B (save-excursion
3965 (goto-char (org-element-property :end elem-B))
3966 (skip-chars-backward " \r\t\n")
3967 (point-at-eol)))
3968 (body-A (buffer-substring beg-A end-A))
3969 (body-B (delete-and-extract-region beg-B end-B)))
3970 (goto-char beg-B)
3971 (insert body-A)
3972 (goto-char beg-A)
3973 (delete-region beg-A end-A)
3974 (insert body-B)
3975 (goto-char (org-element-property :end elem-B))))
3977 (defun org-element-backward ()
3978 "Move backward by one element.
3979 Move to the previous element at the same level, when possible."
3980 (interactive)
3981 (if (save-excursion (skip-chars-backward " \r\t\n") (bobp))
3982 (error "Cannot move further up")
3983 (let* ((trail (org-element-at-point 'keep-trail))
3984 (element (car trail))
3985 (beg (org-element-property :begin element)))
3986 ;; Move to beginning of current element if point isn't there.
3987 (if (/= (point) beg) (goto-char beg)
3988 (let ((type (org-element-type element)))
3989 (cond
3990 ;; At an headline: move to previous headline at the same
3991 ;; level, a parent, or BOB.
3992 ((eq type 'headline)
3993 (let ((dest (save-excursion (org-backward-same-level 1) (point))))
3994 (if (= (point-min) dest) (error "Cannot move further up")
3995 (goto-char dest))))
3996 ;; At an item: try to move to the previous item, if any.
3997 ((and (eq type 'item)
3998 (let* ((struct (org-element-property :structure element))
3999 (prev (org-list-get-prev-item
4000 beg struct (org-list-prevs-alist struct))))
4001 (when prev (goto-char prev)))))
4002 ;; In any other case, find the previous element in the
4003 ;; trail and move to its beginning. If no previous element
4004 ;; can be found, move to headline.
4005 (t (let ((prev (nth 1 trail)))
4006 (if prev (goto-char (org-element-property :begin prev))
4007 (org-back-to-heading))))))))))
4009 (defun org-element-drag-backward ()
4010 "Drag backward element at point."
4011 (interactive)
4012 (let* ((pos (point))
4013 (elem (org-element-at-point)))
4014 (when (= (progn (goto-char (point-min))
4015 (org-skip-whitespace)
4016 (point-at-bol))
4017 (org-element-property :end elem))
4018 (error "Cannot drag element backward"))
4019 (goto-char (org-element-property :begin elem))
4020 (org-element-backward)
4021 (let ((prev-elem (org-element-at-point)))
4022 (when (or (org-element-nested-p elem prev-elem)
4023 (and (eq (org-element-type elem) 'headline)
4024 (not (eq (org-element-type prev-elem) 'headline))))
4025 (goto-char pos)
4026 (error "Cannot drag element backward"))
4027 ;; Compute new position of point: it's shifted by PREV-ELEM
4028 ;; body's length.
4029 (let ((size-prev (- (org-element-property :end prev-elem)
4030 (org-element-property :begin prev-elem))))
4031 (org-element-swap-A-B prev-elem elem)
4032 (goto-char (- pos size-prev))))))
4034 (defun org-element-drag-forward ()
4035 "Move forward element at point."
4036 (interactive)
4037 (let* ((pos (point))
4038 (elem (org-element-at-point)))
4039 (when (= (point-max) (org-element-property :end elem))
4040 (error "Cannot drag element forward"))
4041 (goto-char (org-element-property :end elem))
4042 (let ((next-elem (org-element-at-point)))
4043 (when (or (org-element-nested-p elem next-elem)
4044 (and (eq (org-element-type next-elem) 'headline)
4045 (not (eq (org-element-type elem) 'headline))))
4046 (goto-char pos)
4047 (error "Cannot drag element forward"))
4048 ;; Compute new position of point: it's shifted by NEXT-ELEM
4049 ;; body's length (without final blanks) and by the length of
4050 ;; blanks between ELEM and NEXT-ELEM.
4051 (let ((size-next (- (save-excursion
4052 (goto-char (org-element-property :end next-elem))
4053 (skip-chars-backward " \r\t\n")
4054 (forward-line)
4055 (point))
4056 (org-element-property :begin next-elem)))
4057 (size-blank (- (org-element-property :end elem)
4058 (save-excursion
4059 (goto-char (org-element-property :end elem))
4060 (skip-chars-backward " \r\t\n")
4061 (forward-line)
4062 (point)))))
4063 (org-element-swap-A-B elem next-elem)
4064 (goto-char (+ pos size-next size-blank))))))
4066 (defun org-element-forward ()
4067 "Move forward by one element.
4068 Move to the next element at the same level, when possible."
4069 (interactive)
4070 (if (eobp) (error "Cannot move further down")
4071 (let* ((trail (org-element-at-point 'keep-trail))
4072 (element (car trail))
4073 (type (org-element-type element))
4074 (end (org-element-property :end element)))
4075 (cond
4076 ;; At an headline, move to next headline at the same level.
4077 ((eq type 'headline) (goto-char end))
4078 ;; At an item. Move to the next item, if possible.
4079 ((and (eq type 'item)
4080 (let* ((struct (org-element-property :structure element))
4081 (prevs (org-list-prevs-alist struct))
4082 (beg (org-element-property :begin element))
4083 (next-item (org-list-get-next-item beg struct prevs)))
4084 (when next-item (goto-char next-item)))))
4085 ;; In any other case, move to element's end, unless this
4086 ;; position is also the end of its parent's contents, in which
4087 ;; case, directly jump to parent's end.
4089 (let ((parent
4090 ;; Determine if TRAIL contains the real parent of ELEMENT.
4091 (and (> (length trail) 1)
4092 (let* ((parent-candidate (car (last trail))))
4093 (and (memq (org-element-type parent-candidate)
4094 org-element-greater-elements)
4095 (>= (org-element-property
4096 :contents-end parent-candidate) end)
4097 parent-candidate)))))
4098 (cond ((not parent) (goto-char end))
4099 ((= (org-element-property :contents-end parent) end)
4100 (goto-char (org-element-property :end parent)))
4101 (t (goto-char end)))))))))
4103 (defun org-element-mark-element ()
4104 "Put point at beginning of this element, mark at end.
4106 Interactively, if this command is repeated or (in Transient Mark
4107 mode) if the mark is active, it marks the next element after the
4108 ones already marked."
4109 (interactive)
4110 (let (deactivate-mark)
4111 (if (or (and (eq last-command this-command) (mark t))
4112 (and transient-mark-mode mark-active))
4113 (set-mark
4114 (save-excursion
4115 (goto-char (mark))
4116 (goto-char (org-element-property :end (org-element-at-point)))))
4117 (let ((element (org-element-at-point)))
4118 (end-of-line)
4119 (push-mark (org-element-property :end element) t t)
4120 (goto-char (org-element-property :begin element))))))
4122 (defun org-narrow-to-element ()
4123 "Narrow buffer to current element."
4124 (interactive)
4125 (let ((elem (org-element-at-point)))
4126 (cond
4127 ((eq (car elem) 'headline)
4128 (narrow-to-region
4129 (org-element-property :begin elem)
4130 (org-element-property :end elem)))
4131 ((memq (car elem) org-element-greater-elements)
4132 (narrow-to-region
4133 (org-element-property :contents-begin elem)
4134 (org-element-property :contents-end elem)))
4136 (narrow-to-region
4137 (org-element-property :begin elem)
4138 (org-element-property :end elem))))))
4140 (defun org-transpose-elements ()
4141 "Transpose current and previous elements, keeping blank lines between.
4142 Point is moved after both elements."
4143 (interactive)
4144 (org-skip-whitespace)
4145 (let ((pos (point))
4146 (cur (org-element-at-point)))
4147 (when (= (save-excursion (goto-char (point-min))
4148 (org-skip-whitespace)
4149 (point-at-bol))
4150 (org-element-property :begin cur))
4151 (error "No previous element"))
4152 (goto-char (org-element-property :begin cur))
4153 (forward-line -1)
4154 (let ((prev (org-element-at-point)))
4155 (when (org-element-nested-p cur prev)
4156 (goto-char pos)
4157 (error "Cannot transpose nested elements"))
4158 (org-element-swap-A-B prev cur))))
4160 (defun org-element-unindent-buffer ()
4161 "Un-indent the visible part of the buffer.
4162 Relative indentation \(between items, inside blocks, etc.\) isn't
4163 modified."
4164 (interactive)
4165 (unless (eq major-mode 'org-mode)
4166 (error "Cannot un-indent a buffer not in Org mode"))
4167 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
4168 unindent-tree ; For byte-compiler.
4169 (unindent-tree
4170 (function
4171 (lambda (contents)
4172 (mapc (lambda (element)
4173 (if (eq (org-element-type element) 'headline)
4174 (funcall unindent-tree
4175 (org-element-contents element))
4176 (save-excursion
4177 (save-restriction
4178 (narrow-to-region
4179 (org-element-property :begin element)
4180 (org-element-property :end element))
4181 (org-do-remove-indentation)))))
4182 (reverse contents))))))
4183 (funcall unindent-tree (org-element-contents parse-tree))))
4185 (defun org-element-up ()
4186 "Move to upper element."
4187 (interactive)
4188 (cond
4189 ((bobp) (error "No surrounding element"))
4190 ((org-with-limited-levels (org-at-heading-p))
4191 (or (org-up-heading-safe) (error "No surronding element")))
4193 (let* ((trail (org-element-at-point 'keep-trail))
4194 (element (car trail))
4195 (type (org-element-type element)))
4196 (cond
4197 ;; At an item, with a parent in the list: move to that parent.
4198 ((and (eq type 'item)
4199 (let* ((beg (org-element-property :begin element))
4200 (struct (org-element-property :structure element))
4201 (parents (org-list-parents-alist struct))
4202 (parentp (org-list-get-parent beg struct parents)))
4203 (and parentp (goto-char parentp)))))
4204 ;; Determine parent in the trail.
4206 (let ((parent
4207 (and (> (length trail) 1)
4208 (let ((parentp (car (last trail))))
4209 (and (memq (org-element-type parentp)
4210 org-element-greater-elements)
4211 (>= (org-element-property :contents-end parentp)
4212 (org-element-property :end element))
4213 parentp)))))
4214 (cond
4215 ;; When parent is found move to its beginning.
4216 (parent (goto-char (org-element-property :begin parent)))
4217 ;; If no parent was found, move to headline above, if any
4218 ;; or return an error.
4219 ((org-before-first-heading-p) (error "No surrounding element"))
4220 (t (org-back-to-heading))))))))))
4222 (defun org-element-down ()
4223 "Move to inner element."
4224 (interactive)
4225 (let ((element (org-element-at-point)))
4226 (cond
4227 ((memq (org-element-type element) '(plain-list table))
4228 (goto-char (org-element-property :contents-begin element))
4229 (forward-char))
4230 ((memq (org-element-type element) org-element-greater-elements)
4231 ;; If contents are hidden, first disclose them.
4232 (when (org-element-property :hiddenp element) (org-cycle))
4233 (goto-char (org-element-property :contents-begin element)))
4234 (t (error "No inner element")))))
4237 (provide 'org-element)
4238 ;;; org-element.el ends here