org-element.el 151 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
;;; org-element.el --- Parser And Applications for Org syntax

;; Copyright (C) 2012  Free Software Foundation, Inc.

;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, wp

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; Org syntax can be divided into three categories: "Greater
;; elements", "Elements" and "Objects".
;;
;; Elements are related to the structure of the document.  Indeed, all
;; elements are a cover for the document: each position within belongs
;; to at least one element.
;;
;; An element always starts and ends at the beginning of a line.  With
;; a few exceptions (namely `babel-call', `clock', `headline', `item',
;; `keyword', `planning', `property-drawer' and `section' types), it
;; can also accept a fixed set of keywords as attributes.  Those are
;; called "affiliated keywords" to distinguish them from other
;; keywords, which are full-fledged elements.  Almost all affiliated
;; keywords are referenced in `org-element-affiliated-keywords'; the
;; others are export attributes and start with "ATTR_" prefix.
;;
;; Element containing other elements (and only elements) are called
;; greater elements.  Concerned types are: `center-block', `drawer',
;; `dynamic-block', `footnote-definition', `headline', `inlinetask',
;; `item', `plain-list', `quote-block', `section' and `special-block'.
;;
;; Other element types are: `babel-call', `clock', `comment',
;; `comment-block', `example-block', `export-block', `fixed-width',
;; `horizontal-rule', `keyword', `latex-environment', `paragraph',
;; `planning', `property-drawer', `quote-section', `src-block',
;; `table', `table-row' and `verse-block'.  Among them, `paragraph'
;; and `verse-block' types can contain Org objects and plain text.
;;
;; Objects are related to document's contents.  Some of them are
;; recursive.  Associated types are of the following: `bold', `code',
;; `entity', `export-snippet', `footnote-reference',
;; `inline-babel-call', `inline-src-block', `italic',
;; `latex-fragment', `line-break', `link', `macro', `radio-target',
;; `statistics-cookie', `strike-through', `subscript', `superscript',
;; `table-cell', `target', `timestamp', `underline' and `verbatim'.
;;
;; Some elements also have special properties whose value can hold
;; objects themselves (i.e. an item tag or an headline name).  Such
;; values are called "secondary strings".  Any object belongs to
;; either an element or a secondary string.
;;
;; Notwithstanding affiliated keywords, each greater element, element
;; and object has a fixed set of properties attached to it.  Among
;; them, four are shared by all types: `:begin' and `:end', which
;; refer to the beginning and ending buffer positions of the
;; considered element or object, `:post-blank', which holds the number
;; of blank lines, or white spaces, at its end and `:parent' which
;; refers to the element or object containing it.  Greater elements
;; and elements containing objects will also have `:contents-begin'
;; and `:contents-end' properties to delimit contents.
;;
;; Lisp-wise, an element or an object can be represented as a list.
;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
;;   TYPE is a symbol describing the Org element or object.
;;   PROPERTIES is the property list attached to it.  See docstring of
;;              appropriate parsing function to get an exhaustive
;;              list.
;;   CONTENTS is a list of elements, objects or raw strings contained
;;            in the current element or object, when applicable.
;;
;; An Org buffer is a nested list of such elements and objects, whose
;; type is `org-data' and properties is nil.
;;
;; The first part of this file defines Org syntax, while the second
;; one provide accessors and setters functions.
;;
;; The next part implements a parser and an interpreter for each
;; element and object type in Org syntax.
;;
;; The following part creates a fully recursive buffer parser.  It
;; also provides a tool to map a function to elements or objects
;; matching some criteria in the parse tree.  Functions of interest
;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
;; extent, `org-element-parse-secondary-string'.
;;
;; The penultimate part is the cradle of an interpreter for the
;; obtained parse tree: `org-element-interpret-data'.
;;
;; The library ends by furnishing `org-element-at-point' function, and
;; a way to give information about document structure around point
;; with `org-element-context'.


;;; Code:

(eval-when-compile
  (require 'cl))

(require 'org)


;;; Definitions And Rules
;;
;; Define elements, greater elements and specify recursive objects,
;; along with the affiliated keywords recognized.  Also set up
;; restrictions on recursive objects combinations.
;;
;; These variables really act as a control center for the parsing
;; process.

(defconst org-element-paragraph-separate
  (concat "^\\(?:"
          ;; Headlines, inlinetasks.
          org-outline-regexp "\\|"
          ;; Footnote definitions.
	  "\\[\\(?:[0-9]+\\|fn:[-_[:word:]]+\\)\\]" "\\|"
          "[ \t]*\\(?:"
          ;; Empty lines.
          "$" "\\|"
	  ;; Tables (any type).
	  "\\(?:|\\|\\+-[-+]\\)" "\\|"
          ;; Blocks (any type), Babel calls, drawers (any type),
	  ;; fixed-width areas and keywords.  Note: this is only an
	  ;; indication and need some thorough check.
          "[#:]" "\\|"
          ;; Horizontal rules.
          "-\\{5,\\}[ \t]*$" "\\|"
          ;; LaTeX environments.
          "\\\\begin{\\([A-Za-z0-9]+\\*?\\)}" "\\|"
          ;; Planning and Clock lines.
          (regexp-opt (list org-scheduled-string
                            org-deadline-string
                            org-closed-string
                            org-clock-string))
          "\\|"
          ;; Lists.
          (let ((term (case org-plain-list-ordered-item-terminator
                        (?\) ")") (?. "\\.") (otherwise "[.)]")))
                (alpha (and org-alphabetical-lists "\\|[A-Za-z]")))
            (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
                    "\\(?:[ \t]\\|$\\)"))
          "\\)\\)")
  "Regexp to separate paragraphs in an Org buffer.
In the case of lines starting with \"#\" and \":\", this regexp
is not sufficient to know if point is at a paragraph ending.  See
`org-element-paragraph-parser' for more information.")

(defconst org-element-all-elements
  '(center-block clock comment comment-block drawer dynamic-block example-block
		 export-block fixed-width footnote-definition headline
		 horizontal-rule inlinetask item keyword latex-environment
		 babel-call paragraph plain-list planning property-drawer
		 quote-block quote-section section special-block src-block table
		 table-row verse-block)
  "Complete list of element types.")

(defconst org-element-greater-elements
  '(center-block drawer dynamic-block footnote-definition headline inlinetask
		 item plain-list quote-block section special-block table)
  "List of recursive element types aka Greater Elements.")

(defconst org-element-all-successors
  '(export-snippet footnote-reference inline-babel-call inline-src-block
		   latex-or-entity line-break link macro radio-target
		   statistics-cookie sub/superscript table-cell target
		   text-markup timestamp)
  "Complete list of successors.")

(defconst org-element-object-successor-alist
  '((subscript . sub/superscript) (superscript . sub/superscript)
    (bold . text-markup) (code . text-markup) (italic . text-markup)
    (strike-through . text-markup) (underline . text-markup)
    (verbatim . text-markup) (entity . latex-or-entity)
    (latex-fragment . latex-or-entity))
  "Alist of translations between object type and successor name.

Sharing the same successor comes handy when, for example, the
regexp matching one object can also match the other object.")

(defconst org-element-all-objects
  '(bold code entity export-snippet footnote-reference inline-babel-call
	 inline-src-block italic line-break latex-fragment link macro
	 radio-target statistics-cookie strike-through subscript superscript
	 table-cell target timestamp underline verbatim)
  "Complete list of object types.")

(defconst org-element-recursive-objects
  '(bold italic link macro subscript radio-target strike-through superscript
	 table-cell underline)
  "List of recursive object types.")

(defconst org-element-block-name-alist
  '(("CENTER" . org-element-center-block-parser)
    ("COMMENT" . org-element-comment-block-parser)
    ("EXAMPLE" . org-element-example-block-parser)
    ("QUOTE" . org-element-quote-block-parser)
    ("SRC" . org-element-src-block-parser)
    ("VERSE" . org-element-verse-block-parser))
  "Alist between block names and the associated parsing function.
