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