org-element: Fix item parsing with an empty first line and a child below
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-element.el
blob73687e8f6c9dda35077e5e6923d2a0bc3f829104
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 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 path (org-match-string-no-properties 0)
1930 contents-begin (match-beginning 0)
1931 contents-end (match-end 0)
1932 link-end (match-end 0)))
1933 ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
1934 ((looking-at org-bracket-link-regexp)
1935 (setq contents-begin (match-beginning 3)
1936 contents-end (match-end 3)
1937 link-end (match-end 0)
1938 ;; RAW-LINK is the original link.
1939 raw-link (org-match-string-no-properties 1)
1940 link (org-link-expand-abbrev
1941 (replace-regexp-in-string
1942 " *\n *" " " (org-link-unescape raw-link) t t)))
1943 ;; Determine TYPE of link and set PATH accordingly.
1944 (cond
1945 ;; File type.
1946 ((or (file-name-absolute-p link) (string-match "^\\.\\.?/" link))
1947 (setq type "file" path link))
1948 ;; Explicit type (http, irc, bbdb...). See `org-link-types'.
1949 ((string-match org-link-re-with-space3 link)
1950 (setq type (match-string 1 link) path (match-string 2 link)))
1951 ;; Id type: PATH is the id.
1952 ((string-match "^id:\\([-a-f0-9]+\\)" link)
1953 (setq type "id" path (match-string 1 link)))
1954 ;; Code-ref type: PATH is the name of the reference.
1955 ((string-match "^(\\(.*\\))$" link)
1956 (setq type "coderef" path (match-string 1 link)))
1957 ;; Custom-id type: PATH is the name of the custom id.
1958 ((= (aref link 0) ?#)
1959 (setq type "custom-id" path (substring link 1)))
1960 ;; Fuzzy type: Internal link either matches a target, an
1961 ;; headline name or nothing. PATH is the target or headline's
1962 ;; name.
1963 (t (setq type "fuzzy" path link))))
1964 ;; Type 3: Plain link, i.e. http://orgmode.org
1965 ((looking-at org-plain-link-re)
1966 (setq raw-link (org-match-string-no-properties 0)
1967 type (org-match-string-no-properties 1)
1968 path (org-match-string-no-properties 2)
1969 link-end (match-end 0)))
1970 ;; Type 4: Angular link, i.e. <http://orgmode.org>
1971 ((looking-at org-angle-link-re)
1972 (setq raw-link (buffer-substring-no-properties
1973 (match-beginning 1) (match-end 2))
1974 type (org-match-string-no-properties 1)
1975 path (org-match-string-no-properties 2)
1976 link-end (match-end 0))))
1977 ;; In any case, deduce end point after trailing white space from
1978 ;; LINK-END variable.
1979 (setq post-blank (progn (goto-char link-end) (skip-chars-forward " \t"))
1980 end (point))
1981 `(link
1982 (:type ,type
1983 :path ,path
1984 :raw-link ,(or raw-link path)
1985 :begin ,begin
1986 :end ,end
1987 :contents-begin ,contents-begin
1988 :contents-end ,contents-end
1989 :post-blank ,post-blank)))))
1991 (defun org-element-link-interpreter (link contents)
1992 "Interpret LINK object as Org syntax.
1993 CONTENTS is the contents of the object."
1994 (let ((type (org-element-get-property :type link))
1995 (raw-link (org-element-get-property :raw-link link)))
1996 (cond
1997 ((string= type "radio") raw-link)
1998 (t (format "[[%s]%s]"
1999 raw-link
2000 (if (string= contents "") "" (format "[%s]" contents)))))))
2002 (defun org-element-link-successor (limit)
2003 "Search for the next link object.
2005 LIMIT bounds the search.
2007 Return value is a cons cell whose car is `link' and cdr is
2008 beginning position."
2009 (save-excursion
2010 (let ((link-regexp
2011 (if org-target-link-regexp
2012 (concat org-any-link-re "\\|" org-target-link-regexp)
2013 org-any-link-re)))
2014 (when (re-search-forward link-regexp limit t)
2015 (cons 'link (match-beginning 0))))))
2018 ;;;; Macro
2020 (defun org-element-macro-parser ()
2021 "Parse macro at point.
2023 Return a list whose car is `macro' and cdr a plist with `:key',
2024 `:args', `:begin', `:end', `:value' and `:post-blank' as
2025 keywords.
2027 Assume point is at the macro."
2028 (save-excursion
2029 (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
2030 (let ((begin (point))
2031 (key (downcase (org-match-string-no-properties 1)))
2032 (value (org-match-string-no-properties 0))
2033 (post-blank (progn (goto-char (match-end 0))
2034 (skip-chars-forward " \t")))
2035 (end (point))
2036 (args (let ((args (org-match-string-no-properties 3)) args2)
2037 (when args
2038 (setq args (org-split-string args ","))
2039 (while args
2040 (while (string-match "\\\\\\'" (car args))
2041 ;; Repair bad splits.
2042 (setcar (cdr args) (concat (substring (car args) 0 -1)
2043 "," (nth 1 args)))
2044 (pop args))
2045 (push (pop args) args2))
2046 (mapcar 'org-trim (nreverse args2))))))
2047 `(macro
2048 (:key ,key
2049 :value ,value
2050 :args ,args
2051 :begin ,begin
2052 :end ,end
2053 :post-blank ,post-blank)))))
2055 (defun org-element-macro-interpreter (macro contents)
2056 "Interpret MACRO object as Org syntax.
2057 CONTENTS is nil."
2058 (org-element-get-property :value macro))
2060 (defun org-element-macro-successor (limit)
2061 "Search for the next macro object.
2063 LIMIT bounds the search.
2065 Return value is cons cell whose car is `macro' and cdr is
2066 beginning position."
2067 (save-excursion
2068 (when (re-search-forward
2069 "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}"
2070 limit t)
2071 (cons 'macro (match-beginning 0)))))
2074 ;;;; Radio-target
2076 (defun org-element-radio-target-parser ()
2077 "Parse radio target at point.
2079 Return a list whose car is `radio-target' and cdr a plist with
2080 `:begin', `:end', `:contents-begin', `:contents-end', `raw-value'
2081 and `:post-blank' as keywords.
2083 Assume point is at the radio target."
2084 (save-excursion
2085 (looking-at org-radio-target-regexp)
2086 (let ((begin (point))
2087 (contents-begin (match-beginning 1))
2088 (contents-end (match-end 1))
2089 (raw-value (org-match-string-no-properties 1))
2090 (post-blank (progn (goto-char (match-end 0))
2091 (skip-chars-forward " \t")))
2092 (end (point)))
2093 `(radio-target
2094 (:begin ,begin
2095 :end ,end
2096 :contents-begin ,contents-begin
2097 :contents-end ,contents-end
2098 :raw-value ,raw-value
2099 :post-blank ,post-blank)))))
2101 (defun org-element-radio-target-interpreter (target contents)
2102 "Interpret TARGET object as Org syntax.
2103 CONTENTS is the contents of the object."
2104 (concat "<<<" contents ">>>"))
2106 (defun org-element-radio-target-successor (limit)
2107 "Search for the next radio-target object.
2109 LIMIT bounds the search.
2111 Return value is a cons cell whose car is `radio-target' and cdr
2112 is beginning position."
2113 (save-excursion
2114 (when (re-search-forward org-radio-target-regexp limit t)
2115 (cons 'radio-target (match-beginning 0)))))
2118 ;;;; Statistics Cookie
2120 (defun org-element-statistics-cookie-parser ()
2121 "Parse statistics cookie at point.
2123 Return a list whose car is `statistics-cookie', and cdr a plist
2124 with `:begin', `:end', `:value' and `:post-blank' keywords.
2126 Assume point is at the beginning of the statistics-cookie."
2127 (save-excursion
2128 (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
2129 (let* ((begin (point))
2130 (value (buffer-substring-no-properties
2131 (match-beginning 0) (match-end 0)))
2132 (post-blank (progn (goto-char (match-end 0))
2133 (skip-chars-forward " \t")))
2134 (end (point)))
2135 `(statistics-cookie
2136 (:begin ,begin
2137 :end ,end
2138 :value ,value
2139 :post-blank ,post-blank)))))
2141 (defun org-element-statistics-cookie-interpreter (statistics-cookie contents)
2142 "Interpret STATISTICS-COOKIE object as Org syntax.
2143 CONTENTS is nil."
2144 (org-element-get-property :value statistics-cookie))
2146 (defun org-element-statistics-cookie-successor (limit)
2147 "Search for the next statistics cookie object.
2149 LIMIT bounds the search.
2151 Return value is a cons cell whose car is `statistics-cookie' and
2152 cdr is beginning position."
2153 (save-excursion
2154 (when (re-search-forward "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]" limit t)
2155 (cons 'statistics-cookie (match-beginning 0)))))
2158 ;;;; Subscript
2160 (defun org-element-subscript-parser ()
2161 "Parse subscript at point.
2163 Return a list whose car is `subscript' and cdr a plist with
2164 `:begin', `:end', `:contents-begin', `:contents-end',
2165 `:use-brackets-p' and `:post-blank' as keywords.
2167 Assume point is at the underscore."
2168 (save-excursion
2169 (unless (bolp) (backward-char))
2170 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2172 (not (looking-at org-match-substring-regexp))))
2173 (begin (match-beginning 2))
2174 (contents-begin (or (match-beginning 5)
2175 (match-beginning 3)))
2176 (contents-end (or (match-end 5) (match-end 3)))
2177 (post-blank (progn (goto-char (match-end 0))
2178 (skip-chars-forward " \t")))
2179 (end (point)))
2180 `(subscript
2181 (:begin ,begin
2182 :end ,end
2183 :use-brackets-p ,bracketsp
2184 :contents-begin ,contents-begin
2185 :contents-end ,contents-end
2186 :post-blank ,post-blank)))))
2188 (defun org-element-subscript-interpreter (subscript contents)
2189 "Interpret SUBSCRIPT object as Org syntax.
2190 CONTENTS is the contents of the object."
2191 (format
2192 (if (org-element-get-property :use-brackets-p subscript) "_{%s}" "_%s")
2193 contents))
2195 (defun org-element-sub/superscript-successor (limit)
2196 "Search for the next sub/superscript object.
2198 LIMIT bounds the search.
2200 Return value is a cons cell whose car is either `subscript' or
2201 `superscript' and cdr is beginning position."
2202 (save-excursion
2203 (when (re-search-forward org-match-substring-regexp limit t)
2204 (cons (if (string= (match-string 2) "_") 'subscript 'superscript)
2205 (match-beginning 2)))))
2208 ;;;; Superscript
2210 (defun org-element-superscript-parser ()
2211 "Parse superscript at point.
2213 Return a list whose car is `superscript' and cdr a plist with
2214 `:begin', `:end', `:contents-begin', `:contents-end',
2215 `:use-brackets-p' and `:post-blank' as keywords.
2217 Assume point is at the caret."
2218 (save-excursion
2219 (unless (bolp) (backward-char))
2220 (let ((bracketsp (if (looking-at org-match-substring-with-braces-regexp)
2222 (not (looking-at org-match-substring-regexp))))
2223 (begin (match-beginning 2))
2224 (contents-begin (or (match-beginning 5)
2225 (match-beginning 3)))
2226 (contents-end (or (match-end 5) (match-end 3)))
2227 (post-blank (progn (goto-char (match-end 0))
2228 (skip-chars-forward " \t")))
2229 (end (point)))
2230 `(superscript
2231 (:begin ,begin
2232 :end ,end
2233 :use-brackets-p ,bracketsp
2234 :contents-begin ,contents-begin
2235 :contents-end ,contents-end
2236 :post-blank ,post-blank)))))
2238 (defun org-element-superscript-interpreter (superscript contents)
2239 "Interpret SUPERSCRIPT object as Org syntax.
2240 CONTENTS is the contents of the object."
2241 (format
2242 (if (org-element-get-property :use-brackets-p superscript) "^{%s}" "^%s")
2243 contents))
2246 ;;;; Target
2248 (defun org-element-target-parser ()
2249 "Parse target at point.
2251 Return a list whose car is `target' and cdr a plist with
2252 `:begin', `:end', `:contents-begin', `:contents-end', `raw-value'
2253 and `:post-blank' as keywords.
2255 Assume point is at the target."
2256 (save-excursion
2257 (looking-at org-target-regexp)
2258 (let ((begin (point))
2259 (contents-begin (match-beginning 1))
2260 (contents-end (match-end 1))
2261 (raw-value (org-match-string-no-properties 1))
2262 (post-blank (progn (goto-char (match-end 0))
2263 (skip-chars-forward " \t")))
2264 (end (point)))
2265 `(target
2266 (:begin ,begin
2267 :end ,end
2268 :contents-begin ,contents-begin
2269 :contents-end ,contents-end
2270 :raw-value ,raw-value
2271 :post-blank ,post-blank)))))
2273 (defun org-element-target-interpreter (target contents)
2274 "Interpret TARGET object as Org syntax.
2275 CONTENTS is the contents of target."
2276 (concat ""))
2278 (defun org-element-target-successor (limit)
2279 "Search for the next target object.
2281 LIMIT bounds the search.
2283 Return value is a cons cell whose car is `target' and cdr is
2284 beginning position."
2285 (save-excursion
2286 (when (re-search-forward org-target-regexp limit t)
2287 (cons 'target (match-beginning 0)))))
2290 ;;;; Time-stamp
2292 (defun org-element-time-stamp-parser ()
2293 "Parse time stamp at point.
2295 Return a list whose car is `time-stamp', and cdr a plist with
2296 `:appt-type', `:type', `:begin', `:end', `:value' and
2297 `:post-blank' keywords.
2299 Assume point is at the beginning of the time-stamp."
2300 (save-excursion
2301 (let* ((appt-type (cond
2302 ((looking-at (concat org-deadline-string " +"))
2303 (goto-char (match-end 0))
2304 'deadline)
2305 ((looking-at (concat org-scheduled-string " +"))
2306 (goto-char (match-end 0))
2307 'scheduled)
2308 ((looking-at (concat org-closed-string " +"))
2309 (goto-char (match-end 0))
2310 'closed)))
2311 (begin (and appt-type (match-beginning 0)))
2312 (type (cond
2313 ((looking-at org-tsr-regexp)
2314 (if (match-string 2) 'active-range 'active))
2315 ((looking-at org-tsr-regexp-both)
2316 (if (match-string 2) 'inactive-range 'inactive))
2317 ((looking-at (concat
2318 "\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2319 "\\|"
2320 "\\(<%%\\(([^>\n]+)\\)>\\)"))
2321 'diary)))
2322 (begin (or begin (match-beginning 0)))
2323 (value (buffer-substring-no-properties
2324 (match-beginning 0) (match-end 0)))
2325 (post-blank (progn (goto-char (match-end 0))
2326 (skip-chars-forward " \t")))
2327 (end (point)))
2328 `(time-stamp
2329 (:appt-type ,appt-type
2330 :type ,type
2331 :value ,value
2332 :begin ,begin
2333 :end ,end
2334 :post-blank ,post-blank)))))
2336 (defun org-element-time-stamp-interpreter (time-stamp contents)
2337 "Interpret TIME-STAMP object as Org syntax.
2338 CONTENTS is nil."
2339 (concat
2340 (case (org-element-get-property :appt-type time-stamp)
2341 (closed (concat org-closed-string " "))
2342 (deadline (concat org-deadline-string " "))
2343 (scheduled (concat org-scheduled-string " ")))
2344 (org-element-get-property :value time-stamp)))
2346 (defun org-element-time-stamp-successor (limit)
2347 "Search for the next time-stamp object.
2349 LIMIT bounds the search.
2351 Return value is a cons cell whose car is `time-stamp' and cdr is
2352 beginning position."
2353 (save-excursion
2354 (when (re-search-forward
2355 (concat "\\(?:" org-scheduled-string " +\\|"
2356 org-deadline-string " +\\|" org-closed-string " +\\)?"
2357 org-ts-regexp-both
2358 "\\|"
2359 "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
2360 "\\|"
2361 "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
2362 limit t)
2363 (cons 'time-stamp (match-beginning 0)))))
2366 ;;;; Verbatim
2368 (defun org-element-verbatim-parser ()
2369 "Parse verbatim object at point.
2371 Return a list whose car is `verbatim' and cdr is a plist with
2372 `:marker', `:begin', `:end' and `:post-blank' keywords.
2374 Assume point is at the first verbatim marker."
2375 (save-excursion
2376 (unless (bolp) (backward-char 1))
2377 (looking-at org-emph-re)
2378 (let ((begin (match-beginning 2))
2379 (marker (org-match-string-no-properties 3))
2380 (value (org-match-string-no-properties 4))
2381 (post-blank (progn (goto-char (match-end 2))
2382 (skip-chars-forward " \t")))
2383 (end (point)))
2384 `(verbatim
2385 (:marker ,marker
2386 :begin ,begin
2387 :end ,end
2388 :value ,value
2389 :post-blank ,post-blank)))))
2391 (defun org-element-verbatim-interpreter (verbatim contents)
2392 "Interpret VERBATIM object as Org syntax.
2393 CONTENTS is nil."
2394 (let ((marker (org-element-get-property :marker verbatim))
2395 (value (org-element-get-property :value verbatim)))
2396 (concat marker value marker)))
2400 ;;; Definitions And Rules
2402 ;; Define elements, greater elements and specify recursive objects,
2403 ;; along with the affiliated keywords recognized. Also set up
2404 ;; restrictions on recursive objects combinations.
2406 ;; These variables really act as a control center for the parsing
2407 ;; process.
2408 (defconst org-element-paragraph-separate
2409 (concat "\f" "\\|" "^[ \t]*$" "\\|"
2410 ;; Headlines and inlinetasks.
2411 org-outline-regexp-bol "\\|"
2412 ;; Comments, blocks (any type), keywords and babel calls.
2413 "^[ \t]*#\\+" "\\|" "^#\\( \\|$\\)" "\\|"
2414 ;; Lists.
2415 (org-item-beginning-re) "\\|"
2416 ;; Fixed-width, drawers (any type) and tables.
2417 "^[ \t]*[:|]" "\\|"
2418 ;; Footnote definitions.
2419 org-footnote-definition-re "\\|"
2420 ;; Horizontal rules.
2421 "^[ \t]*-\\{5,\\}[ \t]*$" "\\|"
2422 ;; LaTeX environments.
2423 "^[ \t]*\\\\\\(begin\\|end\\)")
2424 "Regexp to separate paragraphs in an Org buffer.")
2426 (defconst org-element-all-elements
2427 '(center-block comment comment-block drawer dynamic-block example-block
2428 export-block fixed-width footnote-definition headline
2429 horizontal-rule inlinetask item keyword latex-environment
2430 babel-call paragraph plain-list property-drawer quote-block
2431 quote-section section special-block src-block table
2432 verse-block)
2433 "Complete list of elements.")
2435 (defconst org-element-greater-elements
2436 '(center-block drawer dynamic-block footnote-definition headline inlinetask
2437 item plain-list quote-block section special-block)
2438 "List of recursive element types aka Greater Elements.")
2440 (defconst org-element-all-successors
2441 '(export-snippet footnote-reference inline-babel-call inline-src-block
2442 latex-or-entity line-break link macro radio-target
2443 statistics-cookie sub/superscript target text-markup
2444 time-stamp)
2445 "Complete list of successors.")
2447 (defconst org-element-object-successor-alist
2448 '((subscript . sub/superscript) (superscript . sub/superscript)
2449 (emphasis . text-markup) (verbatim . text-markup)
2450 (entity . latex-or-entity) (latex-fragment . latex-or-entity))
2451 "Alist of translations between object type and successor name.
2453 Sharing the same successor comes handy when, for example, the
2454 regexp matching one object can also match the other object.")
2456 (defconst org-element-recursive-objects
2457 '(emphasis link subscript superscript target radio-target)
2458 "List of recursive object types.")
2460 (defconst org-element-non-recursive-block-alist
2461 '(("ascii" . export-block)
2462 ("comment" . comment-block)
2463 ("docbook" . export-block)
2464 ("example" . example-block)
2465 ("html" . export-block)
2466 ("latex" . export-block)
2467 ("odt" . export-block)
2468 ("src" . src-block)
2469 ("verse" . verse-block))
2470 "Alist between non-recursive block name and their element type.")
2472 (defconst org-element-affiliated-keywords
2473 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "caption"
2474 "data" "header" "headers" "label" "name" "plot" "resname" "result" "results"
2475 "source" "srcname" "tblname")
2476 "List of affiliated keywords as strings.")
2478 (defconst org-element-keyword-translation-alist
2479 '(("data" . "name") ("label" . "name") ("resname" . "name")
2480 ("source" . "name") ("srcname" . "name") ("tblname" . "name")
2481 ("result" . "results") ("headers" . "header"))
2482 "Alist of usual translations for keywords.
2483 The key is the old name and the value the new one. The property
2484 holding their value will be named after the translated name.")
2486 (defconst org-element-multiple-keywords
2487 '("attr_ascii" "attr_docbook" "attr_html" "attr_latex" "attr_odt" "header")
2488 "List of affiliated keywords that can occur more that once in an element.
2490 Their value will be consed into a list of strings, which will be
2491 returned as the value of the property.
2493 This list is checked after translations have been applied. See
2494 `org-element-keyword-translation-alist'.")
2496 (defconst org-element-parsed-keywords '("author" "caption" "title")
2497 "List of keywords whose value can be parsed.
2499 Their value will be stored as a secondary string: a list of
2500 strings and objects.
2502 This list is checked after translations have been applied. See
2503 `org-element-keyword-translation-alist'.")
2505 (defconst org-element-dual-keywords '("caption" "results")
2506 "List of keywords which can have a secondary value.
2508 In Org syntax, they can be written with optional square brackets
2509 before the colons. For example, results keyword can be
2510 associated to a hash value with the following:
2512 #+results[hash-string]: some-source
2514 This list is checked after translations have been applied. See
2515 `org-element-keyword-translation-alist'.")
2517 (defconst org-element-object-restrictions
2518 '((emphasis entity export-snippet inline-babel-call inline-src-block
2519 radio-target sub/superscript target text-markup time-stamp)
2520 (link entity export-snippet inline-babel-call inline-src-block
2521 latex-fragment sub/superscript text-markup)
2522 (radio-target entity export-snippet latex-fragment sub/superscript)
2523 (subscript entity export-snippet inline-babel-call inline-src-block
2524 latex-fragment sub/superscript text-markup)
2525 (superscript entity export-snippet inline-babel-call inline-src-block
2526 latex-fragment sub/superscript text-markup)
2527 (target entity export-snippet latex-fragment sub/superscript text-markup))
2528 "Alist of recursive objects restrictions.
2530 Car is a recursive object type and cdr is a list of successors
2531 that will be called within an object of such type.
2533 For example, in a `radio-target' object, one can only find
2534 entities, export snippets, latex-fragments, subscript and
2535 superscript.")
2537 (defconst org-element-string-restrictions
2538 '((headline entity inline-babel-call latex-fragment link macro radio-target
2539 statistics-cookie sub/superscript text-markup time-stamp)
2540 (inlinetask entity inline-babel-call latex-fragment link macro radio-target
2541 sub/superscript text-markup time-stamp)
2542 (item entity inline-babel-call latex-fragment macro radio-target
2543 sub/superscript target text-markup)
2544 (keyword entity latex-fragment macro sub/superscript text-markup)
2545 (table entity latex-fragment macro text-markup)
2546 (verse entity footnote-reference inline-babel-call inline-src-block
2547 latex-fragment line-break link macro radio-target sub/superscript
2548 target text-markup time-stamp))
2549 "Alist of secondary strings restrictions.
2551 When parsed, some elements have a secondary string which could
2552 contain various objects (i.e. headline's name, or table's cells).
2553 For association, the car is the element type, and the cdr a list
2554 of successors that will be called in that secondary string.
2556 Note: `keyword' secondary string type only applies to keywords
2557 matching `org-element-parsed-keywords'.")
2561 ;;; Accessors
2563 ;; Provide two accessors: `org-element-get-property' and
2564 ;; `org-element-get-contents'.
2566 (defun org-element-get-property (property element)
2567 "Extract the value from the PROPERTY of an ELEMENT."
2568 (plist-get (nth 1 element) property))
2570 (defun org-element-get-contents (element)
2571 "Extract contents from an ELEMENT."
2572 (nthcdr 2 element))
2576 ;; Obtaining The Smallest Element Containing Point
2578 ;; `org-element-at-point' is the core function of this section. It
2579 ;; returns the Lisp representation of the element at point. It uses
2580 ;; `org-element-guess-type' and `org-element-skip-keywords' as helper
2581 ;; functions.
2583 ;; When point is at an item, there is no automatic way to determine if
2584 ;; the function should return the `plain-list' element, or the
2585 ;; corresponding `item' element. By default, `org-element-at-point'
2586 ;; works at the `plain-list' level. But, by providing an optional
2587 ;; argument, one can make it switch to the `item' level.
2589 (defconst org-element--affiliated-re
2590 (format "[ \t]*#\\+\\(%s\\):"
2591 (mapconcat
2592 (lambda (keyword)
2593 (if (member keyword org-element-dual-keywords)
2594 (format "\\(%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
2595 (regexp-quote keyword))
2596 (regexp-quote keyword)))
2597 org-element-affiliated-keywords "\\|"))
2598 "Regexp matching any affiliated keyword.
2600 Keyword name is put in match group 1. Moreover, if keyword
2601 belongs to `org-element-dual-keywords', put the dual value in
2602 match group 2.
2604 Don't modify it, set `org-element--affiliated-keywords' instead.")
2606 (defun org-element-at-point (&optional special structure)
2607 "Determine closest element around point.
2609 Return value is a list \(TYPE PROPS\) where TYPE is the type of
2610 the element and PROPS a plist of properties associated to the
2611 element.
2613 Possible types are defined in `org-element-all-elements'.
2615 Optional argument SPECIAL, when non-nil, can be either `item' or
2616 `section'. The former allows to parse item wise instead of
2617 plain-list wise, using STRUCTURE as the current list structure.
2618 The latter will try to parse a section before anything else.
2620 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
2621 be computed."
2622 (save-excursion
2623 (beginning-of-line)
2624 ;; Move before any blank line.
2625 (when (looking-at "[ \t]*$")
2626 (skip-chars-backward " \r\t\n")
2627 (beginning-of-line))
2628 (let ((case-fold-search t))
2629 ;; Check if point is at an affiliated keyword. In that case,
2630 ;; try moving to the beginning of the associated element. If
2631 ;; the keyword is orphaned, treat it as plain text.
2632 (when (looking-at org-element--affiliated-re)
2633 (let ((opoint (point)))
2634 (while (looking-at org-element--affiliated-re) (forward-line))
2635 (when (looking-at "[ \t]*$") (goto-char opoint))))
2636 (let ((type (org-element-guess-type (eq special 'section))))
2637 (cond
2638 ;; Guessing element type on the current line is impossible:
2639 ;; try to find the beginning of the current element to get
2640 ;; more information.
2641 ((not type)
2642 (let ((search-origin (point))
2643 (opoint-in-item-p (org-in-item-p))
2644 (par-found-p
2645 (progn
2646 (end-of-line)
2647 (re-search-backward org-element-paragraph-separate nil 'm))))
2648 (cond
2649 ;; Unable to find a paragraph delimiter above: we're at
2650 ;; bob and looking at a paragraph.
2651 ((not par-found-p) (org-element-paragraph-parser))
2652 ;; Trying to find element's beginning set point back to
2653 ;; its original position. There's something peculiar on
2654 ;; this line that prevents parsing, probably an
2655 ;; ill-formed keyword or an undefined drawer name. Parse
2656 ;; it as plain text anyway.
2657 ((< search-origin (point-at-eol)) (org-element-paragraph-parser))
2658 ;; Original point wasn't in a list but previous paragraph
2659 ;; is. It means that either point was inside some block,
2660 ;; or current list was ended without using a blank line.
2661 ;; In the last case, paragraph really starts at list end.
2662 ((let (item)
2663 (and (not opoint-in-item-p)
2664 (not (looking-at "[ \t]*#\\+begin"))
2665 (setq item (org-in-item-p))
2666 (let ((struct (save-excursion (goto-char item)
2667 (org-list-struct))))
2668 (goto-char (org-list-get-bottom-point struct))
2669 (org-skip-whitespace)
2670 (beginning-of-line)
2671 (org-element-paragraph-parser)))))
2672 ((org-footnote-at-definition-p)
2673 (org-element-footnote-definition-parser))
2674 ((and opoint-in-item-p (org-at-item-p) (= opoint-in-item-p (point)))
2675 (if (eq special 'item)
2676 (org-element-item-parser (or structure (org-list-struct)))
2677 (org-element-plain-list-parser (or structure (org-list-struct)))))
2678 ;; In any other case, the paragraph started the line
2679 ;; below.
2680 (t (forward-line) (org-element-paragraph-parser)))))
2681 ((eq type 'plain-list)
2682 (if (eq special 'item)
2683 (org-element-item-parser (or structure (org-list-struct)))
2684 (org-element-plain-list-parser (or structure (org-list-struct)))))
2685 ;; Straightforward case: call the appropriate parser.
2686 (t (funcall (intern (format "org-element-%s-parser" type)))))))))
2689 ;; It is obvious to tell if point is in most elements, either by
2690 ;; looking for a specific regexp in the current line, or by using
2691 ;; already implemented functions. This is the goal of
2692 ;; `org-element-guess-type'.
2694 (defconst org-element--element-block-types
2695 (mapcar 'car org-element-non-recursive-block-alist)
2696 "List of non-recursive block types, as strings.
2697 Used internally by `org-element-guess-type'. Do not modify it
2698 directly, set `org-element-non-recursive-block-alist' instead.")
2700 (defun org-element-guess-type (&optional section-mode)
2701 "Return the type of element at point, or nil if undetermined.
2703 This function may move point to an appropriate position for
2704 parsing. Used internally by `org-element-at-point'.
2706 When optional argument SECTION-MODE is non-nil, try to find if
2707 point is in a section in priority."
2708 ;; Beware: Order matters for some cases in that function.
2709 (beginning-of-line)
2710 (let ((case-fold-search t))
2711 (cond
2712 ((org-with-limited-levels (org-at-heading-p)) 'headline)
2713 ((let ((headline (ignore-errors (nth 4 (org-heading-components)))))
2714 (and headline
2715 (let (case-fold-search)
2716 (string-match (format "^%s\\(?: \\|$\\)" org-quote-string)
2717 headline))))
2718 ;; Move to section beginning.
2719 (org-back-to-heading t)
2720 (forward-line)
2721 (org-skip-whitespace)
2722 (beginning-of-line)
2723 'quote-section)
2724 ;; Any buffer position not at an headline or in a quote section
2725 ;; is inside a section, provided function is actively looking for
2726 ;; them.
2727 (section-mode 'section)
2728 ;; Non-recursive block.
2729 ((let ((type (org-in-block-p org-element--element-block-types)))
2730 (and type (cdr (assoc type org-element-non-recursive-block-alist)))))
2731 ((org-at-heading-p) 'inlinetask)
2732 ((org-between-regexps-p
2733 "^[ \t]*\\\\begin{" "^[ \t]*\\\\end{[^}]*}[ \t]*") 'latex-environment)
2734 ;; Property drawer. Almost `org-at-property-p', but allow drawer
2735 ;; boundaries.
2736 ((org-with-wide-buffer
2737 (and (not (org-before-first-heading-p))
2738 (let ((pblock (org-get-property-block)))
2739 (and pblock
2740 (<= (point) (cdr pblock))
2741 (>= (point-at-eol) (1- (car pblock)))))))
2742 'property-drawer)
2743 ;; Recursive block. If the block isn't complete, parse the
2744 ;; current part as a paragraph.
2745 ((looking-at "[ \t]*#\\+\\(begin\\|end\\)_\\([-A-Za-z0-9]+\\)\\(?:$\\|\\s-\\)")
2746 (let ((type (downcase (match-string 2))))
2747 (cond
2748 ((not (org-in-block-p (list type))) 'paragraph)
2749 ((string= type "center") 'center-block)
2750 ((string= type "quote") 'quote-block)
2751 (t 'special-block))))
2752 ;; Regular drawers must be tested after property drawer as both
2753 ;; elements share the same ending regexp.
2754 ((or (looking-at org-drawer-regexp) (looking-at "[ \t]*:END:[ \t]*$"))
2755 (let ((completep (org-between-regexps-p
2756 org-drawer-regexp "^[ \t]*:END:[ \t]*$")))
2757 (if (not completep) 'paragraph
2758 (goto-char (car completep)) 'drawer)))
2759 ((looking-at "[ \t]*:\\( \\|$\\)") 'fixed-width)
2760 ;; Babel calls must be tested before general keywords as they are
2761 ;; a subset of them.
2762 ((looking-at org-babel-block-lob-one-liner-regexp) 'babel-call)
2763 ((looking-at org-footnote-definition-re) 'footnote-definition)
2764 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
2765 (if (member (downcase (match-string 1)) org-element-affiliated-keywords)
2766 'paragraph
2767 'keyword))
2768 ;; Dynamic block: simplify regexp used for match. If it isn't
2769 ;; complete, parse the current part as a paragraph.
2770 ((looking-at "[ \t]*#\\+\\(begin\\end\\):\\(?:\\s-\\|$\\)")
2771 (let ((completep (org-between-regexps-p
2772 "^[ \t]*#\\+begin:\\(?:\\s-\\|$\\)"
2773 "^[ \t]*#\\+end:\\(?:\\s-\\|$\\)")))
2774 (if (not completep) 'paragraph
2775 (goto-char (car completep)) 'dynamic-block)))
2776 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)") 'comment)
2777 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$") 'horizontal-rule)
2778 ((org-at-table-p t) 'table)
2779 ((looking-at "[ \t]*#\\+tblfm:")
2780 (forward-line -1)
2781 ;; A TBLFM line separated from any table is just plain text.
2782 (if (org-at-table-p) 'table
2783 (forward-line) 'paragraph))
2784 ((looking-at (org-item-re)) 'plain-list))))
2786 ;; Most elements can have affiliated keywords. When looking for an
2787 ;; element beginning, we want to move before them, as they belong to
2788 ;; that element, and, in the meantime, collect information they give
2789 ;; into appropriate properties. Hence the following function.
2791 ;; Usage of optional arguments may not be obvious at first glance:
2793 ;; - TRANS-LIST is used to polish keywords names that have evolved
2794 ;; during Org history. In example, even though =result= and
2795 ;; =results= coexist, we want to have them under the same =result=
2796 ;; property. It's also true for "srcname" and "name", where the
2797 ;; latter seems to be preferred nowadays (thus the "name" property).
2799 ;; - CONSED allows to regroup multi-lines keywords under the same
2800 ;; property, while preserving their own identity. This is mostly
2801 ;; used for "attr_latex" and al.
2803 ;; - PARSED prepares a keyword value for export. This is useful for
2804 ;; "caption". Objects restrictions for such keywords are defined in
2805 ;; `org-element-string-restrictions'.
2807 ;; - DUALS is used to take care of keywords accepting a main and an
2808 ;; optional secondary values. For example "results" has its
2809 ;; source's name as the main value, and may have an hash string in
2810 ;; optional square brackets as the secondary one.
2812 ;; A keyword may belong to more than one category.
2814 (defun org-element-collect-affiliated-keywords (&optional key-re trans-list
2815 consed parsed duals)
2816 "Collect affiliated keywords before point.
2818 Optional argument KEY-RE is a regexp matching keywords, which
2819 puts matched keyword in group 1. It defaults to
2820 `org-element--affiliated-re'.
2822 TRANS-LIST is an alist where key is the keyword and value the
2823 property name it should be translated to, without the colons. It
2824 defaults to `org-element-keyword-translation-alist'.
2826 CONSED is a list of strings. Any keyword belonging to that list
2827 will have its value consed. The check is done after keyword
2828 translation. It defaults to `org-element-multiple-keywords'.
2830 PARSED is a list of strings. Any keyword member of this list
2831 will have its value parsed. The check is done after keyword
2832 translation. If a keyword is a member of both CONSED and PARSED,
2833 it's value will be a list of parsed strings. It defaults to
2834 `org-element-parsed-keywords'.
2836 DUALS is a list of strings. Any keyword member of this list can
2837 have two parts: one mandatory and one optional. Its value is
2838 a cons cell whose car is the former, and the cdr the latter. If
2839 a keyword is a member of both PARSED and DUALS, both values will
2840 be parsed. It defaults to `org-element-dual-keywords'.
2842 Return a list whose car is the position at the first of them and
2843 cdr a plist of keywords and values."
2844 (save-excursion
2845 (let ((case-fold-search t)
2846 (key-re (or key-re org-element--affiliated-re))
2847 (trans-list (or trans-list org-element-keyword-translation-alist))
2848 (consed (or consed org-element-multiple-keywords))
2849 (parsed (or parsed org-element-parsed-keywords))
2850 (duals (or duals org-element-dual-keywords))
2851 ;; RESTRICT is the list of objects allowed in parsed
2852 ;; keywords value.
2853 (restrict (cdr (assq 'keyword org-element-string-restrictions)))
2854 output)
2855 (unless (bobp)
2856 (while (and (not (bobp))
2857 (progn (forward-line -1) (looking-at key-re)))
2858 (let* ((raw-kwd (downcase (or (match-string 2) (match-string 1))))
2859 ;; Apply translation to RAW-KWD. From there, KWD is
2860 ;; the official keyword.
2861 (kwd (or (cdr (assoc raw-kwd trans-list)) raw-kwd))
2862 ;; Find main value for any keyword.
2863 (value
2864 (save-match-data
2865 (org-trim
2866 (buffer-substring-no-properties
2867 (match-end 0) (point-at-eol)))))
2868 ;; If KWD is a dual keyword, find its secondary
2869 ;; value. Maybe parse it.
2870 (dual-value
2871 (and (member kwd duals)
2872 (let ((sec (org-match-string-no-properties 3)))
2873 (if (or (not sec) (not (member kwd parsed))) sec
2874 (org-element-parse-secondary-string sec restrict)))))
2875 ;; Attribute a property name to KWD.
2876 (kwd-sym (and kwd (intern (concat ":" kwd)))))
2877 ;; Now set final shape for VALUE.
2878 (when (member kwd parsed)
2879 (setq value (org-element-parse-secondary-string value restrict)))
2880 (when (member kwd duals)
2881 ;; VALUE is mandatory. Set it to nil if there is none.
2882 (setq value (and value (cons value dual-value))))
2883 (when (member kwd consed)
2884 (setq value (cons value (plist-get output kwd-sym))))
2885 ;; Eventually store the new value in OUTPUT.
2886 (setq output (plist-put output kwd-sym value))))
2887 (unless (looking-at key-re) (forward-line 1)))
2888 (list (point) output))))
2892 ;;; The Org Parser
2894 ;; The two major functions here are `org-element-parse-buffer', which
2895 ;; parses Org syntax inside the current buffer, taking into account
2896 ;; region, narrowing, or even visibility if specified, and
2897 ;; `org-element-parse-secondary-string', which parses objects within
2898 ;; a given string.
2900 ;; The (almost) almighty `org-element-map' allows to apply a function
2901 ;; on elements or objects matching some type, and accumulate the
2902 ;; resulting values. In an export situation, it also skips unneeded
2903 ;; parts of the parse tree, transparently walks into included files,
2904 ;; and maintain a list of local properties (i.e. those inherited from
2905 ;; parent headlines) for function's consumption.
2907 (defun org-element-parse-buffer (&optional granularity visible-only)
2908 "Recursively parse the buffer and return structure.
2909 If narrowing is in effect, only parse the visible part of the
2910 buffer.
2912 Optional argument GRANULARITY determines the depth of the
2913 recursion. It can be set to the following symbols:
2915 `headline' Only parse headlines.
2916 `greater-element' Don't recurse into greater elements. Thus,
2917 elements parsed are the top-level ones.
2918 `element' Parse everything but objects and plain text.
2919 `object' Parse the complete buffer (default).
2921 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
2922 elements.
2924 Assume buffer is in Org mode."
2925 (save-excursion
2926 (goto-char (point-min))
2927 (org-skip-whitespace)
2928 (nconc (list 'org-data nil)
2929 (org-element-parse-elements
2930 (point-at-bol) (point-max)
2931 ;; Start is section mode so text before the first headline
2932 ;; belongs to a section.
2933 'section nil granularity visible-only nil))))
2935 (defun org-element-parse-secondary-string (string restriction &optional buffer)
2936 "Recursively parse objects in STRING and return structure.
2938 RESTRICTION, when non-nil, is a symbol limiting the object types
2939 that will be looked after.
2941 Optional argument BUFFER indicates the buffer from where the
2942 secondary string was extracted. It is used to determine where to
2943 get extraneous information for an object \(i.e. when resolving
2944 a link or looking for a footnote definition\). It defaults to
2945 the current buffer."
2946 (with-temp-buffer
2947 (insert string)
2948 (org-element-parse-objects (point-min) (point-max) nil restriction)))
2950 (defun org-element-map (data types fun &optional info first-match)
2951 "Map a function on selected elements or objects.
2953 DATA is the parsed tree, as returned by, i.e,
2954 `org-element-parse-buffer'. TYPES is a symbol or list of symbols
2955 of elements or objects types. FUN is the function called on the
2956 matching element or object. It must accept two arguments: the
2957 element or object itself and a plist holding contextual
2958 information.
2960 When optional argument INFO is non-nil, it should be a plist
2961 holding export options. In that case, parts of the parse tree
2962 not exportable according to that property list will be skipped
2963 and files included through a keyword will be visited.
2965 When optional argument FIRST-MATCH is non-nil, stop at the first
2966 match for which FUN doesn't return nil, and return that value.
2968 Nil values returned from FUN are ignored in the result."
2969 ;; Ensure TYPES is a list, even of one element.
2970 (unless (listp types) (setq types (list types)))
2971 ;; Recursion depth is determined by --CATEGORY.
2972 (let* ((--category
2973 (cond
2974 ((loop for type in types
2975 always (memq type org-element-greater-elements))
2976 'greater-elements)
2977 ((loop for type in types
2978 always (memq type org-element-all-elements))
2979 'elements)
2980 (t 'objects)))
2981 walk-tree ; For byte-compiler
2982 --acc
2983 (accumulate-maybe
2984 (function
2985 (lambda (--type types fun --blob --local)
2986 ;; Check if TYPE is matching among TYPES. If so, apply
2987 ;; FUN to --BLOB and accumulate return value
2988 ;; into --ACC. --LOCAL is the communication channel.
2989 (when (memq --type types)
2990 (let ((result (funcall fun --blob --local)))
2991 (cond ((not result))
2992 (first-match (throw 'first-match result))
2993 (t (push result --acc))))))))
2994 (walk-tree
2995 (function
2996 (lambda (--data --local)
2997 ;; Recursively walk DATA. --LOCAL, if non-nil, is
2998 ;; a plist holding contextual information.
2999 (mapc
3000 (lambda (--blob)
3001 (let ((--type (if (stringp --blob) 'plain-text (car --blob))))
3002 ;; Determine if a recursion into --BLOB is
3003 ;; possible and allowed.
3004 (cond
3005 ;; Element or object not exportable.
3006 ((and info (org-export-skip-p --blob info)))
3007 ;; Archived headline: Maybe apply fun on it, but
3008 ;; skip contents.
3009 ((and info
3010 (eq --type 'headline)
3011 (eq (plist-get info :with-archived-trees) 'headline)
3012 (org-element-get-property :archivedp --blob))
3013 (funcall accumulate-maybe --type types fun --blob --local))
3014 ;; At an include keyword: apply mapping to its
3015 ;; contents.
3016 ((and --local
3017 (eq --type 'keyword)
3018 (string=
3019 (downcase (org-element-get-property :key --blob))
3020 "include"))
3021 (funcall accumulate-maybe --type types fun --blob --local)
3022 (let* ((--data
3023 (org-export-parse-included-file --blob --local))
3024 (--value (org-element-get-property :value --blob))
3025 (--file
3026 (and (string-match "^\"\\(\\S-+\\)\"" --value)
3027 (match-string 1 --value))))
3028 (funcall
3029 walk-tree --data
3030 (org-combine-plists
3031 --local
3032 ;; Store full path of already included files
3033 ;; to avoid recursive file inclusion.
3034 `(:included-files
3035 ,(cons (expand-file-name --file)
3036 (plist-get --local :included-files))
3037 ;; Ensure that a top-level headline in the
3038 ;; included file becomes a direct child of
3039 ;; the current headline in the buffer.
3040 :headline-offset
3041 ,(- (+ (plist-get
3042 (plist-get --local :inherited-properties)
3043 :level)
3044 (or (plist-get --local :headline-offset) 0))
3045 (1- (org-export-get-min-level
3046 --data --local))))))))
3047 ;; Limiting recursion to greater elements, and --BLOB
3048 ;; isn't one.
3049 ((and (eq --category 'greater-elements)
3050 (not (memq --type org-element-greater-elements)))
3051 (funcall accumulate-maybe --type types fun --blob --local))
3052 ;; Limiting recursion to elements, and --BLOB only
3053 ;; contains objects.
3054 ((and (eq --category 'elements) (eq --type 'paragraph)))
3055 ;; No limitation on recursion, but --BLOB hasn't
3056 ;; got a recursive type.
3057 ((and (eq --category 'objects)
3058 (not (or (eq --type 'paragraph)
3059 (memq --type org-element-greater-elements)
3060 (memq --type org-element-recursive-objects))))
3061 (funcall accumulate-maybe --type types fun --blob --local))
3062 ;; Recursion is possible and allowed: Update local
3063 ;; information and move into --BLOB.
3064 (t (funcall accumulate-maybe --type types fun --blob --local)
3065 (funcall
3066 walk-tree --blob
3067 (org-combine-plists
3068 info `(:genealogy
3069 ,(cons --blob (plist-get info :genealogy)))))))))
3070 (org-element-get-contents --data))))))
3071 (catch 'first-match
3072 (funcall walk-tree data info)
3073 ;; Return value in a proper order.
3074 (reverse --acc))))
3076 ;; The following functions are internal parts of the parser.
3078 ;; The first one, `org-element-parse-elements' acts at the element's
3079 ;; level. As point is always at the beginning of an element during
3080 ;; parsing, it doesn't have to rely on `org-element-at-point'.
3081 ;; Instead, it calls a more restrictive, though way quicker,
3082 ;; alternative: `org-element-current-element'. That function
3083 ;; internally uses `org-element--element-block-re' for quick access to
3084 ;; a common regexp.
3086 ;; The second one, `org-element-parse-objects' applies on all objects
3087 ;; of a paragraph or a secondary string. It uses
3088 ;; `org-element-get-candidates' to optimize the search of the next
3089 ;; object in the buffer.
3091 ;; More precisely, that function looks for every allowed object type
3092 ;; first. Then, it discards failed searches, keeps further matches,
3093 ;; and searches again types matched behind point, for subsequent
3094 ;; calls. Thus, searching for a given type fails only once, and every
3095 ;; object is searched only once at top level (but sometimes more for
3096 ;; nested types).
3098 (defun org-element-parse-elements
3099 (beg end special structure granularity visible-only acc)
3100 "Parse elements between BEG and END positions.
3102 SPECIAL prioritize some elements over the others. It can set to
3103 `quote-section', `section' or `item', which will focus search,
3104 respectively, on quote sections, sections and items. Moreover,
3105 when value is `item', STRUCTURE will be used as the current list
3106 structure.
3108 GRANULARITY determines the depth of the recursion. It can be set
3109 to the following symbols:
3111 `headline' Only parse headlines.
3112 `greater-element' Don't recurse into greater elements. Thus,
3113 elements parsed are the top-level ones.
3114 `element' Parse everything but objects and plain text.
3115 `object' or nil Parse the complete buffer.
3117 When VISIBLE-ONLY is non-nil, don't parse contents of hidden
3118 elements.
3120 Elements are accumulated into ACC."
3121 (save-excursion
3122 (save-restriction
3123 (narrow-to-region beg end)
3124 (goto-char beg)
3125 ;; When parsing only headlines, skip any text before first one.
3126 (when (and (eq granularity 'headline) (not (org-at-heading-p)))
3127 (org-with-limited-levels (outline-next-heading)))
3128 ;; Main loop start.
3129 (while (not (eobp))
3130 (push
3131 ;; 1. Item mode is active: point must be at an item. Parse it
3132 ;; directly, skipping `org-element-current-element'.
3133 (if (eq special 'item)
3134 (let ((element (org-element-item-parser structure)))
3135 (goto-char (org-element-get-property :end element))
3136 (org-element-parse-elements
3137 (org-element-get-property :contents-begin element)
3138 (org-element-get-property :contents-end element)
3139 nil structure granularity visible-only (reverse element)))
3140 ;; 2. When ITEM is nil, find current element's type and parse
3141 ;; it accordingly to its category.
3142 (let ((element (org-element-current-element special structure)))
3143 (goto-char (org-element-get-property :end element))
3144 (cond
3145 ;; Case 1. ELEMENT is a paragraph. Parse objects inside,
3146 ;; if GRANULARITY allows it.
3147 ((and (eq (car element) 'paragraph)
3148 (or (not granularity) (eq granularity 'object)))
3149 (org-element-parse-objects
3150 (org-element-get-property :contents-begin element)
3151 (org-element-get-property :contents-end element)
3152 (reverse element) nil))
3153 ;; Case 2. ELEMENT is recursive: parse it between
3154 ;; `contents-begin' and `contents-end'. Make sure
3155 ;; GRANULARITY allows the recursion, or ELEMENT is an
3156 ;; headline, in which case going inside is mandatory, in
3157 ;; order to get sub-level headings. If VISIBLE-ONLY is
3158 ;; true and element is hidden, do not recurse into it.
3159 ((and (memq (car element) org-element-greater-elements)
3160 (or (not granularity)
3161 (memq granularity '(element object))
3162 (eq (car element) 'headline))
3163 (not (and visible-only
3164 (org-element-get-property :hiddenp element))))
3165 (org-element-parse-elements
3166 (org-element-get-property :contents-begin element)
3167 (org-element-get-property :contents-end element)
3168 ;; At a plain list, switch to item mode. At an
3169 ;; headline, switch to section mode. Any other
3170 ;; element turns off special modes.
3171 (case (car element)
3172 (plain-list 'item)
3173 (headline (if (org-element-get-property :quotedp element)
3174 'quote-section
3175 'section)))
3176 (org-element-get-property :structure element)
3177 granularity visible-only (reverse element)))
3178 ;; Case 3. Else, just accumulate ELEMENT.
3179 (t element))))
3180 acc)))
3181 ;; Return result.
3182 (nreverse acc)))
3184 (defconst org-element--element-block-re
3185 (format "[ \t]*#\\+begin_\\(%s\\)\\(?: \\|$\\)"
3186 (mapconcat
3187 'regexp-quote
3188 (mapcar 'car org-element-non-recursive-block-alist) "\\|"))
3189 "Regexp matching the beginning of a non-recursive block type.
3190 Used internally by `org-element-current-element'. Do not modify
3191 it directly, set `org-element-recursive-block-alist' instead.")
3193 (defun org-element-current-element (&optional special structure)
3194 "Parse the element at point.
3196 Return value is a list \(TYPE PROPS\) where TYPE is the type of
3197 the element and PROPS a plist of properties associated to the
3198 element.
3200 Possible types are defined in `org-element-all-elements'.
3202 Optional argument SPECIAL, when non-nil, can be either `item',
3203 `section' or `quote-section'. `item' allows to parse item wise
3204 instead of plain-list wise, using STRUCTURE as the current list
3205 structure. `section' (resp. `quote-section') will try to parse
3206 a section (resp. a quote section) before anything else.
3208 If STRUCTURE isn't provided but SPECIAL is set to `item', it will
3209 be computed.
3211 Unlike to `org-element-at-point', this function assumes point is
3212 always at the beginning of the element it has to parse. As such,
3213 it is quicker than its counterpart and always accurate, albeit
3214 more restrictive."
3215 (save-excursion
3216 (beginning-of-line)
3217 ;; If point is at an affiliated keyword, try moving to the
3218 ;; beginning of the associated element. If none is found, the
3219 ;; keyword is orphaned and will be treated as plain text.
3220 (when (looking-at org-element--affiliated-re)
3221 (let ((opoint (point)))
3222 (while (looking-at org-element--affiliated-re) (forward-line))
3223 (when (looking-at "[ \t]*$") (goto-char opoint))))
3224 (let ((case-fold-search t))
3225 (cond
3226 ;; Headline.
3227 ((org-with-limited-levels (org-at-heading-p))
3228 (org-element-headline-parser))
3229 ;; Quote section.
3230 ((eq special 'quote-section) (org-element-quote-section-parser))
3231 ;; Section.
3232 ((eq special 'section) (org-element-section-parser))
3233 ;; Non-recursive block.
3234 ((when (looking-at org-element--element-block-re)
3235 (let ((type (downcase (match-string 1))))
3236 (if (save-excursion
3237 (re-search-forward
3238 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t))
3239 ;; Build appropriate parser.
3240 (funcall
3241 (intern
3242 (format "org-element-%s-parser"
3243 (cdr (assoc type
3244 org-element-non-recursive-block-alist)))))
3245 (org-element-paragraph-parser)))))
3246 ;; Inlinetask.
3247 ((org-at-heading-p) (org-element-inlinetask-parser))
3248 ;; LaTeX Environment or paragraph if incomplete.
3249 ((looking-at "^[ \t]*\\\\begin{")
3250 (if (save-excursion
3251 (re-search-forward "^[ \t]*\\\\end{[^}]*}[ \t]*" nil t))
3252 (org-element-latex-environment-parser)
3253 (org-element-paragraph-parser)))
3254 ;; Property drawer.
3255 ((looking-at org-property-start-re)
3256 (if (save-excursion (re-search-forward org-property-end-re nil t))
3257 (org-element-property-drawer-parser)
3258 (org-element-paragraph-parser)))
3259 ;; Recursive block, or paragraph if incomplete.
3260 ((looking-at "[ \t]*#\\+begin_\\([-A-Za-z0-9]+\\)\\(?: \\|$\\)")
3261 (let ((type (downcase (match-string 1))))
3262 (cond
3263 ((not (save-excursion
3264 (re-search-forward
3265 (format "[ \t]*#\\+end_%s\\(?: \\|$\\)" type) nil t)))
3266 (org-element-paragraph-parser))
3267 ((string= type "center") (org-element-center-block-parser))
3268 ((string= type "quote") (org-element-quote-block-parser))
3269 (t (org-element-special-block-parser)))))
3270 ;; Drawer.
3271 ((looking-at org-drawer-regexp)
3272 (if (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" nil t))
3273 (org-element-drawer-parser)
3274 (org-element-paragraph-parser)))
3275 ((looking-at "[ \t]*:\\( \\|$\\)") (org-element-fixed-width-parser))
3276 ;; Babel call.
3277 ((looking-at org-babel-block-lob-one-liner-regexp)
3278 (org-element-babel-call-parser))
3279 ;; Keyword, or paragraph if at an affiliated keyword.
3280 ((looking-at "[ \t]*#\\+\\([a-z]+\\(:?_[a-z]+\\)*\\):")
3281 (let ((key (downcase (match-string 1))))
3282 (if (or (string= key "tblfm")
3283 (member key org-element-affiliated-keywords))
3284 (org-element-paragraph-parser)
3285 (org-element-keyword-parser))))
3286 ;; Footnote definition.
3287 ((looking-at org-footnote-definition-re)
3288 (org-element-footnote-definition-parser))
3289 ;; Dynamic block or paragraph if incomplete.
3290 ((looking-at "[ \t]*#\\+begin:\\(?: \\|$\\)")
3291 (if (save-excursion
3292 (re-search-forward "^[ \t]*#\\+end:\\(?: \\|$\\)" nil t))
3293 (org-element-dynamic-block-parser)
3294 (org-element-paragraph-parser)))
3295 ;; Comment.
3296 ((looking-at "\\(#\\|[ \t]*#\\+\\(?: \\|$\\)\\)")
3297 (org-element-comment-parser))
3298 ;; Horizontal rule.
3299 ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
3300 (org-element-horizontal-rule-parser))
3301 ;; Table.
3302 ((org-at-table-p t) (org-element-table-parser))
3303 ;; List or item.
3304 ((looking-at (org-item-re))
3305 (if (eq special 'item)
3306 (org-element-item-parser (or structure (org-list-struct)))
3307 (org-element-plain-list-parser (or structure (org-list-struct)))))
3308 ;; Default element: Paragraph.
3309 (t (org-element-paragraph-parser))))))
3311 (defun org-element-parse-objects (beg end acc restriction)
3312 "Parse objects between BEG and END and return recursive structure.
3314 Objects are accumulated in ACC.
3316 RESTRICTION, when non-nil, is a list of object types which are
3317 allowed in the current object."
3318 (let ((get-next-object
3319 (function
3320 (lambda (cand)
3321 ;; Return the parsing function associated to the nearest
3322 ;; object among list of candidates CAND.
3323 (let ((pos (apply #'min (mapcar #'cdr cand))))
3324 (save-excursion
3325 (goto-char pos)
3326 (funcall
3327 (intern
3328 (format "org-element-%s-parser" (car (rassq pos cand))))))))))
3329 next-object candidates)
3330 (save-excursion
3331 (goto-char beg)
3332 (while (setq candidates (org-element-get-next-object-candidates
3333 end restriction candidates))
3334 (setq next-object (funcall get-next-object candidates))
3335 ;; 1. Text before any object. Untabify it.
3336 (let ((obj-beg (org-element-get-property :begin next-object)))
3337 (unless (= (point) obj-beg)
3338 (push (replace-regexp-in-string
3339 "\t" (make-string tab-width ? )
3340 (buffer-substring-no-properties (point) obj-beg))
3341 acc)))
3342 ;; 2. Object...
3343 (let ((obj-end (org-element-get-property :end next-object))
3344 (cont-beg (org-element-get-property :contents-begin next-object)))
3345 (push (if (and (memq (car next-object) org-element-recursive-objects)
3346 cont-beg)
3347 ;; ... recursive. The CONT-BEG check is for
3348 ;; links, as some of them might not be recursive
3349 ;; (i.e. plain links).
3350 (save-restriction
3351 (narrow-to-region
3352 cont-beg
3353 (org-element-get-property :contents-end next-object))
3354 (org-element-parse-objects
3355 (point-min) (point-max) (reverse next-object)
3356 ;; Restrict allowed objects. This is the
3357 ;; intersection of current restriction and next
3358 ;; object's restriction.
3359 (let ((new-restr
3360 (cdr (assq (car next-object)
3361 org-element-object-restrictions))))
3362 (if (not restriction) new-restr
3363 (delq nil (mapcar
3364 (lambda (e) (and (memq e restriction) e))
3365 new-restr))))))
3366 ;; ... not recursive.
3367 next-object)
3368 acc)
3369 (goto-char obj-end)))
3370 ;; 3. Text after last object. Untabify it.
3371 (unless (= (point) end)
3372 (push (replace-regexp-in-string
3373 "\t" (make-string tab-width ? )
3374 (buffer-substring-no-properties (point) end))
3375 acc))
3376 ;; Result.
3377 (nreverse acc))))
3379 (defun org-element-get-next-object-candidates (limit restriction objects)
3380 "Return an alist of candidates for the next object.
3382 LIMIT bounds the search, and RESTRICTION, when non-nil, bounds
3383 the possible object types.
3385 Return value is an alist whose car is position and cdr the object
3386 type, as a string. There is an association for the closest
3387 object of each type within RESTRICTION when non-nil, or for every
3388 type otherwise.
3390 OBJECTS is the previous candidates alist."
3391 (let ((restriction (or restriction org-element-all-successors))
3392 next-candidates types-to-search)
3393 ;; If no previous result, search every object type in RESTRICTION.
3394 ;; Otherwise, keep potential candidates (old objects located after
3395 ;; point) and ask to search again those which had matched before.
3396 (if (not objects) (setq types-to-search restriction)
3397 (mapc (lambda (obj)
3398 (if (< (cdr obj) (point)) (push (car obj) types-to-search)
3399 (push obj next-candidates)))
3400 objects))
3401 ;; Call the appropriate "get-next" function for each type to
3402 ;; search and accumulate matches.
3403 (mapc
3404 (lambda (type)
3405 (let* ((successor-fun
3406 (intern
3407 (format "org-element-%s-successor"
3408 (or (cdr (assq type org-element-object-successor-alist))
3409 type))))
3410 (obj (funcall successor-fun limit)))
3411 (and obj (push obj next-candidates))))
3412 types-to-search)
3413 ;; Return alist.
3414 next-candidates))
3418 ;;; Towards A Bijective Process
3420 ;; The parse tree obtained with `org-element-parse-buffer' is really
3421 ;; a snapshot of the corresponding Org buffer. Therefore, it can be
3422 ;; interpreted and expanded into a string with canonical Org
3423 ;; syntax. Hence `org-element-interpret-data'.
3425 ;; Data parsed from secondary strings, whose shape is slightly
3426 ;; different than the standard parse tree, is expanded with the
3427 ;; equivalent function `org-element-interpret-secondary'.
3429 ;; Both functions rely internally on
3430 ;; `org-element-interpret--affiliated-keywords'.
3432 (defun org-element-interpret-data (data &optional genealogy previous)
3433 "Interpret a parse tree representing Org data.
3435 DATA is the parse tree to interpret.
3437 Optional arguments GENEALOGY and PREVIOUS are used for recursive
3438 calls:
3439 GENEALOGY is the list of its parents types.
3440 PREVIOUS is the type of the element or object at the same level
3441 interpreted before.
3443 Return Org syntax as a string."
3444 (mapconcat
3445 (lambda (blob)
3446 ;; BLOB can be an element, an object, a string, or nil.
3447 (cond
3448 ((not blob) nil)
3449 ((equal blob "") nil)
3450 ((stringp blob) blob)
3452 (let* ((type (car blob))
3453 (interpreter
3454 (if (eq type 'org-data) 'identity
3455 (intern (format "org-element-%s-interpreter" type))))
3456 (contents
3457 (cond
3458 ;; Full Org document.
3459 ((eq type 'org-data)
3460 (org-element-interpret-data blob genealogy previous))
3461 ;; Recursive objects.
3462 ((memq type org-element-recursive-objects)
3463 (org-element-interpret-data
3464 blob (cons type genealogy) nil))
3465 ;; Recursive elements.
3466 ((memq type org-element-greater-elements)
3467 (org-element-normalize-string
3468 (org-element-interpret-data
3469 blob (cons type genealogy) nil)))
3470 ;; Paragraphs.
3471 ((eq type 'paragraph)
3472 (let ((paragraph
3473 (org-element-normalize-contents
3474 blob
3475 ;; When normalizing contents of an item,
3476 ;; ignore first line's indentation.
3477 (and (not previous)
3478 (memq (car genealogy)
3479 '(footnote-definiton item))))))
3480 (org-element-interpret-data
3481 paragraph (cons type genealogy) nil)))))
3482 (results (funcall interpreter blob contents)))
3483 ;; Update PREVIOUS.
3484 (setq previous type)
3485 ;; Build white spaces.
3486 (cond
3487 ((eq type 'org-data) results)
3488 ((memq type org-element-all-elements)
3489 (concat
3490 (org-element-interpret--affiliated-keywords blob)
3491 (org-element-normalize-string results)
3492 (make-string (org-element-get-property :post-blank blob) 10)))
3493 (t (concat
3494 results
3495 (make-string
3496 (org-element-get-property :post-blank blob) 32))))))))
3497 (org-element-get-contents data) ""))
3499 (defun org-element-interpret-secondary (secondary)
3500 "Interpret SECONDARY string as Org syntax.
3502 SECONDARY-STRING is a nested list as returned by
3503 `org-element-parse-secondary-string'.
3505 Return interpreted string."
3506 ;; Make SECONDARY acceptable for `org-element-interpret-data'.
3507 (let ((s (if (listp secondary) secondary (list secondary))))
3508 (org-element-interpret-data `(org-data nil ,@s) nil nil)))
3510 ;; Both functions internally use `org-element--affiliated-keywords'.
3512 (defun org-element-interpret--affiliated-keywords (element)
3513 "Return ELEMENT's affiliated keywords as Org syntax.
3514 If there is no affiliated keyword, return the empty string."
3515 (let ((keyword-to-org
3516 (function
3517 (lambda (key value)
3518 (let (dual)
3519 (when (member key org-element-dual-keywords)
3520 (setq dual (cdr value) value (car value)))
3521 (concat "#+" key (and dual (format "[%s]" dual)) ": "
3522 (if (member key org-element-parsed-keywords)
3523 (org-element-interpret-secondary value)
3524 value)
3525 "\n"))))))
3526 (mapconcat
3527 (lambda (key)
3528 (let ((value (org-element-get-property (intern (concat ":" key)) element)))
3529 (when value
3530 (if (member key org-element-multiple-keywords)
3531 (mapconcat (lambda (line)
3532 (funcall keyword-to-org key line))
3533 value "")
3534 (funcall keyword-to-org key value)))))
3535 ;; Remove translated keywords.
3536 (delq nil
3537 (mapcar
3538 (lambda (key)
3539 (and (not (assoc key org-element-keyword-translation-alist)) key))
3540 org-element-affiliated-keywords))
3541 "")))
3543 ;; Because interpretation of the parse tree must return the same
3544 ;; number of blank lines between elements and the same number of white
3545 ;; space after objects, some special care must be given to white
3546 ;; spaces.
3548 ;; The first function, `org-element-normalize-string', ensures any
3549 ;; string different from the empty string will end with a single
3550 ;; newline character.
3552 ;; The second function, `org-element-normalize-contents', removes
3553 ;; global indentation from the contents of the current element.
3555 (defun org-element-normalize-string (s)
3556 "Ensure string S ends with a single newline character.
3558 If S isn't a string return it unchanged. If S is the empty
3559 string, return it. Otherwise, return a new string with a single
3560 newline character at its end."
3561 (cond
3562 ((not (stringp s)) s)
3563 ((string= "" s) "")
3564 (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
3565 (replace-match "\n" nil nil s)))))
3567 (defun org-element-normalize-contents (element &optional ignore-first)
3568 "Normalize plain text in ELEMENT's contents.
3570 ELEMENT must only contain plain text and objects.
3572 The following changes are applied to plain text:
3573 - Remove global indentation, preserving relative one.
3574 - Untabify it.
3576 If optional argument IGNORE-FIRST is non-nil, ignore first line's
3577 indentation to compute maximal common indentation.
3579 Return the normalized element."
3580 (nconc
3581 (list (car element) (nth 1 element))
3582 (let ((contents (org-element-get-contents element)))
3583 (if (not (or ignore-first (stringp (car contents)))) contents
3584 (catch 'exit
3585 ;; 1. Get maximal common indentation (MCI) among each string
3586 ;; in CONTENTS.
3587 (let* ((ind-list (unless ignore-first
3588 (list (org-get-string-indentation (car contents)))))
3589 (contents
3590 (mapcar
3591 (lambda (object)
3592 (if (not (stringp object)) object
3593 (let ((start 0))
3594 (while (string-match "\n\\( *\\)" object start)
3595 (setq start (match-end 0))
3596 (push (length (match-string 1 object)) ind-list))
3597 object)))
3598 contents))
3599 (mci (if ind-list (apply 'min ind-list)
3600 (throw 'exit contents))))
3601 ;; 2. Remove that indentation from CONTENTS. First string
3602 ;; must be treated differently because it's the only one
3603 ;; whose indentation doesn't happen after a newline
3604 ;; character.
3605 (let ((first-obj (car contents)))
3606 (unless (or (not (stringp first-obj)) ignore-first)
3607 (setq contents
3608 (cons (replace-regexp-in-string
3609 (format "\\` \\{%d\\}" mci) "" first-obj)
3610 (cdr contents)))))
3611 (mapcar (lambda (object)
3612 (if (not (stringp object)) object
3613 (replace-regexp-in-string
3614 (format "\n \\{%d\\}" mci) "\n" object)))
3615 contents)))))))
3619 ;;; The Toolbox
3621 ;; Once the structure of an Org file is well understood, it's easy to
3622 ;; implement some replacements for `forward-paragraph'
3623 ;; `backward-paragraph', namely `org-element-forward' and
3624 ;; `org-element-backward'.
3626 ;; Also, `org-transpose-elements' mimics the behaviour of
3627 ;; `transpose-words', at the element's level, whereas
3628 ;; `org-element-drag-forward', `org-element-drag-backward', and
3629 ;; `org-element-up' generalize, respectively, functions
3630 ;; `org-subtree-down', `org-subtree-up' and `outline-up-heading'.
3632 ;; `org-element-unindent-buffer' will, as its name almost suggests,
3633 ;; smartly remove global indentation from buffer, making it possible
3634 ;; to use Org indent mode on a file created with hard indentation.
3636 ;; `org-element-nested-p' and `org-element-swap-A-B' are used
3637 ;; internally by some of the previously cited tools.
3639 (defsubst org-element-nested-p (elem-A elem-B)
3640 "Non-nil when elements ELEM-A and ELEM-B are nested."
3641 (let ((beg-A (org-element-get-property :begin elem-A))
3642 (beg-B (org-element-get-property :begin elem-B))
3643 (end-A (org-element-get-property :end elem-A))
3644 (end-B (org-element-get-property :end elem-B)))
3645 (or (and (>= beg-A beg-B) (<= end-A end-B))
3646 (and (>= beg-B beg-A) (<= end-B end-A)))))
3648 (defun org-element-swap-A-B (elem-A elem-B)
3649 "Swap elements ELEM-A and ELEM-B.
3651 Leave point at the end of ELEM-A.
3653 Assume ELEM-A is before ELEM-B and that they are not nested."
3654 (goto-char (org-element-get-property :begin elem-A))
3655 (let* ((beg-B (org-element-get-property :begin elem-B))
3656 (end-B-no-blank (save-excursion
3657 (goto-char (org-element-get-property :end elem-B))
3658 (skip-chars-backward " \r\t\n")
3659 (forward-line)
3660 (point)))
3661 (beg-A (org-element-get-property :begin elem-A))
3662 (end-A-no-blank (save-excursion
3663 (goto-char (org-element-get-property :end elem-A))
3664 (skip-chars-backward " \r\t\n")
3665 (forward-line)
3666 (point)))
3667 (body-A (buffer-substring beg-A end-A-no-blank))
3668 (body-B (buffer-substring beg-B end-B-no-blank))
3669 (between-A-B (buffer-substring end-A-no-blank beg-B)))
3670 (delete-region beg-A end-B-no-blank)
3671 (insert body-B between-A-B body-A)
3672 (goto-char (org-element-get-property :end elem-B))))
3674 (defun org-element-backward ()
3675 "Move backward by one element."
3676 (interactive)
3677 (let* ((opoint (point))
3678 (element (org-element-at-point))
3679 (start-el-beg (org-element-get-property :begin element)))
3680 ;; At an headline. The previous element is the previous sibling,
3681 ;; or the parent if any.
3682 (cond
3683 ;; Already at the beginning of the current element: move to the
3684 ;; beginning of the previous one.
3685 ((= opoint start-el-beg)
3686 (forward-line -1)
3687 (skip-chars-backward " \r\t\n")
3688 (let* ((prev-element (org-element-at-point))
3689 (itemp (org-in-item-p))
3690 (struct (and itemp
3691 (save-excursion (goto-char itemp)
3692 (org-list-struct)))))
3693 ;; When moving into a new list, go directly at the
3694 ;; beginning of the top list structure.
3695 (if (and itemp (<= (org-list-get-bottom-point struct) opoint))
3696 (progn
3697 (goto-char (org-list-get-top-point struct))
3698 (goto-char (org-element-get-property
3699 :begin (org-element-at-point))))
3700 (goto-char (org-element-get-property :begin prev-element))))
3701 (while (org-truely-invisible-p) (org-element-up)))
3702 ;; Else, move at the element beginning. One exception: if point
3703 ;; was in the blank lines after the end of a list, move directly
3704 ;; to the top item.
3706 (let (struct itemp)
3707 (if (and (setq itemp (org-in-item-p))
3708 (<= (org-list-get-bottom-point
3709 (save-excursion (goto-char itemp)
3710 (setq struct (org-list-struct))))
3711 opoint))
3712 (progn (goto-char (org-list-get-top-point struct))
3713 (goto-char (org-element-get-property
3714 :begin (org-element-at-point))))
3715 (goto-char start-el-beg)))))))
3717 (defun org-element-drag-backward ()
3718 "Drag backward element at point."
3719 (interactive)
3720 (let* ((pos (point))
3721 (elem (org-element-at-point)))
3722 (when (= (progn (goto-char (point-min))
3723 (org-skip-whitespace)
3724 (point-at-bol))
3725 (org-element-get-property :end elem))
3726 (error "Cannot drag element backward"))
3727 (goto-char (org-element-get-property :begin elem))
3728 (org-element-backward)
3729 (let ((prev-elem (org-element-at-point)))
3730 (when (or (org-element-nested-p elem prev-elem)
3731 (and (eq (car elem) 'headline)
3732 (not (eq (car prev-elem) 'headline))))
3733 (goto-char pos)
3734 (error "Cannot drag element backward"))
3735 ;; Compute new position of point: it's shifted by PREV-ELEM
3736 ;; body's length.
3737 (let ((size-prev (- (org-element-get-property :end prev-elem)
3738 (org-element-get-property :begin prev-elem))))
3739 (org-element-swap-A-B prev-elem elem)
3740 (goto-char (- pos size-prev))))))
3742 (defun org-element-drag-forward ()
3743 "Move forward element at point."
3744 (interactive)
3745 (let* ((pos (point))
3746 (elem (org-element-at-point)))
3747 (when (= (point-max) (org-element-get-property :end elem))
3748 (error "Cannot drag element forward"))
3749 (goto-char (org-element-get-property :end elem))
3750 (let ((next-elem (org-element-at-point)))
3751 (when (or (org-element-nested-p elem next-elem)
3752 (and (eq (car next-elem) 'headline)
3753 (not (eq (car elem) 'headline))))
3754 (goto-char pos)
3755 (error "Cannot drag element forward"))
3756 ;; Compute new position of point: it's shifted by NEXT-ELEM
3757 ;; body's length (without final blanks) and by the length of
3758 ;; blanks between ELEM and NEXT-ELEM.
3759 (let ((size-next (- (save-excursion
3760 (goto-char (org-element-get-property :end next-elem))
3761 (skip-chars-backward " \r\t\n")
3762 (forward-line)
3763 (point))
3764 (org-element-get-property :begin next-elem)))
3765 (size-blank (- (org-element-get-property :end elem)
3766 (save-excursion
3767 (goto-char (org-element-get-property :end elem))
3768 (skip-chars-backward " \r\t\n")
3769 (forward-line)
3770 (point)))))
3771 (org-element-swap-A-B elem next-elem)
3772 (goto-char (+ pos size-next size-blank))))))
3774 (defun org-element-forward ()
3775 "Move forward by one element."
3776 (interactive)
3777 (beginning-of-line)
3778 (cond ((eobp) (error "Cannot move further down"))
3779 ((looking-at "[ \t]*$")
3780 (org-skip-whitespace)
3781 (goto-char (if (eobp) (point) (point-at-bol))))
3783 (let ((element (org-element-at-point t))
3784 (origin (point)))
3785 (cond
3786 ;; At an item: Either move to the next element inside, or
3787 ;; to its end if it's hidden.
3788 ((eq (car element) 'item)
3789 (if (org-element-get-property :hiddenp element)
3790 (goto-char (org-element-get-property :end element))
3791 (end-of-line)
3792 (re-search-forward org-element-paragraph-separate nil t)
3793 (org-skip-whitespace)
3794 (beginning-of-line)))
3795 ;; At a recursive element: Either move inside, or if it's
3796 ;; hidden, move to its end.
3797 ((memq (car element) org-element-greater-elements)
3798 (let ((cbeg (org-element-get-property :contents-begin element)))
3799 (goto-char
3800 (if (or (org-element-get-property :hiddenp element)
3801 (> origin cbeg))
3802 (org-element-get-property :end element)
3803 cbeg))))
3804 ;; Else: move to the current element's end.
3805 (t (goto-char (org-element-get-property :end element))))))))
3807 (defun org-element-mark-element ()
3808 "Put point at beginning of this element, mark at end.
3810 Interactively, if this command is repeated or (in Transient Mark
3811 mode) if the mark is active, it marks the next element after the
3812 ones already marked."
3813 (interactive)
3814 (let (deactivate-mark)
3815 (if (or (and (eq last-command this-command) (mark t))
3816 (and transient-mark-mode mark-active))
3817 (set-mark
3818 (save-excursion
3819 (goto-char (mark))
3820 (goto-char (org-element-get-property :end (org-element-at-point)))))
3821 (let ((element (org-element-at-point)))
3822 (end-of-line)
3823 (push-mark (org-element-get-property :end element) t t)
3824 (goto-char (org-element-get-property :begin element))))))
3826 (defun org-narrow-to-element ()
3827 "Narrow buffer to current element."
3828 (interactive)
3829 (let ((elem (org-element-at-point)))
3830 (cond
3831 ((eq (car elem) 'headline)
3832 (narrow-to-region
3833 (org-element-get-property :begin elem)
3834 (org-element-get-property :end elem)))
3835 ((memq (car elem) org-element-greater-elements)
3836 (narrow-to-region
3837 (org-element-get-property :contents-begin elem)
3838 (org-element-get-property :contents-end elem)))
3840 (narrow-to-region
3841 (org-element-get-property :begin elem)
3842 (org-element-get-property :end elem))))))
3844 (defun org-transpose-elements ()
3845 "Transpose current and previous elements, keeping blank lines between.
3846 Point is moved after both elements."
3847 (interactive)
3848 (org-skip-whitespace)
3849 (let ((pos (point))
3850 (cur (org-element-at-point)))
3851 (when (= (save-excursion (goto-char (point-min))
3852 (org-skip-whitespace)
3853 (point-at-bol))
3854 (org-element-get-property :begin cur))
3855 (error "No previous element"))
3856 (goto-char (org-element-get-property :begin cur))
3857 (forward-line -1)
3858 (let ((prev (org-element-at-point)))
3859 (when (org-element-nested-p cur prev)
3860 (goto-char pos)
3861 (error "Cannot transpose nested elements"))
3862 (org-element-swap-A-B prev cur))))
3864 (defun org-element-unindent-buffer ()
3865 "Un-indent the visible part of the buffer.
3866 Relative indentation \(between items, inside blocks, etc.\) isn't
3867 modified."
3868 (interactive)
3869 (unless (eq major-mode 'org-mode)
3870 (error "Cannot un-indent a buffer not in Org mode"))
3871 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
3872 unindent-tree ; For byte-compiler.
3873 (unindent-tree
3874 (function
3875 (lambda (contents)
3876 (mapc (lambda (element)
3877 (if (eq (car element) 'headline)
3878 (funcall unindent-tree
3879 (org-element-get-contents element))
3880 (save-excursion
3881 (save-restriction
3882 (narrow-to-region
3883 (org-element-get-property :begin element)
3884 (org-element-get-property :end element))
3885 (org-do-remove-indentation)))))
3886 (reverse contents))))))
3887 (funcall unindent-tree (org-element-get-contents parse-tree))))
3889 (defun org-element-up ()
3890 "Move to upper element.
3891 Return position at the beginning of the upper element."
3892 (interactive)
3893 (let ((opoint (point)) elem)
3894 (cond
3895 ((bobp) (error "No surrounding element"))
3896 ((org-with-limited-levels (org-at-heading-p))
3897 (or (org-up-heading-safe) (error "No surronding element")))
3898 ((and (org-at-item-p)
3899 (setq elem (org-element-at-point))
3900 (let* ((top-list-p (zerop (org-element-get-property :level elem))))
3901 (unless top-list-p
3902 ;; If parent is bound to be in the same list as the
3903 ;; original point, move to that parent.
3904 (let ((struct (org-element-get-property :structure elem)))
3905 (goto-char
3906 (org-list-get-parent
3907 (point-at-bol) struct (org-list-parents-alist struct))))))))
3909 (let* ((elem (or elem (org-element-at-point)))
3910 (end (save-excursion
3911 (goto-char (org-element-get-property :end elem))
3912 (skip-chars-backward " \r\t\n")
3913 (forward-line)
3914 (point)))
3915 prev-elem)
3916 (goto-char (org-element-get-property :begin elem))
3917 (forward-line -1)
3918 (while (and (< (org-element-get-property
3919 :end (setq prev-elem (org-element-at-point)))
3920 end)
3921 (not (bobp)))
3922 (goto-char (org-element-get-property :begin prev-elem))
3923 (forward-line -1))
3924 (if (and (bobp) (< (org-element-get-property :end prev-elem) end))
3925 (progn (goto-char opoint)
3926 (error "No surrounding element"))
3927 (goto-char (org-element-get-property :begin prev-elem))))))))
3930 (provide 'org-element)
3931 ;;; org-element.el ends here