Names must be uppercase.  Any block whose name has no association
is parsed with `org-element-special-block-parser'.")

(defconst org-element-affiliated-keywords
  '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
    "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  "List of affiliated keywords as strings.
By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
are affiliated keywords and need not to be in this list.")

(defconst org-element--affiliated-re
  (format "[ \t]*#\\+%s:"
	  ;; Regular affiliated keywords.
	  (format "\\(%s\\|ATTR_[-_A-Za-z0-9]+\\)\\(?:\\[\\(.*\\)\\]\\)?"
		  (regexp-opt org-element-affiliated-keywords)))
  "Regexp matching any affiliated keyword.

Keyword name is put in match group 1.  Moreover, if keyword
belongs to `org-element-dual-keywords', put the dual value in
match group 2.

Don't modify it, set `org-element-affiliated-keywords' instead.")

(defconst org-element-keyword-translation-alist
  '(("DATA" . "NAME")  ("LABEL" . "NAME") ("RESNAME" . "NAME")
    ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
    ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  "Alist of usual translations for keywords.
The key is the old name and the value the new one.  The property
holding their value will be named after the translated name.")

(defconst org-element-multiple-keywords '("HEADER")
  "List of affiliated keywords that can occur more that once in an element.

Their value will be consed into a list of strings, which will be
returned as the value of the property.

This list is checked after translations have been applied.  See
`org-element-keyword-translation-alist'.

By default, all keywords setting attributes (i.e. \"ATTR_LATEX\")
allow multiple occurrences and need not to be in this list.")

(defconst org-element-parsed-keywords '("AUTHOR" "CAPTION" "DATE" "TITLE")
  "List of keywords whose value can be parsed.

Their value will be stored as a secondary string: a list of
strings and objects.

This list is checked after translations have been applied.  See
`org-element-keyword-translation-alist'.")

(defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  "List of keywords which can have a secondary value.

In Org syntax, they can be written with optional square brackets
before the colons.  For example, results keyword can be
associated to a hash value with the following:

  #+RESULTS[hash-string]: some-source

This list is checked after translations have been applied.  See
`org-element-keyword-translation-alist'.")

(defconst org-element-object-restrictions
  '((bold export-snippet inline-babel-call inline-src-block latex-or-entity link
	  radio-target sub/superscript target text-markup timestamp)
    (footnote-reference export-snippet footnote-reference inline-babel-call
			inline-src-block latex-or-entity line-break link macro
			radio-target sub/superscript target text-markup
			timestamp)
    (headline inline-babel-call inline-src-block latex-or-entity link macro
	      radio-target statistics-cookie sub/superscript target text-markup
	      timestamp)
    (inlinetask inline-babel-call inline-src-block latex-or-entity link macro
		radio-target sub/superscript target text-markup timestamp)
    (italic export-snippet inline-babel-call inline-src-block latex-or-entity
	    link radio-target sub/superscript target text-markup timestamp)
    (item export-snippet footnote-reference inline-babel-call latex-or-entity
	  link macro radio-target sub/superscript target text-markup)
    (keyword latex-or-entity macro sub/superscript text-markup)
    (link export-snippet inline-babel-call inline-src-block latex-or-entity link
	  sub/superscript text-markup)
    (macro macro)
    (paragraph export-snippet footnote-reference inline-babel-call
	       inline-src-block latex-or-entity line-break link macro
	       radio-target statistics-cookie sub/superscript target text-markup
	       timestamp)
    (radio-target export-snippet latex-or-entity sub/superscript)
    (strike-through export-snippet inline-babel-call inline-src-block
		    latex-or-entity link radio-target sub/superscript target
		    text-markup timestamp)
    (subscript export-snippet inline-babel-call inline-src-block latex-or-entity
	       sub/superscript target text-markup)
    (superscript export-snippet inline-babel-call inline-src-block
		 latex-or-entity sub/superscript target text-markup)
    (table-cell export-snippet latex-or-entity link macro radio-target
		sub/superscript target text-markup timestamp)
    (table-row table-cell)
    (underline export-snippet inline-babel-call inline-src-block latex-or-entity
	       link radio-target sub/superscript target text-markup timestamp)
    (verse-block footnote-reference inline-babel-call inline-src-block
		 latex-or-entity line-break link macro radio-target
		 sub/superscript target text-markup timestamp))
  "Alist of objects restrictions.

CAR is an element or object type containing objects and CDR is
a list of successors that will be called within an element or
object of such type.

For example, in a `radio-target' object, one can only find
entities, export snippets, latex-fragments, subscript and
superscript.

This alist also applies to secondary string.  For example, an
`headline' type element doesn't directly contain objects, but
still has an entry since one of its properties (`:title') does.")

(defconst org-element-secondary-value-alist
  '((headline . :title)
    (inlinetask . :title)
    (item . :tag)
    (footnote-reference . :inline-definition))
  "Alist between element types and location of secondary value.")



;;; Accessors and Setters
;;
;; Provide four accessors: `org-element-type', `org-element-property'
;; `org-element-contents' and `org-element-restriction'.
;;
;; Setter functions allow to modify elements by side effect.  There is
;; `org-element-put-property', `org-element-set-contents',
;; `org-element-set-element' and `org-element-adopt-element'.  Note
;; that `org-element-set-element' and `org-element-adopt-elements' are
;; higher level functions since also update `:parent' property.

(defsubst org-element-type (element)
  "Return type of ELEMENT.

The function returns the type of the element or object provided.
It can also return the following special value:
  `plain-text'       for a string
  `org-data'         for a complete document
  nil                in any other case."
  (cond
   ((not (consp element)) (and (stringp element) 'plain-text))
   ((symbolp (car element)) (car element))))

(defsubst org-element-property (property element)
  "Extract the value from the PROPERTY of an ELEMENT."
  (plist-get (nth 1 element) property))

(defsubst org-element-contents (element)
  "Extract contents from an ELEMENT."
  (and (consp element) (nthcdr 2 element)))

(defsubst org-element-restriction (element)
  "Return restriction associated to ELEMENT.
ELEMENT can be an element, an object or a symbol representing an
element or object type."
  (cdr (assq (if (symbolp element) element (org-element-type element))
	     org-element-object-restrictions)))

(defsubst org-element-put-property (element property value)
  "In ELEMENT set PROPERTY to VALUE.
Return modified element."
  (when (consp element)
    (setcar (cdr element) (plist-put (nth 1 element) property value)))
  element)

(defsubst org-element-set-contents (element &rest contents)
  "Set ELEMENT contents to CONTENTS.
Return modified element."
  (cond ((not element) (list contents))
	((cdr element) (setcdr (cdr element) contents))
	(t (nconc element contents))))

(defsubst org-element-set-element (old new)
  "Replace element or object OLD with element or object NEW.
The function takes care of setting `:parent' property for NEW."
  ;; Since OLD is going to be changed into NEW by side-effect, first
  ;; make sure that every element or object within NEW has OLD as
  ;; parent.
  (mapc (lambda (blob) (org-element-put-property blob :parent old))
	(org-element-contents new))
  ;; Transfer contents.
  (apply 'org-element-set-contents old (org-element-contents new))
  ;; Ensure NEW has same parent as OLD, then overwrite OLD properties
  ;; with NEW's.
  (org-element-put-property new :parent (org-element-property :parent old))
  (setcar (cdr old) (nth 1 new))
  ;; Transfer type.
  (setcar old (car new)))

(defsubst org-element-adopt-elements (parent &rest children)
  "Append elements to the contents of another element.

PARENT is an element or object.  CHILDREN can be elements,
objects, or a strings.

The function takes care of setting `:parent' property for CHILD.
Return parent element."
  (if (not parent) children
    ;; Link every child to PARENT.
    (mapc (lambda (child)
	    (unless (stringp child)
	      (org-element-put-property child :parent parent)))
	  children)
    ;; Add CHILDREN at the end of PARENT contents.
    (apply 'org-element-set-contents
	   parent
	   (nconc (org-element-contents parent) children))
    ;; Return modified PARENT element.
    parent))



;;; Greater elements
;;
;; For each greater element type, we define a parser and an
;; interpreter.
;;
;; A parser returns the element or object as the list described above.
;; Most of them accepts no argument.  Though, exceptions exist.  Hence
;; every element containing a secondary string (see
;; `org-element-secondary-value-alist') will accept an optional
;; argument to toggle parsing of that secondary string.  Moreover,
;; `item' parser requires current list's structure as its first
;; element.
;;
;; An interpreter accepts two arguments: the list representation of
;; the element or object, and its contents.  The latter may be nil,
;; depending on the element or object considered.  It returns the
;; appropriate Org syntax, as a string.
;;
;; Parsing functions must follow the naming convention:
;; org-element-TYPE-parser, where TYPE is greater element's type, as
;; defined in `org-element-greater-elements'.
;;
;; Similarly, interpreting functions must follow the naming
;; convention: org-element-TYPE-interpreter.
;;
;; With the exception of `headline' and `item' types, greater elements
;; cannot contain other greater elements of their own type.
;;
;; Beside implementing a parser and an interpreter, adding a new
;; greater element requires to tweak `org-element--current-element'.
;; Moreover, the newly defined type must be added to both
;; `org-element-all-elements' and `org-element-greater-elements'.


;;;; Center Block

(defun org-element-center-block-parser (limit)
  "Parse a center block.

LIMIT bounds the search.

Return a list whose CAR is `center-block' and CDR is a plist
containing `:begin', `:end', `:hiddenp', `:contents-begin',
`:contents-end' and `:post-blank' keywords.

Assume point is at the beginning of the block."
  (let ((case-fold-search t))
    (if (not (save-excursion
481
	       (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((block-end-line (match-beginning 0)))
	(let* ((keywords (org-element--collect-affiliated-keywords))
	       (begin (car keywords))
	       ;; Empty blocks have no contents.
	       (contents-begin (progn (forward-line)
				      (and (< (point) block-end-line)
					   (point))))
	       (contents-end (and contents-begin block-end-line))
	       (hidden (org-invisible-p2))
	       (pos-before-blank (progn (goto-char block-end-line)
					(forward-line)
					(point)))
	       (end (save-excursion (skip-chars-forward " \r\t\n" limit)
497 498
				    (skip-chars-backward " \t")
				    (if (bolp) (point) (line-end-position)))))
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	  (list 'center-block
		(nconc
		 (list :begin begin
		       :end end
		       :hiddenp hidden
		       :contents-begin contents-begin
		       :contents-end contents-end
		       :post-blank (count-lines pos-before-blank end))
		 (cadr keywords))))))))

(defun org-element-center-block-interpreter (center-block contents)
  "Interpret CENTER-BLOCK element as Org syntax.
CONTENTS is the contents of the element."
  (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))


;;;; Drawer

(defun org-element-drawer-parser (limit)
  "Parse a drawer.

LIMIT bounds the search.

Return a list whose CAR is `drawer' and CDR is a plist containing
`:drawer-name', `:begin', `:end', `:hiddenp', `:contents-begin',
`:contents-end' and `:post-blank' keywords.

Assume point is at beginning of drawer."
  (let ((case-fold-search t))
528
    (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	;; Incomplete drawer: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((drawer-end-line (match-beginning 0)))
	(save-excursion
	  (let* ((case-fold-search t)
		 (name (progn (looking-at org-drawer-regexp)
			      (org-match-string-no-properties 1)))
		 (keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 ;; Empty drawers have no contents.
		 (contents-begin (progn (forward-line)
					(and (< (point) drawer-end-line)
					     (point))))
		 (contents-end (and contents-begin drawer-end-line))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char drawer-end-line)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
548 549
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position)))))
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
	    (list 'drawer
		  (nconc
		   (list :begin begin
			 :end end
			 :drawer-name name
			 :hiddenp hidden
			 :contents-begin contents-begin
			 :contents-end contents-end
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-drawer-interpreter (drawer contents)
  "Interpret DRAWER element as Org syntax.
CONTENTS is the contents of the element."
  (format ":%s:\n%s:END:"
	  (org-element-property :drawer-name drawer)
	  contents))


;;;; Dynamic Block

(defun org-element-dynamic-block-parser (limit)
  "Parse a dynamic block.

LIMIT bounds the search.

Return a list whose CAR is `dynamic-block' and CDR is a plist
containing `:block-name', `:begin', `:end', `:hiddenp',
`:contents-begin', `:contents-end', `:arguments' and
`:post-blank' keywords.

Assume point is at beginning of dynamic block."
  (let ((case-fold-search t))
583 584
    (if (not (save-excursion
	       (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((block-end-line (match-beginning 0)))
	(save-excursion
	  (let* ((name (progn (looking-at org-dblock-start-re)
			      (org-match-string-no-properties 1)))
		 (arguments (org-match-string-no-properties 3))
		 (keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 ;; Empty blocks have no contents.
		 (contents-begin (progn (forward-line)
					(and (< (point) block-end-line)
					     (point))))
		 (contents-end (and contents-begin block-end-line))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char block-end-line)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
604 605
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position)))))
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
	    (list 'dynamic-block
		  (nconc
		   (list :begin begin
			 :end end
			 :block-name name
			 :arguments arguments
			 :hiddenp hidden
			 :contents-begin contents-begin
			 :contents-end contents-end
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-dynamic-block-interpreter (dynamic-block contents)
  "Interpret DYNAMIC-BLOCK element as Org syntax.
CONTENTS is the contents of the element."
  (format "#+BEGIN: %s%s\n%s#+END:"
	  (org-element-property :block-name dynamic-block)
	  (let ((args (org-element-property :arguments dynamic-block)))
	    (and args (concat " " args)))
	  contents))


;;;; Footnote Definition

(defun org-element-footnote-definition-parser (limit)
  "Parse a footnote definition.

LIMIT bounds the search.

Return a list whose CAR is `footnote-definition' and CDR is
a plist containing `:label', `:begin' `:end', `:contents-begin',
`:contents-end' and `:post-blank' keywords.

Assume point is at the beginning of the footnote definition."
  (save-excursion
    (let* ((label (progn (looking-at org-footnote-definition-re)
			 (org-match-string-no-properties 1)))
	   (keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (ending (save-excursion
		     (if (progn
			   (end-of-line)
			   (re-search-forward
			    (concat org-outline-regexp-bol "\\|"
				    org-footnote-definition-re "\\|"
				    "^[ \t]*$") limit 'move))
			 (match-beginning 0)
		       (point))))
	   (contents-begin (progn (search-forward "]")
				  (skip-chars-forward " \r\t\n" ending)
				  (and (/= (point) ending) (point))))
	   (contents-end (and contents-begin ending))
	   (end (progn (goto-char ending)
		       (skip-chars-forward " \r\t\n" limit)
660 661
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
      (list 'footnote-definition
	    (nconc
	     (list :label label
		   :begin begin
		   :end end
		   :contents-begin contents-begin
		   :contents-end contents-end
		   :post-blank (count-lines ending end))
	     (cadr keywords))))))

(defun org-element-footnote-definition-interpreter (footnote-definition contents)
  "Interpret FOOTNOTE-DEFINITION element as Org syntax.
CONTENTS is the contents of the footnote-definition."
  (concat (format "[%s]" (org-element-property :label footnote-definition))
	  " "
	  contents))


;;;; Headline

(defun org-element-headline-parser (limit &optional raw-secondary-p)
  "Parse an headline.

Return a list whose CAR is `headline' and CDR is a plist
containing `:raw-value', `:title', `:begin', `:end',
`:pre-blank', `:hiddenp', `:contents-begin' and `:contents-end',
`:level', `:priority', `:tags', `:todo-keyword',`:todo-type',
`:scheduled', `:deadline', `:timestamp', `:clock', `:category',
`:quotedp', `:archivedp', `:commentedp' and `:footnote-section-p'
keywords.

The plist also contains any property set in the property drawer,
with its name in lowercase, the underscores replaced with hyphens
and colons at the beginning (i.e. `:custom-id').

When RAW-SECONDARY-P is non-nil, headline's title will not be
parsed as a secondary string, but as a plain string instead.

Assume point is at beginning of the headline."
  (save-excursion
    (let* ((components (org-heading-components))
	   (level (nth 1 components))
	   (todo (nth 2 components))
	   (todo-type
	    (and todo (if (member todo org-done-keywords) 'done 'todo)))
	   (tags (let ((raw-tags (nth 5 components)))
		   (and raw-tags (org-split-string raw-tags ":"))))
	   (raw-value (or (nth 4 components) ""))
	   (quotedp
	    (let ((case-fold-search nil))
	      (string-match (format "^%s\\( \\|$\\)" org-quote-string)
			    raw-value)))
	   (commentedp
	    (let ((case-fold-search nil))
	      (string-match (format "^%s\\( \\|$\\)" org-comment-string)
			    raw-value)))
	   (archivedp (member org-archive-tag tags))
	   (footnote-section-p (and org-footnote-section
				    (string= org-footnote-section raw-value)))
	   ;; Normalize property names: ":SOME_PROP:" becomes
	   ;; ":some-prop".
	   (standard-props (let (plist)
			     (mapc
			      (lambda (p)
				(let ((p-name (downcase (car p))))
				  (while (string-match "_" p-name)
				    (setq p-name
					  (replace-match "-" nil nil p-name)))
				  (setq p-name (intern (concat ":" p-name)))
				  (setq plist
					(plist-put plist p-name (cdr p)))))
			      (org-entry-properties nil 'standard))
			     plist))
	   (time-props (org-entry-properties nil 'special "CLOCK"))
	   (scheduled (cdr (assoc "SCHEDULED" time-props)))
	   (deadline (cdr (assoc "DEADLINE" time-props)))
	   (clock (cdr (assoc "CLOCK" time-props)))
	   (timestamp (cdr (assoc "TIMESTAMP" time-props)))
	   (begin (point))
	   (end (save-excursion (goto-char (org-end-of-subtree t t))))
	   (pos-after-head (progn (forward-line) (point)))
	   (contents-begin (save-excursion
			     (skip-chars-forward " \r\t\n" end)
			     (and (/= (point) end) (line-beginning-position))))
	   (hidden (org-invisible-p2))
	   (contents-end (and contents-begin
			      (progn (goto-char end)
				     (skip-chars-backward " \r\t\n")
				     (forward-line)
				     (point)))))
      ;; Clean RAW-VALUE from any quote or comment string.
      (when (or quotedp commentedp)
	(let ((case-fold-search nil))
	  (setq raw-value
		(replace-regexp-in-string
		 (concat
		  (regexp-opt (list org-quote-string org-comment-string))
		  "\\(?: \\|$\\)")
		 ""
		 raw-value))))
      ;; Clean TAGS from archive tag, if any.
      (when archivedp (setq tags (delete org-archive-tag tags)))
      (let ((headline
	     (list 'headline
		   (nconc
		    (list :raw-value raw-value
			  :begin begin
			  :end end
			  :pre-blank
			  (if (not contents-begin) 0
			    (count-lines pos-after-head contents-begin))
			  :hiddenp hidden
			  :contents-begin contents-begin
			  :contents-end contents-end
			  :level level
			  :priority (nth 3 components)
			  :tags tags
			  :todo-keyword todo
			  :todo-type todo-type
			  :scheduled scheduled
			  :deadline deadline
			  :timestamp timestamp
			  :clock clock
			  :post-blank (count-lines
				       (if (not contents-end) pos-after-head
					 (goto-char contents-end)
					 (forward-line)
					 (point))
				       end)
			  :footnote-section-p footnote-section-p
			  :archivedp archivedp
			  :commentedp commentedp
			  :quotedp quotedp)
		    standard-props))))
	(org-element-put-property
	 headline :title
	 (if raw-secondary-p raw-value
	   (org-element-parse-secondary-string
	    raw-value (org-element-restriction 'headline) headline)))))))

(defun org-element-headline-interpreter (headline contents)
  "Interpret HEADLINE element as Org syntax.
CONTENTS is the contents of the element."
  (let* ((level (org-element-property :level headline))
	 (todo (org-element-property :todo-keyword headline))
	 (priority (org-element-property :priority headline))
	 (title (org-element-interpret-data
		 (org-element-property :title headline)))
	 (tags (let ((tag-list (if (org-element-property :archivedp headline)
				   (cons org-archive-tag
					 (org-element-property :tags headline))
				 (org-element-property :tags headline))))
		 (and tag-list
		      (format ":%s:" (mapconcat 'identity tag-list ":")))))
	 (commentedp (org-element-property :commentedp headline))
	 (quotedp (org-element-property :quotedp headline))
	 (pre-blank (or (org-element-property :pre-blank headline) 0))
	 (heading (concat (make-string level ?*)
			  (and todo (concat " " todo))
			  (and quotedp (concat " " org-quote-string))
			  (and commentedp (concat " " org-comment-string))
			  (and priority
			       (format " [#%s]" (char-to-string priority)))
			  (cond ((and org-footnote-section
				      (org-element-property
				       :footnote-section-p headline))
				 (concat " " org-footnote-section))
				(title (concat " " title))))))
    (concat heading
	    ;; Align tags.
	    (when tags
	      (cond
	       ((zerop org-tags-column) (format " %s" tags))
	       ((< org-tags-column 0)
		(concat
		 (make-string
		  (max (- (+ org-tags-column (length heading) (length tags))) 1)
		  ? )
		 tags))
	       (t
		(concat
		 (make-string (max (- org-tags-column (length heading)) 1) ? )
		 tags))))
	    (make-string (1+ pre-blank) 10)
	    contents)))


;;;; Inlinetask

(defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  "Parse an inline task.

Return a list whose CAR is `inlinetask' and CDR is a plist
containing `:title', `:begin', `:end', `:hiddenp',
`:contents-begin' and `:contents-end', `:level', `:priority',
`:raw-value', `:tags', `:todo-keyword', `:todo-type',
`:scheduled', `:deadline', `:timestamp', `:clock' and
`:post-blank' keywords.

The plist also contains any property set in the property drawer,
with its name in lowercase, the underscores replaced with hyphens
and colons at the beginning (i.e. `:custom-id').

When optional argument RAW-SECONDARY-P is non-nil, inline-task's
title will not be parsed as a secondary string, but as a plain
string instead.

Assume point is at beginning of the inline task."
  (save-excursion
    (let* ((keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (components (org-heading-components))
	   (todo (nth 2 components))
	   (todo-type (and todo
			   (if (member todo org-done-keywords) 'done 'todo)))
	   (tags (let ((raw-tags (nth 5 components)))
		   (and raw-tags (org-split-string raw-tags ":"))))
	   (raw-value (or (nth 4 components) ""))
	   ;; Normalize property names: ":SOME_PROP:" becomes
	   ;; ":some-prop".
	   (standard-props (let (plist)
			     (mapc
			      (lambda (p)
				(let ((p-name (downcase (car p))))
				  (while (string-match "_" p-name)
				    (setq p-name
					  (replace-match "-" nil nil p-name)))
				  (setq p-name (intern (concat ":" p-name)))
				  (setq plist
					(plist-put plist p-name (cdr p)))))
			      (org-entry-properties nil 'standard))
			     plist))
	   (time-props (org-entry-properties nil 'special "CLOCK"))
	   (scheduled (cdr (assoc "SCHEDULED" time-props)))
	   (deadline (cdr (assoc "DEADLINE" time-props)))
	   (clock (cdr (assoc "CLOCK" time-props)))
	   (timestamp (cdr (assoc "TIMESTAMP" time-props)))
	   (task-end (save-excursion
		       (end-of-line)
		       (and (re-search-forward "^\\*+ END" limit t)
			    (match-beginning 0))))
	   (contents-begin (progn (forward-line)
				  (and task-end (< (point) task-end) (point))))
	   (hidden (and contents-begin (org-invisible-p2)))
	   (contents-end (and contents-begin task-end))
	   (before-blank (if (not task-end) (point)
			   (goto-char task-end)
			   (forward-line)
			   (point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
912 913
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position))))
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
	   (inlinetask
	    (list 'inlinetask
		  (nconc
		   (list :raw-value raw-value
			 :begin begin
			 :end end
			 :hiddenp hidden
			 :contents-begin contents-begin
			 :contents-end contents-end
			 :level (nth 1 components)
			 :priority (nth 3 components)
			 :tags tags
			 :todo-keyword todo
			 :todo-type todo-type
			 :scheduled scheduled
			 :deadline deadline
			 :timestamp timestamp
			 :clock clock
			 :post-blank (count-lines before-blank end))
		   standard-props
		   (cadr keywords)))))
      (org-element-put-property
       inlinetask :title
       (if raw-secondary-p raw-value
	 (org-element-parse-secondary-string
	  raw-value
	  (org-element-restriction 'inlinetask)
	  inlinetask))))))

(defun org-element-inlinetask-interpreter (inlinetask contents)
  "Interpret INLINETASK element as Org syntax.
CONTENTS is the contents of inlinetask."
  (let* ((level (org-element-property :level inlinetask))
	 (todo (org-element-property :todo-keyword inlinetask))
	 (priority (org-element-property :priority inlinetask))
	 (title (org-element-interpret-data
		 (org-element-property :title inlinetask)))
	 (tags (let ((tag-list (org-element-property :tags inlinetask)))
		 (and tag-list
		      (format ":%s:" (mapconcat 'identity tag-list ":")))))
	 (task (concat (make-string level ?*)
		       (and todo (concat " " todo))
		       (and priority
			    (format " [#%s]" (char-to-string priority)))
		       (and title (concat " " title)))))
    (concat task
	    ;; Align tags.
	    (when tags
	      (cond
	       ((zerop org-tags-column) (format " %s" tags))
	       ((< org-tags-column 0)
		(concat
		 (make-string
		  (max (- (+ org-tags-column (length task) (length tags))) 1)
		  ? )
		 tags))
	       (t
		(concat
		 (make-string (max (- org-tags-column (length task)) 1) ? )
		 tags))))
	    ;; Prefer degenerate inlinetasks when there are no
	    ;; contents.
	    (when contents
	      (concat "\n"
		      contents
		      (make-string level ?*) " END")))))


;;;; Item

(defun org-element-item-parser (limit struct &optional raw-secondary-p)
  "Parse an item.

STRUCT is the structure of the plain list.

Return a list whose CAR is `item' and CDR is a plist containing
`:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
`:checkbox', `:counter', `:tag', `:structure', `:hiddenp' and
`:post-blank' keywords.

When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
any, will not be parsed as a secondary string, but as a plain
string instead.

Assume point is at the beginning of the item."
  (save-excursion
    (beginning-of-line)
    (looking-at org-list-full-item-re)
    (let* ((begin (point))
	   (bullet (org-match-string-no-properties 1))
	   (checkbox (let ((box (org-match-string-no-properties 3)))
		       (cond ((equal "[ ]" box) 'off)
			     ((equal "[X]" box) 'on)
			     ((equal "[-]" box) 'trans))))
	   (counter (let ((c (org-match-string-no-properties 2)))
		      (save-match-data
			(cond
			 ((not c) nil)
			 ((string-match "[A-Za-z]" c)
			  (- (string-to-char (upcase (match-string 0 c)))
			     64))
			 ((string-match "[0-9]+" c)
			  (string-to-number (match-string 0 c)))))))
	   (end (save-excursion (goto-char (org-list-get-item-end begin struct))
				(unless (bolp) (forward-line))
				(point)))
	   (contents-begin
	    (progn (goto-char
		    ;; Ignore tags in un-ordered lists: they are just
		    ;; a part of item's body.
		    (if (and (match-beginning 4)
			     (save-match-data (string-match "[.)]" bullet)))
			(match-beginning 4)
		      (match-end 0)))
		   (skip-chars-forward " \r\t\n" limit)
		   ;; If first line isn't empty, contents really start
		   ;; at the text after item's meta-data.
		   (if (= (point-at-bol) begin) (point) (point-at-bol))))
	   (hidden (progn (forward-line)
			  (and (not (= (point) end)) (org-invisible-p2))))
	   (contents-end (progn (goto-char end)
				(skip-chars-backward " \r\t\n")
				(forward-line)
				(point)))
	   (item
	    (list 'item
		  (list :bullet bullet
			:begin begin
			:end end
			;; CONTENTS-BEGIN and CONTENTS-END may be
			;; mixed up in the case of an empty item
			;; separated from the next by a blank line.
			;; Thus ensure the former is always the
			;; smallest.
			:contents-begin (min contents-begin contents-end)
			:contents-end (max contents-begin contents-end)
			:checkbox checkbox
			:counter counter
			:hiddenp hidden
			:structure struct
			:post-blank (count-lines contents-end end)))))
      (org-element-put-property
       item :tag
       (let ((raw-tag (org-list-get-tag begin struct)))
	 (and raw-tag
	      (if raw-secondary-p raw-tag
		(org-element-parse-secondary-string
		 raw-tag (org-element-restriction 'item) item))))))))

(defun org-element-item-interpreter (item contents)
  "Interpret ITEM element as Org syntax.
CONTENTS is the contents of the element."
  (let* ((bullet (org-list-bullet-string (org-element-property :bullet item)))
	 (checkbox (org-element-property :checkbox item))
	 (counter (org-element-property :counter item))
	 (tag (let ((tag (org-element-property :tag item)))
		(and tag (org-element-interpret-data tag))))
	 ;; Compute indentation.
	 (ind (make-string (length bullet) 32))
	 (item-starts-with-par-p
	  (eq (org-element-type (car (org-element-contents item)))
	      'paragraph)))
    ;; Indent contents.
    (concat
     bullet
     (and counter (format "[@%d] " counter))
     (case checkbox
       (on "[X] ")
       (off "[ ] ")
       (trans "[-] "))
     (and tag (format "%s :: " tag))
     (let ((contents (replace-regexp-in-string
		      "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
       (if item-starts-with-par-p (org-trim contents)
	 (concat "\n" contents))))))


;;;; Plain List

(defun org-element-plain-list-parser (limit &optional structure)
  "Parse a plain list.

Optional argument STRUCTURE, when non-nil, is the structure of
the plain list being parsed.

Return a list whose CAR is `plain-list' and CDR is a plist
containing `:type', `:begin', `:end', `:contents-begin' and
`:contents-end', `:structure' and `:post-blank' keywords.

Assume point is at the beginning of the list."
  (save-excursion
    (let* ((struct (or structure (org-list-struct)))
	   (prevs (org-list-prevs-alist struct))
	   (parents (org-list-parents-alist struct))
	   (type (org-list-get-list-type (point) struct prevs))
	   (contents-begin (point))
	   (keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (contents-end
	    (progn (goto-char (org-list-get-list-end (point) struct prevs))
		   (unless (bolp) (forward-line))
		   (point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1117 1118
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
      ;; Return value.
      (list 'plain-list
	    (nconc
	     (list :type type
		   :begin begin
		   :end end
		   :contents-begin contents-begin
		   :contents-end contents-end
		   :structure struct
		   :post-blank (count-lines contents-end end))
	     (cadr keywords))))))

(defun org-element-plain-list-interpreter (plain-list contents)
  "Interpret PLAIN-LIST element as Org syntax.
CONTENTS is the contents of the element."
  (with-temp-buffer
    (insert contents)
    (goto-char (point-min))
    (org-list-repair)
    (buffer-string)))


;;;; Quote Block

(defun org-element-quote-block-parser (limit)
  "Parse a quote block.

LIMIT bounds the search.

Return a list whose CAR is `quote-block' and CDR is a plist
containing `:begin', `:end', `:hiddenp', `:contents-begin',
`:contents-end' and `:post-blank' keywords.

Assume point is at the beginning of the block."
  (let ((case-fold-search t))
    (if (not (save-excursion
1155
	       (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((block-end-line (match-beginning 0)))
	(save-excursion
	  (let* ((keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 ;; Empty blocks have no contents.
		 (contents-begin (progn (forward-line)
					(and (< (point) block-end-line)
					     (point))))
		 (contents-end (and contents-begin block-end-line))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char block-end-line)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
1172 1173
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position)))))
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
	    (list 'quote-block
		  (nconc
		   (list :begin begin
			 :end end
			 :hiddenp hidden
			 :contents-begin contents-begin
			 :contents-end contents-end
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-quote-block-interpreter (quote-block contents)
  "Interpret QUOTE-BLOCK element as Org syntax.
CONTENTS is the contents of the element."
  (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))


;;;; Section

(defun org-element-section-parser (limit)
  "Parse a section.

LIMIT bounds the search.

Return a list whose CAR is `section' and CDR is a plist
containing `:begin', `:end', `:contents-begin', `contents-end'
and `:post-blank' keywords."
  (save-excursion
    ;; Beginning of section is the beginning of the first non-blank
    ;; line after previous headline.
    (let ((begin (point))
	  (end (progn (org-with-limited-levels (outline-next-heading))
		      (point)))
	  (pos-before-blank (progn (skip-chars-backward " \r\t\n")
				   (forward-line)
				   (point))))
      (list 'section
	    (list :begin begin
		  :end end
		  :contents-begin begin
		  :contents-end pos-before-blank
		  :post-blank (count-lines pos-before-blank end))))))

(defun org-element-section-interpreter (section contents)
  "Interpret SECTION element as Org syntax.
CONTENTS is the contents of the element."
  contents)


;;;; Special Block

(defun org-element-special-block-parser (limit)
  "Parse a special block.

LIMIT bounds the search.

Return a list whose CAR is `special-block' and CDR is a plist
containing `:type', `:begin', `:end', `:hiddenp',
`:contents-begin', `:contents-end' and `:post-blank' keywords.

Assume point is at the beginning of the block."
  (let* ((case-fold-search t)
	 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(S-+\\)")
		      (upcase (match-string-no-properties 1)))))
    (if (not (save-excursion
1238 1239
	       (re-search-forward
		(format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((block-end-line (match-beginning 0)))
	(save-excursion
	  (let* ((keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 ;; Empty blocks have no contents.
		 (contents-begin (progn (forward-line)
					(and (< (point) block-end-line)
					     (point))))
		 (contents-end (and contents-begin block-end-line))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char block-end-line)
					  (forward-line)
					  (point)))
1255 1256 1257
		 (end (progn (skip-chars-forward " \r\t\n" limit)
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position)))))
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
	    (list 'special-block
		  (nconc
		   (list :type type
			 :begin begin
			 :end end
			 :hiddenp hidden
			 :contents-begin contents-begin
			 :contents-end contents-end
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-special-block-interpreter (special-block contents)
  "Interpret SPECIAL-BLOCK element as Org syntax.
CONTENTS is the contents of the element."
  (let ((block-type (org-element-property :type special-block)))
    (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))



;;; Elements
;;
;; For each element, a parser and an interpreter are also defined.
;; Both follow the same naming convention used for greater elements.
;;
;; Also, as for greater elements, adding a new element type is done
;; through the following steps: implement a parser and an interpreter,
;; tweak `org-element--current-element' so that it recognizes the new
;; type and add that new type to `org-element-all-elements'.
;;
;; As a special case, when the newly defined type is a block type,
;; `org-element-block-name-alist' has to be modified accordingly.


;;;; Babel Call

(defun org-element-babel-call-parser (limit)
  "Parse a babel call.

LIMIT bounds the search.

Return a list whose CAR is `babel-call' and CDR is a plist
containing `:begin', `:end', `:info' and `:post-blank' as
keywords."
  (save-excursion
    (let ((case-fold-search t)
	  (info (progn (looking-at org-babel-block-lob-one-liner-regexp)
		       (org-babel-lob-get-info)))
	  (begin (point-at-bol))
	  (pos-before-blank (progn (forward-line) (point)))
	  (end (progn (skip-chars-forward " \r\t\n" limit)
1308 1309
		      (skip-chars-backward " \t")
		      (if (bolp) (point) (line-end-position)))))
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
      (list 'babel-call
	    (list :begin begin
		  :end end
		  :info info
		  :post-blank (count-lines pos-before-blank end))))))

(defun org-element-babel-call-interpreter (babel-call contents)
  "Interpret BABEL-CALL element as Org syntax.
CONTENTS is nil."
  (let* ((babel-info (org-element-property :info babel-call))
	 (main (car babel-info))
	 (post-options (nth 1 babel-info)))
    (concat "#+CALL: "
	    (if (not (string-match "\\[\\(\\[.*?\\]\\)\\]" main)) main
	      ;; Remove redundant square brackets.
	      (replace-match (match-string 1 main) nil nil main))
	    (and post-options (format "[%s]" post-options)))))


;;;; Clock

(defun org-element-clock-parser (limit)
  "Parse a clock.

LIMIT bounds the search.

Return a list whose CAR is `clock' and CDR is a plist containing
`:status', `:value', `:time', `:begin', `:end' and `:post-blank'
as keywords."
  (save-excursion
    (let* ((case-fold-search nil)
	   (begin (point))
	   (value (progn (search-forward org-clock-string (line-end-position) t)
			 (org-skip-whitespace)
			 (looking-at "\\[.*\\]")
			 (org-match-string-no-properties 0)))
	   (time (and (progn (goto-char (match-end 0))
			     (looking-at " +=> +\\(\\S-+\\)[ \t]*$"))
		      (org-match-string-no-properties 1)))
	   (status (if time 'closed 'running))
	   (post-blank (let ((before-blank (progn (forward-line) (point))))
			 (skip-chars-forward " \r\t\n" limit)
1352 1353
			 (skip-chars-backward " \t")
			 (unless (bolp) (end-of-line))
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
			 (count-lines before-blank (point))))
	   (end (point)))
      (list 'clock
	    (list :status status
		  :value value
		  :time time
		  :begin begin
		  :end end
		  :post-blank post-blank)))))

(defun org-element-clock-interpreter (clock contents)
  "Interpret CLOCK element as Org syntax.
CONTENTS is nil."
  (concat org-clock-string " "
	  (org-element-property :value clock)
	  (let ((time (org-element-property :time clock)))
	    (and time
		 (concat " => "
			 (apply 'format
				"%2s:%02s"
				(org-split-string time ":")))))))


;;;; Comment

(defun org-element-comment-parser (limit)
  "Parse a comment.

LIMIT bounds the search.

Return a list whose CAR is `comment' and CDR is a plist
containing `:begin', `:end', `:value' and `:post-blank'
keywords.

Assume point is at comment beginning."
  (save-excursion
    (let* ((keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (value (prog2 (looking-at "[ \t]*# ?")
		      (buffer-substring-no-properties
		       (match-end 0) (line-end-position))
		    (forward-line)))
	   (com-end
	    ;; Get comments ending.
	    (progn
	      (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
		;; Accumulate lines without leading hash and first
		;; whitespace.
		(setq value
		      (concat value
			      "\n"
			      (buffer-substring-no-properties
			       (match-end 0) (line-end-position))))
		(forward-line))
	      (point)))
	   (end (progn (goto-char com-end)
		       (skip-chars-forward " \r\t\n" limit)
1411 1412
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
      (list 'comment
	    (nconc
	     (list :begin begin
		   :end end
		   :value value
		   :post-blank (count-lines com-end end))
	     (cadr keywords))))))

(defun org-element-comment-interpreter (comment contents)
  "Interpret COMMENT element as Org syntax.
CONTENTS is nil."
  (replace-regexp-in-string "^" "# " (org-element-property :value comment)))


;;;; Comment Block

(defun org-element-comment-block-parser (limit)
  "Parse an export block.

LIMIT bounds the search.

Return a list whose CAR is `comment-block' and CDR is a plist
containing `:begin', `:end', `:hiddenp', `:value' and
`:post-blank' keywords.

Assume point is at comment block beginning."
  (let ((case-fold-search t))
    (if (not (save-excursion
1441
	       (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((contents-end (match-beginning 0)))
	(save-excursion
	  (let* ((keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 (contents-begin (progn (forward-line) (point)))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char contents-end)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
1454 1455
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position))))
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
		 (value (buffer-substring-no-properties
			 contents-begin contents-end)))
	    (list 'comment-block
		  (nconc
		   (list :begin begin
			 :end end
			 :value value
			 :hiddenp hidden
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-comment-block-interpreter (comment-block contents)
  "Interpret COMMENT-BLOCK element as Org syntax.
CONTENTS is nil."
  (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
	  (org-remove-indentation (org-element-property :value comment-block))))


;;;; Example Block

(defun org-element-example-block-parser (limit)
  "Parse an example block.

LIMIT bounds the search.

Return a list whose CAR is `example-block' and CDR is a plist
containing `:begin', `:end', `:number-lines', `:preserve-indent',
`:retain-labels', `:use-labels', `:label-fmt', `:hiddenp',
`:switches', `:value' and `:post-blank' keywords."
  (let ((case-fold-search t))
    (if (not (save-excursion
1487
	       (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((contents-end (match-beginning 0)))
	(save-excursion
	  (let* ((switches
		  (progn (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
			 (org-match-string-no-properties 1)))
		 ;; Switches analysis
		 (number-lines (cond ((not switches) nil)
				     ((string-match "-n\\>" switches) 'new)
				     ((string-match "+n\\>" switches) 'continued)))
		 (preserve-indent (and switches (string-match "-i\\>" switches)))
		 ;; Should labels be retained in (or stripped from) example
		 ;; blocks?
		 (retain-labels
		  (or (not switches)
		      (not (string-match "-r\\>" switches))
		      (and number-lines (string-match "-k\\>" switches))))
		 ;; What should code-references use - labels or
		 ;; line-numbers?
		 (use-labels
		  (or (not switches)
		      (and retain-labels (not (string-match "-k\\>" switches)))))
		 (label-fmt (and switches
				 (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
				 (match-string 1 switches)))
		 ;; Standard block parsing.
		 (keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 (contents-begin (progn (forward-line) (point)))
		 (hidden (org-invisible-p2))
1519 1520 1521
		 (value (org-unescape-code-in-string
			 (buffer-substring-no-properties
			  contents-begin contents-end)))
1522 1523 1524 1525
		 (pos-before-blank (progn (goto-char contents-end)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
1526 1527
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position)))))
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
	    (list 'example-block
		  (nconc
		   (list :begin begin
			 :end end
			 :value value
			 :switches switches
			 :number-lines number-lines
			 :preserve-indent preserve-indent
			 :retain-labels retain-labels
			 :use-labels use-labels
			 :label-fmt label-fmt
			 :hiddenp hidden
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-example-block-interpreter (example-block contents)
  "Interpret EXAMPLE-BLOCK element as Org syntax.
CONTENTS is nil."
  (let ((switches (org-element-property :switches example-block)))
    (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
	    (org-remove-indentation
1549 1550
	     (org-escape-code-in-string
	      (org-element-property :value example-block)))
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
	    "#+END_EXAMPLE")))


;;;; Export Block

(defun org-element-export-block-parser (limit)
  "Parse an export block.

LIMIT bounds the search.

Return a list whose CAR is `export-block' and CDR is a plist
containing `:begin', `:end', `:type', `:hiddenp', `:value' and
`:post-blank' keywords.

Assume point is at export-block beginning."
  (let* ((case-fold-search t)
	 (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
		      (upcase (org-match-string-no-properties 1)))))
    (if (not (save-excursion
1570 1571
	       (re-search-forward
		(format "^[ \t]*#\\+END_%s[ \t]*$" type) limit t)))
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
	;; Incomplete block: parse it as a paragraph.
	(org-element-paragraph-parser limit)
      (let ((contents-end (match-beginning 0)))
	(save-excursion
	  (let* ((keywords (org-element--collect-affiliated-keywords))
		 (begin (car keywords))
		 (contents-begin (progn (forward-line) (point)))
		 (hidden (org-invisible-p2))
		 (pos-before-blank (progn (goto-char contents-end)
					  (forward-line)
					  (point)))
		 (end (progn (skip-chars-forward " \r\t\n" limit)
1584 1585
			     (skip-chars-backward " \t")
			     (if (bolp) (point) (line-end-position))))
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
		 (value (buffer-substring-no-properties contents-begin
							contents-end)))
	    (list 'export-block
		  (nconc
		   (list :begin begin
			 :end end
			 :type type
			 :value value
			 :hiddenp hidden
			 :post-blank (count-lines pos-before-blank end))
		   (cadr keywords)))))))))

(defun org-element-export-block-interpreter (export-block contents)
  "Interpret EXPORT-BLOCK element as Org syntax.
CONTENTS is nil."
  (let ((type (org-element-property :type export-block)))
    (concat (format "#+BEGIN_%s\n" type)
	    (org-element-property :value export-block)
	    (format "#+END_%s" type))))


;;;; Fixed-width

(defun org-element-fixed-width-parser (limit)
  "Parse a fixed-width section.

LIMIT bounds the search.

Return a list whose CAR is `fixed-width' and CDR is a plist
containing `:begin', `:end', `:value' and `:post-blank' keywords.

Assume point is at the beginning of the fixed-width area."
  (save-excursion
    (let* ((keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   value
	   (end-area
	    (progn
	      (while (and (< (point) limit)
			  (looking-at "[ \t]*:\\( \\|$\\)"))
		;; Accumulate text without starting colons.
		(setq value
		      (concat value
			      (buffer-substring-no-properties
			       (match-end 0) (point-at-eol))
			      "\n"))
		(forward-line))
	      (point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1635 1636
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
      (list 'fixed-width
	    (nconc
	     (list :begin begin
		   :end end
		   :value value
		   :post-blank (count-lines end-area end))
	     (cadr keywords))))))

(defun org-element-fixed-width-interpreter (fixed-width contents)
  "Interpret FIXED-WIDTH element as Org syntax.
CONTENTS is nil."
  (replace-regexp-in-string
   "^" ": " (substring (org-element-property :value fixed-width) 0 -1)))


;;;; Horizontal Rule

(defun org-element-horizontal-rule-parser (limit)
  "Parse an horizontal rule.

LIMIT bounds the search.

Return a list whose CAR is `horizontal-rule' and CDR is a plist
containing `:begin', `:end' and `:post-blank' keywords."
  (save-excursion
    (let* ((keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (post-hr (progn (forward-line) (point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1666 1667
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
      (list 'horizontal-rule
	    (nconc
	     (list :begin begin
		   :end end
		   :post-blank (count-lines post-hr end))
	     (cadr keywords))))))

(defun org-element-horizontal-rule-interpreter (horizontal-rule contents)
  "Interpret HORIZONTAL-RULE element as Org syntax.
CONTENTS is nil."
  "-----")


;;;; Keyword

(defun org-element-keyword-parser (limit)
  "Parse a keyword at point.

LIMIT bounds the search.

Return a list whose CAR is `keyword' and CDR is a plist
containing `:key', `:value', `:begin', `:end' and `:post-blank'
keywords."
  (save-excursion
    (let* ((case-fold-search t)
	   (begin (point))
	   (key (progn (looking-at "[ \t]*#\\+\\(\\S-+\\):")
		       (upcase (org-match-string-no-properties 1))))
	   (value (org-trim (buffer-substring-no-properties
			     (match-end 0) (point-at-eol))))
	   (pos-before-blank (progn (forward-line) (point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1700 1701
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
      (list 'keyword
	    (list :key key
		  :value value
		  :begin begin
		  :end end
		  :post-blank (count-lines pos-before-blank end))))))

(defun org-element-keyword-interpreter (keyword contents)
  "Interpret KEYWORD element as Org syntax.
CONTENTS is nil."
  (format "#+%s: %s"
	  (org-element-property :key keyword)
	  (org-element-property :value keyword)))


;;;; Latex Environment

(defun org-element-latex-environment-parser (limit)
  "Parse a LaTeX environment.

LIMIT bounds the search.

Return a list whose CAR is `latex-environment' and CDR is a plist
containing `:begin', `:end', `:value' and `:post-blank'
keywords.

Assume point is at the beginning of the latex environment."
  (save-excursion
    (let* ((case-fold-search t)
	   (code-begin (point))
	   (keywords (org-element--collect-affiliated-keywords))
	   (begin (car keywords))
	   (env (progn (looking-at "^[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}")
		       (regexp-quote (match-string 1))))
	   (code-end
1737 1738
	    (progn (re-search-forward
		    (format "^[ \t]*\\\\end{%s}[ \t]*$" env) limit t)
1739 1740 1741 1742
		   (forward-line)
		   (point)))
	   (value (buffer-substring-no-properties code-begin code-end))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1743 1744
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
      (list 'latex-environment
	    (nconc
	     (list :begin begin
		   :end end
		   :value value
		   :post-blank (count-lines code-end end))
	     (cadr keywords))))))

(defun org-element-latex-environment-interpreter (latex-environment contents)
  "Interpret LATEX-ENVIRONMENT element as Org syntax.
CONTENTS is nil."
  (org-element-property :value latex-environment))


;;;; Paragraph

(defun org-element-paragraph-parser (limit)
  "Parse a paragraph.

LIMIT bounds the search.

Return a list whose CAR is `paragraph' and CDR is a plist
containing `:begin', `:end', `:contents-begin' and
`:contents-end' and `:post-blank' keywords.

Assume point is at the beginning of the paragraph."
  (save-excursion
1772 1773
    (let* ((contents-begin (point))
	   ;; INNER-PAR-P is non-nil when paragraph is at the
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
	   ;; beginning of an item or a footnote reference. In that
	   ;; case, we mustn't look for affiliated keywords since they
	   ;; belong to the container.
	   (inner-par-p (not (bolp)))
	   (keywords (unless inner-par-p
		       (org-element--collect-affiliated-keywords)))
	   (begin (if inner-par-p contents-begin (car keywords)))
	   (before-blank
	    (let ((case-fold-search t))
	      (end-of-line)
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
	      (if (not (re-search-forward
			org-element-paragraph-separate limit 'm))
		  limit
		;; A matching `org-element-paragraph-separate' is not
		;; necessarily the end of the paragraph.  In
		;; particular, lines starting with # or : as a first
		;; non-space character are ambiguous.  We have check
		;; if they are valid Org syntax (i.e. not an
		;; incomplete keyword).
		(beginning-of-line)
		(while (not
			(or
			 ;; There's no ambiguity for other symbols or
			 ;; empty lines: stop here.
			 (looking-at "[ \t]*\\(?:[^:#]\\|$\\)")
			 ;; Stop at valid fixed-width areas.
			 (looking-at "[ \t]*:\\(?: \\|$\\)")
			 ;; Stop at drawers.
			 (and (looking-at org-drawer-regexp)
			      (save-excursion
				(re-search-forward
				 "^[ \t]*:END:[ \t]*$" limit t)))
			 ;; Stop at valid comments.
			 (looking-at "[ \t]*#\\(?: \\|$\\)")
			 ;; Stop at valid dynamic blocks.
			 (and (looking-at org-dblock-start-re)
			      (save-excursion
				(re-search-forward
				 "^[ \t]*#\\+END:?[ \t]*$" limit t)))
			 ;; Stop at valid blocks.
			 (and (looking-at
			       "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
			      (save-excursion
				(re-search-forward
				 (format "^[ \t]*#\\+END_%s[ \t]*$"
					 (match-string 1))
				 limit t)))
			 ;; Stop at valid latex environments.
			 (and (looking-at
			       "^[ \t]*\\\\begin{\\([A-Za-z0-9]+\\*?\\)}[ \t]*$")
			      (save-excursion
				(re-search-forward
				 (format "^[ \t]*\\\\end{%s}[ \t]*$"
					 (match-string 1))
				 limit t)))
			 ;; Stop at valid keywords.
			 (looking-at "[ \t]*#\\+\\S-+:")
			 ;; Skip everything else.
			 (not
			  (progn
			    (end-of-line)
			    (re-search-forward org-element-paragraph-separate
					       limit 'm)))))
		  (beginning-of-line)))
	      (if (= (point) limit) limit
		(goto-char (line-beginning-position)))))
1840 1841 1842 1843
	   (contents-end (progn (skip-chars-backward " \r\t\n" contents-begin)
				(forward-line)
				(point)))
	   (end (progn (skip-chars-forward " \r\t\n" limit)
1844 1845
		       (skip-chars-backward " \t")
		       (if (bolp) (point) (line-end-position)))))
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
      (list 'paragraph
	    (nconc
	     (list :begin begin
		   :end end
		   :contents-begin contents-begin
		   :contents-end contents-end
		   :post-blank (count-lines before-blank end))
	     (cadr keywords))))))

(defun org-element-paragraph-interpreter (paragraph contents)
  "Interpret PARAGRAPH element as Org syntax.
CONTENTS is the contents of the element."
  contents)


;;;; Planning

(defun org-element-planning-parser (limit)
  "Parse a planning.

LIMIT bounds the search.

Return a list whose CAR is `planning' and CDR is a plist
containing `:closed', `:deadline', `:scheduled', `:begin', `:end'
and `:post-blank' keywords."
  (save-excursion
    (let* ((case-fold-search nil)
	   (begin (point))
	   (post-blank (let ((before-blank (progn (forward-line) (point))))
			 (skip-chars-forward " \r\t\n" limit)
1876 1877
			 (skip-chars-backward " \t")
			 (unless (bolp) (end-of-line))
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
			 (count-lines before-blank (point))))
	   (end (point))
	   closed deadline scheduled)
      (goto-char begin)
      (while (re-search-forward org-keyword-time-not-clock-regexp
				(line-end-position) t)
	(goto-char (match-end 1))
	(org-skip-whitespace)
	(let ((time (buffer-substring-no-properties
		     (1+ (point)) (1- (match-end 0))))
	      (keyword (match-string 1)))
	  (cond ((equal keyword org-closed-string) (setq closed time))
		((equal keyword org-deadline-string) (setq deadline time))
		(t (setq scheduled time)))))
      (list 'planning
	    (list :closed closed
		  :deadline deadline
		  :scheduled scheduled
		  :begin begin
		  :end end
		  :post-blank post-blank)))))

(defun org-element-planning-interpreter (planning contents)
  "Interpret PLANNING element as Org syntax.
CONTENTS is nil."
  (mapconcat
   'identity
   (delq nil
	 (list (let ((closed (org-element-property :closed planning)))
		 (when closed (concat org-closed-string " [" closed "]")))
	       (let ((deadline (org-element-property :deadline planning)))
		 (when deadline (concat org-deadline-string " <" deadline ">")))
	       (let ((scheduled (org-element-property :scheduled planning)))
		 (when scheduled
		   (concat org-scheduled-string " <" scheduled ">")))))
   " "))


;;;; Property Drawer

(defun org-element-property-drawer-parse