org-element: Allow targets in tables
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-element.el
blob806468be81fd6a854bbbf0df08365df79fe60ac0
1 ;;; org-element.el --- Parser And Applications for Org syntax
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; This file is not part of GNU Emacs.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Org syntax can be divided into three categories: "Greater
26 ;; elements", "Elements" and "Objects".
28 ;; An object can be defined anywhere on a line. It may span over more
29 ;; than a line but never contains a blank one. Objects belong to the
30 ;; following types: `emphasis', `entity', `export-snippet',
31 ;; `footnote-reference', `inline-babel-call', `inline-src-block',
32 ;; `latex-fragment', `line-break', `link', `macro', `radio-target',
33 ;; `statistics-cookie', `subscript', `superscript', `target',
34 ;; `time-stamp' and `verbatim'.
36 ;; An element always starts and ends at the beginning of a line. The
37 ;; only element's type containing objects is called a `paragraph'.
38 ;; Other types are: `comment', `comment-block', `example-block',
39 ;; `export-block', `fixed-width', `horizontal-rule', `keyword',
40 ;; `latex-environment', `babel-call', `property-drawer',
41 ;; `quote-section', `src-block', `table' and `verse-block'.
43 ;; Elements containing paragraphs are called greater elements.
44 ;; Concerned types are: `center-block', `drawer', `dynamic-block',
45 ;; `footnote-definition', `headline', `inlinetask', `item',
46 ;; `plain-list', `quote-block', `section' and `special-block'.
48 ;; Greater elements (excepted `headline', `item' and `section' types)
49 ;; and elements (excepted `keyword', `babel-call', and
50 ;; `property-drawer' types) can have a fixed set of keywords as
51 ;; attributes. Those are called "affiliated keywords", to distinguish
52 ;; them from others keywords, which are full-fledged elements. In
53 ;; particular, the "name" affiliated keyword allows to label almost
54 ;; any element in an Org buffer.
56 ;; Notwithstanding affiliated keywords, each greater element, element
57 ;; and object has a fixed set of properties attached to it. Among
58 ;; them, three are shared by all types: `:begin' and `:end', which
59 ;; refer to the beginning and ending buffer positions of the
60 ;; considered element or object, and `:post-blank', which holds the
61 ;; number of blank lines, or white spaces, at its end.
63 ;; Some elements also have special properties whose value can hold
64 ;; objects themselves (i.e. an item tag, an headline name, a table
65 ;; cell). Such values are called "secondary strings".
67 ;; Lisp-wise, an element or an object can be represented as a list.
68 ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
69 ;; TYPE is a symbol describing the Org element or object.
70 ;; PROPERTIES is the property list attached to it. See docstring of
71 ;; appropriate parsing function to get an exhaustive
72 ;; list.
73 ;; CONTENTS is a list of elements, objects or raw strings contained
74 ;; in the current element or object, when applicable.
76 ;; An Org buffer is a nested list of such elements and objects, whose
77 ;; type is `org-data' and properties is nil.
79 ;; The first part of this file implements a parser and an interpreter
80 ;; for each type of Org syntax.
82 ;; The next two parts introduce two accessors and a function
83 ;; retrieving the smallest element containing point (respectively
84 ;; `org-element-get-property', `org-element-get-contents' and
85 ;; `org-element-at-point').
87 ;; The following part creates a fully recursive buffer parser. It
88 ;; also provides a tool to map a function to elements or objects
89 ;; matching some criteria in the parse tree. Functions of interest
90 ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
91 ;; extent, `org-element-parse-secondary-string'.
93 ;; The penultimate part is the cradle of an interpreter for the
94 ;; obtained parse tree: `org-element-interpret-data' (and its
95 ;; relative, `org-element-interpret-secondary').
97 ;; The library ends by furnishing a set of interactive tools for
98 ;; element's navigation and manipulation.
101 ;;; Code:
103 (eval-when-compile (require 'cl))
104 (require 'org)
105 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
108 ;;; Greater elements
110 ;; For each greater element type, we define a parser and an
111 ;; interpreter.
113 ;; A parser (`item''s excepted) accepts no argument and represents the
114 ;; element or object as the list described above. An interpreter
115 ;; accepts two arguments: the list representation of the element or
116 ;; object, and its contents. The latter may be nil, depending on the
117 ;; element or object considered. It returns the appropriate Org
118 ;; syntax, as a string.
120 ;; Parsing functions must follow the naming convention:
121 ;; org-element-TYPE-parser, where TYPE is greater element's type, as
122 ;; defined in `org-element-greater-elements'.
124 ;; Similarly, interpreting functions must follow the naming
125 ;; convention: org-element-TYPE-interpreter.
127 ;; With the exception of `headline' and `item' types, greater elements
128 ;; cannot contain other greater elements of their own type.
130 ;; Beside implementing a parser and an interpreter, adding a new
131 ;; greater element requires to tweak `org-element-guess-type'.
132 ;; Moreover, the newly defined type must be added to both
133 ;; `org-element-all-elements' and `org-element-greater-elements'.
136 ;;;; Center Block
138 (defun org-element-center-block-parser ()
139 "Parse a center block.
141 Return a list whose car is `center-block' and cdr is a plist
142 containing `:begin', `:end', `:hiddenp', `:contents-begin',
143 `:contents-end' and `:post-blank' keywords.
145 Assume point is at beginning or end of the block."
146 (save-excursion
147 (let* ((case-fold-search t)
148 (keywords (progn
149 (end-of-line)
150 (re-search-backward
151 (concat "^[ \t]*#\\+begin_center") nil t)
152 (org-element-collect-affiliated-keywords)))
153 (begin (car keywords))
154 (contents-begin (progn (forward-line) (point)))
155 (hidden (org-truely-invisible-p))
156 (contents-end (progn (re-search-forward
157 (concat "^[ \t]*#\\+end_center") nil t)
158 (point-at-bol)))
159 (pos-before-blank (progn (forward-line) (point)))
160 (end (progn (org-skip-whitespace)
161 (if (eobp) (point) (point-at-bol)))))
162 `(center-block
163 (:begin ,begin
164 :end ,end
165 :hiddenp ,hidden
166 :contents-begin ,contents-begin
167 :contents-end ,contents-end
168 :post-blank ,(count-lines pos-before-blank end)
169 ,@(cadr keywords))))))
171 (defun org-element-center-block-interpreter (center-block contents)
172 "Interpret CENTER-BLOCK element as Org syntax.
173 CONTENTS is the contents of the element."
174 (format "#+begin_center\n%s#+end_center" contents))
177 ;;;; Drawer
179 (defun org-element-drawer-parser ()
180 "Parse a drawer.
182 Return a list whose car is `drawer' and cdr is a plist containing
183 `:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
184 `:contents-end' and `:post-blank' keywords.
186 Assume point is at beginning of drawer."
187 (save-excursion
188 (let* ((case-fold-search t)
189 (name (progn (looking-at org-drawer-regexp)
190 (org-match-string-no-properties 1)))
191 (keywords (org-element-collect-affiliated-keywords))
192 (begin (car keywords))
193 (contents-begin (progn (forward-line) (point)))
194 (hidden (org-truely-invisible-p))
195 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
196 (point-at-bol)))
197 (pos-before-blank (progn (forward-line) (point)))
198 (end (progn (org-skip-whitespace)
199 (if (eobp) (point) (point-at-bol)))))
200 `(drawer
201 (:begin ,begin
202 :end ,end
203 :drawer-name ,name
204 :hiddenp ,hidden
205 :contents-begin ,contents-begin
206 :contents-end ,contents-end
207 :post-blank ,(count-lines pos-before-blank end)
208 ,@(cadr keywords))))))
210 (defun org-element-drawer-interpreter (drawer contents)
211 "Interpret DRAWER element as Org syntax.
212 CONTENTS is the contents of the element."
213 (format ":%s:\n%s:END:"
214 (org-element-get-property :drawer-name drawer)
215 contents))
218 ;;;; Dynamic Block
220 (defun org-element-dynamic-block-parser ()
221 "Parse a dynamic block.
223 Return a list whose car is `dynamic-block' and cdr is a plist
224 containing `:block-name', `:begin', `:end', `:hiddenp',
225 `:contents-begin', `:contents-end', `:arguments' and
226 `:post-blank' keywords.
228 Assume point is at beginning of dynamic block."
229 (save-excursion
230 (let* ((case-fold-search t)
231 (name (progn (looking-at org-dblock-start-re)
232 (org-match-string-no-properties 1)))
233 (arguments (org-match-string-no-properties 3))
234 (keywords (org-element-collect-affiliated-keywords))
235 (begin (car keywords))
236 (contents-begin (progn (forward-line) (point)))
237 (hidden (org-truely-invisible-p))
238 (contents-end (progn (re-search-forward org-dblock-end-re nil t)
239 (point-at-bol)))
240 (pos-before-blank (progn (forward-line) (point)))
241 (end (progn (org-skip-whitespace)
242 (if (eobp) (point) (point-at-bol)))))
243 (list 'dynamic-block
244 `(:begin ,begin
245 :end ,end
246 :block-name ,name
247 :arguments ,arguments
248 :hiddenp ,hidden
249 :contents-begin ,contents-begin
250 :contents-end ,contents-end
251 :post-blank ,(count-lines pos-before-blank end)
252 ,@(cadr keywords))))))
254 (defun org-element-dynamic-block-interpreter (dynamic-block contents)
255 "Interpret DYNAMIC-BLOCK element as Org syntax.
256 CONTENTS is the contents of the element."
257 (format "#+BEGIN: %s%s\n%s#+END:"
258 (org-element-get-property :block-name dynamic-block)
259 (let ((args (org-element-get-property :arguments dynamic-block)))
260 (and arg (concat " " args)))
261 contents))
264 ;;;; Footnote Definition
266 (defun org-element-footnote-definition-parser ()
267 "Parse a footnote definition.
269 Return a list whose car is `footnote-definition' and cdr is
270 a plist containing `:label', `:begin' `:end', `:contents-begin',
271 `:contents-end' and `:post-blank' keywords."
272 (save-excursion
273 (let* ((f-def (org-footnote-at-definition-p))
274 (label (car f-def))
275 (keywords (progn (goto-char (nth 1 f-def))
276 (org-element-collect-affiliated-keywords)))
277 (begin (car keywords))
278 (contents-begin (progn (looking-at (concat "\\[" label "\\]"))
279 (goto-char (match-end 0))
280 (org-skip-whitespace)
281 (point)))
282 (end (goto-char (nth 2 f-def)))
283 (contents-end (progn (skip-chars-backward " \r\t\n")
284 (forward-line)
285 (point))))
286 `(footnote-definition
287 (:label ,label
288 :begin ,begin
289 :end ,end
290 :contents-begin ,contents-begin
291 :contents-end ,contents-end
292 :post-blank ,(count-lines contents-end end)
293 ,@(cadr keywords))))))
295 (defun org-element-footnote-definition-interpreter (footnote-definition contents)
296 "Interpret FOOTNOTE-DEFINITION element as Org syntax.
297 CONTENTS is the contents of the footnote-definition."
298 (concat (format "[%s]" (org-element-get-property :label footnote-definition))
300 contents))
303 ;;;; Headline
305 (defun org-element-headline-parser ()
306 "Parse an headline.
308 Return a list whose car is `headline' and cdr is a plist
309 containing `:raw-value', `:title', `:begin', `:end',
310 `:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
311 `:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
312 `:scheduled', `:deadline', `:timestamp', `:clock', `:category',
313 `:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
314 keywords.
316 The plist also contains any property set in the property drawer,
317 with its name in lowercase, the underscores replaced with hyphens
318 and colons at the beginning (i.e. `:custom-id').
320 Assume point is at beginning of the headline."
321 (save-excursion
322 (let* ((components (org-heading-components))
323 (level (nth 1 components))
324 (todo (nth 2 components))
325 (todo-type (and todo
326 (if (member todo org-done-keywords) 'done 'todo)))
327 (tags (nth 5 components))
328 (raw-value (nth 4 components))
329 (quotedp (string-match (format "^%s +" org-quote-string) raw-value))
330 (commentedp (string-match
331 (format "^%s +" org-comment-string) raw-value))
332 (archivedp (and tags
333 (string-match (format ":%s:" org-archive-tag) tags)))
334 (footnote-section-p (and org-footnote-section
335 (string= org-footnote-section raw-value)))
336 (standard-props (let (plist)
337 (mapc
338 (lambda (p)
339 (let ((p-name (downcase (car p))))
340 (while (string-match "_" p-name)
341 (setq p-name
342 (replace-match "-" nil nil p-name)))
343 (setq p-name (intern (concat ":" p-name)))
344 (setq plist
345 (plist-put plist p-name (cdr p)))))
346 (org-entry-properties nil 'standard))
347 plist))
348 (time-props (org-entry-properties nil 'special "CLOCK"))
349 (scheduled (cdr (assoc "SCHEDULED" time-props)))
350 (deadline (cdr (assoc "DEADLINE" time-props)))
351 (clock (cdr (assoc "CLOCK" time-props)))
352 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
353 (begin (point))
354 (pos-after-head (save-excursion (forward-line) (point)))
355 (contents-begin (save-excursion (forward-line)
356 (org-skip-whitespace)
357 (if (eobp) (point) (point-at-bol))))
358 (hidden (save-excursion (forward-line) (org-truely-invisible-p)))
359 (end (progn (goto-char (org-end-of-subtree t t))))
360 (contents-end (progn (skip-chars-backward " \r\t\n")
361 (forward-line)
362 (point)))
363 title)
364 ;; Clean RAW-VALUE from any quote or comment string.
365 (when (or quotedp commentedp)
366 (setq raw-value
367 (replace-regexp-in-string
368 (concat "\\(" org-quote-string "\\|" org-comment-string "\\) +")
370 raw-value)))
371 ;; Clean TAGS from archive tag, if any.
372 (when archivedp
373 (setq tags
374 (and (not (string= tags (format ":%s:" org-archive-tag)))
375 (replace-regexp-in-string
376 (concat org-archive-tag ":") "" tags)))
377 (when (string= tags ":") (setq tags nil)))
378 ;; Then get TITLE.
379 (setq title (org-element-parse-secondary-string
380 raw-value
381 (cdr (assq 'headline org-element-string-restrictions))))
382 `(headline
383 (:raw-value ,raw-value
384 :title ,title
385 :begin ,begin
386 :end ,end
387 :pre-blank ,(count-lines pos-after-head contents-begin)
388 :hiddenp ,hidden
389 :contents-begin ,contents-begin
390 :contents-end ,contents-end
391 :level ,level
392 :priority ,(nth 3 components)
393 :tags ,tags
394 :todo-keyword ,todo
395 :todo-type ,todo-type
396 :scheduled ,scheduled
397 :deadline ,deadline
398 :timestamp ,timestamp
399 :clock ,clock
400 :post-blank ,(count-lines contents-end end)
401 :footnote-section-p ,footnote-section-p
402 :archivedp ,archivedp
403 :commentedp ,commentedp
404 :quotedp ,quotedp
405 ,@standard-props)))))
407 (defun org-element-headline-interpreter (headline contents)
408 "Interpret HEADLINE element as Org syntax.
409 CONTENTS is the contents of the element."
410 (let* ((level (org-element-get-property :level headline))
411 (todo (org-element-get-property :todo-keyword headline))
412 (priority (org-element-get-property :priority headline))
413 (title (org-element-get-property :raw-value headline))
414 (tags (let ((tag-string (org-element-get-property :tags headline))
415 (archivedp (org-element-get-property :archivedp headline)))
416 (cond
417 ((and (not tag-string) archivedp)
418 (format ":%s:" org-archive-tag))
419 (archivedp (concat ":" org-archive-tag tag-string))
420 (t tag-string))))
421 (commentedp (org-element-get-property :commentedp headline))
422 (quotedp (org-element-get-property :quotedp headline))
423 (pre-blank (org-element-get-property :pre-blank headline))
424 (heading (concat (make-string level ?*)
425 (and todo (concat " " todo))
426 (and quotedp (concat " " org-quote-string))
427 (and commentedp (concat " " org-comment-string))
428 (and priority (concat " " priority))
429 (cond ((and org-footnote-section
430 (org-element-get-property
431 :footnote-section-p headline))
432 (concat " " org-footnote-section))
433 (title (concat " " title)))))
434 ;; Align tags.
435 (tags-fmt (when tags
436 (let ((tags-len (length tags)))
437 (format "%% %ds"
438 (cond
439 ((zerop org-tags-column) (1+ tags-len))
440 ((< org-tags-column 0)
441 (max (- (+ org-tags-column (length heading)))
442 (1+ tags-len)))
443 (t (max (+ (- org-tags-column (length heading))
444 tags-len)
445 (1+ tags-len)))))))))
446 (concat heading (and tags (format tags-fmt tags))
447 (make-string (1+ pre-blank) 10)
448 contents)))
451 ;;;; Inlinetask
453 (defun org-element-inlinetask-parser ()
454 "Parse an inline task.
456 Return a list whose car is `inlinetask' and cdr is a plist
457 containing `:raw-value', `:title', `:begin', `:end', `:hiddenp',
458 `:contents-begin' and `:contents-end', `:level', `:priority',
459 `:raw-value', `:tags', `:todo-keyword', `:todo-type',
460 `:scheduled', `:deadline', `:timestamp', `:clock' and
461 `:post-blank' keywords.
463 The plist also contains any property set in the property drawer,
464 with its name in lowercase, the underscores replaced with hyphens
465 and colons at the beginning (i.e. `:custom-id').
467 Assume point is at beginning of the inline task."
468 (save-excursion
469 (let* ((keywords (org-element-collect-affiliated-keywords))
470 (begin (car keywords))
471 (components (org-heading-components))
472 (todo (nth 2 components))
473 (todo-type (and todo
474 (if (member todo org-done-keywords) 'done 'todo)))
475 (raw-value (nth 4 components))
476 (standard-props (let (plist)
477 (mapc
478 (lambda (p)
479 (let ((p-name (downcase (car p))))
480 (while (string-match "_" p-name)
481 (setq p-name
482 (replace-match "-" nil nil p-name)))
483 (setq p-name (intern (concat ":" p-name)))
484 (setq plist
485 (plist-put plist p-name (cdr p)))))
486 (org-entry-properties nil 'standard))
487 plist))
488 (time-props (org-entry-properties nil 'special "CLOCK"))
489 (scheduled (cdr (assoc "SCHEDULED" time-props)))
490 (deadline (cdr (assoc "DEADLINE" time-props)))
491 (clock (cdr (assoc "CLOCK" time-props)))
492 (timestamp (cdr (assoc "TIMESTAMP" time-props)))
493 (title (org-element-parse-secondary-string
494 raw-value
495 (cdr (assq 'inlinetask org-element-string-restrictions))))
496 (contents-begin (save-excursion (forward-line) (point)))
497 (hidden (org-truely-invisible-p))
498 (pos-before-blank (org-inlinetask-goto-end))
499 ;; In the case of a single line task, CONTENTS-BEGIN and
500 ;; CONTENTS-END might overlap.
501 (contents-end (max contents-begin
502 (save-excursion (forward-line -1) (point))))
503 (end (progn (org-skip-whitespace)
504 (if (eobp) (point) (point-at-bol)))))
505 `(inlinetask
506 (:raw-value ,raw-value
507 :title ,title
508 :begin ,begin
509 :end ,end
510 :hiddenp ,(and (> contents-end contents-begin) hidden)
511 :contents-begin ,contents-begin
512 :contents-end ,contents-end
513 :level ,(nth 1 components)
514 :priority ,(nth 3 components)
515 :tags ,(nth 5 components)
516 :todo-keyword ,todo
517 :todo-type ,todo-type
518 :scheduled ,scheduled
519 :deadline ,deadline
520 :timestamp ,timestamp
521 :clock ,clock
522 :post-blank ,(count-lines pos-before-blank end)
523 ,@standard-props
524 ,@(cadr keywords))))))
526 (defun org-element-inlinetask-interpreter (inlinetask contents)
527 "Interpret INLINETASK element as Org syntax.
528 CONTENTS is the contents of inlinetask."
529 (let* ((level (org-element-get-property :level inlinetask))
530 (todo (org-element-get-property :todo-keyword inlinetask))
531 (priority (org-element-get-property :priority inlinetask))
532 (title (org-element-get-property :raw-value inlinetask))
533 (tags (org-element-get-property :tags inlinetask))
534 (task (concat (make-string level ?*)
535 (and todo (concat " " todo))
536 (and priority (concat " " priority))
537 (and title (concat " " title))))
538 ;; Align tags.
539 (tags-fmt (when tags
540 (format "%% %ds"
541 (cond
542 ((zerop org-tags-column) 1)
543 ((< 0 org-tags-column)
544 (max (+ org-tags-column
545 (length inlinetask)
546 (length tags))
548 (t (max (- org-tags-column (length inlinetask))
549 1)))))))
550 (concat inlinetask (and tags (format tags-fmt tags) "\n" contents))))
553 ;;;; Item
555 (defun org-element-item-parser (struct)
556 "Parse an item.
558 STRUCT is the structure of the plain list.
560 Return a list whose car is `item' and cdr is a plist containing
561 `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
562 `:checkbox', `:counter', `:tag', `:raw-tag', `:structure',
563 `:hiddenp' and `:post-blank' keywords.
565 Assume point is at the beginning of the item."
566 (save-excursion
567 (beginning-of-line)
568 (let* ((begin (point))
569 (bullet (org-list-get-bullet (point) struct))
570 (checkbox (let ((box (org-list-get-checkbox begin struct)))
571 (cond ((equal "[ ]" box) 'off)
572 ((equal "[X]" box) 'on)
573 ((equal "[-]" box) 'trans))))
574 (counter (let ((c (org-list-get-counter begin struct)))
575 (cond
576 ((not c) nil)
577 ((string-match "[A-Za-z]" c)
578 (- (string-to-char (upcase (match-string 0 c)))
579 64))
580 ((string-match "[0-9]+" c)
581 (string-to-number (match-string 0 c))))))
582 (raw-tag (org-list-get-tag begin struct))
583 (tag (and raw-tag
584 (org-element-parse-secondary-string
585 raw-tag
586 (cdr (assq 'item org-element-string-restrictions)))))
587 (end (org-list-get-item-end begin struct))
588 (contents-begin (progn (looking-at org-list-full-item-re)
589 (goto-char (match-end 0))
590 (org-skip-whitespace)
591 ;; If first line isn't empty,
592 ;; contents really start at the text
593 ;; after item's meta-data.
594 (if (= (point-at-bol) begin) (point)
595 (point-at-bol))))
596 (hidden (progn (forward-line)
597 (and (not (= (point) end))
598 (org-truely-invisible-p))))
599 (contents-end (progn (goto-char end)
600 (skip-chars-backward " \r\t\n")
601 (forward-line)
602 (point))))
603 `(item
604 (:bullet ,bullet
605 :begin ,begin
606 :end ,end
607 ;; CONTENTS-BEGIN and CONTENTS-END may be mixed
608 ;; up in the case of an empty item separated
609 ;; from the next by a blank line. Thus, ensure
610 ;; the former is always the smallest of two.
611 :contents-begin ,(min contents-begin contents-end)
612 :contents-end ,(max contents-begin contents-end)
613 :checkbox ,checkbox
614 :counter ,counter
615 :raw-tag ,raw-tag
616 :tag ,tag
617 :hiddenp ,hidden
618 :structure ,struct
619 :post-blank ,(count-lines contents-end end))))))
621 (defun org-element-item-interpreter (item contents)
622 "Interpret ITEM element as Org syntax.
623 CONTENTS is the contents of the element."
624 (let* ((bullet (org-element-get-property :bullet item))
625 (checkbox (org-element-get-property :checkbox item))
626 (counter (org-element-get-property :counter item))
627 (tag (org-element-get-property :raw-tag item))
628 ;; Compute indentation.
629 (ind (make-string (length bullet) 32)))
630 ;; Indent contents.
631 (concat
632 bullet
633 (when (and org-list-two-spaces-after-bullet-regexp
634 (string-match org-list-two-spaces-after-bullet-regexp bullet))
635 " ")
636 (and counter (format "[@%d] " counter))
637 (cond
638 ((eq checkbox 'on) "[X] ")
639 ((eq checkbox 'off) "[ ] ")
640 ((eq checkbox 'trans) "[-] "))
641 (and tag (format "%s :: " tag))
642 (org-trim
643 (replace-regexp-in-string
644 "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))))
647 ;;;; Plain List
649 (defun org-element-plain-list-parser (&optional structure)
650 "Parse a plain list.
652 Optional argument STRUCTURE, when non-nil, is the structure of
653 the plain list being parsed.
655 Return a list whose car is `plain-list' and cdr is a plist
656 containing `:type', `:begin', `:end', `:contents-begin' and
657 `:contents-end', `:level', `:structure' and `:post-blank'
658 keywords.
660 Assume point is at one of the list items."
661 (save-excursion
662 (let* ((struct (or structure (org-list-struct)))
663 (prevs (org-list-prevs-alist struct))
664 (parents (org-list-parents-alist struct))
665 (type (org-list-get-list-type (point) struct prevs))
666 (contents-begin (goto-char
667 (org-list-get-list-begin (point) struct prevs)))
668 (keywords (org-element-collect-affiliated-keywords))
669 (begin (car keywords))
670 (contents-end (goto-char
671 (org-list-get-list-end (point) struct prevs)))
672 (end (save-excursion (org-skip-whitespace)
673 (if (eobp) (point) (point-at-bol))))
674 (level 0))
675 ;; Get list level.
676 (let ((item contents-begin))
677 (while (setq item
678 (org-list-get-parent
679 (org-list-get-list-begin item struct prevs)
680 struct parents))
681 (incf level)))
682 ;; Blank lines below list belong to the top-level list only.
683 (when (> level 0)
684 (setq end (min (org-list-get-bottom-point struct)
685 (progn (org-skip-whitespace)
686 (if (eobp) (point) (point-at-bol))))))
687 ;; Return value.
688 `(plain-list
689 (:type ,type
690 :begin ,begin
691 :end ,end
692 :contents-begin ,contents-begin
693 :contents-end ,contents-end
694 :level ,level
695 :structure ,struct
696 :post-blank ,(count-lines contents-end end)
697 ,@(cadr keywords))))))
699 (defun org-element-plain-list-interpreter (plain-list contents)
700 "Interpret PLAIN-LIST element as Org syntax.
701 CONTENTS is the contents of the element."
702 contents)
705 ;;;; Quote Block
707 (defun org-element-quote-block-parser ()
708 "Parse a quote block.
710 Return a list whose car is `quote-block' and cdr is a plist
711 containing `:begin', `:end', `:hiddenp', `:contents-begin',
712 `:contents-end' and `:post-blank' keywords.
714 Assume point is at beginning or end of the block."
715 (save-excursion
716 (let* ((case-fold-search t)
717 (keywords (progn
718 (end-of-line)
719 (re-search-backward
720 (concat "^[ \t]*#\\+begin_quote") nil t)
721 (org-element-collect-affiliated-keywords)))
722 (begin (car keywords))
723 (contents-begin (progn (forward-line) (point)))
724 (hidden (org-truely-invisible-p))
725 (contents-end (progn (re-search-forward
726 (concat "^[ \t]*#\\+end_quote") nil t)
727 (point-at-bol)))
728 (pos-before-blank (progn (forward-line) (point)))
729 (end (progn (org-skip-whitespace)
730 (if (eobp) (point) (point-at-bol)))))
731 `(quote-block
732 (:begin ,begin
733 :end ,end
734 :hiddenp ,hidden
735 :contents-begin ,contents-begin
736 :contents-end ,contents-end
737 :post-blank ,(count-lines pos-before-blank end)
738 ,@(cadr keywords))))))
740 (defun org-element-quote-block-interpreter (quote-block contents)
741 "Interpret QUOTE-BLOCK element as Org syntax.
742 CONTENTS is the contents of the element."
743 (format "#+begin_quote\n%s#+end_quote" contents))
746 ;;;; Section
748 (defun org-element-section-parser ()
749 "Parse a section.
751 Return a list whose car is `section' and cdr is a plist
752 containing `:begin', `:end', `:contents-begin', `contents-end'
753 and `:post-blank' keywords."
754 (save-excursion
755 ;; Beginning of section is the beginning of the first non-blank
756 ;; line after previous headline.
757 (org-with-limited-levels
758 (let ((begin
759 (save-excursion
760 (outline-previous-heading)
761 (if (not (org-at-heading-p)) (point)
762 (forward-line) (org-skip-whitespace) (point-at-bol))))
763 (end (progn (outline-next-heading) (point)))
764 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
765 (forward-line)
766 (point))))
767 `(section
768 (:begin ,begin
769 :end ,end
770 :contents-begin ,begin
771 :contents-end ,pos-before-blank
772 :post-blank ,(count-lines pos-before-blank end)))))))
774 (defun org-element-section-interpreter (section contents)
775 "Interpret SECTION element as Org syntax.
776 CONTENTS is the contents of the element."
777 contents)
780 ;;;; Special Block
782 (defun org-element-special-block-parser ()
783 "Parse a special block.
785 Return a list whose car is `special-block' and cdr is a plist
786 containing `:type', `:begin', `:end', `:hiddenp',
787 `:contents-begin', `:contents-end' and `:post-blank' keywords.
789 Assume point is at beginning or end of the block."
790 (save-excursion
791 (let* ((case-fold-search t)
792 (type (progn (looking-at
793 "[ \t]*#\\+\\(?:begin\\|end\\)_\\([-A-Za-z0-9]+\\)")
794 (org-match-string-no-properties 1)))
795 (keywords (progn
796 (end-of-line)
797 (re-search-backward
798 (concat "^[ \t]*#\\+begin_" type) nil t)
799 (org-element-collect-affiliated-keywords)))
800 (begin (car keywords))
801 (contents-begin (progn (forward-line) (point)))
802 (hidden (org-truely-invisible-p))
803 (contents-end (progn (re-search-forward
804 (concat "^[ \t]*#\\+end_" type) nil t)
805 (point-at-bol)))
806 (pos-before-blank (progn (forward-line) (point)))
807 (end (progn (org-skip-whitespace)
808 (if (eobp) (point) (point-at-bol)))))
809 `(special-block
810 (:type ,type
811 :begin ,begin
812 :end ,end
813 :hiddenp ,hidden
814 :contents-begin ,contents-begin
815 :contents-end ,contents-end
816 :post-blank ,(count-lines pos-before-blank end)
817 ,@(cadr keywords))))))
819 (defun org-element-special-block-interpreter (special-block contents)
820 "Interpret SPECIAL-BLOCK element as Org syntax.
821 CONTENTS is the contents of the element."
822 (let ((block-type (org-element-get-property :type special-block)))
823 (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
827 ;;; Elements
829 ;; For each element, a parser and an interpreter are also defined.
830 ;; Both follow the same naming convention used for greater elements.
832 ;; Also, as for greater elements, adding a new element type is done
833 ;; through the following steps: implement a parser and an interpreter,
834 ;; tweak `org-element-guess-type' so that it recognizes the new type
835 ;; and add that new type to `org-element-all-elements'.
837 ;; As a special case, when the newly defined type is a block type,
838 ;; `org-element-non-recursive-block-alist' has to be modified
839 ;; accordingly.
842 ;;;; Babel Call
844 (defun org-element-babel-call-parser ()
845 "Parse a babel call.
847 Return a list whose car is `babel-call' and cdr is a plist
848 containing `:begin', `:end', `:info' and `:post-blank' as
849 keywords."
850 (save-excursion
851 (let ((info (progn (looking-at org-babel-block-lob-one-liner-regexp)
852 (org-babel-lob-get-info)))
853 (beg (point-at-bol))
854 (pos-before-blank (progn (forward-line) (point)))
855 (end (progn (org-skip-whitespace)
856 (if (eobp) (point) (point-at-bol)))))
857 `(babel-call
858 (:beg ,beg
859 :end ,end
860 :info ,info
861 :post-blank ,(count-lines pos-before-blank end))))))
863 (defun org-element-babel-call-interpreter (inline-babel-call contents)
864 "Interpret INLINE-BABEL-CALL object as Org syntax.
865 CONTENTS is nil."
866 (let* ((babel-info (org-element-get-property :info inline-babel-call))
867 (main-source (car babel-info))
868 (post-options (nth 1 babel-info)))
869 (concat "#+call: "
870 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
871 ;; Remove redundant square brackets.
872 (replace-match
873 (match-string 1 main-source) nil nil main-source)
874 main-source)
875 (and post-options (format "[%s]" post-options)))))
878 ;;;; Comment
880 (defun org-element-comment-parser ()
881 "Parse a comment.
883 Return a list whose car is `comment' and cdr is a plist
884 containing `:begin', `:end', `:value' and `:post-blank'
885 keywords."
886 (let (beg-coms begin end end-coms keywords)
887 (save-excursion
888 (if (looking-at "#")
889 ;; First type of comment: comments at column 0.
890 (let ((comment-re "^\\([^#]\\|#\\+[a-z]\\)"))
891 (save-excursion
892 (re-search-backward comment-re nil 'move)
893 (if (bobp) (setq keywords nil beg-coms (point))
894 (forward-line)
895 (setq keywords (org-element-collect-affiliated-keywords)
896 beg-coms (point))))
897 (re-search-forward comment-re nil 'move)
898 (setq end-coms (if (eobp) (point) (match-beginning 0))))
899 ;; Second type of comment: indented comments.
900 (let ((comment-re "[ \t]*#\\+\\(?: \\|$\\)"))
901 (unless (bobp)
902 (while (and (not (bobp)) (looking-at comment-re))
903 (forward-line -1))
904 (unless (looking-at comment-re) (forward-line)))
905 (setq beg-coms (point))
906 (setq keywords (org-element-collect-affiliated-keywords))
907 ;; Get comments ending. This may not be accurate if
908 ;; commented lines within an item are followed by commented
909 ;; lines outside of the list. Though, parser will always
910 ;; get it right as it already knows surrounding element and
911 ;; has narrowed buffer to its contents.
912 (while (looking-at comment-re) (forward-line))
913 (setq end-coms (point))))
914 ;; Find position after blank.
915 (goto-char end-coms)
916 (org-skip-whitespace)
917 (setq end (if (eobp) (point) (point-at-bol))))
918 `(comment
919 (:begin ,(or (car keywords) beg-coms)
920 :end ,end
921 :value ,(buffer-substring-no-properties beg-coms end-coms)
922 :post-blank ,(count-lines end-coms end)
923 ,@(cadr keywords)))))
925 (defun org-element-comment-interpreter (comment contents)
926 "Interpret COMMENT element as Org syntax.
927 CONTENTS is nil."
928 (org-element-get-property :value comment))
931 ;;;; Comment Block
933 (defun org-element-comment-block-parser ()
934 "Parse an export block.
936 Return a list whose car is `comment-block' and cdr is a plist
937 containing `:begin', `:end', `:hiddenp', `:value' and
938 `:post-blank' keywords."
939 (save-excursion
940 (end-of-line)
941 (let* ((case-fold-search t)
942 (keywords (progn
943 (re-search-backward "^[ \t]*#\\+begin_comment" nil t)
944 (org-element-collect-affiliated-keywords)))
945 (begin (car keywords))
946 (contents-begin (progn (forward-line) (point)))
947 (hidden (org-truely-invisible-p))
948 (contents-end (progn (re-search-forward
949 "^[ \t]*#\\+end_comment" nil t)
950 (point-at-bol)))
951 (pos-before-blank (progn (forward-line) (point)))
952 (end (progn (org-skip-whitespace)
953 (if (eobp) (point) (point-at-bol))))
954 (value (buffer-substring-no-properties contents-begin contents-end)))
955 `(comment-block
956 (:begin ,begin
957 :end ,end
958 :value ,value
959 :hiddenp ,hidden
960 :post-blank ,(count-lines pos-before-blank end)
961 ,@(cadr keywords))))))
963 (defun org-element-comment-block-interpreter (comment-block contents)
964 "Interpret COMMENT-BLOCK element as Org syntax.
965 CONTENTS is nil."
966 (concat "#+begin_comment\n"
967 (org-remove-indentation
968 (org-element-get-property :value comment-block))
969 "#+begin_comment"))
972 ;;;; Example Block
974 (defun org-element-example-block-parser ()
975 "Parse an example block.
977 Return a list whose car is `example' and cdr is a plist
978 containing `:begin', `:end', `:options', `:hiddenp', `:value' and
979 `:post-blank' keywords."
980 (save-excursion
981 (end-of-line)
982 (let* ((case-fold-search t)
983 (switches (progn
984 (re-search-backward
985 "^[ \t]*#\\+begin_example\\(?: +\\(.*\\)\\)?" nil t)
986 (org-match-string-no-properties 1)))
987 (keywords (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
992 (re-search-forward "^[ \t]*#\\+end_example" nil t)
993 (point-at-bol)))
994 (value (buffer-substring-no-properties contents-begin contents-end))
995 (pos-before-blank (progn (forward-line) (point)))
996 (end (progn (org-skip-whitespace)
997 (if (eobp) (point) (point-at-bol)))))
998 `(example-block
999 (:begin ,begin
1000 :end ,end
1001 :value ,value
1002 :switches ,switches
1003 :hiddenp ,hidden
1004 :post-blank ,(count-lines pos-before-blank end)
1005 ,@(cadr keywords))))))
1007 (defun org-element-example-block-interpreter (example-block contents)
1008 "Interpret EXAMPLE-BLOCK element as Org syntax.
1009 CONTENTS is nil."
1010 (let ((options (org-element-get-property :options example-block)))
1011 (concat "#+begin_example" (and options (concat " " options)) "\n"
1012 (org-remove-indentation
1013 (org-element-get-property :value example-block))
1014 "#+end_example")))
1017 ;;;; Export Block
1019 (defun org-element-export-block-parser ()
1020 "Parse an export block.
1022 Return a list whose car is `export-block' and cdr is a plist
1023 containing `:begin', `:end', `:type', `:hiddenp', `:value' and
1024 `:post-blank' keywords."
1025 (save-excursion
1026 (end-of-line)
1027 (let* ((case-fold-search t)
1028 (contents)
1029 (type (progn (re-search-backward
1030 (concat "[ \t]*#\\+begin_"
1031 (org-re "\\([[:alnum:]]+\\)")))
1032 (downcase (org-match-string-no-properties 1))))
1033 (keywords (org-element-collect-affiliated-keywords))
1034 (begin (car keywords))
1035 (contents-begin (progn (forward-line) (point)))
1036 (hidden (org-truely-invisible-p))
1037 (contents-end (progn (re-search-forward
1038 (concat "^[ \t]*#\\+end_" type) nil t)
1039 (point-at-bol)))
1040 (pos-before-blank (progn (forward-line) (point)))
1041 (end (progn (org-skip-whitespace)
1042 (if (eobp) (point) (point-at-bol))))
1043 (value (buffer-substring-no-properties contents-begin contents-end)))
1044 `(export-block
1045 (:begin ,begin
1046 :end ,end
1047 :type ,type
1048 :value ,value
1049 :hiddenp ,hidden
1050 :post-blank ,(count-lines pos-before-blank end)
1051 ,@(cadr keywords))))))
1053 (defun org-element-export-block-interpreter (export-block contents)
1054 "Interpret EXPORT-BLOCK element as Org syntax.
1055 CONTENTS is nil."
1056 (let ((type (org-element-get-property :type export-block)))
1057 (concat (format "#+begin_%s\n" type)
1058 (org-element-get-property :value export-block)
1059 (format "#+end_%s" type))))
1062 ;;;; Fixed-width
1064 (defun org-element-fixed-width-parser ()
1065 "Parse a fixed-width section.
1067 Return a list whose car is `fixed-width' and cdr is a plist
1068 containing `:begin', `:end', `:value' and `:post-blank'
1069 keywords."
1070 (let ((fixed-re "[ \t]*:\\( \\|$\\)")
1071 beg-area begin end value pos-before-blank keywords)
1072 (save-excursion
1073 ;; Move to the beginning of the fixed-width area.
1074 (unless (bobp)
1075 (while (and (not (bobp)) (looking-at fixed-re))
1076 (forward-line -1))
1077 (unless (looking-at fixed-re) (forward-line 1)))
1078 (setq beg-area (point))
1079 ;; Get affiliated keywords, if any.
1080 (setq keywords (org-element-collect-affiliated-keywords))
1081 ;; Store true beginning of element.
1082 (setq begin (car keywords))
1083 ;; Get ending of fixed-width area. If point is in a list,
1084 ;; ensure to not get outside of it.
1085 (let* ((itemp (org-in-item-p))
1086 (max-pos (if itemp
1087 (org-list-get-bottom-point
1088 (save-excursion (goto-char itemp) (org-list-struct)))
1089 (point-max))))
1090 (while (and (looking-at fixed-re) (< (point) max-pos))
1091 (forward-line)))
1092 (setq pos-before-blank (point))
1093 ;; Find position after blank
1094 (org-skip-whitespace)
1095 (setq end (if (eobp) (point) (point-at-bol)))
1096 ;; Extract value.
1097 (setq value (buffer-substring-no-properties beg-area pos-before-blank)))
1098 `(fixed-width
1099 (:begin ,begin
1100 :end ,end
1101 :value ,value
1102 :post-blank ,(count-lines pos-before-blank end)
1103 ,@(cadr keywords)))))
1105 (defun org-element-fixed-width-interpreter (fixed-width contents)
1106 "Interpret FIXED-WIDTH element as Org syntax.
1107 CONTENTS is nil."
1108 (org-remove-indentation (org-element-get-property :value fixed-width)))
1111 ;;;; Horizontal Rule
1113 (defun org-element-horizontal-rule-parser ()
1114 "Parse an horizontal rule.
1116 Return a list whose car is `horizontal-rule' and cdr is
1117 a plist containing `:begin', `:end' and `:post-blank'
1118 keywords."
1119 (save-excursion
1120 (let* ((keywords (org-element-collect-affiliated-keywords))
1121 (begin (car keywords))
1122 (post-hr (progn (forward-line) (point)))
1123 (end (progn (org-skip-whitespace)
1124 (if (eobp) (point) (point-at-bol)))))
1125 `(horizontal-rule
1126 (:begin ,begin
1127 :end ,end
1128 :post-blank ,(count-lines post-hr end)
1129 ,@(cadr keywords))))))
1131 (defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
1132 "Interpret HORIZONTAL-RULE element as Org syntax.
1133 CONTENTS is nil."
1134 "-----")
1137 ;;;; Keyword
1139 (defun org-element-keyword-parser ()
1140 "Parse a keyword at point.
1142 Return a list whose car is `keyword' and cdr is a plist
1143 containing `:key', `:value', `:begin', `:end' and `:post-blank'
1144 keywords."
1145 (save-excursion
1146 (let* ((begin (point))
1147 (key (progn (looking-at
1148 "[ \t]*#\\+\\(\\(?:[a-z]+\\)\\(?:_[a-z]+\\)*\\):")
1149 (org-match-string-no-properties 1)))
1150 (value (org-trim (buffer-substring-no-properties
1151 (match-end 0) (point-at-eol))))
1152 (pos-before-blank (progn (forward-line) (point)))
1153 (end (progn (org-skip-whitespace)
1154 (if (eobp) (point) (point-at-bol)))))
1155 `(keyword
1156 (:key ,key
1157 :value ,value
1158 :begin ,begin
1159 :end ,end
1160 :post-blank ,(count-lines pos-before-blank end))))))
1162 (defun org-element-keyword-interpreter (keyword contents)
1163 "Interpret KEYWORD element as Org syntax.
1164 CONTENTS is nil."
1165 (format "#+%s: %s"
1166 (org-element-get-property :key keyword)
1167 (org-element-get-property :value keyword)))
1170 ;;;; Latex Environment
1172 (defun org-element-latex-environment-parser ()
1173 "Parse a LaTeX environment.
1175 Return a list whose car is `latex-environment' and cdr is a plist
1176 containing `:begin', `:end', `:value' and `:post-blank' keywords."
1177 (save-excursion
1178 (end-of-line)
1179 (let* ((case-fold-search t)
1180 (contents-begin (re-search-backward "^[ \t]*\\\\begin" nil t))
1181 (keywords (org-element-collect-affiliated-keywords))
1182 (begin (car keywords))
1183 (contents-end (progn (re-search-forward "^[ \t]*\\\\end")
1184 (forward-line)
1185 (point)))
1186 (value (buffer-substring-no-properties contents-begin contents-end))
1187 (end (progn (org-skip-whitespace)
1188 (if (eobp) (point) (point-at-bol)))))
1189 `(latex-environment
1190 (:begin ,begin
1191 :end ,end
1192 :value ,value
1193 :post-blank ,(count-lines contents-end end)
1194 ,@(cadr keywords))))))
1196 (defun org-element-latex-environment-interpreter (latex-environment contents)
1197 "Interpret LATEX-ENVIRONMENT element as Org syntax.
1198 CONTENTS is nil."
1199 (org-element-get-property :value latex-environment))
1202 ;;;; Paragraph
1204 (defun org-element-paragraph-parser ()
1205 "Parse a paragraph.
1207 Return a list whose car is `paragraph' and cdr is a plist
1208 containing `:begin', `:end', `:contents-begin' and
1209 `:contents-end' and `:post-blank' keywords.
1211 Assume point is at the beginning of the paragraph."
1212 (save-excursion
1213 (let* ((contents-begin (point))
1214 (keywords (org-element-collect-affiliated-keywords))
1215 (begin (car keywords))
1216 (contents-end (progn
1217 (end-of-line)
1218 (if (re-search-forward
1219 org-element-paragraph-separate nil 'm)
1220 (progn (forward-line -1) (end-of-line) (point))
1221 (point))))
1222 (pos-before-blank (progn (forward-line) (point)))
1223 (end (progn (org-skip-whitespace)
1224 (if (eobp) (point) (point-at-bol)))))
1225 `(paragraph
1226 (:begin ,begin
1227 :end ,end
1228 :contents-begin ,contents-begin
1229 :contents-end ,contents-end
1230 :post-blank ,(count-lines pos-before-blank end)
1231 ,@(cadr keywords))))))
1233 (defun org-element-paragraph-interpreter (paragraph contents)
1234 "Interpret PARAGRAPH element as Org syntax.
1235 CONTENTS is the contents of the element."
1236 contents)
1239 ;;;; Property Drawer
1241 (defun org-element-property-drawer-parser ()
1242 "Parse a property drawer.
1244 Return a list whose car is `property-drawer' and cdr is a plist
1245 containing `:begin', `:end', `:hiddenp', `:contents-begin',
1246 `:contents-end', `:properties' and `:post-blank' keywords."
1247 (save-excursion
1248 (let ((case-fold-search t)
1249 (begin (progn (end-of-line)
1250 (re-search-backward org-property-start-re)
1251 (match-beginning 0)))
1252 (contents-begin (progn (forward-line) (point)))
1253 (hidden (org-truely-invisible-p))
1254 (properties (let (val)
1255 (while (not (looking-at "^[ \t]*:END:"))
1256 (when (looking-at
1257 (org-re
1258 "[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):"))
1259 (push (cons (match-string 1)
1260 (org-trim
1261 (buffer-substring
1262 (match-end 0) (point-at-eol))))
1263 val))
1264 (forward-line))
1265 val))
1266 (contents-end (progn (re-search-forward "^[ \t]*:END:" nil t)
1267 (point-at-bol)))
1268 (pos-before-blank (progn (forward-line) (point)))
1269 (end (progn (org-skip-whitespace)
1270 (if (eobp) (point) (point-at-bol)))))
1271 `(property-drawer
1272 (:begin ,begin
1273 :end ,end
1274 :hiddenp ,hidden
1275 :properties ,properties
1276 :post-blank ,(count-lines pos-before-blank end))))))
1278 (defun org-element-property-drawer-interpreter (property-drawer contents)
1279 "Interpret PROPERTY-DRAWER element as Org syntax.
1280 CONTENTS is nil."
1281 (let ((props (org-element-get-property :properties property-drawer)))
1282 (concat
1283 ":PROPERTIES:\n"
1284 (mapconcat (lambda (p)
1285 (format org-property-format (format ":%s:" (car p)) (cdr p)))
1286 (nreverse props) "\n")
1287 "\n:END:")))
1290 ;;;; Quote Section
1292 (defun org-element-quote-section-parser ()
1293 "Parse a quote section.
1295 Return a list whose car is `quote-section' and cdr is a plist
1296 containing `:begin', `:end', `:value' and `:post-blank'
1297 keywords.
1299 Assume point is at beginning of the section."
1300 (save-excursion
1301 (let* ((begin (point))
1302 (end (progn (org-with-limited-levels (outline-next-heading))
1303 (point)))
1304 (pos-before-blank (progn (skip-chars-backward " \r\t\n")
1305 (forward-line)
1306 (point)))
1307 (value (buffer-substring-no-properties begin pos-before-blank)))
1308 `(quote-section
1309 (:begin ,begin
1310 :end ,end
1311 :value ,value
1312 :post-blank ,(count-lines pos-before-blank end))))))
1314 (defun org-element-quote-section-interpreter (quote-section contents)
1315 "Interpret QUOTE-SECTION element as Org syntax.
1316 CONTENTS is nil."
1317 (org-element-get-property :value quote-section))
1320 ;;;; Src Block
1322 (defun org-element-src-block-parser ()
1323 "Parse a src block.
1325 Return a list whose car is `src-block' and cdr is a plist
1326 containing `:language', `:switches', `:parameters', `:begin',
1327 `:end', `:hiddenp', `:contents-begin', `:contents-end', `:value'
1328 and `:post-blank' keywords."
1329 (save-excursion
1330 (end-of-line)
1331 (let* ((case-fold-search t)
1332 ;; Get position at beginning of block.
1333 (contents-begin
1334 (re-search-backward
1335 (concat "^[ \t]*#\\+begin_src"
1336 "\\(?: +\\(\\S-+\\)\\)?" ; language
1337 "\\(\\(?: +[-+][A-Za-z]\\)*\\)" ; switches
1338 "\\(.*\\)[ \t]*$") ; arguments
1339 nil t))
1340 ;; Get language as a string.
1341 (language (org-match-string-no-properties 1))
1342 ;; Get switches.
1343 (switches (org-match-string-no-properties 2))
1344 ;; Get parameters.
1345 (parameters (org-trim (org-match-string-no-properties 3)))
1346 ;; Get affiliated keywords.
1347 (keywords (org-element-collect-affiliated-keywords))
1348 ;; Get beginning position.
1349 (begin (car keywords))
1350 ;; Get position at end of block.
1351 (contents-end (progn (re-search-forward "^[ \t]*#\\+end_src" nil t)
1352 (forward-line)
1353 (point)))
1354 ;; Retrieve code.
1355 (value (buffer-substring-no-properties
1356 (save-excursion (goto-char contents-begin)
1357 (forward-line)
1358 (point))
1359 (match-beginning 0)))
1360 ;; Get position after ending blank lines.
1361 (end (progn (org-skip-whitespace)
1362 (if (eobp) (point) (point-at-bol))))
1363 ;; Get visibility status.
1364 (hidden (progn (goto-char contents-begin)
1365 (forward-line)
1366 (org-truely-invisible-p))))
1367 `(src-block
1368 (:language ,language
1369 :switches ,switches
1370 :parameters ,parameters
1371 :begin ,begin
1372 :end ,end
1373 :hiddenp ,hidden
1374 :value ,value
1375 :post-blank ,(count-lines contents-end end)
1376 ,@(cadr keywords))))))
1378 (defun org-element-src-block-interpreter (src-block contents)
1379 "Interpret SRC-BLOCK element as Org syntax.
1380 CONTENTS is nil."
1381 (let ((lang (org-element-get-property :language src-block))
1382 (switches (org-element-get-property :switches src-block))
1383 (params (org-element-get-property :parameters src-block))
1384 (value (let ((val (org-element-get-property :value src-block)))
1385 (cond
1386 (org-src-preserve-indentation val)
1387 ((zerop org-edit-src-content-indentation)
1388 (org-remove-indentation val))
1390 (let ((ind (make-string
1391 org-edit-src-content-indentation 32)))
1392 (replace-regexp-in-string
1393 "\\(^\\)[ \t]*\\S-" ind
1394 (org-remove-indentation val) nil nil 1)))))))
1395 (concat (format "#+begin_src%s\n"
1396 (concat (and lang (concat " " lang))
1397 (and switches (concat " " switches))
1398 (and params (concat " " params))))
1399 value
1400 "#+end_src")))
1403 ;;;; Table
1405 (defun org-element-table-parser ()
1406 "Parse a table at point.
1408 Return a list whose car is `table' and cdr is a plist containing
1409 `:begin', `:end', `:contents-begin', `:contents-end', `:tblfm',
1410 `:type', `:raw-table' and `:post-blank' keywords."
1411 (save-excursion
1412 (let* ((table-begin (goto-char (org-table-begin t)))
1413 (type (if (org-at-table.el-p) 'table.el 'org))
1414 (keywords (org-element-collect-affiliated-keywords))
1415 (begin (car keywords))
1416 (table-end (goto-char (marker-position (org-table-end t))))
1417 (tblfm (when (looking-at "[ \t]*#\\+tblfm: +\\(.*\\)[ \t]*")
1418 (prog1 (org-match-string-no-properties 1)
1419 (forward-line))))
1420 (pos-before-blank (point))
1421 (end (progn (org-skip-whitespace)
1422 (if (eobp) (point) (point-at-bol))))
1423 (raw-table (org-remove-indentation
1424 (buffer-substring-no-properties table-begin table-end))))
1425 `(table
1426 (:begin ,begin
1427 :end ,end
1428 :type ,type
1429 :raw-table ,raw-table
1430 :tblfm ,tblfm
1431 :post-blank ,(count-lines pos-before-blank end)
1432 ,@(cadr keywords))))))
1434 (defun org-element-table-interpreter (table contents)
1435 "Interpret TABLE element as Org syntax.
1436 CONTENTS is nil."
1437 (org-element-get-property :raw-table table))
1440 ;;;; Verse Block
1442 (defun org-element-verse-block-parser ()
1443 "Parse a verse block.
1445 Return a list whose car is `verse-block' and cdr is a plist
1446 containing `:begin', `:end', `:hiddenp', `:raw-value', `:value'
1447 and `:post-blank' keywords.
1449 Assume point is at beginning or end of the block."
1450 (save-excursion
1451 (let* ((case-fold-search t)
1452 (keywords (progn
1453 (end-of-line)
1454 (re-search-backward
1455 (concat "^[ \t]*#\\+begin_verse") nil t)
1456 (org-element-collect-affiliated-keywords)))
1457 (begin (car keywords))
1458 (hidden (progn (forward-line) (org-truely-invisible-p)))
1459 (raw-val (buffer-substring-no-properties
1460 (point)
1461 (progn
1462 (re-search-forward (concat "^[ \t]*#\\+end_verse") nil t)
1463 (point-at-bol))))
1464 (pos-before-blank (progn (forward-line) (point)))
1465 (end (progn (org-skip-whitespace)
1466 (if (eobp) (point) (point-at-bol))))
1467 (value (org-element-parse-secondary-string
1468 (org-remove-indentation raw-val)
1469 (cdr (assq 'verse-block org-element-string-restrictions)))))
1470 `(verse-block
1471 (:begin ,begin
1472 :end ,end
1473 :hiddenp ,hidden
1474 :raw-value ,raw-val
1475 :value ,value
1476 :post-blank ,(count-lines pos-before-blank end)
1477 ,@(cadr keywords))))))
1479 (defun org-element-verse-block-interpreter (verse-block contents)
1480 "Interpret VERSE-BLOCK element as Org syntax.
1481 CONTENTS is nil."
1482 (format "#+begin_verse\n%s#+end_verse"
1483 (org-remove-indentation
1484 (org-element-get-property :raw-value verse-block))))
1488 ;;; Objects
1490 ;; Unlike to elements, interstices can be found between objects.
1491 ;; That's why, along with the parser, successor functions are provided
1492 ;; for each object. Some objects share the same successor
1493 ;; (i.e. `emphasis' and `verbatim' objects).
1495 ;; A successor must accept a single argument bounding the search. It
1496 ;; will return either a cons cell whose car is the object's type, as
1497 ;; a symbol, and cdr the position of its next occurrence, or nil.
1499 ;; Successors follow the naming convention:
1500 ;; org-element-NAME-successor, where NAME is the name of the
1501 ;; successor, as defined in `org-element-all-successors'.
1503 ;; Some object types (i.e. `emphasis') are recursive. Restrictions on
1504 ;; object types they can contain will be specified in
1505 ;; `org-element-object-restrictions'.
1507 ;; Adding a new type of object is simple. Implement a successor,
1508 ;; a parser, and an interpreter for it, all following the naming
1509 ;; convention. Register successor in `org-element-all-successors',
1510 ;; maybe tweak restrictions about it, and that's it.
1512 ;;;; Emphasis
1514 (defun org-element-emphasis-parser ()
1515 "Parse text markup object at point.
1517 Return a list whose car is `emphasis' and cdr is a plist with
1518 `:marker', `:begin', `:end', `:contents-begin' and
1519 `:contents-end' and `:post-blank' keywords.
1521 Assume point is at the first emphasis marker."
1522 (save-excursion
1523 (unless (bolp) (backward-char 1))
1524 (looking-at org-emph-re)
1525 (let ((begin (match-beginning 2))
1526 (marker (org-match-string-no-properties 3))
1527 (contents-begin (match-beginning 4))
1528 (contents-end (match-end 4))
1529 (post-blank (progn (goto-char (match-end 2))
1530 (skip-chars-forward " \t")))
1531 (end (point)))
1532 `(emphasis
1533 (:marker ,marker
1534 :begin ,begin
1535 :end ,end
1536 :contents-begin ,contents-begin
1537 :contents-end ,contents-end
1538 :post-blank ,post-blank)))))
1540 (defun org-element-emphasis-interpreter (emphasis contents)
1541 "Interpret EMPHASIS object as Org syntax.
1542 CONTENTS is the contents of the object."
1543 (let ((marker (org-element-get-property :marker emphasis)))
1544 (concat marker contents marker)))
1546 (defun org-element-text-markup-successor (limit)
1547 "Search for the next emphasis or verbatim object.
1549 LIMIT bounds the search.
1551 Return value is a cons cell whose car is `emphasis' or
1552 `verbatim' and cdr is beginning position."
1553 (save-excursion
1554 (unless (bolp) (backward-char))
1555 (when (re-search-forward org-emph-re limit t)
1556 (cons (if (nth 4 (assoc (match-string 3) org-emphasis-alist))
1557 'verbatim
1558 'emphasis)
1559 (match-beginning 2)))))
1561 ;;;; Entity
1563 (defun org-element-entity-parser ()
1564 "Parse entity at point.
1566 Return a list whose car is `entity' and cdr a plist with
1567 `:begin', `:end', `:latex', `:latex-math-p', `:html', `:latin1',
1568 `:utf-8', `:ascii', `:use-brackets-p' and `:post-blank' as
1569 keywords.
1571 Assume point is at the beginning of the entity."
1572 (save-excursion
1573 (looking-at "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")
1574 (let* ((value (org-entity-get (match-string 1)))
1575 (begin (match-beginning 0))
1576 (bracketsp (string= (match-string 2) "{}"))
1577 (post-blank (progn (goto-char (match-end 1))
1578 (when bracketsp (forward-char 2))
1579 (skip-chars-forward " \t")))
1580 (end (point)))
1581 `(entity
1582 (:name ,(car value)
1583 :latex ,(nth 1 value)
1584 :latex-math-p ,(nth 2 value)
1585 :html ,(nth 3 value)
1586 :ascii ,(nth 4 value)
1587 :latin1 ,(nth 5 value)
1588 :utf-8 ,(nth 6 value)
1589 :begin ,begin
1590 :end ,end
1591 :use-brackets-p ,bracketsp
1592 :post-blank ,post-blank)))))
1594 (defun org-element-entity-interpreter (entity contents)
1595 "Interpret ENTITY object as Org syntax.
1596 CONTENTS is nil."
1597 (concat "\\"
1598 (org-element-get-property :name entity)
1599 (when (org-element-get-property :use-brackets-p entity) "{}")))
1601 (defun org-element-latex-or-entity-successor (limit)
1602 "Search for the next latex-fragment or entity object.
1604 LIMIT bounds the search.
1606 Return value is a cons cell whose car is `entity' or
1607 `latex-fragment' and cdr is beginning position."
1608 (save-excursion
1609 (let ((matchers (plist-get org-format-latex-options :matchers))
1610 ;; ENTITY-RE matches both LaTeX commands and Org entities.
1611 (entity-re
1612 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"))
1613 (when (re-search-forward
1614 (concat (mapconcat (lambda (e) (nth 1 (assoc e org-latex-regexps)))
1615 matchers "\\|")
1616 "\\|" entity-re)
1617 limit t)
1618 (goto-char (match-beginning 0))
1619 (if (looking-at entity-re)
1620 ;; Determine if it's a real entity or a LaTeX command.
1621 (cons (if (org-entity-get (match-string 1)) 'entity 'latex-fragment)
1622 (match-beginning 0))
1623 ;; No entity nor command: point is at a LaTeX fragment.
1624 ;; Determine its type to get the correct beginning position.
1625 (cons 'latex-fragment
1626 (catch 'return
1627 (mapc (lambda (e)
1628 (when (looking-at (nth 1 (assoc e org-latex-regexps)))
1629 (throw 'return
1630 (match-beginning
1631 (nth 2 (assoc e org-latex-regexps))))))
1632 matchers)
1633 (point))))))))
1636 ;;;; Export Snippet
1638 (defun org-element-export-snippet-parser ()
1639 "Parse export snippet at point.
1641 Return a list whose car is `export-snippet' and cdr a plist with
1642 `:begin', `:end', `:back-end', `:value' and `:post-blank' as
1643 keywords.
1645 Assume point is at the beginning of the snippet."
1646 (save-excursion
1647 (looking-at "@\\([-A-Za-z0-9]+\\){")
1648 (let* ((begin (point))
1649 (back-end (org-match-string-no-properties 1))
1650 (before-blank (progn (goto-char (scan-sexps (1- (match-end 0)) 1))))
1651 (value (buffer-substring-no-properties
1652 (match-end 0) (1- before-blank)))
1653 (post-blank (skip-chars-forward " \t"))
1654 (end (point)))
1655 `(export-snippet
1656 (:back-end ,back-end
1657 :value ,value
1658 :begin ,begin
1659 :end ,end
1660 :post-blank ,post-blank)))))
1662 (defun org-element-export-snippet-interpreter (export-snippet contents)
1663 "Interpret EXPORT-SNIPPET object as Org syntax.
1664 CONTENTS is nil."
1665 (format "@%s{%s}"
1666 (org-element-get-property :back-end export-snippet)
1667 (org-element-get-property :value export-snippet)))
1669 (defun org-element-export-snippet-successor (limit)
1670 "Search for the next export-snippet object.
1672 LIMIT bounds the search.
1674 Return value is a cons cell whose car is `export-snippet' cdr is
1675 its beginning position."
1676 (save-excursion
1677 (catch 'exit
1678 (while (re-search-forward "@[-A-Za-z0-9]+{" limit t)
1679 (when (let ((end (ignore-errors (scan-sexps (1- (point)) 1))))
1680 (and end (eq (char-before end) ?})))
1681 (throw 'exit (cons 'export-snippet (match-beginning 0))))))))
1684 ;;;; Footnote Reference
1686 (defun org-element-footnote-reference-parser ()
1687 "Parse footnote reference at point.
1689 Return a list whose car is `footnote-reference' and cdr a plist
1690 with `:label', `:type', `:definition', `:begin', `:end' and
1691 `:post-blank' as keywords."
1692 (save-excursion
1693 (let* ((ref (org-footnote-at-reference-p))
1694 (label (car ref))
1695 (raw-def (nth 3 ref))
1696 (inline-def (and raw-def
1697 (org-element-parse-secondary-string raw-def nil)))
1698 (type (if (nth 3 ref) 'inline 'standard))
1699 (begin (nth 1 ref))
1700 (post-blank (progn (goto-char (nth 2 ref))
1701 (skip-chars-forward " \t")))
1702 (end (point)))
1703 `(footnote-reference
1704 (:label ,label
1705 :type ,type
1706 :inline-definition ,inline-def
1707 :begin ,begin
1708 :end ,end
1709 :post-blank ,post-blank
1710 :raw-definition ,raw-def)))))
1712 (defun org-element-footnote-reference-interpreter (footnote-reference contents)
1713 "Interpret FOOTNOTE-REFERENCE object as Org syntax.
1714 CONTENTS is nil."
1715 (let ((label (or (org-element-get-property :label footnote-reference)
1716 "fn:"))
1717 (def (let ((raw (org-element-get-property
1718 :raw-definition footnote-reference)))
1719 (if raw (concat ":" raw) ""))))
1720 (format "[%s]" (concat label def))))
1722 (defun org-element-footnote-reference-successor (limit)
1723 "Search for the next footnote-reference object.
1725 LIMIT bounds the search.
1727 Return value is a cons cell whose car is `footnote-reference' and
1728 cdr is beginning position."
1729 (let (fn-ref)
1730 (when (setq fn-ref (org-footnote-get-next-reference nil nil limit))
1731 (cons 'footnote-reference (nth 1 fn-ref)))))
1734 ;;;; Inline Babel Call
1736 (defun org-element-inline-babel-call-parser ()
1737 "Parse inline babel call at point.
1739 Return a list whose car is `inline-babel-call' and cdr a plist with
1740 `:begin', `:end', `:info' and `:post-blank' as keywords.
1742 Assume point is at the beginning of the babel call."
1743 (save-excursion
1744 (unless (bolp) (backward-char))
1745 (looking-at org-babel-inline-lob-one-liner-regexp)
1746 (let ((info (save-match-data (org-babel-lob-get-info)))
1747 (begin (match-end 1))
1748 (post-blank (progn (goto-char (match-end 0))
1749 (skip-chars-forward " \t")))
1750 (end (point)))
1751 `(inline-babel-call
1752 (:begin ,begin
1753 :end ,end
1754 :info ,info
1755 :post-blank ,post-blank)))))
1757 (defun org-element-inline-babel-call-interpreter (inline-babel-call contents)
1758 "Interpret INLINE-BABEL-CALL object as Org syntax.
1759 CONTENTS is nil."
1760 (let* ((babel-info (org-element-get-property :info inline-babel-call))
1761 (main-source (car babel-info))
1762 (post-options (nth 1 babel-info)))
1763 (concat "call_"
1764 (if (string-match "\\[\\(\\[.*?\\]\\)\\]" main-source)
1765 ;; Remove redundant square brackets.
1766 (replace-match
1767 (match-string 1 main-source) nil nil main-source)
1768 main-source)
1769 (and post-options (format "[%s]" post-options)))))
1771 (defun org-element-inline-babel-call-successor (limit)
1772 "Search for the next inline-babel-call object.
1774 LIMIT bounds the search.
1776 Return value is a cons cell whose car is `inline-babel-call' and
1777 cdr is beginning position."
1778 (save-excursion
1779 ;; Use a simplified version of
1780 ;; org-babel-inline-lob-one-liner-regexp as regexp for more speed.
1781 (when (re-search-forward
1782 "\\(?:babel\\|call\\)_\\([^()\n]+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\([^\n]*\\))\\(\\[\\(.*?\\)\\]\\)?"
1783 limit t)
1784 (cons 'inline-babel-call (match-beginning 0)))))
1787 ;;;; Inline Src Block
1789 (defun org-element-inline-src-block-parser ()
1790 "Parse inline source block at point.
1792 Return a list whose car is `inline-src-block' and cdr a plist
1793 with `:begin', `:end', `:language', `:value', `:parameters' and
1794 `:post-blank' as keywords.
1796 Assume point is at the beginning of the inline src block."
1797 (save-excursion
1798 (unless (bolp) (backward-char))
1799 (looking-at org-babel-inline-src-block-regexp)
1800 (let ((begin (match-beginning 1))
1801 (language (org-match-string-no-properties 2))
1802 (parameters (org-match-string-no-properties 4))
1803 (value (org-match-string-no-properties 5))
1804 (post-blank (progn (goto-char (match-end 0))
1805 (skip-chars-forward " \t")))
1806 (end (point)))
1807 `(inline-src-block
1808 (:language ,language
1809 :value ,value
1810 :parameters ,parameters
1811 :begin ,begin
1812 :end ,end
1813 :post-blank ,post-blank)))))
1815 (defun org-element-inline-src-block-interpreter (inline-src-block contents)
1816 "Interpret INLINE-SRC-BLOCK object as Org syntax.
1817 CONTENTS is nil."
1818 (let ((language (org-element-get-property :language inline-src-block))
1819 (arguments (org-element-get-property :parameters inline-src-block))
1820 (body (org-element-get-property :value inline-src-block)))
1821 (format "src_%s%s{%s}"
1822 language
1823 (if arguments (format "[%s]" arguments) "")
1824 body)))
1826 (defun org-element-inline-src-block-successor (limit)
1827 "Search for the next inline-babel-call element.
1829 LIMIT bounds the search.
1831 Return value is a cons cell whose car is `inline-babel-call' and
1832 cdr is beginning position."
1833 (save-excursion
1834 (when (re-search-forward org-babel-inline-src-block-regexp limit t)
1835 (cons 'inline-src-block (match-beginning 1)))))
1838 ;;;; Latex Fragment
1840 (defun org-element-latex-fragment-parser ()
1841 "Parse latex fragment at point.
1843 Return a list whose car is `latex-fragment' and cdr a plist with
1844 `:value', `:begin', `:end', and `:post-blank' as keywords.
1846 Assume point is at the beginning of the latex fragment."
1847 (save-excursion
1848 (let* ((begin (point))
1849 (substring-match
1850 (catch 'exit
1851 (mapc (lambda (e)
1852 (let ((latex-regexp (nth 1 (assoc e org-latex-regexps))))
1853 (when (or (looking-at latex-regexp)
1854 (and (not (bobp))
1855 (save-excursion
1856 (backward-char)
1857 (looking-at latex-regexp))))
1858 (throw 'exit (nth 2 (assoc e org-latex-regexps))))))
1859 (plist-get org-format-latex-options :matchers))
1860 ;; None found: it's a macro.
1861 (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")
1863 (value (match-string-no-properties substring-match))
1864 (post-blank (progn (goto-char (match-end substring-match))
1865 (skip-chars-forward " \t")))
1866 (end (point)))
1867 `(latex-fragment
1868 (:value ,value
1869 :begin ,begin
1870 :end ,end
1871 :post-blank ,post-blank)))))
1873 (defun org-element-latex-fragment-interpreter (latex-fragment contents)
1874 "Interpret LATEX-FRAGMENT object as Org syntax.
1875 CONTENTS is nil."
1876 (org-element-get-property :value latex-fragment))
1878 ;;;; Line Break
1880 (defun org-element-line-break-parser ()
1881 "Parse line break at point.
1883 Return a list whose car is `line-break', and cdr a plist with
1884 `:begin', `:end' and `:post-blank' keywords.
1886 Assume point is at the beginning of the line break."
1887 (let ((begin (point))
1888 (end (save-excursion (forward-line) (point))))
1889 `(line-break (:begin ,begin :end ,end :post-blank 0))))
1891 (defun org-element-line-break-interpreter (line-break contents)
1892 "Interpret LINE-BREAK object as Org syntax.
1893 CONTENTS is nil."
1894 "\\\\\n")
1896 (defun org-element-line-break-successor (limit)
1897 "Search for the next line-break object.
1899 LIMIT bounds the search.
1901 Return value is a cons cell whose car is `line-break' and cdr is
1902 beginning position."
1903 (save-excursion
1904 (let ((beg (and (re-search-forward "[^\\\\]\\(\\\\\\\\\\)[ \t]*$" limit t)
1905 (goto-char (match-beginning 1)))))
1906 ;; A line break can only happen on a non-empty line.
1907 (when (and beg (re-search-backward "\\S-" (point-at-bol) t))
1908 (cons 'line-break beg)))))
1911 ;;;; Link
1913 (defun org-element-link-parser ()
1914 "Parse link at point.
1916 Return a list whose car is `link' and cdr a plist with `:type',
1917 `:path', `:raw-link', `:begin', `:end', `:contents-begin',
1918 `:contents-end' and `:post-blank' as keywords.
1920 Assume point is at the beginning of the link."
1921 (save-excursion
1922 (let ((begin (point))
1923 end contents-begin contents-end link-end post-blank path type
1924 raw-link link)
1925 (cond
1926 ;; Type 1: Text targeted from a radio target.
1927 ((and org-target-link-regexp (looking-at org-target-link-regexp))
1928 (setq type "radio"
1929 link-end (match-end 0)
1930 path (org-match-string-no-properties 0)))
1931 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
1932 ((looking-at org-bracket-link-regexp)
1933 (setq contents-begin (match-beginning 3)
1934 contents-end (match-end 3)
1935 link-end (match-end 0)
1936 ;; RAW-LINK is the original link.
1937 raw-link (org-match-string-no-properties 1)
1938 link (org-link-expand-abbrev
1939 (replace-regexp-in-string
1940 " *\n *" " " (org-link-unescape raw-link) t t)))
1941 ;; Determine TYPE of link and set PATH accordingly.
1942 (cond
1943 ;; File type.
1944 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
1945 (setq type "file" path link))
1946 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
1947 ((string-match org-link-re-with-space3 link)
1948 (setq type (match-string 1 link) path (match-string 2 link)))
1949 ;; Ref type: PATH is the name of the target element.
1950 ((string-match "^ref:\\(.*\\)" link)
1951 (setq type "ref" path (org-trim (match-string 1 link))))
1952 ;; Id type: PATH is the id.
1953 ((string-match "^id:\\([-a-f0-9]+\\)" link)
1954 (setq type "id" path (match-string 1 link)))
1955 ;; Code-ref type: PATH is the name of the reference.
1956 ((string-match "^(\\(.*\\))$" link)
1957 (setq type "coderef" path (match-string 1 link)))
1958 ;; Custom-id type: PATH is the name of the custom id.
1959 ((= (aref link 0) ?#)
1960 (setq type "custom-id" path (substring link 1)))
1961 ;; Fuzzy type: Internal link either matches a target, an
1962 ;; headline name or nothing. PATH is the target or headline's
1963 ;; name.
1964 (t (setq type "fuzzy" path link))))
1965 ;; Type 3: Plain link, i.e. http://orgmode.org
1966 ((looking-at org-plain-link-re)
1967 (setq raw-link (org-match-string-no-properties 0)
1968 type (org-match-string-no-properties 1)
1969 path (org-match-string-no-properties 2)
1970 link-end (match-end 0)))
1971 ;; Type 4: Angular link, i.e. <http://orgmode.org>
1972 ((looking-at org-angle-link-re)
1973 (setq raw-link (buffer-substring-no-properties
1974 (match-beginning 1) (match-end 2))
1975 type (org-match-string-no-properties 1)
1976 path (org-match-string-no-properties 2)
1977 link-end (match-end 0))))
1978 ;; In any case, deduce end point after trailing white space from
1979 ;; LINK-END variable.
1980 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
1981 end (point))
1982 `(link
1983 (:type ,type
1984 :path ,path
1985 :raw-link ,(or raw-link path)
1986 :begin ,begin
1987 :end ,end
1988 :contents-begin ,contents-begin
1989 :contents-end ,contents-end
1990 :post-blank ,post-blank)))))
1992 (defun org-element-link-interpreter (link contents)
1993 "Interpret LINK object as Org syntax.
1994 CONTENTS is the contents of the object."
1995 (let ((type (org-element-get-property :type link))
1996 (raw-link (org-element-get-property :raw-link link)))
1997 (cond
1998 ((string= type "radio") raw-link)
1999 (t (format "[[%s]%s]"
2000 raw-link
2001 (if (string= contents "") "" (format "[%s]" contents)))))))
2003 (defun org-element-link-successor (limit)
2004 "Search for the next link object.
2006 LIMIT bounds the search.
2008 Return value is a cons cell whose car is `link' and cdr is
2009 beginning position."
2010 (save-excursion
2011 (let ((link-regexp
2012 (if org-target-link-regexp
2013 (concat org-any-link-re "\\|" org-target-link-regexp)
2014 org-any-link-re)))
2015 (when (re-search-forward link-regexp limit t)
2016 (cons 'link (match-beginning 0))))))
2019 ;;;; Macro
2021 (defun org-element-macro-parser ()
2022 "Parse macro at point.
2024 Return a list whose car is `macro' and cdr a plist with `:key',
2025 `:args', `:begin', `:end', `:value' and `:post-blank' as
2026 keywords.
2028 Assume point is at the macro."
2029 (save-excursion
2030 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2031 (let ((begin (point))
2032 (key (downcase (org-match-string-no-properties 1)))
2033 (value (org-match-string-no-properties 0))
2034 (post-blank (progn (goto-char (match-end 0))
2035 (skip-chars-forward " \t")))
2036 (end (point))
2037 (args (let ((args (org-match-string-no-properties 3)) args2)
2038 (when args
2039 (setq args (org-split-string args ","))
2040 (while args
2041 (while (string-match "\\\\\\'" (car args))
2042 ;; Repair bad splits.
2043 (setcar (cdr args) (concat (substring (car args) 0 -1)
2044 "," (nth 1 args)))
2045 (pop args))
2046 (push (pop args) args2))
2047 (mapcar 'org-trim (nreverse args2))))))
2048 `(macro
2049 (:key ,key
2050 :value ,value
2051 :args ,args
2052 :begin ,begin
2053 :end ,end
2054 :post-blank ,post-blank)))))
2056 (defun org-element-macro-interpreter (macro contents)
2057 "Interpret MACRO object as Org syntax.
2058 CONTENTS is nil."
2059 (org-element-get-property :value macro))
2061 (defun org-element-macro-successor (limit)
2062 "Search for the next macro object.
2064 LIMIT bounds the search.
2066 Return value is cons cell whose car is `macro' and cdr is
2067 beginning position."
2068 (save-excursion
2069 (when (re-search-forward
2070 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2071 limit t)
2072 (cons 'macro (match-beginning 0)))))
2075 ;;;; Radio-target
2077 (defun org-element-radio-target-parser ()
2078 "Parse radio target at point.
2080 Return a list whose car is `radio-target' and cdr a plist with
2081 `:begin', `:end', `:contents-begin', `:contents-end', `raw-value'
2082 and `:post-blank' as keywords.
2084 Assume point is at the radio target."
2085 (save-excursion
2086 (looking-at org-radio-target-regexp)
2087 (let ((begin (point))
2088 (contents-begin (match-beginning 1))
2089 (contents-end (match-end 1))
2090 (raw-value (org-match-string-no-properties 1))
2091 (post-blank (progn (goto-char (match-end 0))
2092 (skip-chars-forward " \t")))
2093 (end (point)))
2094 `(radio-target
2095 (:begin ,begin
2096 :end ,end
2097 :contents-begin ,contents-begin
2098 :contents-end ,contents-end
2099 :raw-value ,raw-value
2100 :post-blank ,post-blank)))))
2102 (defun org-element-radio-target-interpreter (target contents)
2103 "Interpret TARGET object as Org syntax.
2104 CONTENTS is the contents of the object."
2105 (concat "<<<" contents ">>>"))
2107 (defun org-element-radio-target-successor (limit)
2108 "Search for the next radio-target object.
2110 LIMIT bounds the search.
2112 Return value is a cons cell whose car is `radio-target' and cdr
2113 is beginning position."
2114 (save-excursion
2115 (when (re-search-forward org-radio-target-regexp limit t)
2116 (cons 'radio-target (match-beginning 0)))))
2119 ;;;; Statistics Cookie
2121 (defun org-element-statistics-cookie-parser ()
2122 "Parse statistics cookie at point.
2124 Return a list whose car is `statistics-cookie', and cdr a plist
2125 with `:begin', `:end', `:value' and `:post-blank' keywords.
2127 Assume point is at the beginning of the statistics-cookie."
2128 (save-excursion
2129 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2130 (let* ((begin (point))
2131 (value (buffer-substring-no-properties
2132 (match-beginning 0) (match-end 0)))
2133 (post-blank (progn (goto-char (match-end 0))
2134 (skip-chars-forward " \t")))
2135 (end (point)))
2136 `(statistics-cookie
2137 (:begin ,begin
2138 :end ,end
2139 :value ,value
2140 :post-blank ,post-blank)))))
2142 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2143 "Interpret STATISTICS-COOKIE object as Org syntax.
2144 CONTENTS is nil."
2145 (org-element-get-property :value statistics-cookie))
2147 (defun org-element-statistics-cookie-successor (limit)
2148 "Search for the next statistics cookie object.
2150 LIMIT bounds the search.
2152 Return value is a cons cell whose car is `statistics-cookie' and
2153 cdr is beginning position."
2154 (save-excursion
2155 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2156 (cons 'statistics-cookie (match-beginning 0)))))
2159 ;;;; Subscript
2161 (defun org-element-subscript-parser ()
2162 "Parse subscript at point.
2164 Return a list whose car is `subscript' and cdr a plist with
2165 `:begin', `:end', `:contents-begin', `:contents-end',
2166 `:use-brackets-p' and `:post-blank' as keywords.
2168 Assume point is at the underscore."
2169 (save-excursion
2170 (unless (bolp) (backward-char))
2171 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2173 (not (looking-at org-match-substring-regexp))))
2174 (begin (match-beginning 2))
2175 (contents-begin (or (match-beginning 5)
2176 (match-beginning 3)))
2177 (contents-end (or (match-end 5) (match-end 3)))
2178 (post-blank (progn (goto-char (match-end 0))
2179 (skip-chars-forward " \t")))
2180 (end (point)))
2181 `(subscript
2182 (:begin ,begin
2183 :end ,end
2184 :use-brackets-p ,bracketsp
2185 :contents-begin ,contents-begin
2186 :contents-end ,contents-end
2187 :post-blank ,post-blank)))))
2189 (defun org-element-subscript-interpreter (subscript contents)
2190 "Interpret SUBSCRIPT object as Org syntax.
2191 CONTENTS is the contents of the object."
2192 (format
2193 (if (org-element-get-property :use-brackets-p subscript) "_{%s}" "_%s")
2194 contents))
2196 (defun org-element-sub/superscript-successor (limit)
2197 "Search for the next sub/superscript object.
2199 LIMIT bounds the search.
2201 Return value is a cons cell whose car is either `subscript' or
2202 `superscript' and cdr is beginning position."
2203 (save-excursion
2204 (when (re-search-forward org-match-substring-regexp limit t)
2205 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2206 (match-beginning 2)))))
2209 ;;;; Superscript
2211 (defun org-element-superscript-parser ()
2212 "Parse superscript at point.
2214 Return a list whose car is `superscript' and cdr a plist with
2215 `:begin', `:end', `:contents-begin', `:contents-end',
2216 `:use-brackets-p' and `:post-blank' as keywords.
2218 Assume point is at the caret."
2219 (save-excursion
2220 (unless (bolp) (backward-char))
2221 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2223 (not (looking-at org-match-substring-regexp))))
2224 (begin (match-beginning 2))
2225 (contents-begin (or (match-beginning 5)
2226 (match-beginning 3)))
2227 (contents-end (or (match-end 5) (match-end 3)))
2228 (post-blank (progn (goto-char (match-end 0))
2229 (skip-chars-forward " \t")))
2230 (end (point)))
2231 `(superscript
2232 (:begin ,begin
2233 :end ,end
2234 :use-brackets-p ,bracketsp
2235 :contents-begin ,contents-begin
2236 :contents-end ,contents-end
2237 :post-blank ,post-blank)))))
2239 (defun org-element-superscript-interpreter (superscript contents)
2240 "Interpret SUPERSCRIPT object as Org syntax.
2241 CONTENTS is the contents of the object."
2242 (format
2243 (if (org-element-get-property :use-brackets-p superscript) "^{%s}" "^%s")
2244 contents))
2247 ;;;; Target
2249 (defun org-element-target-parser ()
2250 "Parse target at point.
2252 Return a list whose car is `target' and cdr a plist with
2253 `:begin', `:end', `:contents-begin', `:contents-end', `raw-value'
2254 and `:post-blank' as keywords.
2256 Assume point is at the target."
2257 (save-excursion
2258 (looking-at org-target-regexp)
2259 (let ((begin (point))
2260 (contents-begin (match-beginning 1))
2261 (contents-end (match-end 1))
2262 (raw-value (org-match-string-no-properties 1))
2263 (post-blank (progn (goto-char (match-end 0))
2264 (skip-chars-forward " \t")))
2265 (end (point)))
2266 `(target
2267 (:begin ,begin
2268 :end ,end
2269 :contents-begin ,contents-begin
2270 :contents-end ,contents-end
2271 :raw-value ,raw-value
2272 :post-blank ,post-blank)))))
2274 (defun org-element-target-interpreter (target contents)
2275 "Interpret TARGET object as Org syntax.
2276 CONTENTS is the contents of target."
2277 (concat ""))
2279 (defun org-element-target-successor (limit)
2280 "Search for the next target object.
2282 LIMIT bounds the search.
2284 Return value is a cons cell whose car is `target' and cdr is
2285 beginning position."
2286 (save-excursion
2287 (when (re-search-forward org-target-regexp limit t)
2288 (cons 'target (match-beginning 0)))))
2291 ;;;; Time-stamp
2293 (defun org-element-time-stamp-parser ()
2294 "Parse time stamp at point.
2296 Return a list whose car is `time-stamp', and cdr a plist with
2297 `:appt-type', `:type', `:begin', `:end', `:value' and
2298 `:post-blank' keywords.
2300 Assume point is at the beginning of the time-stamp."
2301 (save-excursion
2302 (let* ((appt-type (cond
2303 ((looking-at (concat org-deadline-string " +"))
2304 (goto-char (match-end 0))
2305 'deadline)
2306 ((looking-at (concat org-scheduled-string " +"))
2307 (goto-char (match-end 0))
2308 'scheduled)
2309 ((looking-at (concat org-closed-string " +"))
2310 (goto-char (match-end 0))
2311 'closed)))
2312 (begin (and appt-type (match-beginning 0)))
2313 (type (cond
2314 ((looking-at org-tsr-regexp)
2315 (if (match-string 2) 'active-range 'active))
2316 ((looking-at org-tsr-regexp-both)
2317 (if (match-string 2) 'inactive-range 'inactive))
2318 ((looking-at (concat
2319 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2320 "\\|"
2321 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2322 'diary)))
2323 (begin (or begin (match-beginning 0)))
2324 (value (buffer-substring-no-properties
2325 (match-beginning 0) (match-end 0)))
2326 (post-blank (progn (goto-char (match-end 0))
2327 (skip-chars-forward " \t")))
2328 (end (point)))
2329 `(time-stamp
2330 (:appt-type ,appt-type
2331 :type ,type
2332 :value ,value
2333 :begin ,begin
2334 :end ,end
2335 :post-blank ,post-blank)))))
2337 (defun org-element-time-stamp-interpreter (time-stamp contents)
2338 "Interpret TIME-STAMP object as Org syntax.
2339 CONTENTS is nil."
2340 (concat
2341 (case (org-element-get-property :appt-type time-stamp)
2342 (closed (concat org-closed-string " "))
2343 (deadline (concat org-deadline-string " "))
2344 (scheduled (concat org-scheduled-string " ")))
2345 (org-element-get-property :value time-stamp)))
2347 (defun org-element-time-stamp-successor (limit)
2348 "Search for the next time-stamp object.
2350 LIMIT bounds the search.
2352 Return value is a cons cell whose car is `time-stamp' and cdr is
2353 beginning position."
2354 (save-excursion
2355 (when (re-search-forward
2356 (concat "\\(?:" org-scheduled-string " +\\|"
2357 org-deadline-string " +\\|" org-closed-string " +\\)?"
2358 org-ts-regexp-both
2359 "\\|"
2360 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2361 "\\|"
2362 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2363 limit t)
2364 (cons 'time-stamp (match-beginning 0)))))
2367 ;;;; Verbatim
2369 (defun org-element-verbatim-parser ()
2370 "Parse verbatim object at point.
2372 Return a list whose car is `verbatim' and cdr is a plist with
2373 `:marker', `:begin', `:end' and `:post-blank' keywords.
2375 Assume point is at the first verbatim marker."
2376 (save-excursion
2377 (unless (bolp) (backward-char 1))
2378 (looking-at org-emph-re)
2379 (let ((begin (match-beginning 2))
2380 (marker (org-match-string-no-properties 3))
2381 (value (org-match-string-no-properties 4))
2382 (post-blank (progn (goto-char (match-end 2))
2383 (skip-chars-forward " \t")))
2384 (end (point)))
2385 `(verbatim
2386 (:marker ,marker
2387 :begin ,begin
2388 :end ,end
2389 :value ,value
2390 :post-blank ,post-blank)))))
2392 (defun org-element-verbatim-interpreter (verbatim contents)
2393 "Interpret VERBATIM object as Org syntax.
2394 CONTENTS is nil."
2395 (let ((marker (org-element-get-property :marker verbatim))
2396 (value (org-element-get-property :value verbatim)))
2397 (concat marker value marker)))
2401 ;;; Definitions And Rules
2403 ;; Define elements, greater elements and specify recursive objects,
2404 ;; along with the affiliated keywords recognized. Also set up
2405 ;; restrictions on recursive objects combinations.
2407 ;; These variables really act as a control center for the parsing
2408 ;; process.
2409 (defconst org-element-paragraph-separate
2410 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2411 ;; Headlines and inlinetasks.
2412 org-outline-regexp-bol "\\|"
2413 ;; Comments, blocks (any type), keywords and babel calls.
2414 "^[ \t]*#\\+" "\\|" "^#\\( \\|$\\)" "\\|"
2415 ;; Lists.
2416 (org-item-beginning-re) "\\|"
2417 ;; Fixed-width, drawers (any type) and tables.
2418 "^[ \t]*[:|]" "\\|"
2419 ;; Footnote definitions.
2420 org-footnote-definition-re "\\|"
2421 ;; Horizontal rules.
2422 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2423 ;; LaTeX environments.
2424 "^[ \t]*\\\\\\(begin\\|end\\)")
2425 "Regexp to separate paragraphs in an Org buffer.")
2427 (defconst org-element-all-elements
2428 '(center-block comment comment-block drawer dynamic-block example-block
2429 export-block fixed-width footnote-definition headline
2430 horizontal-rule inlinetask item keyword latex-environment
2431 babel-call paragraph plain-list property-drawer quote-block
2432 quote-section section special-block src-block table
2433 verse-block)
2434 "Complete list of elements.")
2436 (defconst org-element-greater-elements
2437 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2438 item plain-list quote-block section special-block)
2439 "List of recursive element types aka Greater Elements.")
2441 (defconst org-element-all-successors
2442 '(export-snippet footnote-reference inline-babel-call inline-src-block
2443 latex-or-entity line-break link macro radio-target
2444 statistics-cookie sub/superscript target text-markup
2445 time-stamp)
2446 "Complete list of successors.")
2448 (defconst org-element-object-successor-alist
2449 '((subscript . sub/superscript) (superscript . sub/superscript)
2450 (emphasis . text-markup) (verbatim . text-markup)
2451 (entity . latex-or-entity) (latex-fragment . latex-or-entity))
2452 "Alist of translations between object type and successor name.
2454 Sharing the same successor comes handy when, for example, the
2455 regexp matching one object can also match the other object.")
2457 (defconst org-element-recursive-objects
2458 '(emphasis link macro subscript superscript target radio-target)
2459 "List of recursive object types.")
2461 (defconst org-element-non-recursive-block-alist
2462 '(("ascii" . export-block)
2463 ("comment" . comment-block)
2464 ("docbook" . export-block)
2465 ("example" . example-block)
2466 ("html" . export-block)
2467 ("latex" . export-block)
2468 ("odt" . export-block)
2469 ("src" . src-block)
2470 ("verse" . verse-block))
2471 "Alist between non-recursive block name and their element type.")
2473 (defconst org-element-affiliated-keywords
2474 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "caption"
2475 "data" "header" "headers" "label" "name" "plot" "resname" "result" "results"
2476 "source" "srcname" "tblname")
2477 "List of affiliated keywords as strings.")
2479 (defconst org-element-keyword-translation-alist
2480 '(("data" . "name") ("label" . "name") ("resname" . "name")
2481 ("source" . "name") ("srcname" . "name") ("tblname" . "name")
2482 ("result" . "results") ("headers" . "header"))
2483 "Alist of usual translations for keywords.
2484 The key is the old name and the value the new one. The property
2485 holding their value will be named after the translated name.")
2487 (defconst org-element-multiple-keywords
2488 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "header")
2489 "List of affiliated keywords that can occur more that once in an element.
2491 Their value will be consed into a list of strings, which will be
2492 returned as the value of the property.
2494 This list is checked after translations have been applied. See
2495 `org-element-keyword-translation-alist'.")
2497 (defconst org-element-parsed-keywords '("author" "caption" "title")
2498 "List of keywords whose value can be parsed.
2500 Their value will be stored as a secondary string: a list of
2501 strings and objects.
2503 This list is checked after translations have been applied. See
2504 `org-element-keyword-translation-alist'.")
2506 (defconst org-element-dual-keywords '("caption" "results")
2507 "List of keywords which can have a secondary value.
2509 In Org syntax, they can be written with optional square brackets
2510 before the colons. For example, results keyword can be
2511 associated to a hash value with the following:
2513 #+results[hash-string]: some-source
2515 This list is checked after translations have been applied. See
2516 `org-element-keyword-translation-alist'.")
2518 (defconst org-element-object-restrictions
2519 '((emphasis entity export-snippet inline-babel-call inline-src-block
2520 radio-target sub/superscript target text-markup time-stamp)
2521 (link entity export-snippet inline-babel-call inline-src-block
2522 latex-fragment link sub/superscript text-markup)
2523 (macro macro)
2524 (radio-target entity export-snippet latex-fragment sub/superscript)
2525 (subscript entity export-snippet inline-babel-call inline-src-block
2526 latex-fragment sub/superscript text-markup)
2527 (superscript entity export-snippet inline-babel-call inline-src-block
2528 latex-fragment sub/superscript text-markup)
2529 (target entity export-snippet latex-fragment sub/superscript text-markup))
2530 "Alist of recursive objects restrictions.
2532 Car is a recursive object type and cdr is a list of successors
2533 that will be called within an object of such type.
2535 For example, in a `radio-target' object, one can only find
2536 entities, export snippets, latex-fragments, subscript and
2537 superscript.")
2539 (defconst org-element-string-restrictions
2540 '((headline entity inline-babel-call latex-fragment link macro radio-target
2541 statistics-cookie sub/superscript text-markup time-stamp)
2542 (inlinetask entity inline-babel-call latex-fragment link macro radio-target
2543 sub/superscript text-markup time-stamp)
2544 (item entity inline-babel-call latex-fragment macro radio-target
2545 sub/superscript target text-markup)
2546 (keyword entity latex-fragment macro sub/superscript text-markup)
2547 (table entity latex-fragment macro target text-markup)
2548 (verse-block entity footnote-reference inline-babel-call inline-src-block
2549 latex-fragment line-break link macro radio-target
2550 sub/superscript target text-markup time-stamp))
2551 "Alist of secondary strings restrictions.
2553 When parsed, some elements have a secondary string which could
2554 contain various objects (i.e. headline's name, or table's cells).
2555 For association, the car is the element type, and the cdr a list
2556 of successors that will be called in that secondary string.
2558 Note: `keyword' secondary string type only applies to keywords
2559 matching `org-element-parsed-keywords'.")
2563 ;;; Accessors
2565 ;; Provide two accessors: `org-element-get-property' and
2566 ;; `org-element-get-contents'.
2568 (defun org-element-get-property (property element)
2569 "Extract the value from the PROPERTY of an ELEMENT."
2570 (plist-get (nth 1 element) property))
2572 (defun org-element-get-contents (element)
2573 "Extract contents from an ELEMENT."
2574 (nthcdr 2 element))
2578 ;; Obtaining The Smallest Element Containing Point
2580 ;; `org-element-at-point' is the core function of this section. It
2581 ;; returns the Lisp representation of the element at point. It uses
2582 ;; `org-element-guess-type' and `org-element-skip-keywords' as helper
2583 ;; functions.
2585 ;; When point is at an item, there is no automatic way to determine if
2586 ;; the function should return the `plain-list' element, or the
2587 ;; corresponding `item' element. By default, `org-element-at-point'
2588 ;; works at the `plain-list' level. But, by providing an optional
2589 ;; argument, one can make it switch to the `item' level.
2591 (defconst org-element--affiliated-re
2592 (format "[ \t]*#\\+\\(%s\\):"
2593 (mapconcat
2594 (lambda (keyword)
2595 (if (member keyword org-element-dual-keywords)
2596 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
2597 (regexp-quote keyword))
2598 (regexp-quote keyword)))
2599 org-element-affiliated-keywords "\\|"))
2600 "Regexp matching any affiliated keyword.
2602 Keyword name is put in match group 1. Moreover, if keyword
2603 belongs to `org-element-dual-keywords', put the dual value in
2604 match group 2.
2606 Don't modify it, set `org-element--affiliated-keywords' instead.")
2608 (defun org-element-at-point (&optional special structure)
2609 "Determine closest element around point.
2611 Return value is a list \(TYPE PROPS\) where TYPE is the type of
2612 the element and PROPS a plist of properties associated to the
2613 element.
2615 Possible types are defined in `org-element-all-elements'.
2617 Optional argument SPECIAL, when non-nil, can be either `item' or
2618 `section'. The former allows to parse item wise instead of
2619 plain-list wise, using STRUCTURE as the current list structure.
2620 The latter will try to parse a section before anything else.
2622 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
2623 be computed."
2624 (save-excursion
2625 (beginning-of-line)
2626 ;; Move before any blank line.
2627 (when (looking-at "[ \t]*$")
2628 (skip-chars-backward " \r\t\n")
2629 (beginning-of-line))
2630 (let ((case-fold-search t))
2631 ;; Check if point is at an affiliated keyword. In that case,
2632 ;; try moving to the beginning of the associated element. If
2633 ;; the keyword is orphaned, treat it as plain text.
2634 (when (looking-at org-element--affiliated-re)
2635 (let ((opoint (point)))
2636 (while (looking-at org-element--affiliated-re) (forward-line))
2637 (when (looking-at "[ \t]*$") (goto-char opoint))))
2638 (let ((type (org-element-guess-type (eq special 'section))))
2639 (cond
2640 ;; Guessing element type on the current line is impossible:
2641 ;; try to find the beginning of the current element to get
2642 ;; more information.
2643 ((not type)
2644 (let ((search-origin (point))
2645 (opoint-in-item-p (org-in-item-p))
2646 (par-found-p
2647 (progn
2648 (end-of-line)
2649 (re-search-backward org-element-paragraph-separate nil 'm))))
2650 (cond
2651 ;; Unable to find a paragraph delimiter above: we're at
2652 ;; bob and looking at a paragraph.
2653 ((not par-found-p) (org-element-paragraph-parser))
2654 ;; Trying to find element's beginning set point back to
2655 ;; its original position. There's something peculiar on
2656 ;; this line that prevents parsing, probably an
2657 ;; ill-formed keyword or an undefined drawer name. Parse
2658 ;; it as plain text anyway.
2659 ((< search-origin (point-at-eol)) (org-element-paragraph-parser))
2660 ;; Original point wasn't in a list but previous paragraph
2661 ;; is. It means that either point was inside some block,
2662 ;; or current list was ended without using a blank line.
2663 ;; In the last case, paragraph really starts at list end.
2664 ((let (item)
2665 (and (not opoint-in-item-p)
2666 (not (looking-at "[ \t]*#\\+begin"))
2667 (setq item (org-in-item-p))
2668 (let ((struct (save-excursion (goto-char item)
2669 (org-list-struct))))
2670 (goto-char (org-list-get-bottom-point struct))
2671 (org-skip-whitespace)
2672 (beginning-of-line)
2673 (org-element-paragraph-parser)))))
2674 ((org-footnote-at-definition-p)
2675 (org-element-footnote-definition-parser))
2676 ((and opoint-in-item-p (org-at-item-p) (= opoint-in-item-p (point)))
2677 (if (eq special 'item)
2678 (org-element-item-parser (or structure (org-list-struct)))
2679 (org-element-plain-list-parser (or structure (org-list-struct)))))
2680 ;; In any other case, the paragraph started the line
2681 ;; below.
2682 (t (forward-line) (org-element-paragraph-parser)))))
2683 ((eq type 'plain-list)
2684 (if (eq special 'item)
2685 (org-element-item-parser (or structure (org-list-struct)))
2686 (org-element-plain-list-parser (or structure (org-list-struct)))))
2687 ;; Straightforward case: call the appropriate parser.
2688 (t (funcall (intern (format "org-element-%s-parser" type)))))))))
2691 ;; It is obvious to tell if point is in most elements, either by
2692 ;; looking for a specific regexp in the current line, or by using
2693 ;; already implemented functions. This is the goal of
2694 ;; `org-element-guess-type'.
2696 (defconst org-element--element-block-types
2697 (mapcar 'car org-element-non-recursive-block-alist)
2698 "List of non-recursive block types, as strings.
2699 Used internally by `org-element-guess-type'. Do not modify it
2700 directly, set `org-element-non-recursive-block-alist' instead.")
2702 (defun org-element-guess-type (&optional section-mode)
2703 "Return the type of element at point, or nil if undetermined.
2705 This function may move point to an appropriate position for
2706 parsing. Used internally by `org-element-at-point'.
2708 When optional argument SECTION-MODE is non-nil, try to find if
2709 point is in a section in priority."
2710 ;; Beware: Order matters for some cases in that function.
2711 (beginning-of-line)
2712 (let ((case-fold-search t))
2713 (cond
2714 ((org-with-limited-levels (org-at-heading-p)) 'headline)
2715 ((let ((headline (ignore-errors (nth 4 (org-heading-components)))))
2716 (and headline
2717 (let (case-fold-search)
2718 (string-match (format "^%s\\(?: \\|$\\)" org-quote-string)
2719 headline))))
2720 ;; Move to section beginning.
2721 (org-back-to-heading t)
2722 (forward-line)
2723 (org-skip-whitespace)
2724 (beginning-of-line)
2725 'quote-section)
2726 ;; Any buffer position not at an headline or in a quote section
2727 ;; is inside a section, provided function is actively looking for
2728 ;; them.
2729 (section-mode 'section)
2730 ;; Non-recursive block.
2731 ((let ((type (org-in-block-p org-element--element-block-types)))
2732 (and type (cdr (assoc type org-element-non-recursive-block-alist)))))
2733 ((org-at-heading-p) 'inlinetask)
2734 ((org-between-regexps-p
2735 "^[ \t]*\\\\begin{" "^[ \t]*\\\\end{[^}]*}[ \t]*") 'latex-environment)
2736 ;; Property drawer. Almost `org-at-property-p', but allow drawer
2737 ;; boundaries.
2738 ((org-with-wide-buffer
2739 (and (not (org-before-first-heading-p))
2740 (let ((pblock (org-get-property-block)))
2741 (and pblock
2742 (<= (point) (cdr pblock))
2743 (>= (point-at-eol) (1- (car pblock)))))))
2744 'property-drawer)
2745 ;; Recursive block. If the block isn't complete, parse the
2746 ;; current part as a paragraph.
2747 ((looking-at "[ \t]*#\\+\\(begin\\|end\\)_\\([-A-Za-z0-9]+\\)\\(?:$\\|\\s-\\)")
2748 (let ((type (downcase (match-string 2))))
2749 (cond
2750 ((not (org-in-block-p (list type))) 'paragraph)
2751 ((string= type "center") 'center-block)
2752 ((string= type "quote") 'quote-block)
2753 (t 'special-block))))
2754 ;; Regular drawers must be tested after property drawer as both
2755 ;; elements share the same ending regexp.
2756 ((or (looking-at org-drawer-regexp) (looking-at "[ \t]*:END:[ \t]*$"))
2757 (let ((completep (org-between-regexps-p
2758 org-drawer-regexp "^[ \t]*:END:[ \t]*$")))
2759 (if (not completep) 'paragraph
2760 (goto-char (car completep)) 'drawer)))
2761 ((looking-at "[ \t]*:\\( \\|$\\)") 'fixed-width)
2762 ;; Babel calls must be tested before general keywords as they are
2763 ;; a subset of them.
2764 ((looking-at org-babel-block-lob-one-liner-regexp) 'babel-call)
2765 ((looking-at org-footnote-definition-re) 'footnote-definition)
2766 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
2767 (if (member (downcase (match-string 1)) org-element-affiliated-keywords)
2768 'paragraph
2769 'keyword))
2770 ;; Dynamic block: simplify regexp used for match. If it isn't
2771 ;; complete, parse the current part as a paragraph.
2772 ((looking-at "[ \t]*#\\+\\(begin\\end\\):\\(?:\\s-\\|$\\)")
2773 (let ((completep (org-between-regexps-p
2774 "^[ \t]*#\\+begin:\\(?:\\s-\\|$\\)"
2775 "^[ \t]*#\\+end:\\(?:\\s-\\|$\\)")))
2776 (if (not completep) 'paragraph
2777 (goto-char (car completep)) 'dynamic-block)))
2778 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)") 'comment)
2779 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$") 'horizontal-rule)
2780 ((org-at-table-p t) 'table)
2781 ((looking-at "[ \t]*#\\+tblfm:")
2782 (forward-line -1)
2783 ;; A TBLFM line separated from any table is just plain text.
2784 (if (org-at-table-p) 'table
2785 (forward-line) 'paragraph))
2786 ((looking-at (org-item-re)) 'plain-list))))
2788 ;; Most elements can have affiliated keywords. When looking for an
2789 ;; element beginning, we want to move before them, as they belong to
2790 ;; that element, and, in the meantime, collect information they give
2791 ;; into appropriate properties. Hence the following function.
2793 ;; Usage of optional arguments may not be obvious at first glance:
2795 ;; - TRANS-LIST is used to polish keywords names that have evolved
2796 ;; during Org history. In example, even though =result= and
2797 ;; =results= coexist, we want to have them under the same =result=
2798 ;; property. It's also true for "srcname" and "name", where the
2799 ;; latter seems to be preferred nowadays (thus the "name" property).
2801 ;; - CONSED allows to regroup multi-lines keywords under the same
2802 ;; property, while preserving their own identity. This is mostly
2803 ;; used for "attr_latex" and al.
2805 ;; - PARSED prepares a keyword value for export. This is useful for
2806 ;; "caption". Objects restrictions for such keywords are defined in
2807 ;; `org-element-string-restrictions'.
2809 ;; - DUALS is used to take care of keywords accepting a main and an
2810 ;; optional secondary values. For example "results" has its
2811 ;; source's name as the main value, and may have an hash string in
2812 ;; optional square brackets as the secondary one.
2814 ;; A keyword may belong to more than one category.
2816 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
2817 consed parsed duals)
2818 "Collect affiliated keywords before point.
2820 Optional argument KEY-RE is a regexp matching keywords, which
2821 puts matched keyword in group 1. It defaults to
2822 `org-element--affiliated-re'.
2824 TRANS-LIST is an alist where key is the keyword and value the
2825 property name it should be translated to, without the colons. It
2826 defaults to `org-element-keyword-translation-alist'.
2828 CONSED is a list of strings. Any keyword belonging to that list
2829 will have its value consed. The check is done after keyword
2830 translation. It defaults to `org-element-multiple-keywords'.
2832 PARSED is a list of strings. Any keyword member of this list
2833 will have its value parsed. The check is done after keyword
2834 translation. If a keyword is a member of both CONSED and PARSED,
2835 it's value will be a list of parsed strings. It defaults to
2836 `org-element-parsed-keywords'.
2838 DUALS is a list of strings. Any keyword member of this list can
2839 have two parts: one mandatory and one optional. Its value is
2840 a cons cell whose car is the former, and the cdr the latter. If
2841 a keyword is a member of both PARSED and DUALS, both values will
2842 be parsed. It defaults to `org-element-dual-keywords'.
2844 Return a list whose car is the position at the first of them and
2845 cdr a plist of keywords and values."
2846 (save-excursion
2847 (let ((case-fold-search t)
2848 (key-re (or key-re org-element--affiliated-re))
2849 (trans-list (or trans-list org-element-keyword-translation-alist))
2850 (consed (or consed org-element-multiple-keywords))
2851 (parsed (or parsed org-element-parsed-keywords))
2852 (duals (or duals org-element-dual-keywords))
2853 ;; RESTRICT is the list of objects allowed in parsed
2854 ;; keywords value.
2855 (restrict (cdr (assq 'keyword org-element-string-restrictions)))
2856 output)
2857 (unless (bobp)
2858 (while (and (not (bobp))
2859 (progn (forward-line -1) (looking-at key-re)))
2860 (let* ((raw-kwd (downcase (or (match-string 2) (match-string 1))))
2861 ;; Apply translation to RAW-KWD. From there, KWD is
2862 ;; the official keyword.
2863 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
2864 ;; Find main value for any keyword.
2865 (value
2866 (save-match-data
2867 (org-trim
2868 (buffer-substring-no-properties
2869 (match-end 0) (point-at-eol)))))
2870 ;; If KWD is a dual keyword, find its secondary
2871 ;; value. Maybe parse it.
2872 (dual-value
2873 (and (member kwd duals)
2874 (let ((sec (org-match-string-no-properties 3)))
2875 (if (or (not sec) (not (member kwd parsed))) sec
2876 (org-element-parse-secondary-string sec restrict)))))
2877 ;; Attribute a property name to KWD.
2878 (kwd-sym (and kwd (intern (concat ":" kwd)))))
2879 ;; Now set final shape for VALUE.
2880 (when (member kwd parsed)
2881 (setq value (org-element-parse-secondary-string value restrict)))
2882 (when (member kwd duals)
2883 ;; VALUE is mandatory. Set it to nil if there is none.
2884 (setq value (and value (cons value dual-value))))
2885 (when (member kwd consed)
2886 (setq value (cons value (plist-get output kwd-sym))))
2887 ;; Eventually store the new value in OUTPUT.
2888 (setq output (plist-put output kwd-sym value))))
2889 (unless (looking-at key-re) (forward-line 1)))
2890 (list (point) output))))
2894 ;;; The Org Parser
2896 ;; The two major functions here are `org-element-parse-buffer', which
2897 ;; parses Org syntax inside the current buffer, taking into account
2898 ;; region, narrowing, or even visibility if specified, and
2899 ;; `org-element-parse-secondary-string', which parses objects within
2900 ;; a given string.
2902 ;; The (almost) almighty `org-element-map' allows to apply a function
2903 ;; on elements or objects matching some type, and accumulate the
2904 ;; resulting values. In an export situation, it also skips unneeded
2905 ;; parts of the parse tree, transparently walks into included files,
2906 ;; and maintain a list of local properties (i.e. those inherited from
2907 ;; parent headlines) for function's consumption.
2909 (defun org-element-parse-buffer (&optional granularity visible-only)
2910 "Recursively parse the buffer and return structure.
2911 If narrowing is in effect, only parse the visible part of the
2912 buffer.
2914 Optional argument GRANULARITY determines the depth of the
2915 recursion. It can be set to the following symbols:
2917 `headline' Only parse headlines.
2918 `greater-element' Don't recurse into greater elements. Thus,
2919 elements parsed are the top-level ones.
2920 `element' Parse everything but objects and plain text.
2921 `object' Parse the complete buffer (default).
2923 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
2924 elements.
2926 Assume buffer is in Org mode."
2927 (save-excursion
2928 (goto-char (point-min))
2929 (org-skip-whitespace)
2930 (nconc (list 'org-data nil)
2931 (org-element-parse-elements
2932 (point-at-bol) (point-max)
2933 ;; Start is section mode so text before the first headline
2934 ;; belongs to a section.
2935 'section nil granularity visible-only nil))))
2937 (defun org-element-parse-secondary-string (string restriction &optional buffer)
2938 "Recursively parse objects in STRING and return structure.
2940 RESTRICTION, when non-nil, is a symbol limiting the object types
2941 that will be looked after.
2943 Optional argument BUFFER indicates the buffer from where the
2944 secondary string was extracted. It is used to determine where to
2945 get extraneous information for an object \(i.e. when resolving
2946 a link or looking for a footnote definition\). It defaults to
2947 the current buffer."
2948 (with-temp-buffer
2949 (insert string)
2950 (org-element-parse-objects (point-min) (point-max) nil restriction)))
2952 (defun org-element-map (data types fun &optional info first-match)
2953 "Map a function on selected elements or objects.
2955 DATA is the parsed tree, as returned by, i.e,
2956 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
2957 of elements or objects types. FUN is the function called on the
2958 matching element or object. It must accept two arguments: the
2959 element or object itself and a plist holding contextual
2960 information.
2962 When optional argument INFO is non-nil, it should be a plist
2963 holding export options. In that case, parts of the parse tree
2964 not exportable according to that property list will be skipped
2965 and files included through a keyword will be visited.
2967 When optional argument FIRST-MATCH is non-nil, stop at the first
2968 match for which FUN doesn't return nil, and return that value.
2970 Nil values returned from FUN are ignored in the result."
2971 ;; Ensure TYPES is a list, even of one element.
2972 (unless (listp types) (setq types (list types)))
2973 ;; Recursion depth is determined by --CATEGORY.
2974 (let* ((--category
2975 (cond
2976 ((loop for type in types
2977 always (memq type org-element-greater-elements))
2978 'greater-elements)
2979 ((loop for type in types
2980 always (memq type org-element-all-elements))
2981 'elements)
2982 (t 'objects)))
2983 walk-tree ; For byte-compiler
2984 --acc
2985 (accumulate-maybe
2986 (function
2987 (lambda (--type types fun --blob --local)
2988 ;; Check if TYPE is matching among TYPES. If so, apply
2989 ;; FUN to --BLOB and accumulate return value
2990 ;; into --ACC. --LOCAL is the communication channel.
2991 (when (memq --type types)
2992 (let ((result (funcall fun --blob --local)))
2993 (cond ((not result))
2994 (first-match (throw 'first-match result))
2995 (t (push result --acc))))))))
2996 (walk-tree
2997 (function
2998 (lambda (--data --local)
2999 ;; Recursively walk DATA. --LOCAL, if non-nil, is
3000 ;; a plist holding contextual information.
3001 (mapc
3002 (lambda (--blob)
3003 (let ((--type (if (stringp --blob) 'plain-text (car --blob))))
3004 ;; Determine if a recursion into --BLOB is
3005 ;; possible and allowed.
3006 (cond
3007 ;; Element or object not exportable.
3008 ((and info (org-export-skip-p --blob info)))
3009 ;; Archived headline: Maybe apply fun on it, but
3010 ;; skip contents.
3011 ((and info
3012 (eq --type 'headline)
3013 (eq (plist-get info :with-archived-trees) 'headline)
3014 (org-element-get-property :archivedp --blob))
3015 (funcall accumulate-maybe --type types fun --blob --local))
3016 ;; Limiting recursion to greater elements, and --BLOB
3017 ;; isn't one.
3018 ((and (eq --category 'greater-elements)
3019 (not (memq --type org-element-greater-elements)))
3020 (funcall accumulate-maybe --type types fun --blob --local))
3021 ;; Limiting recursion to elements, and --BLOB only
3022 ;; contains objects.
3023 ((and (eq --category 'elements) (eq --type 'paragraph)))
3024 ;; No limitation on recursion, but --BLOB hasn't
3025 ;; got a recursive type.
3026 ((and (eq --category 'objects)
3027 (not (or (eq --type 'paragraph)
3028 (memq --type org-element-greater-elements)
3029 (memq --type org-element-recursive-objects))))
3030 (funcall accumulate-maybe --type types fun --blob --local))
3031 ;; Recursion is possible and allowed: Update local
3032 ;; information and move into --BLOB.
3033 (t (funcall accumulate-maybe --type types fun --blob --local)
3034 (funcall
3035 walk-tree --blob
3036 (org-combine-plists
3037 --local
3038 `(:genealogy
3039 ,(cons --blob (plist-get --local :genealogy)))))))))
3040 (org-element-get-contents --data))))))
3041 (catch 'first-match
3042 (funcall walk-tree data info)
3043 ;; Return value in a proper order.
3044 (reverse --acc))))
3046 ;; The following functions are internal parts of the parser.
3048 ;; The first one, `org-element-parse-elements' acts at the element's
3049 ;; level. As point is always at the beginning of an element during
3050 ;; parsing, it doesn't have to rely on `org-element-at-point'.
3051 ;; Instead, it calls a more restrictive, though way quicker,
3052 ;; alternative: `org-element-current-element'. That function
3053 ;; internally uses `org-element--element-block-re' for quick access to
3054 ;; a common regexp.
3056 ;; The second one, `org-element-parse-objects' applies on all objects
3057 ;; of a paragraph or a secondary string. It uses
3058 ;; `org-element-get-candidates' to optimize the search of the next
3059 ;; object in the buffer.
3061 ;; More precisely, that function looks for every allowed object type
3062 ;; first. Then, it discards failed searches, keeps further matches,
3063 ;; and searches again types matched behind point, for subsequent
3064 ;; calls. Thus, searching for a given type fails only once, and every
3065 ;; object is searched only once at top level (but sometimes more for
3066 ;; nested types).
3068 (defun org-element-parse-elements
3069 (beg end special structure granularity visible-only acc)
3070 "Parse elements between BEG and END positions.
3072 SPECIAL prioritize some elements over the others. It can set to
3073 `quote-section', `section' or `item', which will focus search,
3074 respectively, on quote sections, sections and items. Moreover,
3075 when value is `item', STRUCTURE will be used as the current list
3076 structure.
3078 GRANULARITY determines the depth of the recursion. It can be set
3079 to the following symbols:
3081 `headline' Only parse headlines.
3082 `greater-element' Don't recurse into greater elements. Thus,
3083 elements parsed are the top-level ones.
3084 `element' Parse everything but objects and plain text.
3085 `object' or nil Parse the complete buffer.
3087 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3088 elements.
3090 Elements are accumulated into ACC."
3091 (save-excursion
3092 (save-restriction
3093 (narrow-to-region beg end)
3094 (goto-char beg)
3095 ;; When parsing only headlines, skip any text before first one.
3096 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3097 (org-with-limited-levels (outline-next-heading)))
3098 ;; Main loop start.
3099 (while (not (eobp))
3100 (push
3101 ;; 1. Item mode is active: point must be at an item. Parse it
3102 ;; directly, skipping `org-element-current-element'.
3103 (if (eq special 'item)
3104 (let ((element (org-element-item-parser structure)))
3105 (goto-char (org-element-get-property :end element))
3106 (org-element-parse-elements
3107 (org-element-get-property :contents-begin element)
3108 (org-element-get-property :contents-end element)
3109 nil structure granularity visible-only (reverse element)))
3110 ;; 2. When ITEM is nil, find current element's type and parse
3111 ;; it accordingly to its category.
3112 (let ((element (org-element-current-element special structure)))
3113 (goto-char (org-element-get-property :end element))
3114 (cond
3115 ;; Case 1. ELEMENT is a paragraph. Parse objects inside,
3116 ;; if GRANULARITY allows it.
3117 ((and (eq (car element) 'paragraph)
3118 (or (not granularity) (eq granularity 'object)))
3119 (org-element-parse-objects
3120 (org-element-get-property :contents-begin element)
3121 (org-element-get-property :contents-end element)
3122 (reverse element) nil))
3123 ;; Case 2. ELEMENT is recursive: parse it between
3124 ;; `contents-begin' and `contents-end'. Make sure
3125 ;; GRANULARITY allows the recursion, or ELEMENT is an
3126 ;; headline, in which case going inside is mandatory, in
3127 ;; order to get sub-level headings. If VISIBLE-ONLY is
3128 ;; true and element is hidden, do not recurse into it.
3129 ((and (memq (car element) org-element-greater-elements)
3130 (or (not granularity)
3131 (memq granularity '(element object))
3132 (eq (car element) 'headline))
3133 (not (and visible-only
3134 (org-element-get-property :hiddenp element))))
3135 (org-element-parse-elements
3136 (org-element-get-property :contents-begin element)
3137 (org-element-get-property :contents-end element)
3138 ;; At a plain list, switch to item mode. At an
3139 ;; headline, switch to section mode. Any other
3140 ;; element turns off special modes.
3141 (case (car element)
3142 (plain-list 'item)
3143 (headline (if (org-element-get-property :quotedp element)
3144 'quote-section
3145 'section)))
3146 (org-element-get-property :structure element)
3147 granularity visible-only (reverse element)))
3148 ;; Case 3. Else, just accumulate ELEMENT.
3149 (t element))))
3150 acc)))
3151 ;; Return result.
3152 (nreverse acc)))
3154 (defconst org-element--element-block-re
3155 (format "[ \t]*#\\+begin_\\(%s\\)\\(?: \\|$\\)"
3156 (mapconcat
3157 'regexp-quote
3158 (mapcar 'car org-element-non-recursive-block-alist) "\\|"))
3159 "Regexp matching the beginning of a non-recursive block type.
3160 Used internally by `org-element-current-element'. Do not modify
3161 it directly, set `org-element-recursive-block-alist' instead.")
3163 (defun org-element-current-element (&optional special structure)
3164 "Parse the element at point.
3166 Return value is a list \(TYPE PROPS\) where TYPE is the type of
3167 the element and PROPS a plist of properties associated to the
3168 element.
3170 Possible types are defined in `org-element-all-elements'.
3172 Optional argument SPECIAL, when non-nil, can be either `item',
3173 `section' or `quote-section'. `item' allows to parse item wise
3174 instead of plain-list wise, using STRUCTURE as the current list
3175 structure. `section' (resp. `quote-section') will try to parse
3176 a section (resp. a quote section) before anything else.
3178 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3179 be computed.
3181 Unlike to `org-element-at-point', this function assumes point is
3182 always at the beginning of the element it has to parse. As such,
3183 it is quicker than its counterpart and always accurate, albeit
3184 more restrictive."
3185 (save-excursion
3186 (beginning-of-line)
3187 ;; If point is at an affiliated keyword, try moving to the
3188 ;; beginning of the associated element. If none is found, the
3189 ;; keyword is orphaned and will be treated as plain text.
3190 (when (looking-at org-element--affiliated-re)
3191 (let ((opoint (point)))
3192 (while (looking-at org-element--affiliated-re) (forward-line))
3193 (when (looking-at "[ \t]*$") (goto-char opoint))))
3194 (let ((case-fold-search t))
3195 (cond
3196 ;; Headline.
3197 ((org-with-limited-levels (org-at-heading-p))
3198 (org-element-headline-parser))
3199 ;; Quote section.
3200 ((eq special 'quote-section) (org-element-quote-section-parser))
3201 ;; Section.
3202 ((eq special 'section) (org-element-section-parser))
3203 ;; Non-recursive block.
3204 ((when (looking-at org-element--element-block-re)
3205 (let ((type (downcase (match-string 1))))
3206 (if (save-excursion
3207 (re-search-forward
3208 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t))
3209 ;; Build appropriate parser.
3210 (funcall
3211 (intern
3212 (format "org-element-%s-parser"
3213 (cdr (assoc type
3214 org-element-non-recursive-block-alist)))))
3215 (org-element-paragraph-parser)))))
3216 ;; Inlinetask.
3217 ((org-at-heading-p) (org-element-inlinetask-parser))
3218 ;; LaTeX Environment or paragraph if incomplete.
3219 ((looking-at "^[ \t]*\\\\begin{")
3220 (if (save-excursion
3221 (re-search-forward "^[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
3222 (org-element-latex-environment-parser)
3223 (org-element-paragraph-parser)))
3224 ;; Property drawer.
3225 ((looking-at org-property-start-re)
3226 (if (save-excursion (re-search-forward org-property-end-re nil t))
3227 (org-element-property-drawer-parser)
3228 (org-element-paragraph-parser)))
3229 ;; Recursive block, or paragraph if incomplete.
3230 ((looking-at "[ \t]*#\\+begin_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
3231 (let ((type (downcase (match-string 1))))
3232 (cond
3233 ((not (save-excursion
3234 (re-search-forward
3235 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t)))
3236 (org-element-paragraph-parser))
3237 ((string= type "center") (org-element-center-block-parser))
3238 ((string= type "quote") (org-element-quote-block-parser))
3239 (t (org-element-special-block-parser)))))
3240 ;; Drawer.
3241 ((looking-at org-drawer-regexp)
3242 (if (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t))
3243 (org-element-drawer-parser)
3244 (org-element-paragraph-parser)))
3245 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
3246 ;; Babel call.
3247 ((looking-at org-babel-block-lob-one-liner-regexp)
3248 (org-element-babel-call-parser))
3249 ;; Keyword, or paragraph if at an affiliated keyword.
3250 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
3251 (let ((key (downcase (match-string 1))))
3252 (if (or (string= key "tblfm")
3253 (member key org-element-affiliated-keywords))
3254 (org-element-paragraph-parser)
3255 (org-element-keyword-parser))))
3256 ;; Footnote definition.
3257 ((looking-at org-footnote-definition-re)
3258 (org-element-footnote-definition-parser))
3259 ;; Dynamic block or paragraph if incomplete.
3260 ((looking-at "[ \t]*#\\+begin:\\(?: \\|$\\)")
3261 (if (save-excursion
3262 (re-search-forward "^[ \t]*#\\+end:\\(?: \\|$\\)" nil t))
3263 (org-element-dynamic-block-parser)
3264 (org-element-paragraph-parser)))
3265 ;; Comment.
3266 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
3267 (org-element-comment-parser))
3268 ;; Horizontal rule.
3269 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3270 (org-element-horizontal-rule-parser))
3271 ;; Table.
3272 ((org-at-table-p t) (org-element-table-parser))
3273 ;; List or item.
3274 ((looking-at (org-item-re))
3275 (if (eq special 'item)
3276 (org-element-item-parser (or structure (org-list-struct)))
3277 (org-element-plain-list-parser (or structure (org-list-struct)))))
3278 ;; Default element: Paragraph.
3279 (t (org-element-paragraph-parser))))))
3281 (defun org-element-parse-objects (beg end acc restriction)
3282 "Parse objects between BEG and END and return recursive structure.
3284 Objects are accumulated in ACC.
3286 RESTRICTION, when non-nil, is a list of object types which are
3287 allowed in the current object."
3288 (let ((get-next-object
3289 (function
3290 (lambda (cand)
3291 ;; Return the parsing function associated to the nearest
3292 ;; object among list of candidates CAND.
3293 (let ((pos (apply #'min (mapcar #'cdr cand))))
3294 (save-excursion
3295 (goto-char pos)
3296 (funcall
3297 (intern
3298 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3299 next-object candidates)
3300 (save-excursion
3301 (goto-char beg)
3302 (while (setq candidates (org-element-get-next-object-candidates
3303 end restriction candidates))
3304 (setq next-object (funcall get-next-object candidates))
3305 ;; 1. Text before any object. Untabify it.
3306 (let ((obj-beg (org-element-get-property :begin next-object)))
3307 (unless (= (point) obj-beg)
3308 (push (replace-regexp-in-string
3309 "\t" (make-string tab-width ? )
3310 (buffer-substring-no-properties (point) obj-beg))
3311 acc)))
3312 ;; 2. Object...
3313 (let ((obj-end (org-element-get-property :end next-object))
3314 (cont-beg (org-element-get-property :contents-begin next-object)))
3315 (push (if (and (memq (car next-object) org-element-recursive-objects)
3316 cont-beg)
3317 ;; ... recursive. The CONT-BEG check is for
3318 ;; links, as some of them might not be recursive
3319 ;; (i.e. plain links).
3320 (save-restriction
3321 (narrow-to-region
3322 cont-beg
3323 (org-element-get-property :contents-end next-object))
3324 (org-element-parse-objects
3325 (point-min) (point-max) (reverse next-object)
3326 ;; Restrict allowed objects. This is the
3327 ;; intersection of current restriction and next
3328 ;; object's restriction.
3329 (let ((new-restr
3330 (cdr (assq (car next-object)
3331 org-element-object-restrictions))))
3332 (if (not restriction) new-restr
3333 (delq nil (mapcar
3334 (lambda (e) (and (memq e restriction) e))
3335 new-restr))))))
3336 ;; ... not recursive.
3337 next-object)
3338 acc)
3339 (goto-char obj-end)))
3340 ;; 3. Text after last object. Untabify it.
3341 (unless (= (point) end)
3342 (push (replace-regexp-in-string
3343 "\t" (make-string tab-width ? )
3344 (buffer-substring-no-properties (point) end))
3345 acc))
3346 ;; Result.
3347 (nreverse acc))))
3349 (defun org-element-get-next-object-candidates (limit restriction objects)
3350 "Return an alist of candidates for the next object.
3352 LIMIT bounds the search, and RESTRICTION, when non-nil, bounds
3353 the possible object types.
3355 Return value is an alist whose car is position and cdr the object
3356 type, as a string. There is an association for the closest
3357 object of each type within RESTRICTION when non-nil, or for every
3358 type otherwise.
3360 OBJECTS is the previous candidates alist."
3361 (let ((restriction (or restriction org-element-all-successors))
3362 next-candidates types-to-search)
3363 ;; If no previous result, search every object type in RESTRICTION.
3364 ;; Otherwise, keep potential candidates (old objects located after
3365 ;; point) and ask to search again those which had matched before.
3366 (if (not objects) (setq types-to-search restriction)
3367 (mapc (lambda (obj)
3368 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3369 (push obj next-candidates)))
3370 objects))
3371 ;; Call the appropriate "get-next" function for each type to
3372 ;; search and accumulate matches.
3373 (mapc
3374 (lambda (type)
3375 (let* ((successor-fun
3376 (intern
3377 (format "org-element-%s-successor"
3378 (or (cdr (assq type org-element-object-successor-alist))
3379 type))))
3380 (obj (funcall successor-fun limit)))
3381 (and obj (push obj next-candidates))))
3382 types-to-search)
3383 ;; Return alist.
3384 next-candidates))
3388 ;;; Towards A Bijective Process
3390 ;; The parse tree obtained with `org-element-parse-buffer' is really
3391 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3392 ;; interpreted and expanded into a string with canonical Org
3393 ;; syntax. Hence `org-element-interpret-data'.
3395 ;; Data parsed from secondary strings, whose shape is slightly
3396 ;; different than the standard parse tree, is expanded with the
3397 ;; equivalent function `org-element-interpret-secondary'.
3399 ;; Both functions rely internally on
3400 ;; `org-element-interpret--affiliated-keywords'.
3402 (defun org-element-interpret-data (data &optional genealogy previous)
3403 "Interpret a parse tree representing Org data.
3405 DATA is the parse tree to interpret.
3407 Optional arguments GENEALOGY and PREVIOUS are used for recursive
3408 calls:
3409 GENEALOGY is the list of its parents types.
3410 PREVIOUS is the type of the element or object at the same level
3411 interpreted before.
3413 Return Org syntax as a string."
3414 (mapconcat
3415 (lambda (blob)
3416 ;; BLOB can be an element, an object, a string, or nil.
3417 (cond
3418 ((not blob) nil)
3419 ((equal blob "") nil)
3420 ((stringp blob) blob)
3422 (let* ((type (car blob))
3423 (interpreter
3424 (if (eq type 'org-data) 'identity
3425 (intern (format "org-element-%s-interpreter" type))))
3426 (contents
3427 (cond
3428 ;; Full Org document.
3429 ((eq type 'org-data)
3430 (org-element-interpret-data blob genealogy previous))
3431 ;; Recursive objects.
3432 ((memq type org-element-recursive-objects)
3433 (org-element-interpret-data
3434 blob (cons type genealogy) nil))
3435 ;; Recursive elements.
3436 ((memq type org-element-greater-elements)
3437 (org-element-normalize-string
3438 (org-element-interpret-data
3439 blob (cons type genealogy) nil)))
3440 ;; Paragraphs.
3441 ((eq type 'paragraph)
3442 (let ((paragraph
3443 (org-element-normalize-contents
3444 blob
3445 ;; When normalizing contents of an item,
3446 ;; ignore first line's indentation.
3447 (and (not previous)
3448 (memq (car genealogy)
3449 '(footnote-definiton item))))))
3450 (org-element-interpret-data
3451 paragraph (cons type genealogy) nil)))))
3452 (results (funcall interpreter blob contents)))
3453 ;; Update PREVIOUS.
3454 (setq previous type)
3455 ;; Build white spaces.
3456 (cond
3457 ((eq type 'org-data) results)
3458 ((memq type org-element-all-elements)
3459 (concat
3460 (org-element-interpret--affiliated-keywords blob)
3461 (org-element-normalize-string results)
3462 (make-string (org-element-get-property :post-blank blob) 10)))
3463 (t (concat
3464 results
3465 (make-string
3466 (org-element-get-property :post-blank blob) 32))))))))
3467 (org-element-get-contents data) ""))
3469 (defun org-element-interpret-secondary (secondary)
3470 "Interpret SECONDARY string as Org syntax.
3472 SECONDARY-STRING is a nested list as returned by
3473 `org-element-parse-secondary-string'.
3475 Return interpreted string."
3476 ;; Make SECONDARY acceptable for `org-element-interpret-data'.
3477 (let ((s (if (listp secondary) secondary (list secondary))))
3478 (org-element-interpret-data `(org-data nil ,@s) nil nil)))
3480 ;; Both functions internally use `org-element--affiliated-keywords'.
3482 (defun org-element-interpret--affiliated-keywords (element)
3483 "Return ELEMENT's affiliated keywords as Org syntax.
3484 If there is no affiliated keyword, return the empty string."
3485 (let ((keyword-to-org
3486 (function
3487 (lambda (key value)
3488 (let (dual)
3489 (when (member key org-element-dual-keywords)
3490 (setq dual (cdr value) value (car value)))
3491 (concat "#+" key (and dual (format "[%s]" dual)) ": "
3492 (if (member key org-element-parsed-keywords)
3493 (org-element-interpret-secondary value)
3494 value)
3495 "\n"))))))
3496 (mapconcat
3497 (lambda (key)
3498 (let ((value (org-element-get-property (intern (concat ":" key)) element)))
3499 (when value
3500 (if (member key org-element-multiple-keywords)
3501 (mapconcat (lambda (line)
3502 (funcall keyword-to-org key line))
3503 value "")
3504 (funcall keyword-to-org key value)))))
3505 ;; Remove translated keywords.
3506 (delq nil
3507 (mapcar
3508 (lambda (key)
3509 (and (not (assoc key org-element-keyword-translation-alist)) key))
3510 org-element-affiliated-keywords))
3511 "")))
3513 ;; Because interpretation of the parse tree must return the same
3514 ;; number of blank lines between elements and the same number of white
3515 ;; space after objects, some special care must be given to white
3516 ;; spaces.
3518 ;; The first function, `org-element-normalize-string', ensures any
3519 ;; string different from the empty string will end with a single
3520 ;; newline character.
3522 ;; The second function, `org-element-normalize-contents', removes
3523 ;; global indentation from the contents of the current element.
3525 (defun org-element-normalize-string (s)
3526 "Ensure string S ends with a single newline character.
3528 If S isn't a string return it unchanged. If S is the empty
3529 string, return it. Otherwise, return a new string with a single
3530 newline character at its end."
3531 (cond
3532 ((not (stringp s)) s)
3533 ((string= "" s) "")
3534 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3535 (replace-match "\n" nil nil s)))))
3537 (defun org-element-normalize-contents (element &optional ignore-first)
3538 "Normalize plain text in ELEMENT's contents.
3540 ELEMENT must only contain plain text and objects.
3542 The following changes are applied to plain text:
3543 - Remove global indentation, preserving relative one.
3544 - Untabify it.
3546 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3547 indentation to compute maximal common indentation.
3549 Return the normalized element."
3550 (nconc
3551 (list (car element) (nth 1 element))
3552 (let ((contents (org-element-get-contents element)))
3553 (if (not (or ignore-first (stringp (car contents)))) contents
3554 (catch 'exit
3555 ;; 1. Get maximal common indentation (MCI) among each string
3556 ;; in CONTENTS.
3557 (let* ((ind-list (unless ignore-first
3558 (list (org-get-string-indentation (car contents)))))
3559 (contents
3560 (mapcar
3561 (lambda (object)
3562 (if (not (stringp object)) object
3563 (let ((start 0))
3564 (while (string-match "\n\\( *\\)" object start)
3565 (setq start (match-end 0))
3566 (push (length (match-string 1 object)) ind-list))
3567 object)))
3568 contents))
3569 (mci (if ind-list (apply 'min ind-list)
3570 (throw 'exit contents))))
3571 ;; 2. Remove that indentation from CONTENTS. First string
3572 ;; must be treated differently because it's the only one
3573 ;; whose indentation doesn't happen after a newline
3574 ;; character.
3575 (let ((first-obj (car contents)))
3576 (unless (or (not (stringp first-obj)) ignore-first)
3577 (setq contents
3578 (cons (replace-regexp-in-string
3579 (format "\\` \\{%d\\}" mci) "" first-obj)
3580 (cdr contents)))))
3581 (mapcar (lambda (object)
3582 (if (not (stringp object)) object
3583 (replace-regexp-in-string
3584 (format "\n \\{%d\\}" mci) "\n" object)))
3585 contents)))))))
3589 ;;; The Toolbox
3591 ;; Once the structure of an Org file is well understood, it's easy to
3592 ;; implement some replacements for `forward-paragraph'
3593 ;; `backward-paragraph', namely `org-element-forward' and
3594 ;; `org-element-backward'.
3596 ;; Also, `org-transpose-elements' mimics the behaviour of
3597 ;; `transpose-words', at the element's level, whereas
3598 ;; `org-element-drag-forward', `org-element-drag-backward', and
3599 ;; `org-element-up' generalize, respectively, functions
3600 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3602 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3603 ;; smartly remove global indentation from buffer, making it possible
3604 ;; to use Org indent mode on a file created with hard indentation.
3606 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3607 ;; internally by some of the previously cited tools.
3609 (defsubst org-element-nested-p (elem-A elem-B)
3610 "Non-nil when elements ELEM-A and ELEM-B are nested."
3611 (let ((beg-A (org-element-get-property :begin elem-A))
3612 (beg-B (org-element-get-property :begin elem-B))
3613 (end-A (org-element-get-property :end elem-A))
3614 (end-B (org-element-get-property :end elem-B)))
3615 (or (and (>= beg-A beg-B) (<= end-A end-B))
3616 (and (>= beg-B beg-A) (<= end-B end-A)))))
3618 (defun org-element-swap-A-B (elem-A elem-B)
3619 "Swap elements ELEM-A and ELEM-B.
3621 Leave point at the end of ELEM-A.
3623 Assume ELEM-A is before ELEM-B and that they are not nested."
3624 (goto-char (org-element-get-property :begin elem-A))
3625 (let* ((beg-B (org-element-get-property :begin elem-B))
3626 (end-B-no-blank (save-excursion
3627 (goto-char (org-element-get-property :end elem-B))
3628 (skip-chars-backward " \r\t\n")
3629 (forward-line)
3630 (point)))
3631 (beg-A (org-element-get-property :begin elem-A))
3632 (end-A-no-blank (save-excursion
3633 (goto-char (org-element-get-property :end elem-A))
3634 (skip-chars-backward " \r\t\n")
3635 (forward-line)
3636 (point)))
3637 (body-A (buffer-substring beg-A end-A-no-blank))
3638 (body-B (buffer-substring beg-B end-B-no-blank))
3639 (between-A-B (buffer-substring end-A-no-blank beg-B)))
3640 (delete-region beg-A end-B-no-blank)
3641 (insert body-B between-A-B body-A)
3642 (goto-char (org-element-get-property :end elem-B))))
3644 (defun org-element-backward ()
3645 "Move backward by one element."
3646 (interactive)
3647 (let* ((opoint (point))
3648 (element (org-element-at-point))
3649 (start-el-beg (org-element-get-property :begin element)))
3650 ;; At an headline. The previous element is the previous sibling,
3651 ;; or the parent if any.
3652 (cond
3653 ;; Already at the beginning of the current element: move to the
3654 ;; beginning of the previous one.
3655 ((= opoint start-el-beg)
3656 (forward-line -1)
3657 (skip-chars-backward " \r\t\n")
3658 (let* ((prev-element (org-element-at-point))
3659 (itemp (org-in-item-p))
3660 (struct (and itemp
3661 (save-excursion (goto-char itemp)
3662 (org-list-struct)))))
3663 ;; When moving into a new list, go directly at the
3664 ;; beginning of the top list structure.
3665 (if (and itemp (<= (org-list-get-bottom-point struct) opoint))
3666 (progn
3667 (goto-char (org-list-get-top-point struct))
3668 (goto-char (org-element-get-property
3669 :begin (org-element-at-point))))
3670 (goto-char (org-element-get-property :begin prev-element))))
3671 (while (org-truely-invisible-p) (org-element-up)))
3672 ;; Else, move at the element beginning. One exception: if point
3673 ;; was in the blank lines after the end of a list, move directly
3674 ;; to the top item.
3676 (let (struct itemp)
3677 (if (and (setq itemp (org-in-item-p))
3678 (<= (org-list-get-bottom-point
3679 (save-excursion (goto-char itemp)
3680 (setq struct (org-list-struct))))
3681 opoint))
3682 (progn (goto-char (org-list-get-top-point struct))
3683 (goto-char (org-element-get-property
3684 :begin (org-element-at-point))))
3685 (goto-char start-el-beg)))))))
3687 (defun org-element-drag-backward ()
3688 "Drag backward element at point."
3689 (interactive)
3690 (let* ((pos (point))
3691 (elem (org-element-at-point)))
3692 (when (= (progn (goto-char (point-min))
3693 (org-skip-whitespace)
3694 (point-at-bol))
3695 (org-element-get-property :end elem))
3696 (error "Cannot drag element backward"))
3697 (goto-char (org-element-get-property :begin elem))
3698 (org-element-backward)
3699 (let ((prev-elem (org-element-at-point)))
3700 (when (or (org-element-nested-p elem prev-elem)
3701 (and (eq (car elem) 'headline)
3702 (not (eq (car prev-elem) 'headline))))
3703 (goto-char pos)
3704 (error "Cannot drag element backward"))
3705 ;; Compute new position of point: it's shifted by PREV-ELEM
3706 ;; body's length.
3707 (let ((size-prev (- (org-element-get-property :end prev-elem)
3708 (org-element-get-property :begin prev-elem))))
3709 (org-element-swap-A-B prev-elem elem)
3710 (goto-char (- pos size-prev))))))
3712 (defun org-element-drag-forward ()
3713 "Move forward element at point."
3714 (interactive)
3715 (let* ((pos (point))
3716 (elem (org-element-at-point)))
3717 (when (= (point-max) (org-element-get-property :end elem))
3718 (error "Cannot drag element forward"))
3719 (goto-char (org-element-get-property :end elem))
3720 (let ((next-elem (org-element-at-point)))
3721 (when (or (org-element-nested-p elem next-elem)
3722 (and (eq (car next-elem) 'headline)
3723 (not (eq (car elem) 'headline))))
3724 (goto-char pos)
3725 (error "Cannot drag element forward"))
3726 ;; Compute new position of point: it's shifted by NEXT-ELEM
3727 ;; body's length (without final blanks) and by the length of
3728 ;; blanks between ELEM and NEXT-ELEM.
3729 (let ((size-next (- (save-excursion
3730 (goto-char (org-element-get-property :end next-elem))
3731 (skip-chars-backward " \r\t\n")
3732 (forward-line)
3733 (point))
3734 (org-element-get-property :begin next-elem)))
3735 (size-blank (- (org-element-get-property :end elem)
3736 (save-excursion
3737 (goto-char (org-element-get-property :end elem))
3738 (skip-chars-backward " \r\t\n")
3739 (forward-line)
3740 (point)))))
3741 (org-element-swap-A-B elem next-elem)
3742 (goto-char (+ pos size-next size-blank))))))
3744 (defun org-element-forward ()
3745 "Move forward by one element."
3746 (interactive)
3747 (beginning-of-line)
3748 (cond ((eobp) (error "Cannot move further down"))
3749 ((looking-at "[ \t]*$")
3750 (org-skip-whitespace)
3751 (goto-char (if (eobp) (point) (point-at-bol))))
3753 (let ((element (org-element-at-point t))
3754 (origin (point)))
3755 (cond
3756 ;; At an item: Either move to the next element inside, or
3757 ;; to its end if it's hidden.
3758 ((eq (car element) 'item)
3759 (if (org-element-get-property :hiddenp element)
3760 (goto-char (org-element-get-property :end element))
3761 (end-of-line)
3762 (re-search-forward org-element-paragraph-separate nil t)
3763 (org-skip-whitespace)
3764 (beginning-of-line)))
3765 ;; At a recursive element: Either move inside, or if it's
3766 ;; hidden, move to its end.
3767 ((memq (car element) org-element-greater-elements)
3768 (let ((cbeg (org-element-get-property :contents-begin element)))
3769 (goto-char
3770 (if (or (org-element-get-property :hiddenp element)
3771 (> origin cbeg))
3772 (org-element-get-property :end element)
3773 cbeg))))
3774 ;; Else: move to the current element's end.
3775 (t (goto-char (org-element-get-property :end element))))))))
3777 (defun org-element-mark-element ()
3778 "Put point at beginning of this element, mark at end.
3780 Interactively, if this command is repeated or (in Transient Mark
3781 mode) if the mark is active, it marks the next element after the
3782 ones already marked."
3783 (interactive)
3784 (let (deactivate-mark)
3785 (if (or (and (eq last-command this-command) (mark t))
3786 (and transient-mark-mode mark-active))
3787 (set-mark
3788 (save-excursion
3789 (goto-char (mark))
3790 (goto-char (org-element-get-property :end (org-element-at-point)))))
3791 (let ((element (org-element-at-point)))
3792 (end-of-line)
3793 (push-mark (org-element-get-property :end element) t t)
3794 (goto-char (org-element-get-property :begin element))))))
3796 (defun org-narrow-to-element ()
3797 "Narrow buffer to current element."
3798 (interactive)
3799 (let ((elem (org-element-at-point)))
3800 (cond
3801 ((eq (car elem) 'headline)
3802 (narrow-to-region
3803 (org-element-get-property :begin elem)
3804 (org-element-get-property :end elem)))
3805 ((memq (car elem) org-element-greater-elements)
3806 (narrow-to-region
3807 (org-element-get-property :contents-begin elem)
3808 (org-element-get-property :contents-end elem)))
3810 (narrow-to-region
3811 (org-element-get-property :begin elem)
3812 (org-element-get-property :end elem))))))
3814 (defun org-transpose-elements ()
3815 "Transpose current and previous elements, keeping blank lines between.
3816 Point is moved after both elements."
3817 (interactive)
3818 (org-skip-whitespace)
3819 (let ((pos (point))
3820 (cur (org-element-at-point)))
3821 (when (= (save-excursion (goto-char (point-min))
3822 (org-skip-whitespace)
3823 (point-at-bol))
3824 (org-element-get-property :begin cur))
3825 (error "No previous element"))
3826 (goto-char (org-element-get-property :begin cur))
3827 (forward-line -1)
3828 (let ((prev (org-element-at-point)))
3829 (when (org-element-nested-p cur prev)
3830 (goto-char pos)
3831 (error "Cannot transpose nested elements"))
3832 (org-element-swap-A-B prev cur))))
3834 (defun org-element-unindent-buffer ()
3835 "Un-indent the visible part of the buffer.
3836 Relative indentation \(between items, inside blocks, etc.\) isn't
3837 modified."
3838 (interactive)
3839 (unless (eq major-mode 'org-mode)
3840 (error "Cannot un-indent a buffer not in Org mode"))
3841 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
3842 unindent-tree ; For byte-compiler.
3843 (unindent-tree
3844 (function
3845 (lambda (contents)
3846 (mapc (lambda (element)
3847 (if (eq (car element) 'headline)
3848 (funcall unindent-tree
3849 (org-element-get-contents element))
3850 (save-excursion
3851 (save-restriction
3852 (narrow-to-region
3853 (org-element-get-property :begin element)
3854 (org-element-get-property :end element))
3855 (org-do-remove-indentation)))))
3856 (reverse contents))))))
3857 (funcall unindent-tree (org-element-get-contents parse-tree))))
3859 (defun org-element-up ()
3860 "Move to upper element.
3861 Return position at the beginning of the upper element."
3862 (interactive)
3863 (let ((opoint (point)) elem)
3864 (cond
3865 ((bobp) (error "No surrounding element"))
3866 ((org-with-limited-levels (org-at-heading-p))
3867 (or (org-up-heading-safe) (error "No surronding element")))
3868 ((and (org-at-item-p)
3869 (setq elem (org-element-at-point))
3870 (let* ((top-list-p (zerop (org-element-get-property :level elem))))
3871 (unless top-list-p
3872 ;; If parent is bound to be in the same list as the
3873 ;; original point, move to that parent.
3874 (let ((struct (org-element-get-property :structure elem)))
3875 (goto-char
3876 (org-list-get-parent
3877 (point-at-bol) struct (org-list-parents-alist struct))))))))
3879 (let* ((elem (or elem (org-element-at-point)))
3880 (end (save-excursion
3881 (goto-char (org-element-get-property :end elem))
3882 (skip-chars-backward " \r\t\n")
3883 (forward-line)
3884 (point)))
3885 prev-elem)
3886 (goto-char (org-element-get-property :begin elem))
3887 (forward-line -1)
3888 (while (and (< (org-element-get-property
3889 :end (setq prev-elem (org-element-at-point)))
3890 end)
3891 (not (bobp)))
3892 (goto-char (org-element-get-property :begin prev-elem))
3893 (forward-line -1))
3894 (if (and (bobp) (< (org-element-get-property :end prev-elem) end))
3895 (progn (goto-char opoint)
3896 (error "No surrounding element"))
3897 (goto-char (org-element-get-property :begin prev-elem))))))))
3900 (provide 'org-element)
3901 ;;; org-element.el ends here