Manually revert to the Release 7.8.04 tag.
[org-mode.git] / contrib / lisp / org-element.el
blob3cc5c984280c2f9743e12a13abac452342e546e9
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 ;; An object can be defined anywhere on a line. It may span over more
29 ;; than a line but never contains a blank one. Objects belong to the
30 ;; following types: `emphasis', `entity', `export-snippet',
31 ;; `footnote-reference', `inline-babel-call', `inline-src-block',
32 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
33 ;; `statistics-cookie', `subscript', `superscript', `target',
34 ;; `time-stamp' and `verbatim'.
36 ;; An element always starts and ends at the beginning of a line. The
37 ;; only element's type containing objects is called a `paragraph'.
38 ;; Other types are: `comment', `comment-block', `example-block',
39 ;; `export-block', `fixed-width', `horizontal-rule', `keyword',
40 ;; `latex-environment', `babel-call', `property-drawer',
41 ;; `quote-section', `src-block', `table' and `verse-block'.
43 ;; Elements containing paragraphs are called greater elements.
44 ;; Concerned types are: `center-block', `drawer', `dynamic-block',
45 ;; `footnote-definition', `headline', `inlinetask', `item',
46 ;; `plain-list', `quote-block', `section' and `special-block'.
48 ;; Greater elements (excepted `headline', `item' and `section' types)
49 ;; and elements (excepted `keyword', `babel-call', and
50 ;; `property-drawer' types) can have a fixed set of keywords as
51 ;; attributes. Those are called "affiliated keywords", to distinguish
52 ;; them from others keywords, which are full-fledged elements. In
53 ;; particular, the "name" affiliated keyword allows to label almost
54 ;; any element in an Org buffer.
56 ;; Notwithstanding affiliated keywords, each greater element, element
57 ;; and object has a fixed set of properties attached to it. Among
58 ;; them, three are shared by all types: `:begin' and `:end', which
59 ;; refer to the beginning and ending buffer positions of the
60 ;; considered element or object, and `:post-blank', which holds the
61 ;; number of blank lines, or white spaces, at its end.
63 ;; Some elements also have special properties whose value can hold
64 ;; objects themselves (i.e. an item tag, an headline name, a table
65 ;; cell). Such values are called "secondary strings".
67 ;; Lisp-wise, an element or an object can be represented as a list.
68 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
69 ;; TYPE is a symbol describing the Org element or object.
70 ;; PROPERTIES is the property list attached to it. See docstring of
71 ;; appropriate parsing function to get an exhaustive
72 ;; list.
73 ;; CONTENTS is a list of elements, objects or raw strings contained
74 ;; in the current element or object, when applicable.
76 ;; An Org buffer is a nested list of such elements and objects, whose
77 ;; type is `org-data' and properties is nil.
79 ;; The first part of this file implements a parser and an interpreter
80 ;; for each type of Org syntax.
82 ;; The next two parts introduce three accessors and a function
83 ;; retrieving the smallest element starting at point (respectively
84 ;; `org-element-type', `org-element-property', `org-element-contents'
85 ;; and `org-element-current-element').
87 ;; The following part creates a fully recursive buffer parser. It
88 ;; also provides a tool to map a function to elements or objects
89 ;; matching some criteria in the parse tree. Functions of interest
90 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
91 ;; extent, `org-element-parse-secondary-string'.
93 ;; The penultimate part is the cradle of an interpreter for the
94 ;; obtained parse tree: `org-element-interpret-data' (and its
95 ;; relative, `org-element-interpret-secondary').
97 ;; The library ends by furnishing a set of interactive tools for
98 ;; element's navigation and manipulation, mostly based on
99 ;; `org-element-at-point' function.
102 ;;; Code:
104 (eval-when-compile (require 'cl))
105 (require 'org)
106 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
109 ;;; Greater elements
111 ;; For each greater element type, we define a parser and an
112 ;; interpreter.
114 ;; A parser (`item''s excepted) accepts no argument and represents the
115 ;; element or object as the list described above. An interpreter
116 ;; accepts two arguments: the list representation of the element or
117 ;; object, and its contents. The latter may be nil, depending on the
118 ;; element or object considered. It returns the appropriate Org
119 ;; syntax, as a string.
121 ;; Parsing functions must follow the naming convention:
122 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
123 ;; defined in `org-element-greater-elements'.
125 ;; Similarly, interpreting functions must follow the naming
126 ;; convention: org-element-TYPE-interpreter.
128 ;; With the exception of `headline' and `item' types, greater elements
129 ;; cannot contain other greater elements of their own type.
131 ;; Beside implementing a parser and an interpreter, adding a new
132 ;; greater element requires to tweak `org-element-current-element'.
133 ;; Moreover, the newly defined type must be added to both
134 ;; `org-element-all-elements' and `org-element-greater-elements'.
137 ;;;; Center Block
139 (defun org-element-center-block-parser ()
140 "Parse a center block.
142 Return a list whose car is `center-block' and cdr is a plist
143 containing `:begin', `:end', `:hiddenp', `:contents-begin',
144 `:contents-end' and `:post-blank' keywords.
146 Assume point is at beginning or end of the block."
147 (save-excursion
148 (let* ((case-fold-search t)
149 (keywords (progn
150 (end-of-line)
151 (re-search-backward
152 (concat "^[ \t]*#\\+begin_center") nil t)
153 (org-element-collect-affiliated-keywords)))
154 (begin (car keywords))
155 (contents-begin (progn (forward-line) (point)))
156 (hidden (org-truely-invisible-p))
157 (contents-end (progn (re-search-forward
158 (concat "^[ \t]*#\\+end_center") nil t)
159 (point-at-bol)))
160 (pos-before-blank (progn (forward-line) (point)))
161 (end (progn (org-skip-whitespace)
162 (if (eobp) (point) (point-at-bol)))))
163 `(center-block
164 (:begin ,begin
165 :end ,end
166 :hiddenp ,hidden
167 :contents-begin ,contents-begin
168 :contents-end ,contents-end
169 :post-blank ,(count-lines pos-before-blank end)
170 ,@(cadr keywords))))))
172 (defun org-element-center-block-interpreter (center-block contents)
173 "Interpret CENTER-BLOCK element as Org syntax.
174 CONTENTS is the contents of the element."
175 (format "#+begin_center\n%s#+end_center" contents))
178 ;;;; Drawer
180 (defun org-element-drawer-parser ()
181 "Parse a drawer.
183 Return a list whose car is `drawer' and cdr is a plist containing
184 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
185 `:contents-end' and `:post-blank' keywords.
187 Assume point is at beginning of drawer."
188 (save-excursion
189 (let* ((case-fold-search t)
190 (name (progn (looking-at org-drawer-regexp)
191 (org-match-string-no-properties 1)))
192 (keywords (org-element-collect-affiliated-keywords))
193 (begin (car keywords))
194 (contents-begin (progn (forward-line) (point)))
195 (hidden (org-truely-invisible-p))
196 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
197 (point-at-bol)))
198 (pos-before-blank (progn (forward-line) (point)))
199 (end (progn (org-skip-whitespace)
200 (if (eobp) (point) (point-at-bol)))))
201 `(drawer
202 (:begin ,begin
203 :end ,end
204 :drawer-name ,name
205 :hiddenp ,hidden
206 :contents-begin ,contents-begin
207 :contents-end ,contents-end
208 :post-blank ,(count-lines pos-before-blank end)
209 ,@(cadr keywords))))))
211 (defun org-element-drawer-interpreter (drawer contents)
212 "Interpret DRAWER element as Org syntax.
213 CONTENTS is the contents of the element."
214 (format ":%s:\n%s:END:"
215 (org-element-property :drawer-name drawer)
216 contents))
219 ;;;; Dynamic Block
221 (defun org-element-dynamic-block-parser ()
222 "Parse a dynamic block.
224 Return a list whose car is `dynamic-block' and cdr is a plist
225 containing `:block-name', `:begin', `:end', `:hiddenp',
226 `:contents-begin', `:contents-end', `:arguments' and
227 `:post-blank' keywords.
229 Assume point is at beginning of dynamic block."
230 (save-excursion
231 (let* ((case-fold-search t)
232 (name (progn (looking-at org-dblock-start-re)
233 (org-match-string-no-properties 1)))
234 (arguments (org-match-string-no-properties 3))
235 (keywords (org-element-collect-affiliated-keywords))
236 (begin (car keywords))
237 (contents-begin (progn (forward-line) (point)))
238 (hidden (org-truely-invisible-p))
239 (contents-end (progn (re-search-forward org-dblock-end-re nil t)
240 (point-at-bol)))
241 (pos-before-blank (progn (forward-line) (point)))
242 (end (progn (org-skip-whitespace)
243 (if (eobp) (point) (point-at-bol)))))
244 (list 'dynamic-block
245 `(:begin ,begin
246 :end ,end
247 :block-name ,name
248 :arguments ,arguments
249 :hiddenp ,hidden
250 :contents-begin ,contents-begin
251 :contents-end ,contents-end
252 :post-blank ,(count-lines pos-before-blank end)
253 ,@(cadr keywords))))))
255 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
256 "Interpret DYNAMIC-BLOCK element as Org syntax.
257 CONTENTS is the contents of the element."
258 (format "#+BEGIN: %s%s\n%s#+END:"
259 (org-element-property :block-name dynamic-block)
260 (let ((args (org-element-property :arguments dynamic-block)))
261 (and arg (concat " " args)))
262 contents))
265 ;;;; Footnote Definition
267 (defun org-element-footnote-definition-parser ()
268 "Parse a footnote definition.
270 Return a list whose car is `footnote-definition' and cdr is
271 a plist containing `:label', `:begin' `:end', `:contents-begin',
272 `:contents-end' and `:post-blank' keywords."
273 (save-excursion
274 (let* ((f-def (org-footnote-at-definition-p))
275 (label (car f-def))
276 (keywords (progn (goto-char (nth 1 f-def))
277 (org-element-collect-affiliated-keywords)))
278 (begin (car keywords))
279 (contents-begin (progn (looking-at (concat "\\[" label "\\]"))
280 (goto-char (match-end 0))
281 (org-skip-whitespace)
282 (point)))
283 (end (goto-char (nth 2 f-def)))
284 (contents-end (progn (skip-chars-backward " \r\t\n")
285 (forward-line)
286 (point))))
287 `(footnote-definition
288 (:label ,label
289 :begin ,begin
290 :end ,end
291 :contents-begin ,contents-begin
292 :contents-end ,contents-end
293 :post-blank ,(count-lines contents-end end)
294 ,@(cadr keywords))))))
296 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
297 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
298 CONTENTS is the contents of the footnote-definition."
299 (concat (format "[%s]" (org-element-property :label footnote-definition))
301 contents))
304 ;;;; Headline
306 (defun org-element-headline-parser ()
307 "Parse an headline.
309 Return a list whose car is `headline' and cdr is a plist
310 containing `:raw-value', `:title', `:begin', `:end',
311 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
312 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
313 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
314 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
315 keywords.
317 The plist also contains any property set in the property drawer,
318 with its name in lowercase, the underscores replaced with hyphens
319 and colons at the beginning (i.e. `:custom-id').
321 Assume point is at beginning of the headline."
322 (save-excursion
323 (let* ((components (org-heading-components))
324 (level (nth 1 components))
325 (todo (nth 2 components))
326 (todo-type
327 (and todo (if (member todo org-done-keywords) 'done 'todo)))
328 (tags (nth 5 components))
329 (raw-value (nth 4 components))
330 (quotedp
331 (let ((case-fold-search nil))
332 (string-match (format "^%s +" org-quote-string) raw-value)))
333 (commentedp
334 (let ((case-fold-search nil))
335 (string-match (format "^%s +" org-comment-string) raw-value)))
336 (archivedp
337 (and tags
338 (let ((case-fold-search nil))
339 (string-match (format ":%s:" org-archive-tag) tags))))
340 (footnote-section-p (and org-footnote-section
341 (string= org-footnote-section raw-value)))
342 (standard-props (let (plist)
343 (mapc
344 (lambda (p)
345 (let ((p-name (downcase (car p))))
346 (while (string-match "_" p-name)
347 (setq p-name
348 (replace-match "-" nil nil p-name)))
349 (setq p-name (intern (concat ":" p-name)))
350 (setq plist
351 (plist-put plist p-name (cdr p)))))
352 (org-entry-properties nil 'standard))
353 plist))
354 (time-props (org-entry-properties nil 'special "CLOCK"))
355 (scheduled (cdr (assoc "SCHEDULED" time-props)))
356 (deadline (cdr (assoc "DEADLINE" time-props)))
357 (clock (cdr (assoc "CLOCK" time-props)))
358 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
359 (begin (point))
360 (pos-after-head (save-excursion (forward-line) (point)))
361 (contents-begin (save-excursion (forward-line)
362 (org-skip-whitespace)
363 (if (eobp) (point) (point-at-bol))))
364 (hidden (save-excursion (forward-line) (org-truely-invisible-p)))
365 (end (progn (goto-char (org-end-of-subtree t t))))
366 (contents-end (progn (skip-chars-backward " \r\t\n")
367 (forward-line)
368 (point)))
369 title)
370 ;; Clean RAW-VALUE from any quote or comment string.
371 (when (or quotedp commentedp)
372 (setq raw-value
373 (replace-regexp-in-string
374 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
376 raw-value)))
377 ;; Clean TAGS from archive tag, if any.
378 (when archivedp
379 (setq tags
380 (and (not (string= tags (format ":%s:" org-archive-tag)))
381 (replace-regexp-in-string
382 (concat org-archive-tag ":") "" tags)))
383 (when (string= tags ":") (setq tags nil)))
384 ;; Then get TITLE.
385 (setq title (org-element-parse-secondary-string
386 raw-value
387 (cdr (assq 'headline org-element-string-restrictions))))
388 `(headline
389 (:raw-value ,raw-value
390 :title ,title
391 :begin ,begin
392 :end ,end
393 :pre-blank ,(count-lines pos-after-head contents-begin)
394 :hiddenp ,hidden
395 :contents-begin ,contents-begin
396 :contents-end ,contents-end
397 :level ,level
398 :priority ,(nth 3 components)
399 :tags ,tags
400 :todo-keyword ,todo
401 :todo-type ,todo-type
402 :scheduled ,scheduled
403 :deadline ,deadline
404 :timestamp ,timestamp
405 :clock ,clock
406 :post-blank ,(count-lines contents-end end)
407 :footnote-section-p ,footnote-section-p
408 :archivedp ,archivedp
409 :commentedp ,commentedp
410 :quotedp ,quotedp
411 ,@standard-props)))))
413 (defun org-element-headline-interpreter (headline contents)
414 "Interpret HEADLINE element as Org syntax.
415 CONTENTS is the contents of the element."
416 (let* ((level (org-element-property :level headline))
417 (todo (org-element-property :todo-keyword headline))
418 (priority (org-element-property :priority headline))
419 (title (org-element-property :raw-value headline))
420 (tags (let ((tag-string (org-element-property :tags headline))
421 (archivedp (org-element-property :archivedp headline)))
422 (cond
423 ((and (not tag-string) archivedp)
424 (format ":%s:" org-archive-tag))
425 (archivedp (concat ":" org-archive-tag tag-string))
426 (t tag-string))))
427 (commentedp (org-element-property :commentedp headline))
428 (quotedp (org-element-property :quotedp headline))
429 (pre-blank (org-element-property :pre-blank headline))
430 (heading (concat (make-string level ?*)
431 (and todo (concat " " todo))
432 (and quotedp (concat " " org-quote-string))
433 (and commentedp (concat " " org-comment-string))
434 (and priority (concat " " priority))
435 (cond ((and org-footnote-section
436 (org-element-property
437 :footnote-section-p headline))
438 (concat " " org-footnote-section))
439 (title (concat " " title)))))
440 ;; Align tags.
441 (tags-fmt (when tags
442 (let ((tags-len (length tags)))
443 (format "%% %ds"
444 (cond
445 ((zerop org-tags-column) (1+ tags-len))
446 ((< org-tags-column 0)
447 (max (- (+ org-tags-column (length heading)))
448 (1+ tags-len)))
449 (t (max (+ (- org-tags-column (length heading))
450 tags-len)
451 (1+ tags-len)))))))))
452 (concat heading (and tags (format tags-fmt tags))
453 (make-string (1+ pre-blank) 10)
454 contents)))
457 ;;;; Inlinetask
459 (defun org-element-inlinetask-parser ()
460 "Parse an inline task.
462 Return a list whose car is `inlinetask' and cdr is a plist
463 containing `:raw-value', `:title', `:begin', `:end', `:hiddenp',
464 `:contents-begin' and `:contents-end', `:level', `:priority',
465 `:raw-value', `:tags', `:todo-keyword', `:todo-type',
466 `:scheduled', `:deadline', `:timestamp', `:clock' and
467 `:post-blank' keywords.
469 The plist also contains any property set in the property drawer,
470 with its name in lowercase, the underscores replaced with hyphens
471 and colons at the beginning (i.e. `:custom-id').
473 Assume point is at beginning of the inline task."
474 (save-excursion
475 (let* ((keywords (org-element-collect-affiliated-keywords))
476 (begin (car keywords))
477 (components (org-heading-components))
478 (todo (nth 2 components))
479 (todo-type (and todo
480 (if (member todo org-done-keywords) 'done 'todo)))
481 (raw-value (nth 4 components))
482 (standard-props (let (plist)
483 (mapc
484 (lambda (p)
485 (let ((p-name (downcase (car p))))
486 (while (string-match "_" p-name)
487 (setq p-name
488 (replace-match "-" nil nil p-name)))
489 (setq p-name (intern (concat ":" p-name)))
490 (setq plist
491 (plist-put plist p-name (cdr p)))))
492 (org-entry-properties nil 'standard))
493 plist))
494 (time-props (org-entry-properties nil 'special "CLOCK"))
495 (scheduled (cdr (assoc "SCHEDULED" time-props)))
496 (deadline (cdr (assoc "DEADLINE" time-props)))
497 (clock (cdr (assoc "CLOCK" time-props)))
498 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
499 (title (org-element-parse-secondary-string
500 raw-value
501 (cdr (assq 'inlinetask org-element-string-restrictions))))
502 (contents-begin (save-excursion (forward-line) (point)))
503 (hidden (org-truely-invisible-p))
504 (pos-before-blank (org-inlinetask-goto-end))
505 ;; In the case of a single line task, CONTENTS-BEGIN and
506 ;; CONTENTS-END might overlap.
507 (contents-end (max contents-begin
508 (save-excursion (forward-line -1) (point))))
509 (end (progn (org-skip-whitespace)
510 (if (eobp) (point) (point-at-bol)))))
511 `(inlinetask
512 (:raw-value ,raw-value
513 :title ,title
514 :begin ,begin
515 :end ,end
516 :hiddenp ,(and (> contents-end contents-begin) hidden)
517 :contents-begin ,contents-begin
518 :contents-end ,contents-end
519 :level ,(nth 1 components)
520 :priority ,(nth 3 components)
521 :tags ,(nth 5 components)
522 :todo-keyword ,todo
523 :todo-type ,todo-type
524 :scheduled ,scheduled
525 :deadline ,deadline
526 :timestamp ,timestamp
527 :clock ,clock
528 :post-blank ,(count-lines pos-before-blank end)
529 ,@standard-props
530 ,@(cadr keywords))))))
532 (defun org-element-inlinetask-interpreter (inlinetask contents)
533 "Interpret INLINETASK element as Org syntax.
534 CONTENTS is the contents of inlinetask."
535 (let* ((level (org-element-property :level inlinetask))
536 (todo (org-element-property :todo-keyword inlinetask))
537 (priority (org-element-property :priority inlinetask))
538 (title (org-element-property :raw-value inlinetask))
539 (tags (org-element-property :tags inlinetask))
540 (task (concat (make-string level ?*)
541 (and todo (concat " " todo))
542 (and priority (concat " " priority))
543 (and title (concat " " title))))
544 ;; Align tags.
545 (tags-fmt (when tags
546 (format "%% %ds"
547 (cond
548 ((zerop org-tags-column) 1)
549 ((< 0 org-tags-column)
550 (max (+ org-tags-column
551 (length inlinetask)
552 (length tags))
554 (t (max (- org-tags-column (length inlinetask))
555 1)))))))
556 (concat inlinetask (and tags (format tags-fmt tags) "\n" contents))))
559 ;;;; Item
561 (defun org-element-item-parser (struct)
562 "Parse an item.
564 STRUCT is the structure of the plain list.
566 Return a list whose car is `item' and cdr is a plist containing
567 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
568 `:checkbox', `:counter', `:tag', `:raw-tag', `:structure',
569 `:hiddenp' and `:post-blank' keywords.
571 Assume point is at the beginning of the item."
572 (save-excursion
573 (beginning-of-line)
574 (let* ((begin (point))
575 (bullet (org-list-get-bullet (point) struct))
576 (checkbox (let ((box (org-list-get-checkbox begin struct)))
577 (cond ((equal "[ ]" box) 'off)
578 ((equal "[X]" box) 'on)
579 ((equal "[-]" box) 'trans))))
580 (counter (let ((c (org-list-get-counter begin struct)))
581 (cond
582 ((not c) nil)
583 ((string-match "[A-Za-z]" c)
584 (- (string-to-char (upcase (match-string 0 c)))
585 64))
586 ((string-match "[0-9]+" c)
587 (string-to-number (match-string 0 c))))))
588 (raw-tag (org-list-get-tag begin struct))
589 (tag (and raw-tag
590 (org-element-parse-secondary-string
591 raw-tag
592 (cdr (assq 'item org-element-string-restrictions)))))
593 (end (org-list-get-item-end begin struct))
594 (contents-begin (progn (looking-at org-list-full-item-re)
595 (goto-char (match-end 0))
596 (org-skip-whitespace)
597 ;; If first line isn't empty,
598 ;; contents really start at the text
599 ;; after item's meta-data.
600 (if (= (point-at-bol) begin) (point)
601 (point-at-bol))))
602 (hidden (progn (forward-line)
603 (and (not (= (point) end))
604 (org-truely-invisible-p))))
605 (contents-end (progn (goto-char end)
606 (skip-chars-backward " \r\t\n")
607 (forward-line)
608 (point))))
609 `(item
610 (:bullet ,bullet
611 :begin ,begin
612 :end ,end
613 ;; CONTENTS-BEGIN and CONTENTS-END may be mixed
614 ;; up in the case of an empty item separated
615 ;; from the next by a blank line. Thus, ensure
616 ;; the former is always the smallest of two.
617 :contents-begin ,(min contents-begin contents-end)
618 :contents-end ,(max contents-begin contents-end)
619 :checkbox ,checkbox
620 :counter ,counter
621 :raw-tag ,raw-tag
622 :tag ,tag
623 :hiddenp ,hidden
624 :structure ,struct
625 :post-blank ,(count-lines contents-end end))))))
627 (defun org-element-item-interpreter (item contents)
628 "Interpret ITEM element as Org syntax.
629 CONTENTS is the contents of the element."
630 (let* ((bullet
631 (let* ((beg (org-element-property :begin item))
632 (struct (org-element-property :structure item))
633 (pre (org-list-prevs-alist struct))
634 (bul (org-element-property :bullet item)))
635 (org-list-bullet-string
636 (if (not (eq (org-list-get-list-type beg struct pre) 'ordered)) "-"
637 (let ((num
638 (car
639 (last
640 (org-list-get-item-number
641 beg struct pre (org-list-parents-alist struct))))))
642 (format "%d%s"
644 (if (eq org-plain-list-ordered-item-terminator ?\)) ")"
645 ".")))))))
646 (checkbox (org-element-property :checkbox item))
647 (counter (org-element-property :counter item))
648 (tag (org-element-property :raw-tag item))
649 ;; Compute indentation.
650 (ind (make-string (length bullet) 32)))
651 ;; Indent contents.
652 (concat
653 bullet
654 (and counter (format "[@%d] " counter))
655 (cond
656 ((eq checkbox 'on) "[X] ")
657 ((eq checkbox 'off) "[ ] ")
658 ((eq checkbox 'trans) "[-] "))
659 (and tag (format "%s :: " tag))
660 (org-trim
661 (replace-regexp-in-string "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))))
664 ;;;; Plain List
666 (defun org-element-plain-list-parser (&optional structure)
667 "Parse a plain list.
669 Optional argument STRUCTURE, when non-nil, is the structure of
670 the plain list being parsed.
672 Return a list whose car is `plain-list' and cdr is a plist
673 containing `:type', `:begin', `:end', `:contents-begin' and
674 `:contents-end', `:level', `:structure' and `:post-blank'
675 keywords.
677 Assume point is at one of the list items."
678 (save-excursion
679 (let* ((struct (or structure (org-list-struct)))
680 (prevs (org-list-prevs-alist struct))
681 (parents (org-list-parents-alist struct))
682 (type (org-list-get-list-type (point) struct prevs))
683 (contents-begin (goto-char
684 (org-list-get-list-begin (point) struct prevs)))
685 (keywords (org-element-collect-affiliated-keywords))
686 (begin (car keywords))
687 (contents-end (goto-char
688 (org-list-get-list-end (point) struct prevs)))
689 (end (save-excursion (org-skip-whitespace)
690 (if (eobp) (point) (point-at-bol))))
691 (level 0))
692 ;; Get list level.
693 (let ((item contents-begin))
694 (while (setq item
695 (org-list-get-parent
696 (org-list-get-list-begin item struct prevs)
697 struct parents))
698 (incf level)))
699 ;; Blank lines below list belong to the top-level list only.
700 (when (> level 0)
701 (setq end (min (org-list-get-bottom-point struct)
702 (progn (org-skip-whitespace)
703 (if (eobp) (point) (point-at-bol))))))
704 ;; Return value.
705 `(plain-list
706 (:type ,type
707 :begin ,begin
708 :end ,end
709 :contents-begin ,contents-begin
710 :contents-end ,contents-end
711 :level ,level
712 :structure ,struct
713 :post-blank ,(count-lines contents-end end)
714 ,@(cadr keywords))))))
716 (defun org-element-plain-list-interpreter (plain-list contents)
717 "Interpret PLAIN-LIST element as Org syntax.
718 CONTENTS is the contents of the element."
719 contents)
722 ;;;; Quote Block
724 (defun org-element-quote-block-parser ()
725 "Parse a quote block.
727 Return a list whose car is `quote-block' and cdr is a plist
728 containing `:begin', `:end', `:hiddenp', `:contents-begin',
729 `:contents-end' and `:post-blank' keywords.
731 Assume point is at beginning or end of the block."
732 (save-excursion
733 (let* ((case-fold-search t)
734 (keywords (progn
735 (end-of-line)
736 (re-search-backward
737 (concat "^[ \t]*#\\+begin_quote") nil t)
738 (org-element-collect-affiliated-keywords)))
739 (begin (car keywords))
740 (contents-begin (progn (forward-line) (point)))
741 (hidden (org-truely-invisible-p))
742 (contents-end (progn (re-search-forward
743 (concat "^[ \t]*#\\+end_quote") nil t)
744 (point-at-bol)))
745 (pos-before-blank (progn (forward-line) (point)))
746 (end (progn (org-skip-whitespace)
747 (if (eobp) (point) (point-at-bol)))))
748 `(quote-block
749 (:begin ,begin
750 :end ,end
751 :hiddenp ,hidden
752 :contents-begin ,contents-begin
753 :contents-end ,contents-end
754 :post-blank ,(count-lines pos-before-blank end)
755 ,@(cadr keywords))))))
757 (defun org-element-quote-block-interpreter (quote-block contents)
758 "Interpret QUOTE-BLOCK element as Org syntax.
759 CONTENTS is the contents of the element."
760 (format "#+begin_quote\n%s#+end_quote" contents))
763 ;;;; Section
765 (defun org-element-section-parser ()
766 "Parse a section.
768 Return a list whose car is `section' and cdr is a plist
769 containing `:begin', `:end', `:contents-begin', `contents-end'
770 and `:post-blank' keywords."
771 (save-excursion
772 ;; Beginning of section is the beginning of the first non-blank
773 ;; line after previous headline.
774 (org-with-limited-levels
775 (let ((begin
776 (save-excursion
777 (outline-previous-heading)
778 (if (not (org-at-heading-p)) (point)
779 (forward-line) (org-skip-whitespace) (point-at-bol))))
780 (end (progn (outline-next-heading) (point)))
781 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
782 (forward-line)
783 (point))))
784 `(section
785 (:begin ,begin
786 :end ,end
787 :contents-begin ,begin
788 :contents-end ,pos-before-blank
789 :post-blank ,(count-lines pos-before-blank end)))))))
791 (defun org-element-section-interpreter (section contents)
792 "Interpret SECTION element as Org syntax.
793 CONTENTS is the contents of the element."
794 contents)
797 ;;;; Special Block
799 (defun org-element-special-block-parser ()
800 "Parse a special block.
802 Return a list whose car is `special-block' and cdr is a plist
803 containing `:type', `:begin', `:end', `:hiddenp',
804 `:contents-begin', `:contents-end' and `:post-blank' keywords.
806 Assume point is at beginning or end of the block."
807 (save-excursion
808 (let* ((case-fold-search t)
809 (type (progn (looking-at
810 "[ \t]*#\\+\\(?:begin\\|end\\)_\\([-A-Za-z0-9]+\\)")
811 (org-match-string-no-properties 1)))
812 (keywords (progn
813 (end-of-line)
814 (re-search-backward
815 (concat "^[ \t]*#\\+begin_" type) nil t)
816 (org-element-collect-affiliated-keywords)))
817 (begin (car keywords))
818 (contents-begin (progn (forward-line) (point)))
819 (hidden (org-truely-invisible-p))
820 (contents-end (progn (re-search-forward
821 (concat "^[ \t]*#\\+end_" type) nil t)
822 (point-at-bol)))
823 (pos-before-blank (progn (forward-line) (point)))
824 (end (progn (org-skip-whitespace)
825 (if (eobp) (point) (point-at-bol)))))
826 `(special-block
827 (:type ,type
828 :begin ,begin
829 :end ,end
830 :hiddenp ,hidden
831 :contents-begin ,contents-begin
832 :contents-end ,contents-end
833 :post-blank ,(count-lines pos-before-blank end)
834 ,@(cadr keywords))))))
836 (defun org-element-special-block-interpreter (special-block contents)
837 "Interpret SPECIAL-BLOCK element as Org syntax.
838 CONTENTS is the contents of the element."
839 (let ((block-type (org-element-property :type special-block)))
840 (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
844 ;;; Elements
846 ;; For each element, a parser and an interpreter are also defined.
847 ;; Both follow the same naming convention used for greater elements.
849 ;; Also, as for greater elements, adding a new element type is done
850 ;; through the following steps: implement a parser and an interpreter,
851 ;; tweak `org-element-current-element' so that it recognizes the new
852 ;; type and add that new type to `org-element-all-elements'.
854 ;; As a special case, when the newly defined type is a block type,
855 ;; `org-element-non-recursive-block-alist' has to be modified
856 ;; accordingly.
859 ;;;; Babel Call
861 (defun org-element-babel-call-parser ()
862 "Parse a babel call.
864 Return a list whose car is `babel-call' and cdr is a plist
865 containing `:begin', `:end', `:info' and `:post-blank' as
866 keywords."
867 (save-excursion
868 (let ((info (progn (looking-at org-babel-block-lob-one-liner-regexp)
869 (org-babel-lob-get-info)))
870 (beg (point-at-bol))
871 (pos-before-blank (progn (forward-line) (point)))
872 (end (progn (org-skip-whitespace)
873 (if (eobp) (point) (point-at-bol)))))
874 `(babel-call
875 (:beg ,beg
876 :end ,end
877 :info ,info
878 :post-blank ,(count-lines pos-before-blank end))))))
880 (defun org-element-babel-call-interpreter (inline-babel-call contents)
881 "Interpret INLINE-BABEL-CALL object as Org syntax.
882 CONTENTS is nil."
883 (let* ((babel-info (org-element-property :info inline-babel-call))
884 (main-source (car babel-info))
885 (post-options (nth 1 babel-info)))
886 (concat "#+call: "
887 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
888 ;; Remove redundant square brackets.
889 (replace-match
890 (match-string 1 main-source) nil nil main-source)
891 main-source)
892 (and post-options (format "[%s]" post-options)))))
895 ;;;; Comment
897 (defun org-element-comment-parser ()
898 "Parse a comment.
900 Return a list whose car is `comment' and cdr is a plist
901 containing `:begin', `:end', `:value' and `:post-blank'
902 keywords."
903 (let (beg-coms begin end end-coms keywords)
904 (save-excursion
905 (if (looking-at "#")
906 ;; First type of comment: comments at column 0.
907 (let ((comment-re "^\\([^#]\\|#\\+[a-z]\\)"))
908 (save-excursion
909 (re-search-backward comment-re nil 'move)
910 (if (bobp) (setq keywords nil beg-coms (point))
911 (forward-line)
912 (setq keywords (org-element-collect-affiliated-keywords)
913 beg-coms (point))))
914 (re-search-forward comment-re nil 'move)
915 (setq end-coms (if (eobp) (point) (match-beginning 0))))
916 ;; Second type of comment: indented comments.
917 (let ((comment-re "[ \t]*#\\+\\(?: \\|$\\)"))
918 (unless (bobp)
919 (while (and (not (bobp)) (looking-at comment-re))
920 (forward-line -1))
921 (unless (looking-at comment-re) (forward-line)))
922 (setq beg-coms (point))
923 (setq keywords (org-element-collect-affiliated-keywords))
924 ;; Get comments ending. This may not be accurate if
925 ;; commented lines within an item are followed by commented
926 ;; lines outside of the list. Though, parser will always
927 ;; get it right as it already knows surrounding element and
928 ;; has narrowed buffer to its contents.
929 (while (looking-at comment-re) (forward-line))
930 (setq end-coms (point))))
931 ;; Find position after blank.
932 (goto-char end-coms)
933 (org-skip-whitespace)
934 (setq end (if (eobp) (point) (point-at-bol))))
935 `(comment
936 (:begin ,(or (car keywords) beg-coms)
937 :end ,end
938 :value ,(buffer-substring-no-properties beg-coms end-coms)
939 :post-blank ,(count-lines end-coms end)
940 ,@(cadr keywords)))))
942 (defun org-element-comment-interpreter (comment contents)
943 "Interpret COMMENT element as Org syntax.
944 CONTENTS is nil."
945 (org-element-property :value comment))
948 ;;;; Comment Block
950 (defun org-element-comment-block-parser ()
951 "Parse an export block.
953 Return a list whose car is `comment-block' and cdr is a plist
954 containing `:begin', `:end', `:hiddenp', `:value' and
955 `:post-blank' keywords."
956 (save-excursion
957 (end-of-line)
958 (let* ((case-fold-search t)
959 (keywords (progn
960 (re-search-backward "^[ \t]*#\\+begin_comment" nil t)
961 (org-element-collect-affiliated-keywords)))
962 (begin (car keywords))
963 (contents-begin (progn (forward-line) (point)))
964 (hidden (org-truely-invisible-p))
965 (contents-end (progn (re-search-forward
966 "^[ \t]*#\\+end_comment" nil t)
967 (point-at-bol)))
968 (pos-before-blank (progn (forward-line) (point)))
969 (end (progn (org-skip-whitespace)
970 (if (eobp) (point) (point-at-bol))))
971 (value (buffer-substring-no-properties contents-begin contents-end)))
972 `(comment-block
973 (:begin ,begin
974 :end ,end
975 :value ,value
976 :hiddenp ,hidden
977 :post-blank ,(count-lines pos-before-blank end)
978 ,@(cadr keywords))))))
980 (defun org-element-comment-block-interpreter (comment-block contents)
981 "Interpret COMMENT-BLOCK element as Org syntax.
982 CONTENTS is nil."
983 (concat "#+begin_comment\n"
984 (org-remove-indentation
985 (org-element-property :value comment-block))
986 "#+begin_comment"))
989 ;;;; Example Block
991 (defun org-element-example-block-parser ()
992 "Parse an example block.
994 Return a list whose car is `example-block' and cdr is a plist
995 containing `:begin', `:end', `:number-lines', `:preserve-indent',
996 `:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
997 `:switches', `:value' and `:post-blank' keywords."
998 (save-excursion
999 (end-of-line)
1000 (let* ((case-fold-search t)
1001 (switches (progn
1002 (re-search-backward
1003 "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?" nil t)
1004 (org-match-string-no-properties 1)))
1005 ;; Switches analysis
1006 (number-lines (cond ((not switches) nil)
1007 ((string-match "-n\\>" switches) 'new)
1008 ((string-match "+n\\>" switches) 'continued)))
1009 (preserve-indent (and switches (string-match "-i\\>" switches)))
1010 ;; Should labels be retained in (or stripped from) example
1011 ;; blocks?
1012 (retain-labels
1013 (or (not switches)
1014 (not (string-match "-r\\>" switches))
1015 (and number-lines (string-match "-k\\>" switches))))
1016 ;; What should code-references use - labels or
1017 ;; line-numbers?
1018 (use-labels
1019 (or (not switches)
1020 (and retain-labels (not (string-match "-k\\>" switches)))))
1021 (label-fmt (and switches
1022 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1023 (match-string 1 switches)))
1024 ;; Standard block parsing.
1025 (keywords (org-element-collect-affiliated-keywords))
1026 (begin (car keywords))
1027 (contents-begin (progn (forward-line) (point)))
1028 (hidden (org-truely-invisible-p))
1029 (contents-end (progn
1030 (re-search-forward "^[ \t]*#\\+END_EXAMPLE" nil t)
1031 (point-at-bol)))
1032 (value (buffer-substring-no-properties contents-begin contents-end))
1033 (pos-before-blank (progn (forward-line) (point)))
1034 (end (progn (org-skip-whitespace)
1035 (if (eobp) (point) (point-at-bol)))))
1036 `(example-block
1037 (:begin ,begin
1038 :end ,end
1039 :value ,value
1040 :switches ,switches
1041 :number-lines ,number-lines
1042 :preserve-indent ,preserve-indent
1043 :retain-labels ,retain-labels
1044 :use-labels ,use-labels
1045 :label-fmt ,label-fmt
1046 :hiddenp ,hidden
1047 :post-blank ,(count-lines pos-before-blank end)
1048 ,@(cadr keywords))))))
1050 (defun org-element-example-block-interpreter (example-block contents)
1051 "Interpret EXAMPLE-BLOCK element as Org syntax.
1052 CONTENTS is nil."
1053 (let ((options (org-element-property :options example-block)))
1054 (concat "#+begin_example" (and options (concat " " options)) "\n"
1055 (org-remove-indentation
1056 (org-element-property :value example-block))
1057 "#+end_example")))
1060 ;;;; Export Block
1062 (defun org-element-export-block-parser ()
1063 "Parse an export block.
1065 Return a list whose car is `export-block' and cdr is a plist
1066 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1067 `:post-blank' keywords."
1068 (save-excursion
1069 (end-of-line)
1070 (let* ((case-fold-search t)
1071 (contents)
1072 (type (progn (re-search-backward
1073 (concat "[ \t]*#\\+begin_"
1074 (org-re "\\([[:alnum:]]+\\)")))
1075 (downcase (org-match-string-no-properties 1))))
1076 (keywords (org-element-collect-affiliated-keywords))
1077 (begin (car keywords))
1078 (contents-begin (progn (forward-line) (point)))
1079 (hidden (org-truely-invisible-p))
1080 (contents-end (progn (re-search-forward
1081 (concat "^[ \t]*#\\+end_" type) nil t)
1082 (point-at-bol)))
1083 (pos-before-blank (progn (forward-line) (point)))
1084 (end (progn (org-skip-whitespace)
1085 (if (eobp) (point) (point-at-bol))))
1086 (value (buffer-substring-no-properties contents-begin contents-end)))
1087 `(export-block
1088 (:begin ,begin
1089 :end ,end
1090 :type ,type
1091 :value ,value
1092 :hiddenp ,hidden
1093 :post-blank ,(count-lines pos-before-blank end)
1094 ,@(cadr keywords))))))
1096 (defun org-element-export-block-interpreter (export-block contents)
1097 "Interpret EXPORT-BLOCK element as Org syntax.
1098 CONTENTS is nil."
1099 (let ((type (org-element-property :type export-block)))
1100 (concat (format "#+begin_%s\n" type)
1101 (org-element-property :value export-block)
1102 (format "#+end_%s" type))))
1105 ;;;; Fixed-width
1107 (defun org-element-fixed-width-parser ()
1108 "Parse a fixed-width section.
1110 Return a list whose car is `fixed-width' and cdr is a plist
1111 containing `:begin', `:end', `:value' and `:post-blank'
1112 keywords."
1113 (let ((fixed-re "[ \t]*:\\( \\|$\\)")
1114 beg-area begin end value pos-before-blank keywords)
1115 (save-excursion
1116 ;; Move to the beginning of the fixed-width area.
1117 (unless (bobp)
1118 (while (and (not (bobp)) (looking-at fixed-re))
1119 (forward-line -1))
1120 (unless (looking-at fixed-re) (forward-line 1)))
1121 (setq beg-area (point))
1122 ;; Get affiliated keywords, if any.
1123 (setq keywords (org-element-collect-affiliated-keywords))
1124 ;; Store true beginning of element.
1125 (setq begin (car keywords))
1126 ;; Get ending of fixed-width area. If point is in a list,
1127 ;; ensure to not get outside of it.
1128 (let* ((itemp (org-in-item-p))
1129 (max-pos (if itemp
1130 (org-list-get-bottom-point
1131 (save-excursion (goto-char itemp) (org-list-struct)))
1132 (point-max))))
1133 (while (and (looking-at fixed-re) (< (point) max-pos))
1134 (forward-line)))
1135 (setq pos-before-blank (point))
1136 ;; Find position after blank
1137 (org-skip-whitespace)
1138 (setq end (if (eobp) (point) (point-at-bol)))
1139 ;; Extract value.
1140 (setq value (buffer-substring-no-properties beg-area pos-before-blank)))
1141 `(fixed-width
1142 (:begin ,begin
1143 :end ,end
1144 :value ,value
1145 :post-blank ,(count-lines pos-before-blank end)
1146 ,@(cadr keywords)))))
1148 (defun org-element-fixed-width-interpreter (fixed-width contents)
1149 "Interpret FIXED-WIDTH element as Org syntax.
1150 CONTENTS is nil."
1151 (org-remove-indentation (org-element-property :value fixed-width)))
1154 ;;;; Horizontal Rule
1156 (defun org-element-horizontal-rule-parser ()
1157 "Parse an horizontal rule.
1159 Return a list whose car is `horizontal-rule' and cdr is
1160 a plist containing `:begin', `:end' and `:post-blank'
1161 keywords."
1162 (save-excursion
1163 (let* ((keywords (org-element-collect-affiliated-keywords))
1164 (begin (car keywords))
1165 (post-hr (progn (forward-line) (point)))
1166 (end (progn (org-skip-whitespace)
1167 (if (eobp) (point) (point-at-bol)))))
1168 `(horizontal-rule
1169 (:begin ,begin
1170 :end ,end
1171 :post-blank ,(count-lines post-hr end)
1172 ,@(cadr keywords))))))
1174 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1175 "Interpret HORIZONTAL-RULE element as Org syntax.
1176 CONTENTS is nil."
1177 "-----")
1180 ;;;; Keyword
1182 (defun org-element-keyword-parser ()
1183 "Parse a keyword at point.
1185 Return a list whose car is `keyword' and cdr is a plist
1186 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1187 keywords."
1188 (save-excursion
1189 (let* ((begin (point))
1190 (key (progn (looking-at
1191 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1192 (org-match-string-no-properties 1)))
1193 (value (org-trim (buffer-substring-no-properties
1194 (match-end 0) (point-at-eol))))
1195 (pos-before-blank (progn (forward-line) (point)))
1196 (end (progn (org-skip-whitespace)
1197 (if (eobp) (point) (point-at-bol)))))
1198 `(keyword
1199 (:key ,key
1200 :value ,value
1201 :begin ,begin
1202 :end ,end
1203 :post-blank ,(count-lines pos-before-blank end))))))
1205 (defun org-element-keyword-interpreter (keyword contents)
1206 "Interpret KEYWORD element as Org syntax.
1207 CONTENTS is nil."
1208 (format "#+%s: %s"
1209 (org-element-property :key keyword)
1210 (org-element-property :value keyword)))
1213 ;;;; Latex Environment
1215 (defun org-element-latex-environment-parser ()
1216 "Parse a LaTeX environment.
1218 Return a list whose car is `latex-environment' and cdr is a plist
1219 containing `:begin', `:end', `:value' and `:post-blank' keywords."
1220 (save-excursion
1221 (end-of-line)
1222 (let* ((case-fold-search t)
1223 (contents-begin (re-search-backward "^[ \t]*\\\\begin" nil t))
1224 (keywords (org-element-collect-affiliated-keywords))
1225 (begin (car keywords))
1226 (contents-end (progn (re-search-forward "^[ \t]*\\\\end")
1227 (forward-line)
1228 (point)))
1229 (value (buffer-substring-no-properties contents-begin contents-end))
1230 (end (progn (org-skip-whitespace)
1231 (if (eobp) (point) (point-at-bol)))))
1232 `(latex-environment
1233 (:begin ,begin
1234 :end ,end
1235 :value ,value
1236 :post-blank ,(count-lines contents-end end)
1237 ,@(cadr keywords))))))
1239 (defun org-element-latex-environment-interpreter (latex-environment contents)
1240 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1241 CONTENTS is nil."
1242 (org-element-property :value latex-environment))
1245 ;;;; Paragraph
1247 (defun org-element-paragraph-parser ()
1248 "Parse a paragraph.
1250 Return a list whose car is `paragraph' and cdr is a plist
1251 containing `:begin', `:end', `:contents-begin' and
1252 `:contents-end' and `:post-blank' keywords.
1254 Assume point is at the beginning of the paragraph."
1255 (save-excursion
1256 (let* ((contents-begin (point))
1257 (keywords (org-element-collect-affiliated-keywords))
1258 (begin (car keywords))
1259 (contents-end (progn
1260 (end-of-line)
1261 (if (re-search-forward
1262 org-element-paragraph-separate nil 'm)
1263 (progn (forward-line -1) (end-of-line) (point))
1264 (point))))
1265 (pos-before-blank (progn (forward-line) (point)))
1266 (end (progn (org-skip-whitespace)
1267 (if (eobp) (point) (point-at-bol)))))
1268 `(paragraph
1269 (:begin ,begin
1270 :end ,end
1271 :contents-begin ,contents-begin
1272 :contents-end ,contents-end
1273 :post-blank ,(count-lines pos-before-blank end)
1274 ,@(cadr keywords))))))
1276 (defun org-element-paragraph-interpreter (paragraph contents)
1277 "Interpret PARAGRAPH element as Org syntax.
1278 CONTENTS is the contents of the element."
1279 contents)
1282 ;;;; Property Drawer
1284 (defun org-element-property-drawer-parser ()
1285 "Parse a property drawer.
1287 Return a list whose car is `property-drawer' and cdr is a plist
1288 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1289 `:contents-end', `:properties' and `:post-blank' keywords."
1290 (save-excursion
1291 (let ((case-fold-search t)
1292 (begin (progn (end-of-line)
1293 (re-search-backward org-property-start-re)
1294 (match-beginning 0)))
1295 (contents-begin (progn (forward-line) (point)))
1296 (hidden (org-truely-invisible-p))
1297 (properties (let (val)
1298 (while (not (looking-at "^[ \t]*:END:"))
1299 (when (looking-at
1300 (org-re
1301 "[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):"))
1302 (push (cons (match-string 1)
1303 (org-trim
1304 (buffer-substring
1305 (match-end 0) (point-at-eol))))
1306 val))
1307 (forward-line))
1308 val))
1309 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1310 (point-at-bol)))
1311 (pos-before-blank (progn (forward-line) (point)))
1312 (end (progn (org-skip-whitespace)
1313 (if (eobp) (point) (point-at-bol)))))
1314 `(property-drawer
1315 (:begin ,begin
1316 :end ,end
1317 :hiddenp ,hidden
1318 :properties ,properties
1319 :post-blank ,(count-lines pos-before-blank end))))))
1321 (defun org-element-property-drawer-interpreter (property-drawer contents)
1322 "Interpret PROPERTY-DRAWER element as Org syntax.
1323 CONTENTS is nil."
1324 (let ((props (org-element-property :properties property-drawer)))
1325 (concat
1326 ":PROPERTIES:\n"
1327 (mapconcat (lambda (p)
1328 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1329 (nreverse props) "\n")
1330 "\n:END:")))
1333 ;;;; Quote Section
1335 (defun org-element-quote-section-parser ()
1336 "Parse a quote section.
1338 Return a list whose car is `quote-section' and cdr is a plist
1339 containing `:begin', `:end', `:value' and `:post-blank'
1340 keywords.
1342 Assume point is at beginning of the section."
1343 (save-excursion
1344 (let* ((begin (point))
1345 (end (progn (org-with-limited-levels (outline-next-heading))
1346 (point)))
1347 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1348 (forward-line)
1349 (point)))
1350 (value (buffer-substring-no-properties begin pos-before-blank)))
1351 `(quote-section
1352 (:begin ,begin
1353 :end ,end
1354 :value ,value
1355 :post-blank ,(count-lines pos-before-blank end))))))
1357 (defun org-element-quote-section-interpreter (quote-section contents)
1358 "Interpret QUOTE-SECTION element as Org syntax.
1359 CONTENTS is nil."
1360 (org-element-property :value quote-section))
1363 ;;;; Src Block
1365 (defun org-element-src-block-parser ()
1366 "Parse a src block.
1368 Return a list whose car is `src-block' and cdr is a plist
1369 containing `:language', `:switches', `:parameters', `:begin',
1370 `:end', `:hiddenp', `:contents-begin', `:contents-end',
1371 `:number-lines', `:retain-labels', `:use-labels', `:label-fmt',
1372 `:preserve-indent', `:value' and `:post-blank' keywords."
1373 (save-excursion
1374 (end-of-line)
1375 (let* ((case-fold-search t)
1376 ;; Get position at beginning of block.
1377 (contents-begin
1378 (re-search-backward
1379 (concat
1380 "^[ \t]*#\\+BEGIN_SRC"
1381 "\\(?: +\\(\\S-+\\)\\)?" ; language
1382 "\\(\\(?: +\\(?:-l \".*?\"\\|[-+][A-Za-z]\\)\\)*\\)" ; switches
1383 "\\(.*\\)[ \t]*$") ; parameters
1384 nil t))
1385 ;; Get language as a string.
1386 (language (org-match-string-no-properties 1))
1387 ;; Get parameters.
1388 (parameters (org-trim (org-match-string-no-properties 3)))
1389 ;; Get switches.
1390 (switches (org-match-string-no-properties 2))
1391 ;; Switches analysis
1392 (number-lines (cond ((not switches) nil)
1393 ((string-match "-n\\>" switches) 'new)
1394 ((string-match "+n\\>" switches) 'continued)))
1395 (preserve-indent (and switches (string-match "-i\\>" switches)))
1396 (label-fmt (and switches
1397 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
1398 (match-string 1 switches)))
1399 ;; Should labels be retained in (or stripped from) src
1400 ;; blocks?
1401 (retain-labels
1402 (or (not switches)
1403 (not (string-match "-r\\>" switches))
1404 (and number-lines (string-match "-k\\>" switches))))
1405 ;; What should code-references use - labels or
1406 ;; line-numbers?
1407 (use-labels
1408 (or (not switches)
1409 (and retain-labels (not (string-match "-k\\>" switches)))))
1410 ;; Get affiliated keywords.
1411 (keywords (org-element-collect-affiliated-keywords))
1412 ;; Get beginning position.
1413 (begin (car keywords))
1414 ;; Get position at end of block.
1415 (contents-end (progn (re-search-forward "^[ \t]*#\\+END_SRC" nil t)
1416 (forward-line)
1417 (point)))
1418 ;; Retrieve code.
1419 (value (buffer-substring-no-properties
1420 (save-excursion (goto-char contents-begin)
1421 (forward-line)
1422 (point))
1423 (match-beginning 0)))
1424 ;; Get position after ending blank lines.
1425 (end (progn (org-skip-whitespace)
1426 (if (eobp) (point) (point-at-bol))))
1427 ;; Get visibility status.
1428 (hidden (progn (goto-char contents-begin)
1429 (forward-line)
1430 (org-truely-invisible-p))))
1431 `(src-block
1432 (:language ,language
1433 :switches ,switches
1434 :parameters ,parameters
1435 :begin ,begin
1436 :end ,end
1437 :number-lines ,number-lines
1438 :preserve-indent ,preserve-indent
1439 :retain-labels ,retain-labels
1440 :use-labels ,use-labels
1441 :label-fmt ,label-fmt
1442 :hiddenp ,hidden
1443 :value ,value
1444 :post-blank ,(count-lines contents-end end)
1445 ,@(cadr keywords))))))
1447 (defun org-element-src-block-interpreter (src-block contents)
1448 "Interpret SRC-BLOCK element as Org syntax.
1449 CONTENTS is nil."
1450 (let ((lang (org-element-property :language src-block))
1451 (switches (org-element-property :switches src-block))
1452 (params (org-element-property :parameters src-block))
1453 (value (let ((val (org-element-property :value src-block)))
1454 (cond
1455 (org-src-preserve-indentation val)
1456 ((zerop org-edit-src-content-indentation)
1457 (org-remove-indentation val))
1459 (let ((ind (make-string
1460 org-edit-src-content-indentation 32)))
1461 (replace-regexp-in-string
1462 "\\(^\\)[ \t]*\\S-" ind
1463 (org-remove-indentation val) nil nil 1)))))))
1464 (concat (format "#+begin_src%s\n"
1465 (concat (and lang (concat " " lang))
1466 (and switches (concat " " switches))
1467 (and params (concat " " params))))
1468 value
1469 "#+end_src")))
1472 ;;;; Table
1474 (defun org-element-table-parser ()
1475 "Parse a table at point.
1477 Return a list whose car is `table' and cdr is a plist containing
1478 `:begin', `:end', `:contents-begin', `:contents-end', `:tblfm',
1479 `:type', `:raw-table' and `:post-blank' keywords."
1480 (save-excursion
1481 (let* ((table-begin (goto-char (org-table-begin t)))
1482 (type (if (org-at-table.el-p) 'table.el 'org))
1483 (keywords (org-element-collect-affiliated-keywords))
1484 (begin (car keywords))
1485 (table-end (goto-char (marker-position (org-table-end t))))
1486 (tblfm (when (looking-at "[ \t]*#\\+tblfm: +\\(.*\\)[ \t]*")
1487 (prog1 (org-match-string-no-properties 1)
1488 (forward-line))))
1489 (pos-before-blank (point))
1490 (end (progn (org-skip-whitespace)
1491 (if (eobp) (point) (point-at-bol))))
1492 (raw-table (org-remove-indentation
1493 (buffer-substring-no-properties table-begin table-end))))
1494 `(table
1495 (:begin ,begin
1496 :end ,end
1497 :type ,type
1498 :raw-table ,raw-table
1499 :tblfm ,tblfm
1500 :post-blank ,(count-lines pos-before-blank end)
1501 ,@(cadr keywords))))))
1503 (defun org-element-table-interpreter (table contents)
1504 "Interpret TABLE element as Org syntax.
1505 CONTENTS is nil."
1506 (org-element-property :raw-table table))
1509 ;;;; Verse Block
1511 (defun org-element-verse-block-parser ()
1512 "Parse a verse block.
1514 Return a list whose car is `verse-block' and cdr is a plist
1515 containing `:begin', `:end', `:hiddenp', `:raw-value', `:value'
1516 and `:post-blank' keywords.
1518 Assume point is at beginning or end of the block."
1519 (save-excursion
1520 (let* ((case-fold-search t)
1521 (keywords (progn
1522 (end-of-line)
1523 (re-search-backward
1524 (concat "^[ \t]*#\\+begin_verse") nil t)
1525 (org-element-collect-affiliated-keywords)))
1526 (begin (car keywords))
1527 (hidden (progn (forward-line) (org-truely-invisible-p)))
1528 (raw-val (buffer-substring-no-properties
1529 (point)
1530 (progn
1531 (re-search-forward (concat "^[ \t]*#\\+end_verse") nil t)
1532 (point-at-bol))))
1533 (pos-before-blank (progn (forward-line) (point)))
1534 (end (progn (org-skip-whitespace)
1535 (if (eobp) (point) (point-at-bol))))
1536 (value (org-element-parse-secondary-string
1537 (org-remove-indentation raw-val)
1538 (cdr (assq 'verse-block org-element-string-restrictions)))))
1539 `(verse-block
1540 (:begin ,begin
1541 :end ,end
1542 :hiddenp ,hidden
1543 :raw-value ,raw-val
1544 :value ,value
1545 :post-blank ,(count-lines pos-before-blank end)
1546 ,@(cadr keywords))))))
1548 (defun org-element-verse-block-interpreter (verse-block contents)
1549 "Interpret VERSE-BLOCK element as Org syntax.
1550 CONTENTS is nil."
1551 (format "#+begin_verse\n%s#+end_verse"
1552 (org-remove-indentation
1553 (org-element-property :raw-value verse-block))))
1557 ;;; Objects
1559 ;; Unlike to elements, interstices can be found between objects.
1560 ;; That's why, along with the parser, successor functions are provided
1561 ;; for each object. Some objects share the same successor
1562 ;; (i.e. `emphasis' and `verbatim' objects).
1564 ;; A successor must accept a single argument bounding the search. It
1565 ;; will return either a cons cell whose car is the object's type, as
1566 ;; a symbol, and cdr the position of its next occurrence, or nil.
1568 ;; Successors follow the naming convention:
1569 ;; org-element-NAME-successor, where NAME is the name of the
1570 ;; successor, as defined in `org-element-all-successors'.
1572 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1573 ;; object types they can contain will be specified in
1574 ;; `org-element-object-restrictions'.
1576 ;; Adding a new type of object is simple. Implement a successor,
1577 ;; a parser, and an interpreter for it, all following the naming
1578 ;; convention. Register type in `org-element-all-objects' and
1579 ;; successor in `org-element-all-successors'. Maybe tweak
1580 ;; restrictions about it, and that's it.
1582 ;;;; Emphasis
1584 (defun org-element-emphasis-parser ()
1585 "Parse text markup object at point.
1587 Return a list whose car is `emphasis' and cdr is a plist with
1588 `:marker', `:begin', `:end', `:contents-begin' and
1589 `:contents-end' and `:post-blank' keywords.
1591 Assume point is at the first emphasis marker."
1592 (save-excursion
1593 (unless (bolp) (backward-char 1))
1594 (looking-at org-emph-re)
1595 (let ((begin (match-beginning 2))
1596 (marker (org-match-string-no-properties 3))
1597 (contents-begin (match-beginning 4))
1598 (contents-end (match-end 4))
1599 (post-blank (progn (goto-char (match-end 2))
1600 (skip-chars-forward " \t")))
1601 (end (point)))
1602 `(emphasis
1603 (:marker ,marker
1604 :begin ,begin
1605 :end ,end
1606 :contents-begin ,contents-begin
1607 :contents-end ,contents-end
1608 :post-blank ,post-blank)))))
1610 (defun org-element-emphasis-interpreter (emphasis contents)
1611 "Interpret EMPHASIS object as Org syntax.
1612 CONTENTS is the contents of the object."
1613 (let ((marker (org-element-property :marker emphasis)))
1614 (concat marker contents marker)))
1616 (defun org-element-text-markup-successor (limit)
1617 "Search for the next emphasis or verbatim object.
1619 LIMIT bounds the search.
1621 Return value is a cons cell whose car is `emphasis' or
1622 `verbatim' and cdr is beginning position."
1623 (save-excursion
1624 (unless (bolp) (backward-char))
1625 (when (re-search-forward org-emph-re limit t)
1626 (cons (if (nth 4 (assoc (match-string 3) org-emphasis-alist))
1627 'verbatim
1628 'emphasis)
1629 (match-beginning 2)))))
1631 ;;;; Entity
1633 (defun org-element-entity-parser ()
1634 "Parse entity at point.
1636 Return a list whose car is `entity' and cdr a plist with
1637 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1638 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1639 keywords.
1641 Assume point is at the beginning of the entity."
1642 (save-excursion
1643 (looking-at "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1644 (let* ((value (org-entity-get (match-string 1)))
1645 (begin (match-beginning 0))
1646 (bracketsp (string= (match-string 2) "{}"))
1647 (post-blank (progn (goto-char (match-end 1))
1648 (when bracketsp (forward-char 2))
1649 (skip-chars-forward " \t")))
1650 (end (point)))
1651 `(entity
1652 (:name ,(car value)
1653 :latex ,(nth 1 value)
1654 :latex-math-p ,(nth 2 value)
1655 :html ,(nth 3 value)
1656 :ascii ,(nth 4 value)
1657 :latin1 ,(nth 5 value)
1658 :utf-8 ,(nth 6 value)
1659 :begin ,begin
1660 :end ,end
1661 :use-brackets-p ,bracketsp
1662 :post-blank ,post-blank)))))
1664 (defun org-element-entity-interpreter (entity contents)
1665 "Interpret ENTITY object as Org syntax.
1666 CONTENTS is nil."
1667 (concat "\\"
1668 (org-element-property :name entity)
1669 (when (org-element-property :use-brackets-p entity) "{}")))
1671 (defun org-element-latex-or-entity-successor (limit)
1672 "Search for the next latex-fragment or entity object.
1674 LIMIT bounds the search.
1676 Return value is a cons cell whose car is `entity' or
1677 `latex-fragment' and cdr is beginning position."
1678 (save-excursion
1679 (let ((matchers (plist-get org-format-latex-options :matchers))
1680 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1681 (entity-re
1682 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"))
1683 (when (re-search-forward
1684 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1685 matchers "\\|")
1686 "\\|" entity-re)
1687 limit t)
1688 (goto-char (match-beginning 0))
1689 (if (looking-at entity-re)
1690 ;; Determine if it's a real entity or a LaTeX command.
1691 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1692 (match-beginning 0))
1693 ;; No entity nor command: point is at a LaTeX fragment.
1694 ;; Determine its type to get the correct beginning position.
1695 (cons 'latex-fragment
1696 (catch 'return
1697 (mapc (lambda (e)
1698 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1699 (throw 'return
1700 (match-beginning
1701 (nth 2 (assoc e org-latex-regexps))))))
1702 matchers)
1703 (point))))))))
1706 ;;;; Export Snippet
1708 (defun org-element-export-snippet-parser ()
1709 "Parse export snippet at point.
1711 Return a list whose car is `export-snippet' and cdr a plist with
1712 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1713 keywords.
1715 Assume point is at the beginning of the snippet."
1716 (save-excursion
1717 (looking-at "@\\([-A-Za-z0-9]+\\){")
1718 (let* ((begin (point))
1719 (back-end (org-match-string-no-properties 1))
1720 (before-blank (progn (goto-char (scan-sexps (1- (match-end 0)) 1))))
1721 (value (buffer-substring-no-properties
1722 (match-end 0) (1- before-blank)))
1723 (post-blank (skip-chars-forward " \t"))
1724 (end (point)))
1725 `(export-snippet
1726 (:back-end ,back-end
1727 :value ,value
1728 :begin ,begin
1729 :end ,end
1730 :post-blank ,post-blank)))))
1732 (defun org-element-export-snippet-interpreter (export-snippet contents)
1733 "Interpret EXPORT-SNIPPET object as Org syntax.
1734 CONTENTS is nil."
1735 (format "@%s{%s}"
1736 (org-element-property :back-end export-snippet)
1737 (org-element-property :value export-snippet)))
1739 (defun org-element-export-snippet-successor (limit)
1740 "Search for the next export-snippet object.
1742 LIMIT bounds the search.
1744 Return value is a cons cell whose car is `export-snippet' cdr is
1745 its beginning position."
1746 (save-excursion
1747 (catch 'exit
1748 (while (re-search-forward "@[-A-Za-z0-9]+{" limit t)
1749 (when (let ((end (ignore-errors (scan-sexps (1- (point)) 1))))
1750 (and end (eq (char-before end) ?})))
1751 (throw 'exit (cons 'export-snippet (match-beginning 0))))))))
1754 ;;;; Footnote Reference
1756 (defun org-element-footnote-reference-parser ()
1757 "Parse footnote reference at point.
1759 Return a list whose car is `footnote-reference' and cdr a plist
1760 with `:label', `:type', `:definition', `:begin', `:end' and
1761 `:post-blank' as keywords."
1762 (save-excursion
1763 (let* ((ref (org-footnote-at-reference-p))
1764 (label (car ref))
1765 (raw-def (nth 3 ref))
1766 (inline-def
1767 (and raw-def
1768 (org-element-parse-secondary-string
1769 raw-def
1770 (cdr (assq 'footnote-reference
1771 org-element-string-restrictions)))))
1772 (type (if (nth 3 ref) 'inline 'standard))
1773 (begin (nth 1 ref))
1774 (post-blank (progn (goto-char (nth 2 ref))
1775 (skip-chars-forward " \t")))
1776 (end (point)))
1777 `(footnote-reference
1778 (:label ,label
1779 :type ,type
1780 :inline-definition ,inline-def
1781 :begin ,begin
1782 :end ,end
1783 :post-blank ,post-blank
1784 :raw-definition ,raw-def)))))
1786 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1787 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1788 CONTENTS is nil."
1789 (let ((label (or (org-element-property :label footnote-reference) "fn:"))
1790 (def
1791 (let ((raw (org-element-property :raw-definition footnote-reference)))
1792 (if raw (concat ":" raw) ""))))
1793 (format "[%s]" (concat label def))))
1795 (defun org-element-footnote-reference-successor (limit)
1796 "Search for the next footnote-reference object.
1798 LIMIT bounds the search.
1800 Return value is a cons cell whose car is `footnote-reference' and
1801 cdr is beginning position."
1802 (let (fn-ref)
1803 (when (setq fn-ref (org-footnote-get-next-reference nil nil limit))
1804 (cons 'footnote-reference (nth 1 fn-ref)))))
1807 ;;;; Inline Babel Call
1809 (defun org-element-inline-babel-call-parser ()
1810 "Parse inline babel call at point.
1812 Return a list whose car is `inline-babel-call' and cdr a plist with
1813 `:begin', `:end', `:info' and `:post-blank' as keywords.
1815 Assume point is at the beginning of the babel call."
1816 (save-excursion
1817 (unless (bolp) (backward-char))
1818 (looking-at org-babel-inline-lob-one-liner-regexp)
1819 (let ((info (save-match-data (org-babel-lob-get-info)))
1820 (begin (match-end 1))
1821 (post-blank (progn (goto-char (match-end 0))
1822 (skip-chars-forward " \t")))
1823 (end (point)))
1824 `(inline-babel-call
1825 (:begin ,begin
1826 :end ,end
1827 :info ,info
1828 :post-blank ,post-blank)))))
1830 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
1831 "Interpret INLINE-BABEL-CALL object as Org syntax.
1832 CONTENTS is nil."
1833 (let* ((babel-info (org-element-property :info inline-babel-call))
1834 (main-source (car babel-info))
1835 (post-options (nth 1 babel-info)))
1836 (concat "call_"
1837 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
1838 ;; Remove redundant square brackets.
1839 (replace-match
1840 (match-string 1 main-source) nil nil main-source)
1841 main-source)
1842 (and post-options (format "[%s]" post-options)))))
1844 (defun org-element-inline-babel-call-successor (limit)
1845 "Search for the next inline-babel-call object.
1847 LIMIT bounds the search.
1849 Return value is a cons cell whose car is `inline-babel-call' and
1850 cdr is beginning position."
1851 (save-excursion
1852 ;; Use a simplified version of
1853 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
1854 (when (re-search-forward
1855 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
1856 limit t)
1857 (cons 'inline-babel-call (match-beginning 0)))))
1860 ;;;; Inline Src Block
1862 (defun org-element-inline-src-block-parser ()
1863 "Parse inline source block at point.
1865 Return a list whose car is `inline-src-block' and cdr a plist
1866 with `:begin', `:end', `:language', `:value', `:parameters' and
1867 `:post-blank' as keywords.
1869 Assume point is at the beginning of the inline src block."
1870 (save-excursion
1871 (unless (bolp) (backward-char))
1872 (looking-at org-babel-inline-src-block-regexp)
1873 (let ((begin (match-beginning 1))
1874 (language (org-match-string-no-properties 2))
1875 (parameters (org-match-string-no-properties 4))
1876 (value (org-match-string-no-properties 5))
1877 (post-blank (progn (goto-char (match-end 0))
1878 (skip-chars-forward " \t")))
1879 (end (point)))
1880 `(inline-src-block
1881 (:language ,language
1882 :value ,value
1883 :parameters ,parameters
1884 :begin ,begin
1885 :end ,end
1886 :post-blank ,post-blank)))))
1888 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
1889 "Interpret INLINE-SRC-BLOCK object as Org syntax.
1890 CONTENTS is nil."
1891 (let ((language (org-element-property :language inline-src-block))
1892 (arguments (org-element-property :parameters inline-src-block))
1893 (body (org-element-property :value inline-src-block)))
1894 (format "src_%s%s{%s}"
1895 language
1896 (if arguments (format "[%s]" arguments) "")
1897 body)))
1899 (defun org-element-inline-src-block-successor (limit)
1900 "Search for the next inline-babel-call element.
1902 LIMIT bounds the search.
1904 Return value is a cons cell whose car is `inline-babel-call' and
1905 cdr is beginning position."
1906 (save-excursion
1907 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
1908 (cons 'inline-src-block (match-beginning 1)))))
1911 ;;;; Latex Fragment
1913 (defun org-element-latex-fragment-parser ()
1914 "Parse latex fragment at point.
1916 Return a list whose car is `latex-fragment' and cdr a plist with
1917 `:value', `:begin', `:end', and `:post-blank' as keywords.
1919 Assume point is at the beginning of the latex fragment."
1920 (save-excursion
1921 (let* ((begin (point))
1922 (substring-match
1923 (catch 'exit
1924 (mapc (lambda (e)
1925 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
1926 (when (or (looking-at latex-regexp)
1927 (and (not (bobp))
1928 (save-excursion
1929 (backward-char)
1930 (looking-at latex-regexp))))
1931 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
1932 (plist-get org-format-latex-options :matchers))
1933 ;; None found: it's a macro.
1934 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
1936 (value (match-string-no-properties substring-match))
1937 (post-blank (progn (goto-char (match-end substring-match))
1938 (skip-chars-forward " \t")))
1939 (end (point)))
1940 `(latex-fragment
1941 (:value ,value
1942 :begin ,begin
1943 :end ,end
1944 :post-blank ,post-blank)))))
1946 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
1947 "Interpret LATEX-FRAGMENT object as Org syntax.
1948 CONTENTS is nil."
1949 (org-element-property :value latex-fragment))
1951 ;;;; Line Break
1953 (defun org-element-line-break-parser ()
1954 "Parse line break at point.
1956 Return a list whose car is `line-break', and cdr a plist with
1957 `:begin', `:end' and `:post-blank' keywords.
1959 Assume point is at the beginning of the line break."
1960 (let ((begin (point))
1961 (end (save-excursion (forward-line) (point))))
1962 `(line-break (:begin ,begin :end ,end :post-blank 0))))
1964 (defun org-element-line-break-interpreter (line-break contents)
1965 "Interpret LINE-BREAK object as Org syntax.
1966 CONTENTS is nil."
1967 "\\\\\n")
1969 (defun org-element-line-break-successor (limit)
1970 "Search for the next line-break object.
1972 LIMIT bounds the search.
1974 Return value is a cons cell whose car is `line-break' and cdr is
1975 beginning position."
1976 (save-excursion
1977 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
1978 (goto-char (match-beginning 1)))))
1979 ;; A line break can only happen on a non-empty line.
1980 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
1981 (cons 'line-break beg)))))
1984 ;;;; Link
1986 (defun org-element-link-parser ()
1987 "Parse link at point.
1989 Return a list whose car is `link' and cdr a plist with `:type',
1990 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
1991 `:contents-end' and `:post-blank' as keywords.
1993 Assume point is at the beginning of the link."
1994 (save-excursion
1995 (let ((begin (point))
1996 end contents-begin contents-end link-end post-blank path type
1997 raw-link link)
1998 (cond
1999 ;; Type 1: Text targeted from a radio target.
2000 ((and org-target-link-regexp (looking-at org-target-link-regexp))
2001 (setq type "radio"
2002 link-end (match-end 0)
2003 path (org-match-string-no-properties 0)))
2004 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
2005 ((looking-at org-bracket-link-regexp)
2006 (setq contents-begin (match-beginning 3)
2007 contents-end (match-end 3)
2008 link-end (match-end 0)
2009 ;; RAW-LINK is the original link.
2010 raw-link (org-match-string-no-properties 1)
2011 link (org-link-expand-abbrev
2012 (replace-regexp-in-string
2013 " *\n *" " " (org-link-unescape raw-link) t t)))
2014 ;; Determine TYPE of link and set PATH accordingly.
2015 (cond
2016 ;; File type.
2017 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
2018 (setq type "file" path link))
2019 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
2020 ((string-match org-link-re-with-space3 link)
2021 (setq type (match-string 1 link) path (match-string 2 link)))
2022 ;; Id type: PATH is the id.
2023 ((string-match "^id:\\([-a-f0-9]+\\)" link)
2024 (setq type "id" path (match-string 1 link)))
2025 ;; Code-ref type: PATH is the name of the reference.
2026 ((string-match "^(\\(.*\\))$" link)
2027 (setq type "coderef" path (match-string 1 link)))
2028 ;; Custom-id type: PATH is the name of the custom id.
2029 ((= (aref link 0) ?#)
2030 (setq type "custom-id" path (substring link 1)))
2031 ;; Fuzzy type: Internal link either matches a target, an
2032 ;; headline name or nothing. PATH is the target or headline's
2033 ;; name.
2034 (t (setq type "fuzzy" path link))))
2035 ;; Type 3: Plain link, i.e. http://orgmode.org
2036 ((looking-at org-plain-link-re)
2037 (setq raw-link (org-match-string-no-properties 0)
2038 type (org-match-string-no-properties 1)
2039 path (org-match-string-no-properties 2)
2040 link-end (match-end 0)))
2041 ;; Type 4: Angular link, i.e. <http://orgmode.org>
2042 ((looking-at org-angle-link-re)
2043 (setq raw-link (buffer-substring-no-properties
2044 (match-beginning 1) (match-end 2))
2045 type (org-match-string-no-properties 1)
2046 path (org-match-string-no-properties 2)
2047 link-end (match-end 0))))
2048 ;; In any case, deduce end point after trailing white space from
2049 ;; LINK-END variable.
2050 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
2051 end (point))
2052 `(link
2053 (:type ,type
2054 :path ,path
2055 :raw-link ,(or raw-link path)
2056 :begin ,begin
2057 :end ,end
2058 :contents-begin ,contents-begin
2059 :contents-end ,contents-end
2060 :post-blank ,post-blank)))))
2062 (defun org-element-link-interpreter (link contents)
2063 "Interpret LINK object as Org syntax.
2064 CONTENTS is the contents of the object."
2065 (let ((type (org-element-property :type link))
2066 (raw-link (org-element-property :raw-link link)))
2067 (if (string= type "radio") raw-link
2068 (format "[[%s]%s]"
2069 raw-link
2070 (if (string= contents "") "" (format "[%s]" contents))))))
2072 (defun org-element-link-successor (limit)
2073 "Search for the next link object.
2075 LIMIT bounds the search.
2077 Return value is a cons cell whose car is `link' and cdr is
2078 beginning position."
2079 (save-excursion
2080 (let ((link-regexp
2081 (if (not org-target-link-regexp) org-any-link-re
2082 (concat org-any-link-re "\\|" org-target-link-regexp))))
2083 (when (re-search-forward link-regexp limit t)
2084 (cons 'link (match-beginning 0))))))
2087 ;;;; Macro
2089 (defun org-element-macro-parser ()
2090 "Parse macro at point.
2092 Return a list whose car is `macro' and cdr a plist with `:key',
2093 `:args', `:begin', `:end', `:value' and `:post-blank' as
2094 keywords.
2096 Assume point is at the macro."
2097 (save-excursion
2098 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2099 (let ((begin (point))
2100 (key (downcase (org-match-string-no-properties 1)))
2101 (value (org-match-string-no-properties 0))
2102 (post-blank (progn (goto-char (match-end 0))
2103 (skip-chars-forward " \t")))
2104 (end (point))
2105 (args (let ((args (org-match-string-no-properties 3)) args2)
2106 (when args
2107 (setq args (org-split-string args ","))
2108 (while args
2109 (while (string-match "\\\\\\'" (car args))
2110 ;; Repair bad splits.
2111 (setcar (cdr args) (concat (substring (car args) 0 -1)
2112 "," (nth 1 args)))
2113 (pop args))
2114 (push (pop args) args2))
2115 (mapcar 'org-trim (nreverse args2))))))
2116 `(macro
2117 (:key ,key
2118 :value ,value
2119 :args ,args
2120 :begin ,begin
2121 :end ,end
2122 :post-blank ,post-blank)))))
2124 (defun org-element-macro-interpreter (macro contents)
2125 "Interpret MACRO object as Org syntax.
2126 CONTENTS is nil."
2127 (org-element-property :value macro))
2129 (defun org-element-macro-successor (limit)
2130 "Search for the next macro object.
2132 LIMIT bounds the search.
2134 Return value is cons cell whose car is `macro' and cdr is
2135 beginning position."
2136 (save-excursion
2137 (when (re-search-forward
2138 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2139 limit t)
2140 (cons 'macro (match-beginning 0)))))
2143 ;;;; Radio-target
2145 (defun org-element-radio-target-parser ()
2146 "Parse radio target at point.
2148 Return a list whose car is `radio-target' and cdr a plist with
2149 `:begin', `:end', `:contents-begin', `:contents-end', `raw-value'
2150 and `:post-blank' as keywords.
2152 Assume point is at the radio target."
2153 (save-excursion
2154 (looking-at org-radio-target-regexp)
2155 (let ((begin (point))
2156 (contents-begin (match-beginning 1))
2157 (contents-end (match-end 1))
2158 (raw-value (org-match-string-no-properties 1))
2159 (post-blank (progn (goto-char (match-end 0))
2160 (skip-chars-forward " \t")))
2161 (end (point)))
2162 `(radio-target
2163 (:begin ,begin
2164 :end ,end
2165 :contents-begin ,contents-begin
2166 :contents-end ,contents-end
2167 :raw-value ,raw-value
2168 :post-blank ,post-blank)))))
2170 (defun org-element-radio-target-interpreter (target contents)
2171 "Interpret TARGET object as Org syntax.
2172 CONTENTS is the contents of the object."
2173 (concat "<<<" contents ">>>"))
2175 (defun org-element-radio-target-successor (limit)
2176 "Search for the next radio-target object.
2178 LIMIT bounds the search.
2180 Return value is a cons cell whose car is `radio-target' and cdr
2181 is beginning position."
2182 (save-excursion
2183 (when (re-search-forward org-radio-target-regexp limit t)
2184 (cons 'radio-target (match-beginning 0)))))
2187 ;;;; Statistics Cookie
2189 (defun org-element-statistics-cookie-parser ()
2190 "Parse statistics cookie at point.
2192 Return a list whose car is `statistics-cookie', and cdr a plist
2193 with `:begin', `:end', `:value' and `:post-blank' keywords.
2195 Assume point is at the beginning of the statistics-cookie."
2196 (save-excursion
2197 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2198 (let* ((begin (point))
2199 (value (buffer-substring-no-properties
2200 (match-beginning 0) (match-end 0)))
2201 (post-blank (progn (goto-char (match-end 0))
2202 (skip-chars-forward " \t")))
2203 (end (point)))
2204 `(statistics-cookie
2205 (:begin ,begin
2206 :end ,end
2207 :value ,value
2208 :post-blank ,post-blank)))))
2210 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2211 "Interpret STATISTICS-COOKIE object as Org syntax.
2212 CONTENTS is nil."
2213 (org-element-property :value statistics-cookie))
2215 (defun org-element-statistics-cookie-successor (limit)
2216 "Search for the next statistics cookie object.
2218 LIMIT bounds the search.
2220 Return value is a cons cell whose car is `statistics-cookie' and
2221 cdr is beginning position."
2222 (save-excursion
2223 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2224 (cons 'statistics-cookie (match-beginning 0)))))
2227 ;;;; Subscript
2229 (defun org-element-subscript-parser ()
2230 "Parse subscript at point.
2232 Return a list whose car is `subscript' and cdr a plist with
2233 `:begin', `:end', `:contents-begin', `:contents-end',
2234 `:use-brackets-p' and `:post-blank' as keywords.
2236 Assume point is at the underscore."
2237 (save-excursion
2238 (unless (bolp) (backward-char))
2239 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2241 (not (looking-at org-match-substring-regexp))))
2242 (begin (match-beginning 2))
2243 (contents-begin (or (match-beginning 5)
2244 (match-beginning 3)))
2245 (contents-end (or (match-end 5) (match-end 3)))
2246 (post-blank (progn (goto-char (match-end 0))
2247 (skip-chars-forward " \t")))
2248 (end (point)))
2249 `(subscript
2250 (:begin ,begin
2251 :end ,end
2252 :use-brackets-p ,bracketsp
2253 :contents-begin ,contents-begin
2254 :contents-end ,contents-end
2255 :post-blank ,post-blank)))))
2257 (defun org-element-subscript-interpreter (subscript contents)
2258 "Interpret SUBSCRIPT object as Org syntax.
2259 CONTENTS is the contents of the object."
2260 (format
2261 (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
2262 contents))
2264 (defun org-element-sub/superscript-successor (limit)
2265 "Search for the next sub/superscript object.
2267 LIMIT bounds the search.
2269 Return value is a cons cell whose car is either `subscript' or
2270 `superscript' and cdr is beginning position."
2271 (save-excursion
2272 (when (re-search-forward org-match-substring-regexp limit t)
2273 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2274 (match-beginning 2)))))
2277 ;;;; Superscript
2279 (defun org-element-superscript-parser ()
2280 "Parse superscript at point.
2282 Return a list whose car is `superscript' and cdr a plist with
2283 `:begin', `:end', `:contents-begin', `:contents-end',
2284 `:use-brackets-p' and `:post-blank' as keywords.
2286 Assume point is at the caret."
2287 (save-excursion
2288 (unless (bolp) (backward-char))
2289 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2291 (not (looking-at org-match-substring-regexp))))
2292 (begin (match-beginning 2))
2293 (contents-begin (or (match-beginning 5)
2294 (match-beginning 3)))
2295 (contents-end (or (match-end 5) (match-end 3)))
2296 (post-blank (progn (goto-char (match-end 0))
2297 (skip-chars-forward " \t")))
2298 (end (point)))
2299 `(superscript
2300 (:begin ,begin
2301 :end ,end
2302 :use-brackets-p ,bracketsp
2303 :contents-begin ,contents-begin
2304 :contents-end ,contents-end
2305 :post-blank ,post-blank)))))
2307 (defun org-element-superscript-interpreter (superscript contents)
2308 "Interpret SUPERSCRIPT object as Org syntax.
2309 CONTENTS is the contents of the object."
2310 (format
2311 (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
2312 contents))
2315 ;;;; Target
2317 (defun org-element-target-parser ()
2318 "Parse target at point.
2320 Return a list whose car is `target' and cdr a plist with
2321 `:begin', `:end', `:contents-begin', `:contents-end', `value' and
2322 `:post-blank' as keywords.
2324 Assume point is at the target."
2325 (save-excursion
2326 (looking-at org-target-regexp)
2327 (let ((begin (point))
2328 (value (org-match-string-no-properties 1))
2329 (post-blank (progn (goto-char (match-end 0))
2330 (skip-chars-forward " \t")))
2331 (end (point)))
2332 `(target
2333 (:begin ,begin
2334 :end ,end
2335 :value ,value
2336 :post-blank ,post-blank)))))
2338 (defun org-element-target-interpreter (target contents)
2339 "Interpret TARGET object as Org syntax.
2340 CONTENTS is the contents of target."
2341 (concat ""))
2343 (defun org-element-target-successor (limit)
2344 "Search for the next target object.
2346 LIMIT bounds the search.
2348 Return value is a cons cell whose car is `target' and cdr is
2349 beginning position."
2350 (save-excursion
2351 (when (re-search-forward org-target-regexp limit t)
2352 (cons 'target (match-beginning 0)))))
2355 ;;;; Time-stamp
2357 (defun org-element-time-stamp-parser ()
2358 "Parse time stamp at point.
2360 Return a list whose car is `time-stamp', and cdr a plist with
2361 `:appt-type', `:type', `:begin', `:end', `:value' and
2362 `:post-blank' keywords.
2364 Assume point is at the beginning of the time-stamp."
2365 (save-excursion
2366 (let* ((appt-type (cond
2367 ((looking-at (concat org-deadline-string " +"))
2368 (goto-char (match-end 0))
2369 'deadline)
2370 ((looking-at (concat org-scheduled-string " +"))
2371 (goto-char (match-end 0))
2372 'scheduled)
2373 ((looking-at (concat org-closed-string " +"))
2374 (goto-char (match-end 0))
2375 'closed)))
2376 (begin (and appt-type (match-beginning 0)))
2377 (type (cond
2378 ((looking-at org-tsr-regexp)
2379 (if (match-string 2) 'active-range 'active))
2380 ((looking-at org-tsr-regexp-both)
2381 (if (match-string 2) 'inactive-range 'inactive))
2382 ((looking-at (concat
2383 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2384 "\\|"
2385 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2386 'diary)))
2387 (begin (or begin (match-beginning 0)))
2388 (value (buffer-substring-no-properties
2389 (match-beginning 0) (match-end 0)))
2390 (post-blank (progn (goto-char (match-end 0))
2391 (skip-chars-forward " \t")))
2392 (end (point)))
2393 `(time-stamp
2394 (:appt-type ,appt-type
2395 :type ,type
2396 :value ,value
2397 :begin ,begin
2398 :end ,end
2399 :post-blank ,post-blank)))))
2401 (defun org-element-time-stamp-interpreter (time-stamp contents)
2402 "Interpret TIME-STAMP object as Org syntax.
2403 CONTENTS is nil."
2404 (concat
2405 (case (org-element-property :appt-type time-stamp)
2406 (closed (concat org-closed-string " "))
2407 (deadline (concat org-deadline-string " "))
2408 (scheduled (concat org-scheduled-string " ")))
2409 (org-element-property :value time-stamp)))
2411 (defun org-element-time-stamp-successor (limit)
2412 "Search for the next time-stamp object.
2414 LIMIT bounds the search.
2416 Return value is a cons cell whose car is `time-stamp' and cdr is
2417 beginning position."
2418 (save-excursion
2419 (when (re-search-forward
2420 (concat "\\(?:" org-scheduled-string " +\\|"
2421 org-deadline-string " +\\|" org-closed-string " +\\)?"
2422 org-ts-regexp-both
2423 "\\|"
2424 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2425 "\\|"
2426 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2427 limit t)
2428 (cons 'time-stamp (match-beginning 0)))))
2431 ;;;; Verbatim
2433 (defun org-element-verbatim-parser ()
2434 "Parse verbatim object at point.
2436 Return a list whose car is `verbatim' and cdr is a plist with
2437 `:marker', `:begin', `:end' and `:post-blank' keywords.
2439 Assume point is at the first verbatim marker."
2440 (save-excursion
2441 (unless (bolp) (backward-char 1))
2442 (looking-at org-emph-re)
2443 (let ((begin (match-beginning 2))
2444 (marker (org-match-string-no-properties 3))
2445 (value (org-match-string-no-properties 4))
2446 (post-blank (progn (goto-char (match-end 2))
2447 (skip-chars-forward " \t")))
2448 (end (point)))
2449 `(verbatim
2450 (:marker ,marker
2451 :begin ,begin
2452 :end ,end
2453 :value ,value
2454 :post-blank ,post-blank)))))
2456 (defun org-element-verbatim-interpreter (verbatim contents)
2457 "Interpret VERBATIM object as Org syntax.
2458 CONTENTS is nil."
2459 (let ((marker (org-element-property :marker verbatim))
2460 (value (org-element-property :value verbatim)))
2461 (concat marker value marker)))
2465 ;;; Definitions And Rules
2467 ;; Define elements, greater elements and specify recursive objects,
2468 ;; along with the affiliated keywords recognized. Also set up
2469 ;; restrictions on recursive objects combinations.
2471 ;; These variables really act as a control center for the parsing
2472 ;; process.
2473 (defconst org-element-paragraph-separate
2474 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2475 ;; Headlines and inlinetasks.
2476 org-outline-regexp-bol "\\|"
2477 ;; Comments, blocks (any type), keywords and babel calls.
2478 "^[ \t]*#\\+" "\\|" "^#\\( \\|$\\)" "\\|"
2479 ;; Lists.
2480 (org-item-beginning-re) "\\|"
2481 ;; Fixed-width, drawers (any type) and tables.
2482 "^[ \t]*[:|]" "\\|"
2483 ;; Footnote definitions.
2484 org-footnote-definition-re "\\|"
2485 ;; Horizontal rules.
2486 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2487 ;; LaTeX environments.
2488 "^[ \t]*\\\\\\(begin\\|end\\)")
2489 "Regexp to separate paragraphs in an Org buffer.")
2491 (defconst org-element-all-elements
2492 '(center-block comment comment-block drawer dynamic-block example-block
2493 export-block fixed-width footnote-definition headline
2494 horizontal-rule inlinetask item keyword latex-environment
2495 babel-call paragraph plain-list property-drawer quote-block
2496 quote-section section special-block src-block table
2497 verse-block)
2498 "Complete list of element types.")
2500 (defconst org-element-greater-elements
2501 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2502 item plain-list quote-block section special-block)
2503 "List of recursive element types aka Greater Elements.")
2505 (defconst org-element-all-successors
2506 '(export-snippet footnote-reference inline-babel-call inline-src-block
2507 latex-or-entity line-break link macro radio-target
2508 statistics-cookie sub/superscript target text-markup
2509 time-stamp)
2510 "Complete list of successors.")
2512 (defconst org-element-object-successor-alist
2513 '((subscript . sub/superscript) (superscript . sub/superscript)
2514 (emphasis . text-markup) (verbatim . text-markup)
2515 (entity . latex-or-entity) (latex-fragment . latex-or-entity))
2516 "Alist of translations between object type and successor name.
2518 Sharing the same successor comes handy when, for example, the
2519 regexp matching one object can also match the other object.")
2521 (defconst org-element-all-objects
2522 '(emphasis entity export-snippet footnote-reference inline-babel-call
2523 inline-src-block line-break latex-fragment link macro radio-target
2524 statistics-cookie subscript superscript target time-stamp
2525 verbatim)
2526 "Complete list of object types.")
2528 (defconst org-element-recursive-objects
2529 '(emphasis link macro subscript superscript radio-target)
2530 "List of recursive object types.")
2532 (defconst org-element-non-recursive-block-alist
2533 '(("ascii" . export-block)
2534 ("comment" . comment-block)
2535 ("docbook" . export-block)
2536 ("example" . example-block)
2537 ("html" . export-block)
2538 ("latex" . export-block)
2539 ("odt" . export-block)
2540 ("src" . src-block)
2541 ("verse" . verse-block))
2542 "Alist between non-recursive block name and their element type.")
2544 (defconst org-element-affiliated-keywords
2545 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "caption"
2546 "data" "header" "headers" "label" "name" "plot" "resname" "result" "results"
2547 "source" "srcname" "tblname")
2548 "List of affiliated keywords as strings.")
2550 (defconst org-element-keyword-translation-alist
2551 '(("data" . "name") ("label" . "name") ("resname" . "name")
2552 ("source" . "name") ("srcname" . "name") ("tblname" . "name")
2553 ("result" . "results") ("headers" . "header"))
2554 "Alist of usual translations for keywords.
2555 The key is the old name and the value the new one. The property
2556 holding their value will be named after the translated name.")
2558 (defconst org-element-multiple-keywords
2559 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "header")
2560 "List of affiliated keywords that can occur more that once in an element.
2562 Their value will be consed into a list of strings, which will be
2563 returned as the value of the property.
2565 This list is checked after translations have been applied. See
2566 `org-element-keyword-translation-alist'.")
2568 (defconst org-element-parsed-keywords '("author" "caption" "title")
2569 "List of keywords whose value can be parsed.
2571 Their value will be stored as a secondary string: a list of
2572 strings and objects.
2574 This list is checked after translations have been applied. See
2575 `org-element-keyword-translation-alist'.")
2577 (defconst org-element-dual-keywords '("caption" "results")
2578 "List of keywords which can have a secondary value.
2580 In Org syntax, they can be written with optional square brackets
2581 before the colons. For example, results keyword can be
2582 associated to a hash value with the following:
2584 #+results[hash-string]: some-source
2586 This list is checked after translations have been applied. See
2587 `org-element-keyword-translation-alist'.")
2589 (defconst org-element-object-restrictions
2590 '((emphasis entity export-snippet inline-babel-call inline-src-block link
2591 radio-target sub/superscript target text-markup time-stamp)
2592 (link entity export-snippet inline-babel-call inline-src-block
2593 latex-fragment link sub/superscript text-markup)
2594 (macro macro)
2595 (radio-target entity export-snippet latex-fragment sub/superscript)
2596 (subscript entity export-snippet inline-babel-call inline-src-block
2597 latex-fragment sub/superscript text-markup)
2598 (superscript entity export-snippet inline-babel-call inline-src-block
2599 latex-fragment sub/superscript text-markup))
2600 "Alist of recursive objects restrictions.
2602 CAR is a recursive object type and CDR is a list of successors
2603 that will be called within an object of such type.
2605 For example, in a `radio-target' object, one can only find
2606 entities, export snippets, latex-fragments, subscript and
2607 superscript.")
2609 (defconst org-element-string-restrictions
2610 '((footnote-reference entity export-snippet footnote-reference
2611 inline-babel-call inline-src-block latex-fragment
2612 line-break link macro radio-target sub/superscript
2613 target text-markup time-stamp)
2614 (headline entity inline-babel-call inline-src-block latex-fragment link
2615 macro radio-target statistics-cookie sub/superscript text-markup
2616 time-stamp)
2617 (inlinetask entity inline-babel-call inline-src-block latex-fragment link
2618 macro radio-target sub/superscript text-markup time-stamp)
2619 (item entity inline-babel-call latex-fragment macro radio-target
2620 sub/superscript target text-markup)
2621 (keyword entity latex-fragment macro sub/superscript text-markup)
2622 (table entity latex-fragment macro target text-markup)
2623 (verse-block entity footnote-reference inline-babel-call inline-src-block
2624 latex-fragment line-break link macro radio-target
2625 sub/superscript target text-markup time-stamp))
2626 "Alist of secondary strings restrictions.
2628 When parsed, some elements have a secondary string which could
2629 contain various objects (i.e. headline's name, or table's cells).
2630 For association, CAR is the element type, and CDR a list of
2631 successors that will be called in that secondary string.
2633 Note: `keyword' secondary string type only applies to keywords
2634 matching `org-element-parsed-keywords'.")
2636 (defconst org-element-secondary-value-alist
2637 '((headline . :title)
2638 (inlinetask . :title)
2639 (item . :tag)
2640 (footnote-reference . :inline-definition)
2641 (verse-block . :value))
2642 "Alist between element types and location of secondary value.
2643 Only elements with a secondary value available at parse time are
2644 considered here. This is used internally by `org-element-map',
2645 which will look into the secondary strings of an element only if
2646 its type is listed here.")
2650 ;;; Accessors
2652 ;; Provide three accessors: `org-element-type', `org-element-property'
2653 ;; and `org-element-contents'.
2655 (defun org-element-type (element)
2656 "Return type of element ELEMENT.
2658 The function returns the type of the element or object provided.
2659 It can also return the following special value:
2660 `plain-text' for a string
2661 `org-data' for a complete document
2662 nil in any other case."
2663 (cond
2664 ((not (consp element)) (and (stringp element) 'plain-text))
2665 ((symbolp (car element)) (car element))))
2667 (defun org-element-property (property element)
2668 "Extract the value from the PROPERTY of an ELEMENT."
2669 (plist-get (nth 1 element) property))
2671 (defun org-element-contents (element)
2672 "Extract contents from an ELEMENT."
2673 (nthcdr 2 element))
2677 ;;; Parsing Element Starting At Point
2679 ;; `org-element-current-element' is the core function of this section.
2680 ;; It returns the Lisp representation of the element starting at
2681 ;; point. It uses `org-element--element-block-re' for quick access to
2682 ;; a common regexp.
2684 (defconst org-element--element-block-re
2685 (format "[ \t]*#\\+begin_\\(%s\\)\\(?: \\|$\\)"
2686 (mapconcat
2687 'regexp-quote
2688 (mapcar 'car org-element-non-recursive-block-alist) "\\|"))
2689 "Regexp matching the beginning of a non-recursive block type.
2690 Used internally by `org-element-current-element'. Do not modify
2691 it directly, set `org-element-recursive-block-alist' instead.")
2693 (defun org-element-current-element (&optional special structure)
2694 "Parse the element starting at point.
2696 Return value is a list like (TYPE PROPS) where TYPE is the type
2697 of the element and PROPS a plist of properties associated to the
2698 element.
2700 Possible types are defined in `org-element-all-elements'.
2702 Optional argument SPECIAL, when non-nil, can be either `item',
2703 `section' or `quote-section'. `item' allows to parse item wise
2704 instead of plain-list wise, using STRUCTURE as the current list
2705 structure. `section' (resp. `quote-section') will try to parse
2706 a section (resp. a quote section) before anything else.
2708 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
2709 be computed.
2711 Unlike to `org-element-at-point', this function assumes point is
2712 always at the beginning of the element it has to parse. As such,
2713 it is quicker than its counterpart, albeit more restrictive."
2714 (save-excursion
2715 (beginning-of-line)
2716 ;; If point is at an affiliated keyword, try moving to the
2717 ;; beginning of the associated element. If none is found, the
2718 ;; keyword is orphaned and will be treated as plain text.
2719 (when (looking-at org-element--affiliated-re)
2720 (let ((opoint (point)))
2721 (while (looking-at org-element--affiliated-re) (forward-line))
2722 (when (looking-at "[ \t]*$") (goto-char opoint))))
2723 (let ((case-fold-search t))
2724 (cond
2725 ;; Headline.
2726 ((org-with-limited-levels (org-at-heading-p))
2727 (org-element-headline-parser))
2728 ;; Quote section.
2729 ((eq special 'quote-section) (org-element-quote-section-parser))
2730 ;; Section.
2731 ((eq special 'section) (org-element-section-parser))
2732 ;; Non-recursive block.
2733 ((when (looking-at org-element--element-block-re)
2734 (let ((type (downcase (match-string 1))))
2735 (if (save-excursion
2736 (re-search-forward
2737 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t))
2738 ;; Build appropriate parser.
2739 (funcall
2740 (intern
2741 (format "org-element-%s-parser"
2742 (cdr (assoc type
2743 org-element-non-recursive-block-alist)))))
2744 (org-element-paragraph-parser)))))
2745 ;; Inlinetask.
2746 ((org-at-heading-p) (org-element-inlinetask-parser))
2747 ;; LaTeX Environment or paragraph if incomplete.
2748 ((looking-at "^[ \t]*\\\\begin{")
2749 (if (save-excursion
2750 (re-search-forward "^[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
2751 (org-element-latex-environment-parser)
2752 (org-element-paragraph-parser)))
2753 ;; Property drawer.
2754 ((looking-at org-property-start-re)
2755 (if (save-excursion (re-search-forward org-property-end-re nil t))
2756 (org-element-property-drawer-parser)
2757 (org-element-paragraph-parser)))
2758 ;; Recursive block, or paragraph if incomplete.
2759 ((looking-at "[ \t]*#\\+begin_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
2760 (let ((type (downcase (match-string 1))))
2761 (cond
2762 ((not (save-excursion
2763 (re-search-forward
2764 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t)))
2765 (org-element-paragraph-parser))
2766 ((string= type "center") (org-element-center-block-parser))
2767 ((string= type "quote") (org-element-quote-block-parser))
2768 (t (org-element-special-block-parser)))))
2769 ;; Drawer.
2770 ((looking-at org-drawer-regexp)
2771 (if (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t))
2772 (org-element-drawer-parser)
2773 (org-element-paragraph-parser)))
2774 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
2775 ;; Babel call.
2776 ((looking-at org-babel-block-lob-one-liner-regexp)
2777 (org-element-babel-call-parser))
2778 ;; Keyword, or paragraph if at an affiliated keyword.
2779 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
2780 (let ((key (downcase (match-string 1))))
2781 (if (or (string= key "tblfm")
2782 (member key org-element-affiliated-keywords))
2783 (org-element-paragraph-parser)
2784 (org-element-keyword-parser))))
2785 ;; Footnote definition.
2786 ((looking-at org-footnote-definition-re)
2787 (org-element-footnote-definition-parser))
2788 ;; Dynamic block or paragraph if incomplete.
2789 ((looking-at "[ \t]*#\\+begin:\\(?: \\|$\\)")
2790 (if (save-excursion
2791 (re-search-forward "^[ \t]*#\\+end:\\(?: \\|$\\)" nil t))
2792 (org-element-dynamic-block-parser)
2793 (org-element-paragraph-parser)))
2794 ;; Comment.
2795 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
2796 (org-element-comment-parser))
2797 ;; Horizontal rule.
2798 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
2799 (org-element-horizontal-rule-parser))
2800 ;; Table.
2801 ((org-at-table-p t) (org-element-table-parser))
2802 ;; List or item.
2803 ((looking-at (org-item-re))
2804 (if (eq special 'item)
2805 (org-element-item-parser (or structure (org-list-struct)))
2806 (org-element-plain-list-parser (or structure (org-list-struct)))))
2807 ;; Default element: Paragraph.
2808 (t (org-element-paragraph-parser))))))
2811 ;; Most elements can have affiliated keywords. When looking for an
2812 ;; element beginning, we want to move before them, as they belong to
2813 ;; that element, and, in the meantime, collect information they give
2814 ;; into appropriate properties. Hence the following function.
2816 ;; Usage of optional arguments may not be obvious at first glance:
2818 ;; - TRANS-LIST is used to polish keywords names that have evolved
2819 ;; during Org history. In example, even though =result= and
2820 ;; =results= coexist, we want to have them under the same =result=
2821 ;; property. It's also true for "srcname" and "name", where the
2822 ;; latter seems to be preferred nowadays (thus the "name" property).
2824 ;; - CONSED allows to regroup multi-lines keywords under the same
2825 ;; property, while preserving their own identity. This is mostly
2826 ;; used for "attr_latex" and al.
2828 ;; - PARSED prepares a keyword value for export. This is useful for
2829 ;; "caption". Objects restrictions for such keywords are defined in
2830 ;; `org-element-string-restrictions'.
2832 ;; - DUALS is used to take care of keywords accepting a main and an
2833 ;; optional secondary values. For example "results" has its
2834 ;; source's name as the main value, and may have an hash string in
2835 ;; optional square brackets as the secondary one.
2837 ;; A keyword may belong to more than one category.
2839 (defconst org-element--affiliated-re
2840 (format "[ \t]*#\\+\\(%s\\):"
2841 (mapconcat
2842 (lambda (keyword)
2843 (if (member keyword org-element-dual-keywords)
2844 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
2845 (regexp-quote keyword))
2846 (regexp-quote keyword)))
2847 org-element-affiliated-keywords "\\|"))
2848 "Regexp matching any affiliated keyword.
2850 Keyword name is put in match group 1. Moreover, if keyword
2851 belongs to `org-element-dual-keywords', put the dual value in
2852 match group 2.
2854 Don't modify it, set `org-element-affiliated-keywords' instead.")
2856 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
2857 consed parsed duals)
2858 "Collect affiliated keywords before point.
2860 Optional argument KEY-RE is a regexp matching keywords, which
2861 puts matched keyword in group 1. It defaults to
2862 `org-element--affiliated-re'.
2864 TRANS-LIST is an alist where key is the keyword and value the
2865 property name it should be translated to, without the colons. It
2866 defaults to `org-element-keyword-translation-alist'.
2868 CONSED is a list of strings. Any keyword belonging to that list
2869 will have its value consed. The check is done after keyword
2870 translation. It defaults to `org-element-multiple-keywords'.
2872 PARSED is a list of strings. Any keyword member of this list
2873 will have its value parsed. The check is done after keyword
2874 translation. If a keyword is a member of both CONSED and PARSED,
2875 it's value will be a list of parsed strings. It defaults to
2876 `org-element-parsed-keywords'.
2878 DUALS is a list of strings. Any keyword member of this list can
2879 have two parts: one mandatory and one optional. Its value is
2880 a cons cell whose car is the former, and the cdr the latter. If
2881 a keyword is a member of both PARSED and DUALS, both values will
2882 be parsed. It defaults to `org-element-dual-keywords'.
2884 Return a list whose car is the position at the first of them and
2885 cdr a plist of keywords and values."
2886 (save-excursion
2887 (let ((case-fold-search t)
2888 (key-re (or key-re org-element--affiliated-re))
2889 (trans-list (or trans-list org-element-keyword-translation-alist))
2890 (consed (or consed org-element-multiple-keywords))
2891 (parsed (or parsed org-element-parsed-keywords))
2892 (duals (or duals org-element-dual-keywords))
2893 ;; RESTRICT is the list of objects allowed in parsed
2894 ;; keywords value.
2895 (restrict (cdr (assq 'keyword org-element-string-restrictions)))
2896 output)
2897 (unless (bobp)
2898 (while (and (not (bobp))
2899 (progn (forward-line -1) (looking-at key-re)))
2900 (let* ((raw-kwd (downcase (or (match-string 2) (match-string 1))))
2901 ;; Apply translation to RAW-KWD. From there, KWD is
2902 ;; the official keyword.
2903 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
2904 ;; Find main value for any keyword.
2905 (value
2906 (save-match-data
2907 (org-trim
2908 (buffer-substring-no-properties
2909 (match-end 0) (point-at-eol)))))
2910 ;; If KWD is a dual keyword, find its secondary
2911 ;; value. Maybe parse it.
2912 (dual-value
2913 (and (member kwd duals)
2914 (let ((sec (org-match-string-no-properties 3)))
2915 (if (or (not sec) (not (member kwd parsed))) sec
2916 (org-element-parse-secondary-string sec restrict)))))
2917 ;; Attribute a property name to KWD.
2918 (kwd-sym (and kwd (intern (concat ":" kwd)))))
2919 ;; Now set final shape for VALUE.
2920 (when (member kwd parsed)
2921 (setq value (org-element-parse-secondary-string value restrict)))
2922 (when (member kwd duals)
2923 ;; VALUE is mandatory. Set it to nil if there is none.
2924 (setq value (and value (cons value dual-value))))
2925 (when (member kwd consed)
2926 (setq value (cons value (plist-get output kwd-sym))))
2927 ;; Eventually store the new value in OUTPUT.
2928 (setq output (plist-put output kwd-sym value))))
2929 (unless (looking-at key-re) (forward-line 1)))
2930 (list (point) output))))
2934 ;;; The Org Parser
2936 ;; The two major functions here are `org-element-parse-buffer', which
2937 ;; parses Org syntax inside the current buffer, taking into account
2938 ;; region, narrowing, or even visibility if specified, and
2939 ;; `org-element-parse-secondary-string', which parses objects within
2940 ;; a given string.
2942 ;; The (almost) almighty `org-element-map' allows to apply a function
2943 ;; on elements or objects matching some type, and accumulate the
2944 ;; resulting values. In an export situation, it also skips unneeded
2945 ;; parts of the parse tree.
2947 (defun org-element-parse-buffer (&optional granularity visible-only)
2948 "Recursively parse the buffer and return structure.
2949 If narrowing is in effect, only parse the visible part of the
2950 buffer.
2952 Optional argument GRANULARITY determines the depth of the
2953 recursion. It can be set to the following symbols:
2955 `headline' Only parse headlines.
2956 `greater-element' Don't recurse into greater elements. Thus,
2957 elements parsed are the top-level ones.
2958 `element' Parse everything but objects and plain text.
2959 `object' Parse the complete buffer (default).
2961 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
2962 elements.
2964 Assume buffer is in Org mode."
2965 (save-excursion
2966 (goto-char (point-min))
2967 (org-skip-whitespace)
2968 (nconc (list 'org-data nil)
2969 (org-element-parse-elements
2970 (point-at-bol) (point-max)
2971 ;; Start is section mode so text before the first headline
2972 ;; belongs to a section.
2973 'section nil granularity visible-only nil))))
2975 (defun org-element-parse-secondary-string (string restriction &optional buffer)
2976 "Recursively parse objects in STRING and return structure.
2978 RESTRICTION, when non-nil, is a symbol limiting the object types
2979 that will be looked after.
2981 Optional argument BUFFER indicates the buffer from where the
2982 secondary string was extracted. It is used to determine where to
2983 get extraneous information for an object \(i.e. when resolving
2984 a link or looking for a footnote definition\). It defaults to
2985 the current buffer."
2986 (with-temp-buffer
2987 (insert string)
2988 (org-element-parse-objects (point-min) (point-max) nil restriction)))
2990 (defun org-element-map (data types fun &optional info first-match no-recursion)
2991 "Map a function on selected elements or objects.
2993 DATA is the parsed tree, as returned by, i.e,
2994 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
2995 of elements or objects types. FUN is the function called on the
2996 matching element or object. It must accept one arguments: the
2997 element or object itself.
2999 When optional argument INFO is non-nil, it should be a plist
3000 holding export options. In that case, parts of the parse tree
3001 not exportable according to that property list will be skipped.
3003 When optional argument FIRST-MATCH is non-nil, stop at the first
3004 match for which FUN doesn't return nil, and return that value.
3006 Optional argument NO-RECURSION is a symbol or a list of symbols
3007 representing elements or objects types. `org-element-map' won't
3008 enter any recursive element or object whose type belongs to that
3009 list. Though, FUN can still be applied on them.
3011 Nil values returned from FUN do not appear in the results."
3012 ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
3013 (unless (listp types) (setq types (list types)))
3014 (unless (listp no-recursion) (setq no-recursion (list no-recursion)))
3015 ;; Recursion depth is determined by --CATEGORY.
3016 (let* ((--category
3017 (cond
3018 ((loop for type in types
3019 always (memq type org-element-greater-elements))
3020 'greater-elements)
3021 ((loop for type in types
3022 always (memq type org-element-all-elements))
3023 'elements)
3024 (t 'objects)))
3025 ;; --RESTRICTS is a list of element types whose secondary
3026 ;; string could possibly contain an object with a type among
3027 ;; TYPES.
3028 (--restricts
3029 (and (eq --category 'objects)
3030 (loop for el in org-element-secondary-value-alist
3031 when
3032 (loop for o in types
3033 thereis
3034 (memq o (cdr
3035 (assq (car el)
3036 org-element-string-restrictions))))
3037 collect (car el))))
3038 --acc
3039 (--walk-tree
3040 (function
3041 (lambda (--data)
3042 ;; Recursively walk DATA. INFO, if non-nil, is
3043 ;; a plist holding contextual information.
3044 (mapc
3045 (lambda (--blob)
3046 (unless (and info (member --blob (plist-get info :ignore-list)))
3047 (let ((--type (org-element-type --blob)))
3048 ;; Check if TYPE is matching among TYPES. If so,
3049 ;; apply FUN to --BLOB and accumulate return value
3050 ;; into --ACC (or exit if FIRST-MATCH is non-nil).
3051 (when (memq --type types)
3052 (let ((result (funcall fun --blob)))
3053 (cond ((not result))
3054 (first-match (throw 'first-match result))
3055 (t (push result --acc)))))
3056 ;; If --BLOB has a secondary string that can
3057 ;; contain objects with their type among TYPES,
3058 ;; look into that string.
3059 (when (memq --type --restricts)
3060 (funcall
3061 --walk-tree
3062 `(org-data
3064 ,@(org-element-property
3065 (cdr (assq --type org-element-secondary-value-alist))
3066 --blob))))
3067 ;; Now determine if a recursion into --BLOB is
3068 ;; possible. If so, do it.
3069 (unless (memq --type no-recursion)
3070 (when (or (and (memq --type org-element-greater-elements)
3071 (not (eq --category 'greater-elements)))
3072 (and (memq --type org-element-all-elements)
3073 (not (eq --category 'elements)))
3074 (memq --type org-element-recursive-objects))
3075 (funcall --walk-tree --blob))))))
3076 (org-element-contents --data))))))
3077 (catch 'first-match
3078 (funcall --walk-tree data)
3079 ;; Return value in a proper order.
3080 (reverse --acc))))
3082 ;; The following functions are internal parts of the parser.
3084 ;; The first one, `org-element-parse-elements' acts at the element's
3085 ;; level.
3087 ;; The second one, `org-element-parse-objects' applies on all objects
3088 ;; of a paragraph or a secondary string. It uses
3089 ;; `org-element-get-candidates' to optimize the search of the next
3090 ;; object in the buffer.
3092 ;; More precisely, that function looks for every allowed object type
3093 ;; first. Then, it discards failed searches, keeps further matches,
3094 ;; and searches again types matched behind point, for subsequent
3095 ;; calls. Thus, searching for a given type fails only once, and every
3096 ;; object is searched only once at top level (but sometimes more for
3097 ;; nested types).
3099 (defun org-element-parse-elements
3100 (beg end special structure granularity visible-only acc)
3101 "Parse elements between BEG and END positions.
3103 SPECIAL prioritize some elements over the others. It can set to
3104 `quote-section', `section' or `item', which will focus search,
3105 respectively, on quote sections, sections and items. Moreover,
3106 when value is `item', STRUCTURE will be used as the current list
3107 structure.
3109 GRANULARITY determines the depth of the recursion. It can be set
3110 to the following symbols:
3112 `headline' Only parse headlines.
3113 `greater-element' Don't recurse into greater elements. Thus,
3114 elements parsed are the top-level ones.
3115 `element' Parse everything but objects and plain text.
3116 `object' or nil Parse the complete buffer.
3118 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3119 elements.
3121 Elements are accumulated into ACC."
3122 (save-excursion
3123 (save-restriction
3124 (narrow-to-region beg end)
3125 (goto-char beg)
3126 ;; When parsing only headlines, skip any text before first one.
3127 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3128 (org-with-limited-levels (outline-next-heading)))
3129 ;; Main loop start.
3130 (while (not (eobp))
3131 (push
3132 ;; 1. Item mode is active: point must be at an item. Parse it
3133 ;; directly, skipping `org-element-current-element'.
3134 (if (eq special 'item)
3135 (let ((element (org-element-item-parser structure)))
3136 (goto-char (org-element-property :end element))
3137 (org-element-parse-elements
3138 (org-element-property :contents-begin element)
3139 (org-element-property :contents-end element)
3140 nil structure granularity visible-only (reverse element)))
3141 ;; 2. When ITEM is nil, find current element's type and parse
3142 ;; it accordingly to its category.
3143 (let* ((element (org-element-current-element special structure))
3144 (type (org-element-type element)))
3145 (goto-char (org-element-property :end element))
3146 (cond
3147 ;; Case 1. ELEMENT is a paragraph. Parse objects inside,
3148 ;; if GRANULARITY allows it.
3149 ((and (eq type 'paragraph)
3150 (or (not granularity) (eq granularity 'object)))
3151 (org-element-parse-objects
3152 (org-element-property :contents-begin element)
3153 (org-element-property :contents-end element)
3154 (reverse element) nil))
3155 ;; Case 2. ELEMENT is recursive: parse it between
3156 ;; `contents-begin' and `contents-end'. Make sure
3157 ;; GRANULARITY allows the recursion, or ELEMENT is an
3158 ;; headline, in which case going inside is mandatory, in
3159 ;; order to get sub-level headings. If VISIBLE-ONLY is
3160 ;; true and element is hidden, do not recurse into it.
3161 ((and (memq type org-element-greater-elements)
3162 (or (not granularity)
3163 (memq granularity '(element object))
3164 (eq type 'headline))
3165 (not (and visible-only
3166 (org-element-property :hiddenp element))))
3167 (org-element-parse-elements
3168 (org-element-property :contents-begin element)
3169 (org-element-property :contents-end element)
3170 ;; At a plain list, switch to item mode. At an
3171 ;; headline, switch to section mode. Any other
3172 ;; element turns off special modes.
3173 (case type
3174 (plain-list 'item)
3175 (headline (if (org-element-property :quotedp element)
3176 'quote-section
3177 'section)))
3178 (org-element-property :structure element)
3179 granularity visible-only (reverse element)))
3180 ;; Case 3. Else, just accumulate ELEMENT.
3181 (t element))))
3182 acc)))
3183 ;; Return result.
3184 (nreverse acc)))
3186 (defun org-element-parse-objects (beg end acc restriction)
3187 "Parse objects between BEG and END and return recursive structure.
3189 Objects are accumulated in ACC.
3191 RESTRICTION, when non-nil, is a list of object types which are
3192 allowed in the current object."
3193 (let ((get-next-object
3194 (function
3195 (lambda (cand)
3196 ;; Return the parsing function associated to the nearest
3197 ;; object among list of candidates CAND.
3198 (let ((pos (apply #'min (mapcar #'cdr cand))))
3199 (save-excursion
3200 (goto-char pos)
3201 (funcall
3202 (intern
3203 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3204 next-object candidates)
3205 (save-excursion
3206 (goto-char beg)
3207 (while (setq candidates (org-element-get-next-object-candidates
3208 end restriction candidates))
3209 (setq next-object (funcall get-next-object candidates))
3210 ;; 1. Text before any object. Untabify it.
3211 (let ((obj-beg (org-element-property :begin next-object)))
3212 (unless (= (point) obj-beg)
3213 (push (replace-regexp-in-string
3214 "\t" (make-string tab-width ? )
3215 (buffer-substring-no-properties (point) obj-beg))
3216 acc)))
3217 ;; 2. Object...
3218 (let ((obj-end (org-element-property :end next-object))
3219 (cont-beg (org-element-property :contents-begin next-object)))
3220 (push (if (and (memq (car next-object) org-element-recursive-objects)
3221 cont-beg)
3222 ;; ... recursive. The CONT-BEG check is for
3223 ;; links, as some of them might not be recursive
3224 ;; (i.e. plain links).
3225 (save-restriction
3226 (narrow-to-region
3227 cont-beg
3228 (org-element-property :contents-end next-object))
3229 (org-element-parse-objects
3230 (point-min) (point-max) (reverse next-object)
3231 ;; Restrict allowed objects. This is the
3232 ;; intersection of current restriction and next
3233 ;; object's restriction.
3234 (let ((new-restr
3235 (cdr (assq (car next-object)
3236 org-element-object-restrictions))))
3237 (if (not restriction) new-restr
3238 (delq nil (mapcar
3239 (lambda (e) (and (memq e restriction) e))
3240 new-restr))))))
3241 ;; ... not recursive.
3242 next-object)
3243 acc)
3244 (goto-char obj-end)))
3245 ;; 3. Text after last object. Untabify it.
3246 (unless (= (point) end)
3247 (push (replace-regexp-in-string
3248 "\t" (make-string tab-width ? )
3249 (buffer-substring-no-properties (point) end))
3250 acc))
3251 ;; Result.
3252 (nreverse acc))))
3254 (defun org-element-get-next-object-candidates (limit restriction objects)
3255 "Return an alist of candidates for the next object.
3257 LIMIT bounds the search, and RESTRICTION, when non-nil, bounds
3258 the possible object types.
3260 Return value is an alist whose car is position and cdr the object
3261 type, as a string. There is an association for the closest
3262 object of each type within RESTRICTION when non-nil, or for every
3263 type otherwise.
3265 OBJECTS is the previous candidates alist."
3266 (let ((restriction (or restriction org-element-all-successors))
3267 next-candidates types-to-search)
3268 ;; If no previous result, search every object type in RESTRICTION.
3269 ;; Otherwise, keep potential candidates (old objects located after
3270 ;; point) and ask to search again those which had matched before.
3271 (if (not objects) (setq types-to-search restriction)
3272 (mapc (lambda (obj)
3273 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3274 (push obj next-candidates)))
3275 objects))
3276 ;; Call the appropriate "get-next" function for each type to
3277 ;; search and accumulate matches.
3278 (mapc
3279 (lambda (type)
3280 (let* ((successor-fun
3281 (intern
3282 (format "org-element-%s-successor"
3283 (or (cdr (assq type org-element-object-successor-alist))
3284 type))))
3285 (obj (funcall successor-fun limit)))
3286 (and obj (push obj next-candidates))))
3287 types-to-search)
3288 ;; Return alist.
3289 next-candidates))
3293 ;;; Towards A Bijective Process
3295 ;; The parse tree obtained with `org-element-parse-buffer' is really
3296 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3297 ;; interpreted and expanded into a string with canonical Org
3298 ;; syntax. Hence `org-element-interpret-data'.
3300 ;; Data parsed from secondary strings, whose shape is slightly
3301 ;; different than the standard parse tree, is expanded with the
3302 ;; equivalent function `org-element-interpret-secondary'.
3304 ;; Both functions rely internally on
3305 ;; `org-element-interpret--affiliated-keywords'.
3307 (defun org-element-interpret-data (data &optional genealogy previous)
3308 "Interpret a parse tree representing Org data.
3310 DATA is the parse tree to interpret.
3312 Optional arguments GENEALOGY and PREVIOUS are used for recursive
3313 calls:
3314 GENEALOGY is the list of its parents types.
3315 PREVIOUS is the type of the element or object at the same level
3316 interpreted before.
3318 Return Org syntax as a string."
3319 (mapconcat
3320 (lambda (blob)
3321 ;; BLOB can be an element, an object, a string, or nil.
3322 (cond
3323 ((not blob) nil)
3324 ((equal blob "") nil)
3325 ((stringp blob) blob)
3327 (let* ((type (org-element-type blob))
3328 (interpreter
3329 (if (eq type 'org-data) 'identity
3330 (intern (format "org-element-%s-interpreter" type))))
3331 (contents
3332 (cond
3333 ;; Full Org document.
3334 ((eq type 'org-data)
3335 (org-element-interpret-data blob genealogy previous))
3336 ;; Recursive objects.
3337 ((memq type org-element-recursive-objects)
3338 (org-element-interpret-data
3339 blob (cons type genealogy) nil))
3340 ;; Recursive elements.
3341 ((memq type org-element-greater-elements)
3342 (org-element-normalize-string
3343 (org-element-interpret-data
3344 blob (cons type genealogy) nil)))
3345 ;; Paragraphs.
3346 ((eq type 'paragraph)
3347 (let ((paragraph
3348 (org-element-normalize-contents
3349 blob
3350 ;; When normalizing contents of an item,
3351 ;; ignore first line's indentation.
3352 (and (not previous)
3353 (memq (car genealogy)
3354 '(footnote-definiton item))))))
3355 (org-element-interpret-data
3356 paragraph (cons type genealogy) nil)))))
3357 (results (funcall interpreter blob contents)))
3358 ;; Update PREVIOUS.
3359 (setq previous type)
3360 ;; Build white spaces.
3361 (cond
3362 ((eq type 'org-data) results)
3363 ((memq type org-element-all-elements)
3364 (concat
3365 (org-element-interpret--affiliated-keywords blob)
3366 (org-element-normalize-string results)
3367 (make-string (org-element-property :post-blank blob) 10)))
3368 (t (concat
3369 results
3370 (make-string (org-element-property :post-blank blob) 32))))))))
3371 (org-element-contents data) ""))
3373 (defun org-element-interpret-secondary (secondary)
3374 "Interpret SECONDARY string as Org syntax.
3376 SECONDARY-STRING is a nested list as returned by
3377 `org-element-parse-secondary-string'.
3379 Return interpreted string."
3380 ;; Make SECONDARY acceptable for `org-element-interpret-data'.
3381 (let ((s (if (listp secondary) secondary (list secondary))))
3382 (org-element-interpret-data `(org-data nil ,@s) nil nil)))
3384 ;; Both functions internally use `org-element--affiliated-keywords'.
3386 (defun org-element-interpret--affiliated-keywords (element)
3387 "Return ELEMENT's affiliated keywords as Org syntax.
3388 If there is no affiliated keyword, return the empty string."
3389 (let ((keyword-to-org
3390 (function
3391 (lambda (key value)
3392 (let (dual)
3393 (when (member key org-element-dual-keywords)
3394 (setq dual (cdr value) value (car value)))
3395 (concat "#+" key (and dual (format "[%s]" dual)) ": "
3396 (if (member key org-element-parsed-keywords)
3397 (org-element-interpret-secondary value)
3398 value)
3399 "\n"))))))
3400 (mapconcat
3401 (lambda (key)
3402 (let ((value (org-element-property (intern (concat ":" key)) element)))
3403 (when value
3404 (if (member key org-element-multiple-keywords)
3405 (mapconcat (lambda (line)
3406 (funcall keyword-to-org key line))
3407 value "")
3408 (funcall keyword-to-org key value)))))
3409 ;; Remove translated keywords.
3410 (delq nil
3411 (mapcar
3412 (lambda (key)
3413 (and (not (assoc key org-element-keyword-translation-alist)) key))
3414 org-element-affiliated-keywords))
3415 "")))
3417 ;; Because interpretation of the parse tree must return the same
3418 ;; number of blank lines between elements and the same number of white
3419 ;; space after objects, some special care must be given to white
3420 ;; spaces.
3422 ;; The first function, `org-element-normalize-string', ensures any
3423 ;; string different from the empty string will end with a single
3424 ;; newline character.
3426 ;; The second function, `org-element-normalize-contents', removes
3427 ;; global indentation from the contents of the current element.
3429 (defun org-element-normalize-string (s)
3430 "Ensure string S ends with a single newline character.
3432 If S isn't a string return it unchanged. If S is the empty
3433 string, return it. Otherwise, return a new string with a single
3434 newline character at its end."
3435 (cond
3436 ((not (stringp s)) s)
3437 ((string= "" s) "")
3438 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3439 (replace-match "\n" nil nil s)))))
3441 (defun org-element-normalize-contents (element &optional ignore-first)
3442 "Normalize plain text in ELEMENT's contents.
3444 ELEMENT must only contain plain text and objects.
3446 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3447 indentation to compute maximal common indentation.
3449 Return the normalized element that is element with global
3450 indentation removed from its contents. The function assumes that
3451 indentation is not done with TAB characters."
3452 (let (ind-list
3453 (collect-inds
3454 (function
3455 ;; Return list of indentations within BLOB. This is done by
3456 ;; walking recursively BLOB and updating IND-LIST along the
3457 ;; way. FIRST-FLAG is non-nil when the first string hasn't
3458 ;; been seen yet. It is required as this string is the only
3459 ;; one whose indentation doesn't happen after a newline
3460 ;; character.
3461 (lambda (blob first-flag)
3462 (mapc
3463 (lambda (object)
3464 (when (and first-flag (stringp object))
3465 (setq first-flag nil)
3466 (string-match "\\`\\( *\\)" object)
3467 (let ((len (length (match-string 1 object))))
3468 ;; An indentation of zero means no string will be
3469 ;; modified. Quit the process.
3470 (if (zerop len) (throw 'zero (setq ind-list nil))
3471 (push len ind-list))))
3472 (cond
3473 ((stringp object)
3474 (let ((start 0))
3475 (while (string-match "\n\\( *\\)" object start)
3476 (setq start (match-end 0))
3477 (push (length (match-string 1 object)) ind-list))))
3478 ((memq (org-element-type object) org-element-recursive-objects)
3479 (funcall collect-inds object first-flag))))
3480 (org-element-contents blob))))))
3481 ;; Collect indentation list in ELEMENT. Possibly remove first
3482 ;; value if IGNORE-FIRST is non-nil.
3483 (catch 'zero (funcall collect-inds element (not ignore-first)))
3484 (if (not ind-list) element
3485 ;; Build ELEMENT back, replacing each string with the same
3486 ;; string minus common indentation.
3487 (let ((build
3488 (function
3489 (lambda (blob mci first-flag)
3490 ;; Return BLOB with all its strings indentation
3491 ;; shortened from MCI white spaces. FIRST-FLAG is
3492 ;; non-nil when the first string hasn't been seen
3493 ;; yet.
3494 (nconc
3495 (list (org-element-type blob) (nth 1 blob))
3496 (mapcar
3497 (lambda (object)
3498 (when (and first-flag (stringp object))
3499 (setq first-flag nil)
3500 (setq object
3501 (replace-regexp-in-string
3502 (format "\\` \\{%d\\}" mci) "" object)))
3503 (cond
3504 ((stringp object)
3505 (replace-regexp-in-string
3506 (format "\n \\{%d\\}" mci) "\n" object))
3507 ((memq (org-element-type object) org-element-recursive-objects)
3508 (funcall build object mci first-flag))
3509 (t object)))
3510 (org-element-contents blob)))))))
3511 (funcall build element (apply 'min ind-list) (not ignore-first))))))
3515 ;;; The Toolbox
3517 ;; The first move is to implement a way to obtain the smallest element
3518 ;; containing point. This is the job of `org-element-at-point'. It
3519 ;; basically jumps back to the beginning of section containing point
3520 ;; and moves, element after element, with
3521 ;; `org-element-current-element' until the container is found.
3523 (defun org-element-at-point (&optional keep-trail)
3524 "Determine closest element around point.
3526 Return value is a list like (TYPE PROPS) where TYPE is the type
3527 of the element and PROPS a plist of properties associated to the
3528 element. Possible types are defined in
3529 `org-element-all-elements'.
3531 As a special case, if point is at the very beginning of a list or
3532 sub-list, element returned will be that list instead of the first
3533 item.
3535 If optional argument KEEP-TRAIL is non-nil, the function returns
3536 a list of of elements leading to element at point. The list's
3537 CAR is always the element at point. Its last item will be the
3538 element's parent, unless element was either the first in its
3539 section (in which case the last item in the list is the first
3540 element of section) or an headline (in which case the list
3541 contains that headline as its single element). Elements
3542 in-between, if any, are siblings of the element at point."
3543 (org-with-wide-buffer
3544 ;; If at an headline, parse it. It is the sole element that
3545 ;; doesn't require to know about context.
3546 (if (org-with-limited-levels (org-at-heading-p))
3547 (if (not keep-trail) (org-element-headline-parser)
3548 (list (org-element-headline-parser)))
3549 ;; Otherwise move at the beginning of the section containing
3550 ;; point.
3551 (let ((origin (point)) element type item-flag trail struct prevs)
3552 (org-with-limited-levels
3553 (if (org-before-first-heading-p) (goto-char (point-min))
3554 (org-back-to-heading)
3555 (forward-line)))
3556 (org-skip-whitespace)
3557 (beginning-of-line)
3558 ;; Starting parsing successively each element with
3559 ;; `org-element-current-element'. Skip those ending before
3560 ;; original position.
3561 (catch 'exit
3562 (while t
3563 (setq element (org-element-current-element item-flag struct)
3564 type (car element))
3565 (when keep-trail (push element trail))
3566 (cond
3567 ;; 1. Skip any element ending before point or at point.
3568 ((let ((end (org-element-property :end element)))
3569 (when (<= end origin)
3570 (if (> (point-max) end) (goto-char end)
3571 (throw 'exit (or trail element))))))
3572 ;; 2. An element containing point is always the element at
3573 ;; point.
3574 ((not (memq type org-element-greater-elements))
3575 (throw 'exit (if keep-trail trail element)))
3576 ;; 3. At a plain list.
3577 ((eq type 'plain-list)
3578 (setq struct (org-element-property :structure element)
3579 prevs (or prevs (org-list-prevs-alist struct)))
3580 (let ((beg (org-element-property :contents-begin element)))
3581 (if (= beg origin) (throw 'exit (or trail element))
3582 ;; Find the item at this level containing ORIGIN.
3583 (let ((items (org-list-get-all-items beg struct prevs)))
3584 (let (parent)
3585 (catch 'local
3586 (mapc
3587 (lambda (pos)
3588 (cond
3589 ;; Item ends before point: skip it.
3590 ((<= (org-list-get-item-end pos struct) origin))
3591 ;; Item contains point: store is in PARENT.
3592 ((<= pos origin) (setq parent pos))
3593 ;; We went too far: return PARENT.
3594 (t (throw 'local nil)))) items))
3595 ;; No parent: no item contained point, though
3596 ;; the plain list does. Point is in the blank
3597 ;; lines after the list: return plain list.
3598 (if (not parent) (throw 'exit (or trail element))
3599 (setq item-flag 'item)
3600 (goto-char parent)))))))
3601 ;; 4. At any other greater element type, if point is
3602 ;; within contents, move into it. Otherwise, return
3603 ;; that element.
3605 (when (eq type 'item) (setq item-flag nil))
3606 (let ((beg (org-element-property :contents-begin element))
3607 (end (org-element-property :contents-end element)))
3608 (if (or (> beg origin) (< end origin))
3609 (throw 'exit (or trail element))
3610 ;; Reset trail, since we found a parent.
3611 (when keep-trail (setq trail (list element)))
3612 (narrow-to-region beg end)
3613 (goto-char beg)))))))))))
3616 ;; Once the local structure around point is well understood, it's easy
3617 ;; to implement some replacements for `forward-paragraph'
3618 ;; `backward-paragraph', namely `org-element-forward' and
3619 ;; `org-element-backward'.
3621 ;; Also, `org-transpose-elements' mimics the behaviour of
3622 ;; `transpose-words', at the element's level, whereas
3623 ;; `org-element-drag-forward', `org-element-drag-backward', and
3624 ;; `org-element-up' generalize, respectively, functions
3625 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3627 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3628 ;; smartly remove global indentation from buffer, making it possible
3629 ;; to use Org indent mode on a file created with hard indentation.
3631 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3632 ;; internally by some of the previously cited tools.
3634 (defsubst org-element-nested-p (elem-A elem-B)
3635 "Non-nil when elements ELEM-A and ELEM-B are nested."
3636 (let ((beg-A (org-element-property :begin elem-A))
3637 (beg-B (org-element-property :begin elem-B))
3638 (end-A (org-element-property :end elem-A))
3639 (end-B (org-element-property :end elem-B)))
3640 (or (and (>= beg-A beg-B) (<= end-A end-B))
3641 (and (>= beg-B beg-A) (<= end-B end-A)))))
3643 (defun org-element-swap-A-B (elem-A elem-B)
3644 "Swap elements ELEM-A and ELEM-B.
3646 Leave point at the end of ELEM-A.
3648 Assume ELEM-A is before ELEM-B and that they are not nested."
3649 (goto-char (org-element-property :begin elem-A))
3650 (let* ((beg-B (org-element-property :begin elem-B))
3651 (end-B-no-blank (save-excursion
3652 (goto-char (org-element-property :end elem-B))
3653 (skip-chars-backward " \r\t\n")
3654 (forward-line)
3655 (point)))
3656 (beg-A (org-element-property :begin elem-A))
3657 (end-A-no-blank (save-excursion
3658 (goto-char (org-element-property :end elem-A))
3659 (skip-chars-backward " \r\t\n")
3660 (forward-line)
3661 (point)))
3662 (body-A (buffer-substring beg-A end-A-no-blank))
3663 (body-B (buffer-substring beg-B end-B-no-blank))
3664 (between-A-B (buffer-substring end-A-no-blank beg-B)))
3665 (delete-region beg-A end-B-no-blank)
3666 (insert body-B between-A-B body-A)
3667 (goto-char (org-element-property :end elem-B))))
3669 (defun org-element-backward ()
3670 "Move backward by one element.
3671 Move to the previous element at the same level, when possible."
3672 (interactive)
3673 (if (save-excursion (skip-chars-backward " \r\t\n") (bobp))
3674 (error "Cannot move further up")
3675 (let* ((trail (org-element-at-point 'keep-trail))
3676 (element (car trail))
3677 (beg (org-element-property :begin element)))
3678 ;; Move to beginning of current element if point isn't there.
3679 (if (/= (point) beg) (goto-char beg)
3680 (let ((type (org-element-type element)))
3681 (cond
3682 ;; At an headline: move to previous headline at the same
3683 ;; level, a parent, or BOB.
3684 ((eq type 'headline)
3685 (let ((dest (save-excursion (org-backward-same-level 1) (point))))
3686 (if (= (point-min) dest) (error "Cannot move further up")
3687 (goto-char dest))))
3688 ;; At an item: try to move to the previous item, if any.
3689 ((and (eq type 'item)
3690 (let* ((struct (org-element-property :structure element))
3691 (prev (org-list-get-prev-item
3692 beg struct (org-list-prevs-alist struct))))
3693 (when prev (goto-char prev)))))
3694 ;; In any other case, find the previous element in the
3695 ;; trail and move to its beginning. If no previous element
3696 ;; can be found, move to headline.
3697 (t (let ((prev (nth 1 trail)))
3698 (if prev (goto-char (org-element-property :begin prev))
3699 (org-back-to-heading))))))))))
3701 (defun org-element-drag-backward ()
3702 "Drag backward element at point."
3703 (interactive)
3704 (let* ((pos (point))
3705 (elem (org-element-at-point)))
3706 (when (= (progn (goto-char (point-min))
3707 (org-skip-whitespace)
3708 (point-at-bol))
3709 (org-element-property :end elem))
3710 (error "Cannot drag element backward"))
3711 (goto-char (org-element-property :begin elem))
3712 (org-element-backward)
3713 (let ((prev-elem (org-element-at-point)))
3714 (when (or (org-element-nested-p elem prev-elem)
3715 (and (eq (car elem) 'headline)
3716 (not (eq (car prev-elem) 'headline))))
3717 (goto-char pos)
3718 (error "Cannot drag element backward"))
3719 ;; Compute new position of point: it's shifted by PREV-ELEM
3720 ;; body's length.
3721 (let ((size-prev (- (org-element-property :end prev-elem)
3722 (org-element-property :begin prev-elem))))
3723 (org-element-swap-A-B prev-elem elem)
3724 (goto-char (- pos size-prev))))))
3726 (defun org-element-drag-forward ()
3727 "Move forward element at point."
3728 (interactive)
3729 (let* ((pos (point))
3730 (elem (org-element-at-point)))
3731 (when (= (point-max) (org-element-property :end elem))
3732 (error "Cannot drag element forward"))
3733 (goto-char (org-element-property :end elem))
3734 (let ((next-elem (org-element-at-point)))
3735 (when (or (org-element-nested-p elem next-elem)
3736 (and (eq (car next-elem) 'headline)
3737 (not (eq (car elem) 'headline))))
3738 (goto-char pos)
3739 (error "Cannot drag element forward"))
3740 ;; Compute new position of point: it's shifted by NEXT-ELEM
3741 ;; body's length (without final blanks) and by the length of
3742 ;; blanks between ELEM and NEXT-ELEM.
3743 (let ((size-next (- (save-excursion
3744 (goto-char (org-element-property :end next-elem))
3745 (skip-chars-backward " \r\t\n")
3746 (forward-line)
3747 (point))
3748 (org-element-property :begin next-elem)))
3749 (size-blank (- (org-element-property :end elem)
3750 (save-excursion
3751 (goto-char (org-element-property :end elem))
3752 (skip-chars-backward " \r\t\n")
3753 (forward-line)
3754 (point)))))
3755 (org-element-swap-A-B elem next-elem)
3756 (goto-char (+ pos size-next size-blank))))))
3758 (defun org-element-forward ()
3759 "Move forward by one element.
3760 Move to the next element at the same level, when possible."
3761 (interactive)
3762 (if (eobp) (error "Cannot move further down")
3763 (let* ((trail (org-element-at-point 'keep-trail))
3764 (element (car trail))
3765 (type (org-element-type element))
3766 (end (org-element-property :end element)))
3767 (cond
3768 ;; At an headline, move to next headline at the same level.
3769 ((eq type 'headline) (goto-char end))
3770 ;; At an item. Move to the next item, if possible.
3771 ((and (eq type 'item)
3772 (let* ((struct (org-element-property :structure element))
3773 (prevs (org-list-prevs-alist struct))
3774 (beg (org-element-property :begin element))
3775 (next-item (org-list-get-next-item beg struct prevs)))
3776 (when next-item (goto-char next-item)))))
3777 ;; In any other case, move to element's end, unless this
3778 ;; position is also the end of its parent's contents, in which
3779 ;; case, directly jump to parent's end.
3781 (let ((parent
3782 ;; Determine if TRAIL contains the real parent of ELEMENT.
3783 (and (> (length trail) 1)
3784 (let* ((parent-candidate (car (last trail))))
3785 (and (memq (org-element-type parent-candidate)
3786 org-element-greater-elements)
3787 (>= (org-element-property
3788 :contents-end parent-candidate) end)
3789 parent-candidate)))))
3790 (cond ((not parent) (goto-char end))
3791 ((= (org-element-property :contents-end parent) end)
3792 (goto-char (org-element-property :end parent)))
3793 (t (goto-char end)))))))))
3795 (defun org-element-mark-element ()
3796 "Put point at beginning of this element, mark at end.
3798 Interactively, if this command is repeated or (in Transient Mark
3799 mode) if the mark is active, it marks the next element after the
3800 ones already marked."
3801 (interactive)
3802 (let (deactivate-mark)
3803 (if (or (and (eq last-command this-command) (mark t))
3804 (and transient-mark-mode mark-active))
3805 (set-mark
3806 (save-excursion
3807 (goto-char (mark))
3808 (goto-char (org-element-property :end (org-element-at-point)))))
3809 (let ((element (org-element-at-point)))
3810 (end-of-line)
3811 (push-mark (org-element-property :end element) t t)
3812 (goto-char (org-element-property :begin element))))))
3814 (defun org-narrow-to-element ()
3815 "Narrow buffer to current element."
3816 (interactive)
3817 (let ((elem (org-element-at-point)))
3818 (cond
3819 ((eq (car elem) 'headline)
3820 (narrow-to-region
3821 (org-element-property :begin elem)
3822 (org-element-property :end elem)))
3823 ((memq (car elem) org-element-greater-elements)
3824 (narrow-to-region
3825 (org-element-property :contents-begin elem)
3826 (org-element-property :contents-end elem)))
3828 (narrow-to-region
3829 (org-element-property :begin elem)
3830 (org-element-property :end elem))))))
3832 (defun org-transpose-elements ()
3833 "Transpose current and previous elements, keeping blank lines between.
3834 Point is moved after both elements."
3835 (interactive)
3836 (org-skip-whitespace)
3837 (let ((pos (point))
3838 (cur (org-element-at-point)))
3839 (when (= (save-excursion (goto-char (point-min))
3840 (org-skip-whitespace)
3841 (point-at-bol))
3842 (org-element-property :begin cur))
3843 (error "No previous element"))
3844 (goto-char (org-element-property :begin cur))
3845 (forward-line -1)
3846 (let ((prev (org-element-at-point)))
3847 (when (org-element-nested-p cur prev)
3848 (goto-char pos)
3849 (error "Cannot transpose nested elements"))
3850 (org-element-swap-A-B prev cur))))
3852 (defun org-element-unindent-buffer ()
3853 "Un-indent the visible part of the buffer.
3854 Relative indentation \(between items, inside blocks, etc.\) isn't
3855 modified."
3856 (interactive)
3857 (unless (eq major-mode 'org-mode)
3858 (error "Cannot un-indent a buffer not in Org mode"))
3859 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
3860 unindent-tree ; For byte-compiler.
3861 (unindent-tree
3862 (function
3863 (lambda (contents)
3864 (mapc (lambda (element)
3865 (if (eq (org-element-type element) 'headline)
3866 (funcall unindent-tree
3867 (org-element-contents element))
3868 (save-excursion
3869 (save-restriction
3870 (narrow-to-region
3871 (org-element-property :begin element)
3872 (org-element-property :end element))
3873 (org-do-remove-indentation)))))
3874 (reverse contents))))))
3875 (funcall unindent-tree (org-element-contents parse-tree))))
3877 (defun org-element-up ()
3878 "Move to upper element."
3879 (interactive)
3880 (cond
3881 ((bobp) (error "No surrounding element"))
3882 ((org-with-limited-levels (org-at-heading-p))
3883 (or (org-up-heading-safe) (error "No surronding element")))
3885 (let* ((trail (org-element-at-point 'keep-trail))
3886 (element (car trail))
3887 (type (org-element-type element)))
3888 (cond
3889 ;; At an item, with a parent in the list: move to that parent.
3890 ((and (eq type 'item)
3891 (let* ((beg (org-element-property :begin element))
3892 (struct (org-element-property :structure element))
3893 (parents (org-list-parents-alist struct))
3894 (parentp (org-list-get-parent beg struct parents)))
3895 (and parentp (goto-char parentp)))))
3896 ;; Determine parent in the trail.
3898 (let ((parent
3899 (and (> (length trail) 1)
3900 (let ((parentp (car (last trail))))
3901 (and (memq (org-element-type parentp)
3902 org-element-greater-elements)
3903 (>= (org-element-property :contents-end parentp)
3904 (org-element-property :end element))
3905 parentp)))))
3906 (cond
3907 ;; When parent is found move to its beginning.
3908 (parent (goto-char (org-element-property :begin parent)))
3909 ;; If no parent was found, move to headline above, if any
3910 ;; or return an error.
3911 ((org-before-first-heading-p) (error "No surrounding element"))
3912 (t (org-back-to-heading))))))))))
3914 (defun org-element-down ()
3915 "Move to inner element."
3916 (interactive)
3917 (let ((element (org-element-at-point)))
3918 (cond
3919 ((eq (org-element-type element) 'plain-list)
3920 (forward-char))
3921 ((memq (org-element-type element) org-element-greater-elements)
3922 ;; If contents are hidden, first disclose them.
3923 (when (org-element-property :hiddenp element) (org-cycle))
3924 (goto-char (org-element-property :contents-begin element)))
3925 (t (error "No inner element")))))
3928 (provide 'org-element)
3929 ;;; org-element.el ends here